code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
FactoryGirl.define do
factory :transaction do |t|
t.description "Test transaction"
t.association :account_from, :factory => :foo_account
t.association :account_to, :factory => :foo_account
t.amount 10.00
end
factory :invoice_payment, :parent => :transaction do
auxilliary_model :factory => :invoice
end
end
| Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/favicon.ico">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
<title>TableTools example - Button collections</title>
<link rel="stylesheet" type="text/css" href="../../../media/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="../css/dataTables.tableTools.css">
<link rel="stylesheet" type="text/css" href="../../../examples/resources/syntax/shCore.css">
<link rel="stylesheet" type="text/css" href="../../../examples/resources/demo.css">
<style type="text/css" class="init">
</style>
<script type="text/javascript" language="javascript" src="../../../media/js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="../../../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" src="../js/dataTables.tableTools.js"></script>
<script type="text/javascript" language="javascript" src="../../../examples/resources/syntax/shCore.js"></script>
<script type="text/javascript" language="javascript" src="../../../examples/resources/demo.js"></script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
$('#example').DataTable( {
"dom": 'T<"clear">lfrtip',
"tableTools": {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": "Save",
"aButtons": [ "csv", "xls", "pdf" ]
}
]
}
} );
} );
</script>
</head>
<body class="dt-example">
<div class="container">
<section>
<h1>TableTools example <span>Button collections</span></h1>
<div class="info">
<p>TableTools provides the ability to group buttons into a hidden drop down list, which is activated by clicking on a top-level button. This is achieved by
extending the 'collection' predefined button type and setting it's <code>aButtons</code> parameter with the same options as the top level buttons (note that you
cannot currently use a collection within a collection).</p>
<p>The example below shows the file save buttons grouped into a collection, while the copy and print buttons are left on the top level.</p>
</div>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
</tr>
<tr>
<td>Cedric Kelly</td>
<td>Senior Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
</tr>
<tr>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>2008/11/28</td>
<td>$162,700</td>
</tr>
<tr>
<td>Brielle Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
<td>61</td>
<td>2012/12/02</td>
<td>$372,000</td>
</tr>
<tr>
<td>Herrod Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
<td>59</td>
<td>2012/08/06</td>
<td>$137,500</td>
</tr>
<tr>
<td>Rhona Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
<td>55</td>
<td>2010/10/14</td>
<td>$327,900</td>
</tr>
<tr>
<td>Colleen Hurst</td>
<td>Javascript Developer</td>
<td>San Francisco</td>
<td>39</td>
<td>2009/09/15</td>
<td>$205,500</td>
</tr>
<tr>
<td>Sonya Frost</td>
<td>Software Engineer</td>
<td>Edinburgh</td>
<td>23</td>
<td>2008/12/13</td>
<td>$103,600</td>
</tr>
<tr>
<td>Jena Gaines</td>
<td>Office Manager</td>
<td>London</td>
<td>30</td>
<td>2008/12/19</td>
<td>$90,560</td>
</tr>
<tr>
<td>Quinn Flynn</td>
<td>Support Lead</td>
<td>Edinburgh</td>
<td>22</td>
<td>2013/03/03</td>
<td>$342,000</td>
</tr>
<tr>
<td>Charde Marshall</td>
<td>Regional Director</td>
<td>San Francisco</td>
<td>36</td>
<td>2008/10/16</td>
<td>$470,600</td>
</tr>
<tr>
<td>Haley Kennedy</td>
<td>Senior Marketing Designer</td>
<td>London</td>
<td>43</td>
<td>2012/12/18</td>
<td>$313,500</td>
</tr>
<tr>
<td>Tatyana Fitzpatrick</td>
<td>Regional Director</td>
<td>London</td>
<td>19</td>
<td>2010/03/17</td>
<td>$385,750</td>
</tr>
<tr>
<td>Michael Silva</td>
<td>Marketing Designer</td>
<td>London</td>
<td>66</td>
<td>2012/11/27</td>
<td>$198,500</td>
</tr>
<tr>
<td>Paul Byrd</td>
<td>Chief Financial Officer (CFO)</td>
<td>New York</td>
<td>64</td>
<td>2010/06/09</td>
<td>$725,000</td>
</tr>
<tr>
<td>Gloria Little</td>
<td>Systems Administrator</td>
<td>New York</td>
<td>59</td>
<td>2009/04/10</td>
<td>$237,500</td>
</tr>
<tr>
<td>Bradley Greer</td>
<td>Software Engineer</td>
<td>London</td>
<td>41</td>
<td>2012/10/13</td>
<td>$132,000</td>
</tr>
<tr>
<td>Dai Rios</td>
<td>Personnel Lead</td>
<td>Edinburgh</td>
<td>35</td>
<td>2012/09/26</td>
<td>$217,500</td>
</tr>
<tr>
<td>Jenette Caldwell</td>
<td>Development Lead</td>
<td>New York</td>
<td>30</td>
<td>2011/09/03</td>
<td>$345,000</td>
</tr>
<tr>
<td>Yuri Berry</td>
<td>Chief Marketing Officer (CMO)</td>
<td>New York</td>
<td>40</td>
<td>2009/06/25</td>
<td>$675,000</td>
</tr>
<tr>
<td>Caesar Vance</td>
<td>Pre-Sales Support</td>
<td>New York</td>
<td>21</td>
<td>2011/12/12</td>
<td>$106,450</td>
</tr>
<tr>
<td>Doris Wilder</td>
<td>Sales Assistant</td>
<td>Sidney</td>
<td>23</td>
<td>2010/09/20</td>
<td>$85,600</td>
</tr>
<tr>
<td>Angelica Ramos</td>
<td>Chief Executive Officer (CEO)</td>
<td>London</td>
<td>47</td>
<td>2009/10/09</td>
<td>$1,200,000</td>
</tr>
<tr>
<td>Gavin Joyce</td>
<td>Developer</td>
<td>Edinburgh</td>
<td>42</td>
<td>2010/12/22</td>
<td>$92,575</td>
</tr>
<tr>
<td>Jennifer Chang</td>
<td>Regional Director</td>
<td>Singapore</td>
<td>28</td>
<td>2010/11/14</td>
<td>$357,650</td>
</tr>
<tr>
<td>Brenden Wagner</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>28</td>
<td>2011/06/07</td>
<td>$206,850</td>
</tr>
<tr>
<td>Fiona Green</td>
<td>Chief Operating Officer (COO)</td>
<td>San Francisco</td>
<td>48</td>
<td>2010/03/11</td>
<td>$850,000</td>
</tr>
<tr>
<td>Shou Itou</td>
<td>Regional Marketing</td>
<td>Tokyo</td>
<td>20</td>
<td>2011/08/14</td>
<td>$163,000</td>
</tr>
<tr>
<td>Michelle House</td>
<td>Integration Specialist</td>
<td>Sidney</td>
<td>37</td>
<td>2011/06/02</td>
<td>$95,400</td>
</tr>
<tr>
<td>Suki Burks</td>
<td>Developer</td>
<td>London</td>
<td>53</td>
<td>2009/10/22</td>
<td>$114,500</td>
</tr>
<tr>
<td>Prescott Bartlett</td>
<td>Technical Author</td>
<td>London</td>
<td>27</td>
<td>2011/05/07</td>
<td>$145,000</td>
</tr>
<tr>
<td>Gavin Cortez</td>
<td>Team Leader</td>
<td>San Francisco</td>
<td>22</td>
<td>2008/10/26</td>
<td>$235,500</td>
</tr>
<tr>
<td>Martena Mccray</td>
<td>Post-Sales support</td>
<td>Edinburgh</td>
<td>46</td>
<td>2011/03/09</td>
<td>$324,050</td>
</tr>
<tr>
<td>Unity Butler</td>
<td>Marketing Designer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/12/09</td>
<td>$85,675</td>
</tr>
<tr>
<td>Howard Hatfield</td>
<td>Office Manager</td>
<td>San Francisco</td>
<td>51</td>
<td>2008/12/16</td>
<td>$164,500</td>
</tr>
<tr>
<td>Hope Fuentes</td>
<td>Secretary</td>
<td>San Francisco</td>
<td>41</td>
<td>2010/02/12</td>
<td>$109,850</td>
</tr>
<tr>
<td>Vivian Harrell</td>
<td>Financial Controller</td>
<td>San Francisco</td>
<td>62</td>
<td>2009/02/14</td>
<td>$452,500</td>
</tr>
<tr>
<td>Timothy Mooney</td>
<td>Office Manager</td>
<td>London</td>
<td>37</td>
<td>2008/12/11</td>
<td>$136,200</td>
</tr>
<tr>
<td>Jackson Bradshaw</td>
<td>Director</td>
<td>New York</td>
<td>65</td>
<td>2008/09/26</td>
<td>$645,750</td>
</tr>
<tr>
<td>Olivia Liang</td>
<td>Support Engineer</td>
<td>Singapore</td>
<td>64</td>
<td>2011/02/03</td>
<td>$234,500</td>
</tr>
<tr>
<td>Bruno Nash</td>
<td>Software Engineer</td>
<td>London</td>
<td>38</td>
<td>2011/05/03</td>
<td>$163,500</td>
</tr>
<tr>
<td>Sakura Yamamoto</td>
<td>Support Engineer</td>
<td>Tokyo</td>
<td>37</td>
<td>2009/08/19</td>
<td>$139,575</td>
</tr>
<tr>
<td>Thor Walton</td>
<td>Developer</td>
<td>New York</td>
<td>61</td>
<td>2013/08/11</td>
<td>$98,540</td>
</tr>
<tr>
<td>Finn Camacho</td>
<td>Support Engineer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/07/07</td>
<td>$87,500</td>
</tr>
<tr>
<td>Serge Baldwin</td>
<td>Data Coordinator</td>
<td>Singapore</td>
<td>64</td>
<td>2012/04/09</td>
<td>$138,575</td>
</tr>
<tr>
<td>Zenaida Frank</td>
<td>Software Engineer</td>
<td>New York</td>
<td>63</td>
<td>2010/01/04</td>
<td>$125,250</td>
</tr>
<tr>
<td>Zorita Serrano</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>56</td>
<td>2012/06/01</td>
<td>$115,000</td>
</tr>
<tr>
<td>Jennifer Acosta</td>
<td>Junior Javascript Developer</td>
<td>Edinburgh</td>
<td>43</td>
<td>2013/02/01</td>
<td>$75,650</td>
</tr>
<tr>
<td>Cara Stevens</td>
<td>Sales Assistant</td>
<td>New York</td>
<td>46</td>
<td>2011/12/06</td>
<td>$145,600</td>
</tr>
<tr>
<td>Hermione Butler</td>
<td>Regional Director</td>
<td>London</td>
<td>47</td>
<td>2011/03/21</td>
<td>$356,250</td>
</tr>
<tr>
<td>Lael Greer</td>
<td>Systems Administrator</td>
<td>London</td>
<td>21</td>
<td>2009/02/27</td>
<td>$103,500</td>
</tr>
<tr>
<td>Jonas Alexander</td>
<td>Developer</td>
<td>San Francisco</td>
<td>30</td>
<td>2010/07/14</td>
<td>$86,500</td>
</tr>
<tr>
<td>Shad Decker</td>
<td>Regional Director</td>
<td>Edinburgh</td>
<td>51</td>
<td>2008/11/13</td>
<td>$183,000</td>
</tr>
<tr>
<td>Michael Bruce</td>
<td>Javascript Developer</td>
<td>Singapore</td>
<td>29</td>
<td>2011/06/27</td>
<td>$183,000</td>
</tr>
<tr>
<td>Donna Snider</td>
<td>Customer Support</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$112,000</td>
</tr>
</tbody>
</table>
<ul class="tabs">
<li class="active">Javascript</li>
<li>HTML</li>
<li>CSS</li>
<li>Ajax</li>
<li>Server-side script</li>
</ul>
<div class="tabs">
<div class="js">
<p>The Javascript shown below is used to initialise the table shown in this example:</p><code class="multiline language-js">$(document).ready(function() {
$('#example').DataTable( {
"dom": 'T<"clear">lfrtip',
"tableTools": {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": "Save",
"aButtons": [ "csv", "xls", "pdf" ]
}
]
}
} );
} );</code>
<p>In addition to the above code, the following Javascript library files are loaded for use in this example:</p>
<ul>
<li><a href="../../../media/js/jquery.js">../../../media/js/jquery.js</a></li>
<li><a href="../../../media/js/jquery.dataTables.js">../../../media/js/jquery.dataTables.js</a></li>
<li><a href="../js/dataTables.tableTools.js">../js/dataTables.tableTools.js</a></li>
</ul>
</div>
<div class="table">
<p>The HTML shown below is the raw HTML table element, before it has been enhanced by DataTables:</p>
</div>
<div class="css">
<div>
<p>This example uses a little bit of additional CSS beyond what is loaded from the library files (below), in order to correctly display the table. The
additional CSS used is shown below:</p><code class="multiline language-css"></code>
</div>
<p>The following CSS library files are loaded for use in this example to provide the styling of the table:</p>
<ul>
<li><a href="../../../media/css/jquery.dataTables.css">../../../media/css/jquery.dataTables.css</a></li>
<li><a href="../css/dataTables.tableTools.css">../css/dataTables.tableTools.css</a></li>
</ul>
</div>
<div class="ajax">
<p>This table loads data by Ajax. The latest data that has been loaded is shown below. This data will update automatically as any additional data is
loaded.</p>
</div>
<div class="php">
<p>The script used to perform the server-side processing for this table is shown below. Please note that this is just an example script using PHP. Server-side
processing scripts can be written in any language, using <a href="//datatables.net/manual/server-side">the protocol described in the DataTables
documentation</a>.</p>
</div>
</div>
</section>
</div>
<section>
<div class="footer">
<div class="gradient"></div>
<div class="liner">
<h2>Other examples</h2>
<div class="toc">
<div class="toc-group">
<h3><a href="./index.php">Examples</a></h3>
<ul class="toc active">
<li><a href="./simple.html">Basic initialisation</a></li>
<li><a href="./swf_path.html">Setting the SWF path</a></li>
<li><a href="./new_init.html">Initialisation with `new`</a></li>
<li><a href="./defaults.html">Defaults</a></li>
<li><a href="./select_single.html">Row selection - single row select</a></li>
<li><a href="./select_multi.html">Row selection - multi-row select</a></li>
<li><a href="./select_os.html">Row selection - operating system style</a></li>
<li><a href="./select_column.html">Row selection - row selector on specific cells</a></li>
<li><a href="./multiple_tables.html">Multiple tables</a></li>
<li><a href="./multi_instance.html">Multiple toolbars</a></li>
<li class="active"><a href="./collection.html">Button collections</a></li>
<li><a href="./plug-in.html">Plug-in button types</a></li>
<li><a href="./button_text.html">Custom button text</a></li>
<li><a href="./alter_buttons.html">Button arrangement</a></li>
<li><a href="./ajax.html">Ajax loaded data</a></li>
<li><a href="./pdf_message.html">PDF message</a></li>
<li><a href="./bootstrap.html">Bootstrap styling</a></li>
<li><a href="./jqueryui.html">jQuery UI styling</a></li>
</ul>
</div>
</div>
<div class="epilogue">
<p>Please refer to the <a href="http://www.datatables.net">DataTables documentation</a> for full information about its API properties and methods.<br>
Additionally, there are a wide range of <a href="http://www.datatables.net/extras">extras</a> and <a href="http://www.datatables.net/plug-ins">plug-ins</a>
which extend the capabilities of DataTables.</p>
<p class="copyright">DataTables designed and created by <a href="http://www.sprymedia.co.uk">SpryMedia Ltd</a> © 2007-2015<br>
DataTables is licensed under the <a href="http://www.datatables.net/mit">MIT license</a>.</p>
</div>
</div>
</div>
</section>
</body>
</html> | Java |
//
// AppDelegate.h
// EXTabBarController
//
// Created by apple on 15/5/23.
// Copyright (c) 2015年 DeltaX. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| Java |
"use strict";
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
var task = require("../tasks/tar.gz"),
fs = require("fs");
exports["targz"] = {
setUp: function(done) {
// setup here
done();
},
"targz sqlite3": function(test) {
test.expect(1);
var actual;
actual = fs.statSync("tmp/node_sqlite3.node");
test.equal(actual.size, 831488);
test.done();
}
}; | Java |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Comp625Component } from './comp-625.component';
describe('Comp625Component', () => {
let component: Comp625Component;
let fixture: ComponentFixture<Comp625Component>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ Comp625Component ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(Comp625Component);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| Java |
require 'moosex/types'
require 'moosex/attribute/modifiers'
module MooseX
class Attribute
include MooseX::Types
attr_reader :attr_symbol, :methods, :attribute_map
def is ; @attribute_map[:is] ; end
def writter ; @attribute_map[:writter] ; end
def reader ; @attribute_map[:reader] ; end
def override ; @attribute_map[:override] ; end
def doc ; @attribute_map[:doc] ; end
def default ; @attribute_map[:default] ; end
@@LIST_OF_PARAMETERS = [
:is, #MooseX::AttributeModifiers::Is ],
:isa, #MooseX::AttributeModifiers::Isa ],
:default, #MooseX::AttributeModifiers::Default ],
:required, #MooseX::AttributeModifiers::Required ],
:predicate, #MooseX::AttributeModifiers::Predicate],
:clearer, #MooseX::AttributeModifiers::Clearer ],
:traits, #MooseX::AttributeModifiers::Traits ],
:handles, #MooseX::AttributeModifiers::Handles ],
:lazy, #MooseX::AttributeModifiers::Lazy ],
:reader, #MooseX::AttributeModifiers::Reader ],
:writter, #MooseX::AttributeModifiers::Writter ],
:builder, #MooseX::AttributeModifiers::Builder ],
:init_arg, #MooseX::AttributeModifiers::Init_arg ],
:trigger, #MooseX::AttributeModifiers::Trigger ],
:coerce, #MooseX::AttributeModifiers::Coerce ],
:weak, #MooseX::AttributeModifiers::Weak ],
:doc, #MooseX::AttributeModifiers::Doc ],
:override, #MooseX::AttributeModifiers::Override ],
]
def initialize(attr_symbol, options ,klass)
@attr_symbol = attr_symbol
@attribute_map = {}
init_internal_modifiers(options.clone, klass.__moosex__meta.plugins, klass)
end
def init_internal_modifiers(options, plugins, klass)
list = @@LIST_OF_PARAMETERS.map do |parameter|
MooseX::AttributeModifiers::const_get(parameter.capitalize).new(self)
end
list.each do |plugin|
plugin.prepare(options)
end
plugins.sort.uniq.each do |plugin_klass|
begin
plugin_klass.new(self).prepare(options)
rescue => e
raise "Unexpected Error in #{klass} #{plugin_klass} #{@attr_symbol}: #{e}"
end
end
list.each do |plugin|
plugin.process(options)
end
generate_all_methods
plugins.sort.uniq.each do |plugin_klass|
begin
plugin_klass.new(self).process(options)
rescue NameError => e
next
rescue => e
raise "Unexpected Error in #{klass} #{plugin_klass} #{@attr_symbol}: #{e}"
end
end
MooseX.warn "Unused attributes #{options} for attribute #{@attr_symbol} @ #{klass} #{klass.class}",caller() if ! options.empty?
end
def generate_all_methods
@methods = {}
if @attribute_map[:reader]
@methods[@attribute_map[:reader]] = generate_reader
end
if @attribute_map[:writter]
@methods[@attribute_map[:writter]] = generate_writter
end
inst_variable_name = "@#{@attr_symbol}".to_sym
if @attribute_map[:predicate]
@methods[@attribute_map[:predicate]] = ->(this) do
this.instance_variable_defined? inst_variable_name
end
end
if @attribute_map[:clearer]
@methods[@attribute_map[:clearer]] = ->(this) do
if this.instance_variable_defined? inst_variable_name
this.remove_instance_variable inst_variable_name
end
end
end
generate_handles @attr_symbol
end
def generate_handles(attr_symbol)
delegator = ->(this) { this.__send__(attr_symbol) }
@attribute_map[:handles].each_pair do | method, target_method |
if target_method.is_a? Array
original_method, currying = target_method
@methods[method] = generate_handles_with_currying(delegator, original_method, currying)
else
@methods[method] = Proc.new do |this, *args, &proc|
delegator.call(this).__send__(target_method, *args, &proc)
end
end
end
end
def generate_handles_with_currying(delegator, original_method, currying)
Proc.new do |this, *args, &proc|
a1 = [ currying ]
if currying.is_a?Proc
a1 = currying[]
elsif currying.is_a? Array
a1 = currying.map{|c| (c.is_a?(Proc)) ? c[] : c }
end
delegator.call(this).__send__(original_method, *a1, *args, &proc)
end
end
def init(object, args)
value = nil
value_from_default = false
if args.has_key? @attribute_map[:init_arg]
value = args.delete(@attribute_map[:init_arg])
elsif @attribute_map[:default]
value = @attribute_map[:default].call
value_from_default = true
elsif @attribute_map[:required]
raise InvalidAttributeError, "attr \"#{@attr_symbol}\" is required"
else
return
end
value = @attribute_map[:coerce].call(value)
begin
@attribute_map[:isa].call( value )
rescue MooseX::Types::TypeCheckError => e
raise MooseX::Types::TypeCheckError, "isa check for field #{attr_symbol}: #{e}"
end
unless value_from_default
@attribute_map[:trigger].call(object, value)
end
value = @attribute_map[:traits].call(value)
inst_variable_name = "@#{@attr_symbol}".to_sym
object.instance_variable_set inst_variable_name, value
end
def generate_reader
inst_variable_name = "@#{@attr_symbol}".to_sym
builder = @attribute_map[:builder]
before_get = ->(object) { }
if @attribute_map[:lazy]
type_check = protect_isa(@attribute_map[:isa], "isa check for #{inst_variable_name} from builder")
coerce = @attribute_map[:coerce]
trigger = @attribute_map[:trigger]
traits = @attribute_map[:traits]
before_get = ->(object) do
return if object.instance_variable_defined? inst_variable_name
value = builder.call(object)
value = coerce.call(value)
type_check.call( value )
trigger.call(object, value)
value = traits.call(value)
object.instance_variable_set(inst_variable_name, value)
end
end
->(this) do
before_get.call(this)
this.instance_variable_get inst_variable_name
end
end
def protect_isa(type_check, message)
->(value) do
begin
type_check.call( value )
rescue MooseX::Types::TypeCheckError => e
raise MooseX::Types::TypeCheckError, "#{message}: #{e}"
end
end
end
def generate_writter
writter_name = @attribute_map[:writter]
inst_variable_name = "@#{@attr_symbol}".to_sym
coerce = @attribute_map[:coerce]
type_check = protect_isa(@attribute_map[:isa], "isa check for #{writter_name}")
trigger = @attribute_map[:trigger]
traits = @attribute_map[:traits]
->(this, value) do
value = coerce.call(value)
type_check.call( value )
trigger.call(this,value)
value = traits.call(value)
this.instance_variable_set inst_variable_name, value
end
end
end
end | Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login Page - Photon Admin Panel Theme</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<link rel="shortcut icon" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/favicon.ico"/>
<link rel="apple-touch-icon" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/iosicon.png"/>
<link rel="stylesheet" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/css/css_compiled/photon-min.css?v1.1" media="all"/>
<link rel="stylesheet" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/css/css_compiled/photon-min-part2.css?v1.1" media="all"/>
<link rel="stylesheet" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/css/css_compiled/photon-responsive-min.css?v1.1" media="all"/>
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="css/css_compiled/ie-only-min.css?v1.1" />
<![endif]-->
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" href="css/css_compiled/ie8-only-min.css?v1.1" />
<script type="text/javascript" src="js/plugins/excanvas.js"></script>
<script type="text/javascript" src="js/plugins/html5shiv.js"></script>
<script type="text/javascript" src="js/plugins/respond.min.js"></script>
<script type="text/javascript" src="js/plugins/fixFontIcons.js"></script>
<![endif]-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/bootstrap/bootstrap.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/modernizr.custom.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.pnotify.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/less-1.3.1.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/xbreadcrumbs.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.maskedinput-1.3.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.autotab-1.1b.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/charCount.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.textareaCounter.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/elrte.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/elrte.en.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/select2.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery-picklist.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.validate.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/additional-methods.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.form.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.metadata.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.mockjax.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.uniform.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.tagsinput.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.rating.pack.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/farbtastic.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.timeentry.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.jstree.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/dataTables.bootstrap.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.mousewheel.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.mCustomScrollbar.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.flot.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.flot.stack.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.flot.pie.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.flot.resize.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/raphael.2.1.0.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/justgage.1.0.1.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.qrcode.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.clock.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.countdown.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.jqtweet.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.cookie.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/bootstrap-fileupload.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/prettify/prettify.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/bootstrapSwitch.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/mfupload.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/common.js"></script>
</head>
<body class="body-login">
<div class="nav-fixed-topright" style="visibility: hidden">
<ul class="nav nav-user-menu">
<li class="user-sub-menu-container">
<a href="javascript:;">
<i class="user-icon"></i><span class="nav-user-selection">Theme Options</span><i class="icon-menu-arrow"></i>
</a>
<ul class="nav user-sub-menu">
<li class="light">
<a href="javascript:;">
<i class='icon-photon stop'></i>Light Version
</a>
</li>
<li class="dark">
<a href="javascript:;">
<i class='icon-photon stop'></i>Dark Version
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-photon mail"></i>
</a>
</li>
<li>
<a href="javascript:;">
<i class="icon-photon comment_alt2_stroke"></i>
<div class="notification-count">12</div>
</a>
</li>
</ul>
</div>
<script>
$(function(){
setTimeout(function(){
$('.nav-fixed-topright').removeAttr('style');
}, 300);
$(window).scroll(function(){
if($('.breadcrumb-container').length){
var scrollState = $(window).scrollTop();
if (scrollState > 0) $('.nav-fixed-topright').addClass('nav-released');
else $('.nav-fixed-topright').removeClass('nav-released')
}
});
$('.user-sub-menu-container').on('click', function(){
$(this).toggleClass('active-user-menu');
});
$('.user-sub-menu .light').on('click', function(){
if ($('body').is('.light-version')) return;
$('body').addClass('light-version');
setTimeout(function() {
$.cookie('themeColor', 'light', {
expires: 7,
path: '/'
});
}, 500);
});
$('.user-sub-menu .dark').on('click', function(){
if ($('body').is('.light-version')) {
$('body').removeClass('light-version');
$.cookie('themeColor', 'dark', {
expires: 7,
path: '/'
});
}
});
});
</script>
<div class="container-login">
<div class="form-centering-wrapper">
<div class="form-window-login">
<div class="form-window-login-logo">
<div class="login-logo">
<img src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/images/photon/login-logo@2x.png" alt="Photon UI"/>
</div>
<h2 class="login-title">Welcome to Photon UI!</h2>
<div class="login-member">Not a Member? <a href="jquery.flot.resize.js.html#">Sign Up »</a>
<a href="jquery.flot.resize.js.html#" class="btn btn-facebook"><i class="icon-fb"></i>Login with Facebook<i class="icon-fb-arrow"></i></a>
</div>
<div class="login-or">Or</div>
<div class="login-input-area">
<form method="POST" action="dashboard.php">
<span class="help-block">Login With Your Photon Account</span>
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit" class="btn btn-large btn-success btn-login">Login</button>
</form>
<a href="jquery.flot.resize.js.html#" class="forgot-pass">Forgot Your Password?</a>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1936460-27']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
| Java |
/*
* Copyright (c) 2011-2016, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.alg.filter.binary;
import boofcv.struct.ConnectRule;
import boofcv.struct.image.GrayS32;
import boofcv.struct.image.GrayU8;
import georegression.struct.point.Point2D_I32;
import sapphire.app.SapphireObject;
import org.ddogleg.struct.FastQueue;
import java.util.List;
/**
* Used to trace the external and internal contours around objects for {@link LinearContourLabelChang2004}. As it
* is tracing an object it will modify the binary image by labeling. The input binary image is assumed to have
* a 1-pixel border that needs to be compensated for.
*
* @author Peter Abeles
*/
public class ContourTracer implements SapphireObject {
// which connectivity rule is being used. 4 and 8 supported
private ConnectRule rule;
private int ruleN;
// storage for contour points.
private FastQueue<Point2D_I32> storagePoints;
// binary image being traced
private GrayU8 binary;
// label image being marked
private GrayS32 labeled;
// storage for contour
private List<Point2D_I32> contour;
// coordinate of pixel being examined (x,y)
private int x,y;
// label of the object being traced
private int label;
// direction it moved in
private int dir;
// index of the pixel in the image's internal array
private int indexBinary;
private int indexLabel;
// the pixel index offset to each neighbor
private int offsetsBinary[];
private int offsetsLabeled[];
// lookup table for which direction it should search next given the direction it traveled into the current pixel
private int nextDirection[];
/**
* Specifies connectivity rule
*
* @param rule Specifies 4 or 8 as connectivity rule
*/
public ContourTracer( ConnectRule rule ) {
this.rule = rule;
if( ConnectRule.EIGHT == rule ) {
// start the next search +2 away from the square it came from
// the square it came from is the opposite from the previous 'dir'
nextDirection = new int[8];
for( int i = 0; i < 8; i++ )
nextDirection[i] = ((i+4)%8 + 2)%8;
ruleN = 8;
} else if( ConnectRule.FOUR == rule ) {
nextDirection = new int[4];
for( int i = 0; i < 4; i++ )
nextDirection[i] = ((i+2)%4 + 1)%4;
ruleN = 4;
} else {
throw new IllegalArgumentException("Connectivity rule must be 4 or 8 not "+rule);
}
offsetsBinary = new int[ruleN];
offsetsLabeled = new int[ruleN];
}
/**
*
* @param binary Binary image with a border of zeros added to the outside.
* @param labeled Labeled image. Size is the same as the original binary image without border.
* @param storagePoints
*/
public void setInputs(GrayU8 binary , GrayS32 labeled , FastQueue<Point2D_I32> storagePoints ) {
this.binary = binary;
this.labeled = labeled;
this.storagePoints = storagePoints;
if( rule == ConnectRule.EIGHT ) {
setOffsets8(offsetsBinary,binary.stride);
setOffsets8(offsetsLabeled,labeled.stride);
} else {
setOffsets4(offsetsBinary,binary.stride);
setOffsets4(offsetsLabeled,labeled.stride);
}
}
private void setOffsets8( int offsets[] , int stride ) {
int s = stride;
offsets[0] = 1; // x = 1 y = 0
offsets[1] = 1+s; // x = 1 y = 1
offsets[2] = s; // x = 0 y = 1
offsets[3] = -1+s; // x = -1 y = 1
offsets[4] = -1 ; // x = -1 y = 0
offsets[5] = -1-s; // x = -1 y = -1
offsets[6] = -s; // x = 0 y = -1
offsets[7] = 1-s; // x = 1 y = -1
}
private void setOffsets4( int offsets[] , int stride ) {
int s = stride;
offsets[0] = 1; // x = 1 y = 0
offsets[1] = s; // x = 0 y = 1
offsets[2] = -1; // x = -1 y = 0
offsets[3] = -s; // x = 0 y = -1
}
/**
*
* @param label
* @param initialX
* @param initialY
* @param external True for tracing an external contour or false for internal..
* @param contour
*/
public void trace( int label , int initialX , int initialY , boolean external , List<Point2D_I32> contour )
{
int initialDir;
if( rule == ConnectRule.EIGHT )
initialDir = external ? 7 : 3;
else
initialDir = external ? 0 : 2;
this.label = label;
this.contour = contour;
this.dir = initialDir;
x = initialX;
y = initialY;
// index of pixels in the image array
// binary has a 1 pixel border which labeled lacks, hence the -1,-1 for labeled
indexBinary = binary.getIndex(x,y);
indexLabel = labeled.getIndex(x-1,y-1);
add(x,y);
// find the next black pixel. handle case where its an isolated point
if( !searchBlack() ) {
return;
} else {
initialDir = dir;
moveToNext();
dir = nextDirection[dir];
}
while( true ) {
// search in clockwise direction around the current pixel for next black pixel
searchBlack();
if( x == initialX && y == initialY && dir == initialDir ) {
// returned to the initial state again. search is finished
return;
}else {
add(x, y);
moveToNext();
dir = nextDirection[dir];
}
}
}
/**
* Searches in a circle around the current point in a clock-wise direction for the first black pixel.
*/
private boolean searchBlack() {
for( int i = 0; i < offsetsBinary.length; i++ ) {
if( checkBlack(indexBinary + offsetsBinary[dir]))
return true;
dir = (dir+1)%ruleN;
}
return false;
}
/**
* Checks to see if the specified pixel is black (1). If not the pixel is marked so that it
* won't be searched again
*/
private boolean checkBlack( int index ) {
if( binary.data[index] == 1 ) {
return true;
} else {
// mark white pixels as negative numbers to avoid retracing this contour in the future
binary.data[index] = -1;
return false;
}
}
private void moveToNext() {
// move to the next pixel using the precomputed pixel index offsets
indexBinary += offsetsBinary[dir];
indexLabel += offsetsLabeled[dir];
// compute the new pixel coordinate from the binary pixel index
int a = indexBinary - binary.startIndex;
x = a%binary.stride;
y = a/binary.stride;
}
/**
* Adds a point to the contour list
*/
private void add( int x , int y ) {
Point2D_I32 p = storagePoints.grow();
// compensate for the border added to binary image
p.set(x-1, y-1);
contour.add(p);
labeled.data[indexLabel] = label;
}
}
| Java |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Console.Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Console.Server")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("a7943db8-a75d-467f-aa1e-96134b5739ea")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Java |
#include<stdio.h>
int main(void)
{
double a,b;
printf("Enter a\&b:\n");
while(scanf("%lf%lf",&a,&b)==2)
{
printf("%.3g - %.3g / %.3g * %.3g = %.3g .\n",a,b,a,b,(double)(a-b)/(a*b));
printf("\n");
printf("Enter a\&b:\n");
}
printf("done!");
return 0;
}
| Java |
using Microsoft.SPOT.Hardware;
namespace GrFamily.MainBoard
{
/// <summary>
/// LEDNX
/// </summary>
public class Led
{
/// <summary>LEDªÚ±³ê½s</summary>
protected readonly OutputPort LedPort;
/// <summary>
/// RXgN^
/// </summary>
/// <param name="pin">LEDªÚ±³ê½s</param>
public Led(Cpu.Pin pin)
{
LedPort = new OutputPort(pin, false);
}
/// <summary>
/// LEDð_^Á·é
/// </summary>
/// <param name="on">LEDð_·éêÍ trueAÁ·éêÍ false</param>
public void SetLed(bool on)
{
LedPort.Write(on);
}
}
}
| Java |
FROM midvalestudent/jupyter-scipy:latest
USER root
ENV HOME /root
ADD requirements.txt /usr/local/share/requirements.txt
RUN pip install --upgrade pip && pip install -r /usr/local/share/requirements.txt
# Download/build/install ffmpeg
ARG FFMPEG_VERSION
ENV FFMPEG_VERSION ${FFMPEG_VERSION:-"3.2"}
RUN DEBIAN_FRONTEND=noninteractive \
&& REPO=http://www.deb-multimedia.org \
&& echo "deb $REPO jessie main non-free\ndeb-src $REPO jessie main non-free" >> /etc/apt/sources.list \
&& apt-get update && apt-get install -y --force-yes deb-multimedia-keyring && apt-get update \
&& apt-get remove ffmpeg \
&& apt-get install -yq --no-install-recommends \
build-essential \
libmp3lame-dev \
libvorbis-dev \
libtheora-dev \
libspeex-dev \
yasm \
pkg-config \
libfaac-dev \
libopenjpeg-dev \
libx264-dev \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir -p /usr/src/build && cd /usr/src/build \
&& wget http://ffmpeg.org/releases/ffmpeg-$FFMPEG_VERSION.tar.gz \
&& tar xzf ffmpeg-$FFMPEG_VERSION.tar.gz && cd ffmpeg-$FFMPEG_VERSION \
&& ./configure \
--prefix=/usr/local \
--enable-gpl \
--enable-postproc \
--enable-swscale \
--enable-avfilter \
--enable-libmp3lame \
--enable-libvorbis \
--enable-libtheora \
--enable-libx264 \
--enable-libspeex \
--enable-shared \
--enable-pthreads \
--enable-libopenjpeg \
--enable-nonfree \
&& make -j$(nproc) install && ldconfig \
&& cd /usr/src/build && rm -rf ffmpeg-$FFMPEG_VERSION* \
&& apt-get purge -y cmake && apt-get autoremove -y --purge
# Download/build/install components for opencv
ARG OPENCV_VERSION
ENV OPENCV_VERSION ${OPENCV_VERSION:-"3.2.0"}
RUN DEBIAN_FRONTEND=noninteractive \
&& REPO=http://cdn-fastly.deb.debian.org \
&& echo "deb $REPO/debian jessie main\ndeb $REPO/debian-security jessie/updates main" > /etc/apt/sources.list \
&& apt-get update && apt-get -yq dist-upgrade \
&& apt-get install -yq --no-install-recommends \
build-essential \
cmake \
git-core \
pkg-config \
libjpeg62-turbo-dev \
libtiff5-dev \
libjasper-dev \
libpng12-dev \
libavcodec-dev \
libavformat-dev \
libswscale-dev \
libv4l-dev \
libatlas-base-dev \
gfortran \
tesseract-ocr \
tesseract-ocr-eng \
libtesseract-dev \
libleptonica-dev \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir -p /usr/src/build && cd /usr/src/build \
&& git clone -b $OPENCV_VERSION --depth 1 --recursive https://github.com/opencv/opencv.git \
&& git clone -b $OPENCV_VERSION --depth 1 --recursive https://github.com/opencv/opencv_contrib.git \
&& cd opencv && mkdir build && cd build \
&& cmake \
-D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_C_EXAMPLES=OFF \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D OPENCV_EXTRA_MODULES_PATH=/usr/src/build/opencv_contrib/modules \
-D BUILD_EXAMPLES=OFF \
-D FFMPEG_INCLUDE_DIR=/usr/local/include \
-D FFMPEG_LIB_DIR=/usr/local/lib \
.. \
&& make -j4 install && ldconfig \
&& cd /usr/src/build && rm -rf opencv && rm -rf opencv_contrib \
&& apt-get purge -y cmake && apt-get autoremove -y --purge
# back to unpriviliged user
ENV HOME /home/$NB_USER
| Java |
<img src="icon.png" alt="Icon" width="128">
NUS Exam Paper Downloader
===============
Simple script to download exam papers from the NUS database. Requires NUSNET login.
Runs on Python 2.7 only.
### Using via Command Line
```
$ python examdownloader-cli.py
```
The required username and target destination can be set in the script or passed as a command line argument.
If no command line arguments are provided, the user is prompted for input.
### Using via a Graphical User Interface
```
$ python examdownloader-gui.py
```
### Compiling the Binary
1. Install `pyinstaller`:
```
$ pip install pyinstaller
```
2. Compile the app:
```
$ pyinstaller build.spec
```
The compiled app can be found inside the `dist` folder.
### Credits
- Oh Shunhao [(https://github.com/Ohohcakester)](https://github.com/Ohohcakester)
- Liu Xinan [(https://github.com/xinan)](https://github.com/xinan)
- Yangshun Tay [(https://github.com/yangshun)](https://github.com/yangshun)
| Java |
module ngFoundation.directives {
//@NgDirective('topBarSection')
class TopBarSectionDirective implements ng.IDirective {
template = '<section class="top-bar-section" ng-transclude></section>';
restrict = "E";
transclude = true;
replace = true;
}
} | Java |
# CreditCardValidator
Validate a credit card number with Luhn algorithm.
License: MIT
| Java |
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "Three20" do
it "fails" do
fail "hey buddy, you should probably rename this file and start specing for real"
end
end
| Java |
if (Zepto.ajax.restore) {
Zepto.ajax.restore();
}
sinon.stub(Zepto, "ajax")
.yieldsTo("success", {
responseStatus : 200,
responseDetails : null,
responseData : {
feed: {
link : "http://github.com",
title : "GitHub Public Timeline",
entries : [
{ title : "Croaky signed up",
link : "http://github.com/Croaky/openbeerdatabase",
author : "",
publishedDate : "Thu, 24 Nov 2011 19:00:00 -0600",
content : "\u003cstrong\u003eCroaky\u003c/strong\u003e signed up for GitHub.",
contentSnippet : "Croaky signed up for GitHub.",
categories : []
}
]
}
}
});
| Java |
#include "estimation/sensors/make_interpolator.hh"
namespace estimation {
geometry::spatial::TimeInterpolator make_accel_interpolator(
const std::vector<TimedMeasurement<jet_filter::AccelMeasurement>>&
accel_meas,
const ImuModel& imu_model) {
std::vector<geometry::spatial::TimeControlPoint> points;
for (const auto& accel : accel_meas) {
const jcc::Vec3 corrected_accel =
imu_model.correct_measured_accel(accel.measurement.observed_acceleration);
points.push_back({accel.timestamp, corrected_accel});
}
const geometry::spatial::TimeInterpolator interp(points);
return interp;
}
geometry::spatial::TimeInterpolator make_gyro_interpolator(
const std::vector<TimedMeasurement<jet_filter::GyroMeasurement>>&
gyro_meas) {
std::vector<geometry::spatial::TimeControlPoint> points;
for (const auto& gyro : gyro_meas) {
points.push_back({gyro.timestamp, gyro.measurement.observed_w});
}
const geometry::spatial::TimeInterpolator interp(points);
return interp;
}
} // namespace estimation | Java |
# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
import threading
from typing import Optional, Tuple
from pyqrllib.pyqrllib import bin2hstr
from pyqryptonight.pyqryptonight import StringToUInt256, UInt256ToString
from qrl.core import config, BlockHeader
from qrl.core.AddressState import AddressState
from qrl.core.Block import Block
from qrl.core.BlockMetadata import BlockMetadata
from qrl.core.DifficultyTracker import DifficultyTracker
from qrl.core.GenesisBlock import GenesisBlock
from qrl.core.PoWValidator import PoWValidator
from qrl.core.txs.Transaction import Transaction
from qrl.core.txs.CoinBase import CoinBase
from qrl.core.TransactionPool import TransactionPool
from qrl.core.misc import logger
from qrl.crypto.Qryptonight import Qryptonight
from qrl.generated import qrl_pb2, qrlstateinfo_pb2
class ChainManager:
def __init__(self, state):
self._state = state
self.tx_pool = TransactionPool(None)
self._last_block = Block.deserialize(GenesisBlock().serialize())
self.current_difficulty = StringToUInt256(str(config.user.genesis_difficulty))
self.trigger_miner = False
self.lock = threading.RLock()
@property
def height(self):
with self.lock:
if not self._last_block:
return -1
return self._last_block.block_number
@property
def last_block(self) -> Block:
with self.lock:
return self._last_block
@property
def total_coin_supply(self):
with self.lock:
return self._state.total_coin_supply
def get_block_datapoint(self, headerhash):
with self.lock:
return self._state.get_block_datapoint(headerhash)
def get_cumulative_difficulty(self):
with self.lock:
last_block_metadata = self._state.get_block_metadata(self._last_block.headerhash)
return last_block_metadata.cumulative_difficulty
def get_block_by_number(self, block_number) -> Optional[Block]:
with self.lock:
return self._state.get_block_by_number(block_number)
def get_block_header_hash_by_number(self, block_number) -> Optional[bytes]:
with self.lock:
return self._state.get_block_header_hash_by_number(block_number)
def get_block(self, header_hash: bytes) -> Optional[Block]:
with self.lock:
return self._state.get_block(header_hash)
def get_address_balance(self, address: bytes) -> int:
with self.lock:
return self._state.get_address_balance(address)
def get_address_is_used(self, address: bytes) -> bool:
with self.lock:
return self._state.get_address_is_used(address)
def get_address_state(self, address: bytes) -> AddressState:
with self.lock:
return self._state.get_address_state(address)
def get_all_address_state(self):
with self.lock:
return self._state.get_all_address_state()
def get_tx_metadata(self, transaction_hash) -> list:
with self.lock:
return self._state.get_tx_metadata(transaction_hash)
def get_last_transactions(self):
with self.lock:
return self._state.get_last_txs()
def get_unconfirmed_transaction(self, transaction_hash) -> list:
with self.lock:
for tx_set in self.tx_pool.transactions:
tx = tx_set[1].transaction
if tx.txhash == transaction_hash:
return [tx, tx_set[1].timestamp]
if transaction_hash in self.tx_pool.pending_tx_pool_hash:
for tx_set in self.tx_pool.pending_tx_pool:
tx = tx_set[1].transaction
if tx.txhash == transaction_hash:
return [tx, tx_set[1].timestamp]
return []
def get_block_metadata(self, header_hash: bytes) -> Optional[BlockMetadata]:
with self.lock:
return self._state.get_block_metadata(header_hash)
def get_blockheader_and_metadata(self, block_number=0) -> Tuple:
with self.lock:
block_number = block_number or self.height # if both are non-zero, then block_number takes priority
result = (None, None)
block = self.get_block_by_number(block_number)
if block:
blockheader = block.blockheader
blockmetadata = self.get_block_metadata(blockheader.headerhash)
result = (blockheader, blockmetadata)
return result
def get_block_to_mine(self, miner, wallet_address) -> list:
with miner.lock: # Trying to acquire miner.lock to make sure pre_block_logic is not running
with self.lock:
last_block = self.last_block
last_block_metadata = self.get_block_metadata(last_block.headerhash)
return miner.get_block_to_mine(wallet_address,
self.tx_pool,
last_block,
last_block_metadata.block_difficulty)
def get_measurement(self, block_timestamp, parent_headerhash, parent_metadata: BlockMetadata):
with self.lock:
return self._state.get_measurement(block_timestamp, parent_headerhash, parent_metadata)
def get_block_size_limit(self, block: Block):
with self.lock:
return self._state.get_block_size_limit(block)
def get_block_is_duplicate(self, block: Block) -> bool:
with self.lock:
return self._state.get_block(block.headerhash) is not None
def validate_mining_nonce(self, blockheader: BlockHeader, enable_logging=True):
with self.lock:
parent_metadata = self.get_block_metadata(blockheader.prev_headerhash)
parent_block = self._state.get_block(blockheader.prev_headerhash)
measurement = self.get_measurement(blockheader.timestamp, blockheader.prev_headerhash, parent_metadata)
diff, target = DifficultyTracker.get(
measurement=measurement,
parent_difficulty=parent_metadata.block_difficulty)
if enable_logging:
logger.debug('-----------------START--------------------')
logger.debug('Validate #%s', blockheader.block_number)
logger.debug('block.timestamp %s', blockheader.timestamp)
logger.debug('parent_block.timestamp %s', parent_block.timestamp)
logger.debug('parent_block.difficulty %s', UInt256ToString(parent_metadata.block_difficulty))
logger.debug('diff %s', UInt256ToString(diff))
logger.debug('target %s', bin2hstr(target))
logger.debug('-------------------END--------------------')
if not PoWValidator().verify_input(blockheader.mining_blob, target):
if enable_logging:
logger.warning("PoW verification failed")
qn = Qryptonight()
tmp_hash = qn.hash(blockheader.mining_blob)
logger.warning("{}".format(bin2hstr(tmp_hash)))
logger.debug('%s', blockheader.to_json())
return False
return True
def get_headerhashes(self, start_blocknumber):
with self.lock:
start_blocknumber = max(0, start_blocknumber)
end_blocknumber = min(self._last_block.block_number,
start_blocknumber + 2 * config.dev.reorg_limit)
total_expected_headerhash = end_blocknumber - start_blocknumber + 1
node_header_hash = qrl_pb2.NodeHeaderHash()
node_header_hash.block_number = start_blocknumber
block = self._state.get_block_by_number(end_blocknumber)
block_headerhash = block.headerhash
node_header_hash.headerhashes.append(block_headerhash)
end_blocknumber -= 1
while end_blocknumber >= start_blocknumber:
block_metadata = self._state.get_block_metadata(block_headerhash)
for headerhash in block_metadata.last_N_headerhashes[-1::-1]:
node_header_hash.headerhashes.append(headerhash)
end_blocknumber -= len(block_metadata.last_N_headerhashes)
if len(block_metadata.last_N_headerhashes) == 0:
break
block_headerhash = block_metadata.last_N_headerhashes[0]
node_header_hash.headerhashes[:] = node_header_hash.headerhashes[-1::-1]
del node_header_hash.headerhashes[:len(node_header_hash.headerhashes) - total_expected_headerhash]
return node_header_hash
def set_broadcast_tx(self, broadcast_tx):
with self.lock:
self.tx_pool.set_broadcast_tx(broadcast_tx)
def load(self, genesis_block):
# load() has the following tasks:
# Write Genesis Block into State immediately
# Register block_number <-> blockhash mapping
# Calculate difficulty Metadata for Genesis Block
# Generate AddressStates from Genesis Block balances
# Apply Genesis Block's transactions to the state
# Detect if we are forked from genesis block and if so initiate recovery.
height = self._state.get_mainchain_height()
if height == -1:
self._state.put_block(genesis_block, None)
block_number_mapping = qrl_pb2.BlockNumberMapping(headerhash=genesis_block.headerhash,
prev_headerhash=genesis_block.prev_headerhash)
self._state.put_block_number_mapping(genesis_block.block_number, block_number_mapping, None)
parent_difficulty = StringToUInt256(str(config.user.genesis_difficulty))
self.current_difficulty, _ = DifficultyTracker.get(
measurement=config.dev.mining_setpoint_blocktime,
parent_difficulty=parent_difficulty)
block_metadata = BlockMetadata.create()
block_metadata.set_block_difficulty(self.current_difficulty)
block_metadata.set_cumulative_difficulty(self.current_difficulty)
self._state.put_block_metadata(genesis_block.headerhash, block_metadata, None)
addresses_state = dict()
for genesis_balance in GenesisBlock().genesis_balance:
bytes_addr = genesis_balance.address
addresses_state[bytes_addr] = AddressState.get_default(bytes_addr)
addresses_state[bytes_addr]._data.balance = genesis_balance.balance
for tx_idx in range(1, len(genesis_block.transactions)):
tx = Transaction.from_pbdata(genesis_block.transactions[tx_idx])
for addr in tx.addrs_to:
addresses_state[addr] = AddressState.get_default(addr)
coinbase_tx = Transaction.from_pbdata(genesis_block.transactions[0])
if not isinstance(coinbase_tx, CoinBase):
return False
addresses_state[coinbase_tx.addr_to] = AddressState.get_default(coinbase_tx.addr_to)
if not coinbase_tx.validate_extended(genesis_block.block_number):
return False
coinbase_tx.apply_state_changes(addresses_state)
for tx_idx in range(1, len(genesis_block.transactions)):
tx = Transaction.from_pbdata(genesis_block.transactions[tx_idx])
tx.apply_state_changes(addresses_state)
self._state.put_addresses_state(addresses_state)
self._state.update_tx_metadata(genesis_block, None)
self._state.update_mainchain_height(0, None)
else:
self._last_block = self.get_block_by_number(height)
self.current_difficulty = self._state.get_block_metadata(self._last_block.headerhash).block_difficulty
fork_state = self._state.get_fork_state()
if fork_state:
block = self._state.get_block(fork_state.initiator_headerhash)
self._fork_recovery(block, fork_state)
def _apply_block(self, block: Block, batch) -> bool:
address_set = self._state.prepare_address_list(block) # Prepare list for current block
addresses_state = self._state.get_state_mainchain(address_set)
if not block.apply_state_changes(addresses_state):
return False
self._state.put_addresses_state(addresses_state, batch)
return True
def _update_chainstate(self, block: Block, batch):
self._last_block = block
self._update_block_number_mapping(block, batch)
self.tx_pool.remove_tx_in_block_from_pool(block)
self._state.update_mainchain_height(block.block_number, batch)
self._state.update_tx_metadata(block, batch)
def _try_branch_add_block(self, block, batch, check_stale=True) -> (bool, bool):
"""
This function returns list of bool types. The first bool represent
if the block has been added successfully and the second bool
represent the fork_flag, which becomes true when a block triggered
into fork recovery.
:param block:
:param batch:
:return: [Added successfully, fork_flag]
"""
if self._last_block.headerhash == block.prev_headerhash:
if not self._apply_block(block, batch):
return False, False
self._state.put_block(block, batch)
last_block_metadata = self._state.get_block_metadata(self._last_block.headerhash)
if last_block_metadata is None:
logger.warning("Could not find log metadata for %s", bin2hstr(self._last_block.headerhash))
return False, False
last_block_difficulty = int(UInt256ToString(last_block_metadata.cumulative_difficulty))
new_block_metadata = self._add_block_metadata(block.headerhash, block.timestamp, block.prev_headerhash, batch)
new_block_difficulty = int(UInt256ToString(new_block_metadata.cumulative_difficulty))
if new_block_difficulty > last_block_difficulty:
if self._last_block.headerhash != block.prev_headerhash:
fork_state = qrlstateinfo_pb2.ForkState(initiator_headerhash=block.headerhash)
self._state.put_fork_state(fork_state, batch)
self._state.write_batch(batch)
return self._fork_recovery(block, fork_state), True
self._update_chainstate(block, batch)
if check_stale:
self.tx_pool.check_stale_txn(self._state, block.block_number)
self.trigger_miner = True
return True, False
def _remove_block_from_mainchain(self, block: Block, latest_block_number: int, batch):
addresses_set = self._state.prepare_address_list(block)
addresses_state = self._state.get_state_mainchain(addresses_set)
for tx_idx in range(len(block.transactions) - 1, -1, -1):
tx = Transaction.from_pbdata(block.transactions[tx_idx])
tx.revert_state_changes(addresses_state, self)
self.tx_pool.add_tx_from_block_to_pool(block, latest_block_number)
self._state.update_mainchain_height(block.block_number - 1, batch)
self._state.rollback_tx_metadata(block, batch)
self._state.remove_blocknumber_mapping(block.block_number, batch)
self._state.put_addresses_state(addresses_state, batch)
def _get_fork_point(self, block: Block):
tmp_block = block
hash_path = []
while True:
if not block:
raise Exception('[get_state] No Block Found %s, Initiator %s', block.headerhash, tmp_block.headerhash)
mainchain_block = self.get_block_by_number(block.block_number)
if mainchain_block and mainchain_block.headerhash == block.headerhash:
break
if block.block_number == 0:
raise Exception('[get_state] Alternate chain genesis is different, Initiator %s', tmp_block.headerhash)
hash_path.append(block.headerhash)
block = self._state.get_block(block.prev_headerhash)
return block.headerhash, hash_path
def _rollback(self, forked_header_hash: bytes, fork_state: qrlstateinfo_pb2.ForkState = None):
"""
Rollback from last block to the block just before the forked_header_hash
:param forked_header_hash:
:param fork_state:
:return:
"""
hash_path = []
while self._last_block.headerhash != forked_header_hash:
block = self._state.get_block(self._last_block.headerhash)
mainchain_block = self._state.get_block_by_number(block.block_number)
if block is None:
logger.warning("self.state.get_block(self.last_block.headerhash) returned None")
if mainchain_block is None:
logger.warning("self.get_block_by_number(block.block_number) returned None")
if block.headerhash != mainchain_block.headerhash:
break
hash_path.append(self._last_block.headerhash)
batch = self._state.batch
self._remove_block_from_mainchain(self._last_block, block.block_number, batch)
if fork_state:
fork_state.old_mainchain_hash_path.extend([self._last_block.headerhash])
self._state.put_fork_state(fork_state, batch)
self._state.write_batch(batch)
self._last_block = self._state.get_block(self._last_block.prev_headerhash)
return hash_path
def add_chain(self, hash_path: list, fork_state: qrlstateinfo_pb2.ForkState) -> bool:
"""
Add series of blocks whose headerhash mentioned into hash_path
:param hash_path:
:param fork_state:
:param batch:
:return:
"""
with self.lock:
start = 0
try:
start = hash_path.index(self._last_block.headerhash) + 1
except ValueError:
# Following condition can only be true if the fork recovery was interrupted last time
if self._last_block.headerhash in fork_state.old_mainchain_hash_path:
return False
for i in range(start, len(hash_path)):
header_hash = hash_path[i]
block = self._state.get_block(header_hash)
batch = self._state.batch
if not self._apply_block(block, batch):
return False
self._update_chainstate(block, batch)
logger.debug('Apply block #%d - [batch %d | %s]', block.block_number, i, hash_path[i])
self._state.write_batch(batch)
self._state.delete_fork_state()
return True
def _fork_recovery(self, block: Block, fork_state: qrlstateinfo_pb2.ForkState) -> bool:
logger.info("Triggered Fork Recovery")
# This condition only becomes true, when fork recovery was interrupted
if fork_state.fork_point_headerhash:
logger.info("Recovering from last fork recovery interruption")
forked_header_hash, hash_path = fork_state.fork_point_headerhash, fork_state.new_mainchain_hash_path
else:
forked_header_hash, hash_path = self._get_fork_point(block)
fork_state.fork_point_headerhash = forked_header_hash
fork_state.new_mainchain_hash_path.extend(hash_path)
self._state.put_fork_state(fork_state)
rollback_done = False
if fork_state.old_mainchain_hash_path:
b = self._state.get_block(fork_state.old_mainchain_hash_path[-1])
if b and b.prev_headerhash == fork_state.fork_point_headerhash:
rollback_done = True
if not rollback_done:
logger.info("Rolling back")
old_hash_path = self._rollback(forked_header_hash, fork_state)
else:
old_hash_path = fork_state.old_mainchain_hash_path
if not self.add_chain(hash_path[-1::-1], fork_state):
logger.warning("Fork Recovery Failed... Recovering back to old mainchain")
# If above condition is true, then it means, the node failed to add_chain
# Thus old chain state, must be retrieved
self._rollback(forked_header_hash)
self.add_chain(old_hash_path[-1::-1], fork_state) # Restores the old chain state
return False
logger.info("Fork Recovery Finished")
self.trigger_miner = True
return True
def _add_block(self, block, batch=None, check_stale=True) -> (bool, bool):
self.trigger_miner = False
block_size_limit = self.get_block_size_limit(block)
if block_size_limit and block.size > block_size_limit:
logger.info('Block Size greater than threshold limit %s > %s', block.size, block_size_limit)
return False, False
return self._try_branch_add_block(block, batch, check_stale)
def add_block(self, block: Block, check_stale=True) -> bool:
with self.lock:
if block.block_number < self.height - config.dev.reorg_limit:
logger.debug('Skipping block #%s as beyond re-org limit', block.block_number)
return False
if self.get_block_is_duplicate(block):
return False
batch = self._state.batch
block_flag, fork_flag = self._add_block(block, batch=batch, check_stale=check_stale)
if block_flag:
if not fork_flag:
self._state.write_batch(batch)
logger.info('Added Block #%s %s', block.block_number, bin2hstr(block.headerhash))
return True
return False
def _add_block_metadata(self,
headerhash,
block_timestamp,
parent_headerhash,
batch):
block_metadata = self._state.get_block_metadata(headerhash)
if not block_metadata:
block_metadata = BlockMetadata.create()
parent_metadata = self._state.get_block_metadata(parent_headerhash)
parent_block_difficulty = parent_metadata.block_difficulty
parent_cumulative_difficulty = parent_metadata.cumulative_difficulty
block_metadata.update_last_headerhashes(parent_metadata.last_N_headerhashes, parent_headerhash)
measurement = self._state.get_measurement(block_timestamp, parent_headerhash, parent_metadata)
block_difficulty, _ = DifficultyTracker.get(
measurement=measurement,
parent_difficulty=parent_block_difficulty)
block_cumulative_difficulty = StringToUInt256(str(
int(UInt256ToString(block_difficulty)) +
int(UInt256ToString(parent_cumulative_difficulty))))
block_metadata.set_block_difficulty(block_difficulty)
block_metadata.set_cumulative_difficulty(block_cumulative_difficulty)
parent_metadata.add_child_headerhash(headerhash)
self._state.put_block_metadata(parent_headerhash, parent_metadata, batch)
self._state.put_block_metadata(headerhash, block_metadata, batch)
return block_metadata
def _update_block_number_mapping(self, block, batch):
block_number_mapping = qrl_pb2.BlockNumberMapping(headerhash=block.headerhash,
prev_headerhash=block.prev_headerhash)
self._state.put_block_number_mapping(block.block_number, block_number_mapping, batch)
| Java |
<?php
namespace Nitrapi\Common\Exceptions;
class NitrapiHttpErrorException extends NitrapiException
{
} | Java |
var baseURL;
$.validator.addMethod("alfanumerico", function(value, element) {
return this.optional(element) || /^[-._a-z0-9\- ]+$/i.test(value);
}, "Este campo es alfanumerico.");
$("#frmGuardaTipoDocumento").validate({
rules : {
descripcion : "required",
codigo : {required:true,alfanumerico:true},
},
messages : {
descripcion : "Ingrese este campo.",
codigo : {required:"Ingrese este campo.",alfanumerico:"Este campo es alfanumerico."},
},
submitHandler : function(form) {
$.ajax(form.action, {
async : false,
type : "POST",
data : $(form).serialize(),
success : function(contenido) {
//alert("contenido :"+ contenido);
if(contenido=="error"){
var mensaje="Este tipo de documento ya ha sido registrado";
alert(mensaje);
}
else{
baseURL = $("#baseURL").val();
$.get(baseURL + "mantenimientoInterno/listarTiposDocumentos?info="+contenido, function(respuesta) {
$("#contenidoPrincipal").html(respuesta);
$("#title-page").html("Mantenimiento Tipo Entidad Documento - Listado");
});
}
}
});
}
});
function cancelarTipoDocumento(){
var baseURL;
baseURL = $("#baseURL").val();
$("#contenidoPrincipal").html("Cargando . . .");
$.get(baseURL + "mantenimientoInterno/listarTiposDocumentos", function(respuesta) {
$("#contenidoPrincipal").html(respuesta);
$("#title-page").html("Mantenimiento Tipo Entidad Documento - Listado");
});
}
| Java |
export { default } from 'ember-flexberry-designer/controllers/fd-interface-edit-form/new';
| Java |
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
//Route::middleware('auth:api')->get('/user', function (Request $request) {
// return $request->user();
//});
//Route::get('wechat/index', 'WechatController@index');
| Java |
Symfony Standard Edition
========================
Welcome to the Symfony Standard Edition - a fully-functional Symfony2
application that you can use as the skeleton for your new applications.
This document contains information on how to download, install, and start
using Symfony. For a more detailed explanation, see the [Installation][1]
chapter of the Symfony Documentation.
1) Installing the Standard Edition
----------------------------------
When it comes to installing the Symfony Standard Edition, you have the
following options.
### Use Composer (*recommended*)
As Symfony uses [Composer][2] to manage its dependencies, the recommended way
to create a new project is to use it.
If you don't have Composer yet, download it following the instructions on
http://getcomposer.org/ or just run the following command:
curl -s http://getcomposer.org/installer | php
Then, use the `create-project` command to generate a new Symfony application:
php composer.phar create-project symfony/framework-standard-edition path/to/install
Composer will install Symfony and all its dependencies under the
`path/to/install` directory.
### Download an Archive File
To quickly test Symfony, you can also download an [archive][3] of the Standard
Edition and unpack it somewhere under your web server root directory.
If you downloaded an archive "without vendors", you also need to install all
the necessary dependencies. Download composer (see above) and run the
following command:
php composer.phar install
2) Checking your System Configuration
-------------------------------------
Before starting coding, make sure that your local system is properly
configured for Symfony.
Execute the `check.php` script from the command line:
php app/check.php
The script returns a status code of `0` if all mandatory requirements are met,
`1` otherwise.
Access the `config.php` script from a browser:
http://localhost/path/to/symfony/app/web/config.php
If you get any warnings or recommendations, fix them before moving on.
3) Browsing the Demo Application
--------------------------------
Congratulations! You're now ready to use Symfony.
From the `config.php` page, click the "Bypass configuration and go to the
Welcome page" link to load up your first Symfony page.
You can also use a web-based configurator by clicking on the "Configure your
Symfony Application online" link of the `config.php` page.
To see a real-live Symfony page in action, access the following page:
web/app_dev.php/demo/hello/Fabien
4) Getting started with Symfony
-------------------------------
This distribution is meant to be the starting point for your Symfony
applications, but it also contains some sample code that you can learn from
and play with.
A great way to start learning Symfony is via the [Quick Tour][4], which will
take you through all the basic features of Symfony2.
Once you're feeling good, you can move onto reading the official
[Symfony2 book][5].
A default bundle, `AcmeDemoBundle`, shows you Symfony2 in action. After
playing with it, you can remove it by following these steps:
* delete the `src/Acme` directory;
* remove the routing entry referencing AcmeDemoBundle in `app/config/routing_dev.yml`;
* remove the AcmeDemoBundle from the registered bundles in `app/AppKernel.php`;
* remove the `web/bundles/acmedemo` directory;
* remove the `security.providers`, `security.firewalls.login` and
`security.firewalls.secured_area` entries in the `security.yml` file or
tweak the security configuration to fit your needs.
What's inside?
---------------
The Symfony Standard Edition is configured with the following defaults:
* Twig is the only configured template engine;
* Doctrine ORM/DBAL is configured;
* Swiftmailer is configured;
* Annotations for everything are enabled.
It comes pre-configured with the following bundles:
* **FrameworkBundle** - The core Symfony framework bundle
* [**SensioFrameworkExtraBundle**][6] - Adds several enhancements, including
template and routing annotation capability
* [**DoctrineBundle**][7] - Adds support for the Doctrine ORM
* [**TwigBundle**][8] - Adds support for the Twig templating engine
* [**SecurityBundle**][9] - Adds security by integrating Symfony's security
component
* [**SwiftmailerBundle**][10] - Adds support for Swiftmailer, a library for
sending emails
* [**MonologBundle**][11] - Adds support for Monolog, a logging library
* [**AsseticBundle**][12] - Adds support for Assetic, an asset processing
library
* **WebProfilerBundle** (in dev/test env) - Adds profiling functionality and
the web debug toolbar
* **SensioDistributionBundle** (in dev/test env) - Adds functionality for
configuring and working with Symfony distributions
* [**SensioGeneratorBundle**][13] (in dev/test env) - Adds code generation
capabilities
* **AcmeDemoBundle** (in dev/test env) - A demo bundle with some example
code
All libraries and bundles included in the Symfony Standard Edition are
released under the MIT or BSD license.
Enjoy!
[1]: http://symfony.com/doc/2.3/book/installation.html
[2]: http://getcomposer.org/
[3]: http://symfony.com/download
[4]: http://symfony.com/doc/2.3/quick_tour/the_big_picture.html
[5]: http://symfony.com/doc/2.3/index.html
[6]: http://symfony.com/doc/2.3/bundles/SensioFrameworkExtraBundle/index.html
[7]: http://symfony.com/doc/2.3/book/doctrine.html
[8]: http://symfony.com/doc/2.3/book/templating.html
[9]: http://symfony.com/doc/2.3/book/security.html
[10]: http://symfony.com/doc/2.3/cookbook/email.html
[11]: http://symfony.com/doc/2.3/cookbook/logging/monolog.html
[12]: http://symfony.com/doc/2.3/cookbook/assetic/asset_management.html
[13]: http://symfony.com/doc/2.3/bundles/SensioGeneratorBundle/index.html
# Kifland
| Java |
#ifndef _ZLX_PLATFORM_H
#define _ZLX_PLATFORM_H
#include "arch.h"
#if defined(ZLX_FREESTANDING) && ZLX_FREESTANDING
#else
# undef ZLX_FREESTANDING
# define ZLX_FREESTANDING 0
# if defined(_WIN32)
# define ZLX_MSWIN 1
# elif defined(_AIX)
# define ZLX_AIX 1
# elif defined(__unix__) || defined(__unix)
# define ZLX_UNIX 1
# include <unistd.h>
# if defined(POSIX_VERSION)
# define ZLX_POSIX POSIX_VERSION
# endif
# if defined(__DragonFly__)
# define ZLX_BSD 1
# define ZLX_DRAGONFLY_BSD 1
# elif defined(__FreeBSD__)
# define ZLX_BSD 1
# define ZLX_FREEBSD 1
# elif defined(__NetBSD__)
# define ZLX_BSD 1
# define ZLX_NETBSD 1
# elif defined(__OpenBSD__)
# define ZLX_BSD 1
# define ZLX_OPENBSD 1
# endif
# endif /* OS defines */
#endif /* ZLX_FREESTANDING */
/* assume System V ABI if we're not under a Microsoft environment */
#if !defined(ZLX_ABI_SYSV) && !defined(ZLX_ABI_MS)
# if defined(_WIN32)
# define ZLX_ABI_MS 1
# else
# define ZLX_ABI_SYSV 1
# endif
#endif
#if ZLX_IA32 && ZLX_ABI_MS
# define ZLX_FAST_CALL __fastcall
#elif ZLX_IA32 && ZLX_ABI_SYSV && (ZLX_GCC || ZLX_CLANG)
# define ZLX_FAST_CALL __attribute__((regparm((3))))
#else
# define ZLX_FAST_CALL
#endif
#endif /* _ZLX_PLATFORM_H */
| Java |
## Rails 5.0.4 (June 19, 2017) ##
* Fix regression in numericality validator when comparing Decimal and Float input
values with more scale than the schema.
*Bradley Priest*
## Rails 5.0.3 (May 12, 2017) ##
* The original string assigned to a model attribute is no longer incorrectly
frozen.
Fixes #24185, #28718.
*Matthew Draper*
* Avoid converting integer as a string into float.
*namusyaka*
## Rails 5.0.2 (March 01, 2017) ##
* No changes.
## Rails 5.0.1 (December 21, 2016) ##
* No changes.
## Rails 5.0.1.rc2 (December 10, 2016) ##
* No changes.
## Rails 5.0.1.rc1 (December 01, 2016) ##
* Fix `Type::Date#serialize` to cast a value to a date object properly.
This casting fixes queries for finding records by date column.
Fixes #25354.
*Ryuta Kamizono*
## Rails 5.0.0 (June 30, 2016) ##
* `Dirty`'s `*_changed?` methods now return an actual singleton, never `nil`, as in 4.2.
Fixes #24220.
*Sen-Zhang*
* Ensure that instances of `ActiveModel::Errors` can be marshalled.
Fixes #25165.
*Sean Griffin*
* Allow passing record being validated to the message proc to generate
customized error messages for that object using I18n helper.
*Prathamesh Sonpatki*
* Validate multiple contexts on `valid?` and `invalid?` at once.
Example:
class Person
include ActiveModel::Validations
attr_reader :name, :title
validates_presence_of :name, on: :create
validates_presence_of :title, on: :update
end
person = Person.new
person.valid?([:create, :update]) # => false
person.errors.messages # => {:name=>["can't be blank"], :title=>["can't be blank"]}
*Dmitry Polushkin*
* Add case_sensitive option for confirmation validator in models.
*Akshat Sharma*
* Ensure `method_missing` is called for methods passed to
`ActiveModel::Serialization#serializable_hash` that don't exist.
*Jay Elaraj*
* Remove `ActiveModel::Serializers::Xml` from core.
*Zachary Scott*
* Add `ActiveModel::Dirty#[attr_name]_previously_changed?` and
`ActiveModel::Dirty#[attr_name]_previous_change` to improve access
to recorded changes after the model has been saved.
It makes the dirty-attributes query methods consistent before and after
saving.
*Fernando Tapia Rico*
* Deprecate the `:tokenizer` option for `validates_length_of`, in favor of
plain Ruby.
*Sean Griffin*
* Deprecate `ActiveModel::Errors#add_on_empty` and `ActiveModel::Errors#add_on_blank`
with no replacement.
*Wojciech Wnętrzak*
* Deprecate `ActiveModel::Errors#get`, `ActiveModel::Errors#set` and
`ActiveModel::Errors#[]=` methods that have inconsistent behavior.
*Wojciech Wnętrzak*
* Allow symbol as values for `tokenize` of `LengthValidator`.
*Kensuke Naito*
* Assigning an unknown attribute key to an `ActiveModel` instance during initialization
will now raise `ActiveModel::AttributeAssignment::UnknownAttributeError` instead of
`NoMethodError`.
Example:
User.new(foo: 'some value')
# => ActiveModel::AttributeAssignment::UnknownAttributeError: unknown attribute 'foo' for User.
*Eugene Gilburg*
* Extracted `ActiveRecord::AttributeAssignment` to `ActiveModel::AttributeAssignment`
allowing to use it for any object as an includable module.
Example:
class Cat
include ActiveModel::AttributeAssignment
attr_accessor :name, :status
end
cat = Cat.new
cat.assign_attributes(name: "Gorby", status: "yawning")
cat.name # => 'Gorby'
cat.status # => 'yawning'
cat.assign_attributes(status: "sleeping")
cat.name # => 'Gorby'
cat.status # => 'sleeping'
*Bogdan Gusiev*
* Add `ActiveModel::Errors#details`
To be able to return type of used validator, one can now call `details`
on errors instance.
Example:
class User < ActiveRecord::Base
validates :name, presence: true
end
user = User.new; user.valid?; user.errors.details
=> {name: [{error: :blank}]}
*Wojciech Wnętrzak*
* Change `validates_acceptance_of` to accept `true` by default besides `'1'`.
The default for `validates_acceptance_of` is now `'1'` and `true`.
In the past, only `"1"` was the default and you were required to pass
`accept: true` separately.
*mokhan*
* Remove deprecated `ActiveModel::Dirty#reset_#{attribute}` and
`ActiveModel::Dirty#reset_changes`.
*Rafael Mendonça França*
* Change the way in which callback chains can be halted.
The preferred method to halt a callback chain from now on is to explicitly
`throw(:abort)`.
In the past, returning `false` in an Active Model `before_` callback had
the side effect of halting the callback chain.
This is not recommended anymore and, depending on the value of the
`ActiveSupport.halt_callback_chains_on_return_false` option, will
either not work at all or display a deprecation warning.
*claudiob*
Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activemodel/CHANGELOG.md) for previous changes.
| Java |
---
title: Color Palette
layout: page
description: taCss color palette same as the Material Design Lite color palette.
utilities: true
---
<div class="row p-3">
<h6>color setup</h6>
<div class="code col-12 info p-3 m-b-3">
{% highlight scss %}
/* colors setups in "core/_variables.scss" */
/* enable/disable the default colors for components */
$enable-colors: true !default;
/* don't forget include minimum the primary and the accent color */
/* the palette variables can be found in the "core/_colorpalette.scss" */
$primary-palette: $teal-palette !default;
$accent-palette: $deep-orange-palette !default;
$enable--red-palette: true !default;
$enable--pink-palette: true !default;
$enable--purple-palette: true !default;
$enable--deep-purple-palette: true !default;
$enable--indigo-palette: true !default;
$enable--blue-palette: true !default;
$enable--light-blue-palette: true !default;
$enable--cyan-palette: true !default;
$enable--teal-palette: true !default;
$enable--green-palette: true !default;
$enable--light-green-palette: true !default;
$enable--lime-palette: true !default;
$enable--yellow-palette: true !default;
$enable--amber-palette: true !default;
$enable--orange-palette: true !default;
$enable--deep-orange-palette: true !default;
$enable--brown-palette: true !default;
$enable--grey-palette: true !default;
$enable--blue-grey-palette: true !default;
$enable--black-palette: true !default;
$enable--white-palette: true !default;
/* basic palette contains black, white and the midle colors for the rest even if the color-palette not enabled. no accent color. */
$enable--basic-palette: true !default;
{% endhighlight %}
</div>
<h6>background</h6>
<p>
Use the <span class="code-class">bg-</span> prefix with your <i>color</i> of choice.
</p>
<p class="col-6 col-t-8 ">
<button class='btn bg-red'> red </button>
<button class='btn bg-pink'> pink </button>
<button class='btn bg-purple'> purple </button>
<button class='btn bg-deep-purple'> deep-purple </button>
<button class='btn bg-indigo'> indigo </button>
<button class='btn bg-blue'> blue </button>
<button class='btn bg-light-blue'> light-blue </button>
<button class='btn bg-lime'> lime </button>
<button class='btn bg-yellow'> yellow </button>
<button class='btn bg-amber'> amber </button>
<button class='btn bg-orange'> orange </button>
<button class='btn bg-deep-orange'> deep-orange </button>
<button class='btn bg-brown'> brown </button>
<button class='btn bg-grey'> grey </button>
<button class='btn bg-blue-grey'> blue-grey </button>
<button class='btn bg-black'> black </button>
<button class='btn bg-white'> white </button>
</p>
<div class="code info code-large col-6 col-t-8">
{% highlight html %}
<button class='btn bg-red'> red </button>
<button class='btn bg-pink'> pink </button>
<button class='btn bg-purple'> purple </button>
<button class='btn bg-deep-purple'> deep-purple </button>
<button class='btn bg-indigo'> indigo </button>
<button class='btn bg-blue'> blue </button>
<button class='btn bg-light-blue'> light-blue </button>
<button class='btn bg-lime'> lime </button>
<button class='btn bg-yellow'> yellow </button>
<button class='btn bg-amber'> amber </button>
<button class='btn bg-orange'> orange </button>
<button class='btn bg-deep-orange'> deep-orange </button>
<button class='btn bg-brown'> brown </button>
<button class='btn bg-grey'> grey </button>
<button class='btn bg-blue-grey'> blue-grey </button>
<button class='btn bg-black'> black </button>
<button class='btn bg-white'> white </button>
{% endhighlight %}
</div>
<h6>auto textcolor</h6>
<p>
To choose readable font color automatic to the choosen background use the <span class="code-class">colored</span> class.
</p>
<p class="col-6 col-t-8 ">
<button class='colored btn bg-red'> red </button>
<button class='colored btn bg-pink'> pink </button>
<button class='colored btn bg-purple'> purple </button>
<button class='colored btn bg-deep-purple'> deep-purple </button>
<button class='colored btn bg-indigo'> indigo </button>
<button class='colored btn bg-blue'> blue </button>
<button class='colored btn bg-light-blue'> light-blue </button>
<button class='colored btn bg-lime'> lime </button>
<button class='colored btn bg-yellow'> yellow </button>
<button class='colored btn bg-amber'> amber </button>
<button class='colored btn bg-orange'> orange </button>
<button class='colored btn bg-deep-orange'> deep-orange </button>
<button class='colored btn bg-brown'> brown </button>
<button class='colored btn bg-grey'> grey </button>
<button class='colored btn bg-blue-grey'> blue-grey </button>
<button class='colored btn bg-black'> black </button>
<button class='colored btn bg-white'> white </button>
</p>
<div class="code info code-large col-6 col-t-8">
{% highlight html %}
<button class='colored btn bg-red'> red </button>
<button class='colored btn bg-pink'> pink </button>
<button class='colored btn bg-purple'> purple </button>
<button class='colored btn bg-deep-purple'> deep-purple </button>
<button class='colored btn bg-indigo'> indigo </button>
<button class='colored btn bg-blue'> blue </button>
<button class='colored btn bg-light-blue'> light-blue </button>
<button class='colored btn bg-lime'> lime </button>
<button class='colored btn bg-yellow'> yellow </button>
<button class='colored btn bg-amber'> amber </button>
<button class='colored btn bg-orange'> orange </button>
<button class='colored btn bg-deep-orange'> deep-orange </button>
<button class='colored btn bg-brown'> brown </button>
<button class='colored btn bg-grey'> grey </button>
<button class='colored btn bg-blue-grey'> blue-grey </button>
<button class='colored btn bg-black'> black </button>
<button class='colored btn bg-white'> white </button>
{% endhighlight %}
</div>
<h6>outline (border and text color)</h6>
<p>
Use the <span class="code-class">outline-</span> prefix with your <i>color</i> of choice to get colored border and text.
</p>
<p class="col-6 col-t-9">
<button class='btn outline-red'> red </button>
<button class='btn outline-pink'> pink </button>
<button class='btn outline-purple'> purple </button>
<button class='btn outline-deep-purple'> deep-purple </button>
<button class='btn outline-indigo'> indigo </button>
<button class='btn outline-blue'> blue </button>
<button class='btn outline-light-blue'> light-blue </button>
<button class='btn outline-lime'> lime </button>
<button class='btn outline-yellow'> yellow </button>
<button class='btn outline-amber'> amber </button>
<button class='btn outline-orange'> orange </button>
<button class='btn outline-deep-orange'> deep-orange </button>
<button class='btn outline-brown'> brown </button>
<button class='btn outline-grey'> grey </button>
<button class='btn outline-blue-grey'> blue-grey </button>
<button class='btn outline-black'> black </button>
<button class='btn outline-white'> white </button>
</p>
<div class="code info code-large col-6 col-t-8">
{% highlight html %}
<button class='btn outline-red'> red </button>
<button class='btn outline-pink'> pink </button>
<button class='btn outline-purple'> purple </button>
<button class='btn outline-deep-purple'> deep-purple </button>
<button class='btn outline-indigo'> indigo </button>
<button class='btn outline-blue'> blue </button>
<button class='btn outline-light-blue'> light-blue </button>
<button class='btn outline-lime'> lime </button>
<button class='btn outline-yellow'> yellow </button>
<button class='btn outline-amber'> amber </button>
<button class='btn outline-orange'> orange </button>
<button class='btn outline-deep-orange'> deep-orange </button>
<button class='btn outline-brown'> brown </button>
<button class='btn outline-grey'> grey </button>
<button class='btn outline-blue-grey'> blue-grey </button>
<button class='btn outline-black'> black </button>
<button class='btn outline-white'> white </button>
{% endhighlight %}
</div>
<h6>text color</h6>
<p>
Use the <span class="code-class">text-</span> prefix with your <i>color</i> of choice to get colored text.
</p>
<p class="col-6 col-t-8">
<button class='btn text-red'> red </button>
<button class='btn text-pink'> pink </button>
<button class='btn text-purple'> purple </button>
<button class='btn text-deep-purple'> deep-purple </button>
<button class='btn text-indigo'> indigo </button>
<button class='btn text-blue'> blue </button>
<button class='btn text-light-blue'> light-blue </button>
<button class='btn text-lime'> lime </button>
<button class='btn text-yellow'> yellow </button>
<button class='btn text-amber'> amber </button>
<button class='btn text-orange'> orange </button>
<button class='btn text-deep-orange'> deep-orange </button>
<button class='btn text-brown'> brown </button>
<button class='btn text-grey'> grey </button>
<button class='btn text-blue-grey'> blue-grey </button>
<button class='btn text-black'> black </button>
<button class='btn text-white'> white </button>
</p>
<div class="code info code-large col-6 col-t-8">
{% highlight html %}
<button class='btn text-red'> red </button>
<button class='btn text-pink'> pink </button>
<button class='btn text-purple'> purple </button>
<button class='btn text-deep-purple'> deep-purple </button>
<button class='btn text-indigo'> indigo </button>
<button class='btn text-blue'> blue </button>
<button class='btn text-light-blue'> light-blue </button>
<button class='btn text-lime'> lime </button>
<button class='btn text-yellow'> yellow </button>
<button class='btn text-amber'> amber </button>
<button class='btn text-orange'> orange </button>
<button class='btn text-deep-orange'> deep-orange </button>
<button class='btn text-brown'> brown </button>
<button class='btn text-grey'> grey </button>
<button class='btn text-blue-grey'> blue-grey </button>
<button class='btn text-black'> black </button>
<button class='btn text-white'> white </button>
{% endhighlight %}
</div>
<h6>the full color palette</h6>
<div class="row" id="colorPalettesBlock">
</div>
<div class="row" id=textColorPalettesBlock>
</div>
<script type="text/javascript">
var basicPalette = [
"red", "pink", "purple", "deep-purple", "indigo", "blue", "light-blue", "lime",
"yellow", "amber", "orange", "deep-orange", "brown", "grey", "blue-grey", "black", "white",
];
var redPalette = ['red-0','red-1','red-2','red-3','red-4','red','red-6','red-7','red-8','red-9','red-a1','red-a2','red-a3','red-a4'];
var pinkPalette = ['pink-0','pink-1','pink-2','pink-3','pink-4','pink','pink-6','pink-7','pink-8','pink-9','pink-a1','pink-a2','pink-a3','pink-a4'];
var purplePalette = ['purple-0','purple-1','purple-2','purple-3','purple-4','purple','purple-6','purple-7','purple-8','purple-9','purple-a1','purple-a2','purple-a3','purple-a4'];
var deepPurplePalette = ['deep-purple-0','deep-purple-1','deep-purple-2','deep-purple-3','deep-purple-4','deep-purple','deep-purple-6','deep-purple-7','deep-purple-8','deep-purple-9','deep-purple-a1','deep-purple-a2','deep-purple-a3','deep-purple-a3'];
var indigoPalette = ['indigo-0','indigo-1','indigo-2','indigo-3','indigo-4','indigo','indigo-6','indigo-7','indigo-8','indigo-9','indigo-a1','indigo-a2','indigo-a3','indigo-a4'];
var bluePalette = ['blue-0','blue-1','blue-2','blue-3','blue-4','blue','blue-6','blue-7','blue-8','blue-9','blue-a1','blue-a2','blue-a3','blue-a4'];
var lightBluePalette = ['light-blue-0','light-blue-1','light-blue-2','light-blue-3','light-blue-4','light-blue','light-blue-6','light-blue-7','light-blue-8','light-blue-9','light-blue-a1','light-blue-a2','light-blue-a3','light-blue-a4'];
var cyanPalette = ['cyan-0','cyan-1','cyan-2','cyan-3','cyan-4','cyan','cyan-6','cyan-7','cyan-8','cyan-9','cyan-a1','cyan-a2','cyan-a3','cyan-a4'];
var tealPalette = ['teal-0','teal-1','teal-2','teal-3','teal-4','teal','teal-6','teal-7','teal-8','teal-9','teal-a1','teal-a2','teal-a3','teal-a4'];
var greenPalette = ['green-0','green-1','green-2','green-3','green-4','green','green-6','green-7','green-8','green-9','green-a1','green-a2','green-a3','green-a4'];
var lightGreenPalette = ['light-green-0','light-green-1','light-green-2','light-green-3','light-green-4','light-green','light-green-6','light-green-7','light-green-8','light-green-9','light-green-a1','light-green-a2','light-green-a3','light-green-a4'];
var limePalette = ['lime-0','lime-1','lime-2','lime-3','lime-4','lime','lime-6','lime-7','lime-8','lime-9','lime-a1','lime-a2','lime-a3','lime-a4'];
var yellowPalette = ['yellow-0','yellow-1','yellow-2','yellow-3','yellow-4','yellow','yellow-6','yellow-7','yellow-8','yellow-9','yellow-a1','yellow-a2','yellow-a3','yellow-a4'];
var amberPalette = ['amber-0','amber-1','amber-2','amber-3','amber-4','amber','amber-6','amber-7','amber-8','amber-9','amber-a1','amber-a2','amber-a3','amber-a4'];
var orangePalette = ['orange-0','orange-1','orange-2','orange-3','orange-4','orange','orange-6','orange-7','orange-8','orange-9','orange-a1','orange-a2','orange-a3','orange-a4'];
var deepOrangePalette = ['deep-orange-0','deep-orange-1','deep-orange-2','deep-orange-3','deep-orange-4','deep-orange','deep-orange-6','deep-orange-7','deep-orange-8','deep-orange-9','deep-orange-a1','deep-orange-a2','deep-orange-a3','deep-orange-a4'];
var brownPalette = ['brown-0','brown-1','brown-2','brown-3','brown-4','brown','brown-6','brown-7','brown-8','brown-9'];
var greyPalette = ['grey-0','grey-1','grey-2','grey-3','grey-4','grey','grey-6','grey-7','grey-8','grey-9'];
var blueGreyPalette = ['blue-grey-0','blue-grey-1','blue-grey-2','blue-grey-3','blue-grey-4','blue-grey','blue-grey-6','blue-grey-7','blue-grey-8','blue-grey-9'];
var blackPalette = ['black'];
var whitePalette = ['white'];
var colorPalettes = ['redPalette','pinkPalette','purplePalette','deepPurplePalette','indigoPalette','bluePalette','lightBluePalette','cyanPalette','tealPalette','greenPalette','lightGreenPalette','limePalette','yellowPalette','amberPalette','orangePalette','deepOrangePalette','brownPalette','greyPalette','blueGreyPalette']; //+'blackPalette','whitePalette'
str = '';
str = "<div class='no-gutter col col-m-2 col-t-4 col-6'><div class='bg-black p-1 w-100 t-center colored'>black</div></div><div class='no-gutter col col-m-2 col-t-4 col-6'><div class='bg-white p-1 w-100 t-center colored'>white</div></div><div class='no-gutter col col-m-2 col-t-4 col-6'><div class='bg-white p-1 w-100 t-center colored'>black</div></div><div class='no-gutter col col-m-2 col-t-4 col-6'><div class='bg-black p-1 w-100 t-center colored'>white</div></div>";
for (var i = 0; i < colorPalettes.length; i++) {
str += "<div class='no-gutter col col-2 bg-" + window[colorPalettes[i]][9] + "'>";
for (var j = 0; j < window[colorPalettes[i]].length; j++) {
str += "<div class='bg-" + window[colorPalettes[i]][j] + " p-1 w-100 t-center colored'> " + window[colorPalettes[i]][j] + " </div>";
}
str += "</div>";
}
for (var i = 0; i < colorPalettes.length; i++) {
str += "<div class='bg-black no-gutter col col-2'>";
for (var j = 0; j < window[colorPalettes[i]].length; j++) {
str += "<div class='text-" + window[colorPalettes[i]][j] + " p-1 w-100 t-center colored'> " + window[colorPalettes[i]][j] + " </div>";
}
str += "</div>";
}
document.getElementById("colorPalettesBlock").innerHTML = str;
</script>
</div>
| Java |
---
layout: post
title: "Clean Code: Chapter 5 - Formatting"
date: 2016-03-13
---
Formatting, while not consequential to how the code actually works, does make a huge difference in how future user of the code will be able to navigate and understand what is going on.
In formatting, particularly, the broken window theory applies. The broken window theory is a social science concept that looks at how a single, small act of neglect can lead to snowballing negative effects. The theory gets its name from the idea that a single neglected broken window in an abandoned building would eventually invite more acts of crime and vandalism.
This applies to programming because a consistently and cleanly formatted application reinforces the importance of setting positive norms for future results. Lazy formatting, on the other hand, will set a precedent for those who will add to and edit the code down the line.
There are several aspects that go into a well formatted application. Vertical and horizontal formatting are a couple of considerations to make when considering how your code and files should be organized.
### Vertical Formatting
>Smaller files are usually easier to understand than large files are.
Vertical formatting points to a file’s overall size with regards to lines of code per file. As a general rule, you don’t want to have files over 500 lines of code, but even smaller files are easier to sort through.
Beyond just lines of code, however, are vertical context guidelines. Code should be organized in a file in a meaningful way, with larger concepts towards the top, and smaller and smaller details as one descends down the file. Functions that call other functions should appear above the functions which they call. Variables that are used throughout the file should remain at the top of the file, and local variables should appear at the top of the function that is using them.
With the code organized, you can make other considerations with regards to spacing.
It is appropriate to use empty lines to separate concepts, such as functions. Within a grouped concept, however, using empty lines can draw out methods, making them more difficult to follow.
### Horizontal Formatting
Horizontal formatting, on the other hand, deals with the smaller context of single lines. The guideline for how long your lines should be should take into consideration a reader and the required movement it would take to read from left to right. You don’t want the reader to have to scroll to read a full line, nor would you want to have to shrink the font to a tiny size to get a single line effect. Typically 100-120 characters per line are appropriate.
> We use horizontal white space to associate things that are strongly related and dissassociate things that are more weakly related.
Spacing can have a positive effect on the readability of the code. Consider the following:
```function area(length,width){
return (length*width)/2
}```
Sure, the code runs and does what it is supposed to, but a user friendly refactor could be as follows:
```function area(length, width) {
return (length * width) / 2
}```
Just adding a couple of spaces saves time in allowing yourself to separate the different actions happening in the code.
As another consideration, it is generally not wise to separate things into a column format, as the eye tends to follow the vertical line of the column, rather than the horizontal line as intended.
Indentation is another important horizontal formatting concept. Consider the file as an outline and indent as such. The larger concepts such as class or module declaration would appear farthest left, with smaller details within functions and loops being indented the most. This helps readers know where concepts begin and end.
Paying attention to vertical and horizontal formatting concepts will go a long way in presenting a clean code base that others will want to work with. Keep in mind a goal that you want people to look at your code and think *”wow, this person really cares”*. | Java |
# testtesttest-yo
[![NPM version][npm-image]][npm-url]
[![Build Status][travis-image]][travis-url]
[![Dependency Status][daviddm-image]][daviddm-url]
[![Code Coverage][coverage-image]][coverage-url]
[![Code Climate][climate-image]][climate-url]
[![License][license-image]][license-url]
[![Code Style][code-style-image]][code-style-url]
## Table of Contents
1. [Features](#features)
1. [Requirements](#requirements)
1. [Getting Started](#getting-started)
1. [Application Structure](#application-structure)
1. [Development](#development)
1. [Routing](#routing)
1. [Testing](#testing)
1. [Configuration](#configuration)
1. [Production](#production)
1. [Deployment](#deployment)
## Requirements
* node `^5.0.0` (`6.11.0` suggested)
* yarn `^0.23.0` or npm `^3.0.0`
## Getting Started
1. Install dependencies: `yarn` or `npm install`
2. Start Development server: `yarn start` or `npm start`
While developing, you will probably rely mostly on `npm start`; however, there are additional scripts at your disposal:
|`npm run <script>` |Description|
|-------------------|-----------|
|`start` |Serves your app at `localhost:3000` and displays [Webpack Dashboard](https://github.com/FormidableLabs/webpack-dashboard)|
|`start:simple` |Serves your app at `localhost:3000` without [Webpack Dashboard](https://github.com/FormidableLabs/webpack-dashboard)|
|`build` |Builds the application to ./dist|
|`test` |Runs unit tests with Karma. See [testing](#testing)|
|`test:watch` |Runs `test` in watch mode to re-run tests when changed|
|`lint` |[Lints](http://stackoverflow.com/questions/8503559/what-is-linting) the project for potential errors|
|`lint:fix` |Lints the project and [fixes all correctable errors](http://eslint.org/docs/user-guide/command-line-interface.html#fix)|
[Husky](https://github.com/typicode/husky) is used to enable `prepush` hook capability. The `prepush` script currently runs `eslint`, which will keep you from pushing if there is any lint within your code. If you would like to disable this, remove the `prepush` script from the `package.json`.
## Application Structure
The application structure presented in this boilerplate is **fractal**, where functionality is grouped primarily by feature rather than file type. Please note, however, that this structure is only meant to serve as a guide, it is by no means prescriptive. That said, it aims to represent generally accepted guidelines and patterns for building scalable applications. If you wish to read more about this pattern, please check out this [awesome writeup](https://github.com/davezuko/react-redux-starter-kit/wiki/Fractal-Project-Structure) by [Justin Greenberg](https://github.com/justingreenberg).
```
.
├── build # All build-related configuration
│ └── create-config # Script for building config.js in ci environments
│ └── karma.config.js # Test configuration for Karma
│ └── webpack.config.js # Environment-specific configuration files for webpack
├── server # Express application that provides webpack middleware
│ └── main.js # Server application entry point
├── src # Application source code
│ ├── index.html # Main HTML page container for app
│ ├── main.js # Application bootstrap and rendering
│ ├── normalize.js # Browser normalization and polyfills
│ ├── components # Global Reusable Presentational Components
│ ├── containers # Global Reusable Container Components
│ ├── layouts # Components that dictate major page structure
│ │ └── CoreLayout # Global application layout in which to render routes
│ ├── routes # Main route definitions and async split points
│ │ ├── index.js # Bootstrap main application routes with store
│ │ └── Home # Fractal route
│ │ ├── index.js # Route definitions and async split points
│ │ ├── assets # Assets required to render components
│ │ ├── components # Presentational React Components
│ │ ├── container # Connect components to actions and store
│ │ ├── modules # Collections of reducers/constants/actions
│ │ └── routes ** # Fractal sub-routes (** optional)
│ ├── static # Static assets
│ ├── store # Redux-specific pieces
│ │ ├── createStore.js # Create and instrument redux store
│ │ └── reducers.js # Reducer registry and injection
│ └── styles # Application-wide styles (generally settings)
├── project.config.js # Project configuration settings (includes ci settings)
└── tests # Unit tests
```
### Routing
We use `react-router` [route definitions](https://github.com/ReactTraining/react-router/blob/v3/docs/API.md#plainroute) (`<route>/index.js`) to define units of logic within our application. See the [application structure](#application-structure) section for more information.
## Testing
To add a unit test, create a `.spec.js` file anywhere inside of `./tests`. Karma and webpack will automatically find these files, and Mocha and Chai will be available within your test without the need to import them.
## Production
Build code before deployment by running `npm run build`. There are multiple options below for types of deployment, if you are unsure, checkout the Firebase section.
### Deployment
1. Login to [Firebase](firebase.google.com) (or Signup if you don't have an account) and create a new project
2. Install cli: `npm i -g firebase-tools`
#### CI Deploy (recommended)
**Note**: Config for this is located within `travis.yml`
`firebase-ci` has been added to simplify the CI deployment process. All that is required is providing authentication with Firebase:
1. Login: `firebase login:ci` to generate an authentication token (will be used to give Travis-CI rights to deploy on your behalf)
1. Set `FIREBASE_TOKEN` environment variable within Travis-CI environment
1. Run a build on Travis-CI
If you would like to deploy to different Firebase instances for different branches (i.e. `prod`), change `ci` settings within `.firebaserc`.
For more options on CI settings checkout the [firebase-ci docs](https://github.com/prescottprue/firebase-ci)
#### Manual deploy
1. Run `firebase:login`
1. Initialize project with `firebase init` then answer:
* What file should be used for Database Rules? -> `database.rules.json`
* What do you want to use as your public directory? -> `build`
* Configure as a single-page app (rewrite all urls to /index.html)? -> `Yes`
* What Firebase project do you want to associate as default? -> **your Firebase project name**
1. Build Project: `npm run build`
1. Confirm Firebase config by running locally: `firebase serve`
1. Deploy to firebase: `firebase deploy`
**NOTE:** You can use `firebase serve` to test how your application will work when deployed to Firebase, but make sure you run `npm run build` first.
[npm-image]: https://img.shields.io/npm/v/testtesttest-yo.svg?style=flat-square
[npm-url]: https://npmjs.org/package/testtesttest-yo
[travis-image]: https://img.shields.io/travis/taforyou@hotmail.com/testtesttest-yo/master.svg?style=flat-square
[travis-url]: https://travis-ci.org/taforyou@hotmail.com/testtesttest-yo
[daviddm-image]: https://img.shields.io/david/taforyou@hotmail.com/testtesttest-yo.svg?style=flat-square
[daviddm-url]: https://david-dm.org/taforyou@hotmail.com/testtesttest-yo
[climate-image]: https://img.shields.io/codeclimate/github/taforyou@hotmail.com/testtesttest-yo.svg?style=flat-square
[climate-url]: https://codeclimate.com/github/taforyou@hotmail.com/testtesttest-yo
[coverage-image]: https://img.shields.io/codeclimate/coverage/github/taforyou@hotmail.com/testtesttest-yo.svg?style=flat-square
[coverage-url]: https://codeclimate.com/github/taforyou@hotmail.com/testtesttest-yo
[license-image]: https://img.shields.io/npm/l/testtesttest-yo.svg?style=flat-square
[license-url]: https://github.com/taforyou@hotmail.com/testtesttest-yo/blob/master/LICENSE
[code-style-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square
[code-style-url]: http://standardjs.com/
| Java |
package com.board.gd.domain.stock;
import lombok.Data;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by gd.godong9 on 2017. 5. 19.
*/
@Data
public class StockResult {
private Long id;
private String name;
private String code;
public static StockResult getStockResult(Stock stock) {
StockResult stockResult = new StockResult();
stockResult.setId(stock.getId());
stockResult.setName(stock.getName());
stockResult.setCode(stock.getCode());
return stockResult;
}
public static List<StockResult> getStockResultList(List<Stock> stockList) {
return stockList.stream()
.map(stock -> getStockResult(stock))
.collect(Collectors.toList());
}
}
| Java |
<?php
/**
* General purpose and commonly used PHP interface definitions
*
* @author Михаил Красильников <m.krasilnikov@yandex.ru>
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Mekras\Interfaces\Http\Message;
use Psr\Http\Message\RequestInterface;
/**
* HTTP request factory
*
* Object can create empty instances of {@link \Psr\Http\Message\RequestInterface}.
* This can be used to abstract from concrete PSR-7 implementation.
*
* @deprecated use https://packagist.org/packages/php-http/httplug
*
* @since 3.4 deprecated
* @since 3.02
*/
interface RequestFactory
{
/**
* Create empty HTTP request
*
* @return RequestInterface
*
* @since 3.02
*/
public function createEmptyRequest();
}
| Java |
<!--
Unsafe sample
input : get the UserData field of $_SESSION
Uses a number_float_filter via filter_var function
File : unsafe, use of untrusted data in CSS
-->
<!--Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.-->
<!DOCTYPE html>
<html>
<head>
<style>
<?php
$tainted = $_SESSION['UserData'];
$sanitized = filter_var($tainted, FILTER_SANITIZE_NUMBER_FLOAT);
if (filter_var($sanitized, FILTER_VALIDATE_FLOAT))
$tainted = $sanitized ;
else
$tainted = "" ;
//flaw
echo $tainted ;
?>
</style>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html> | Java |
var today = new Date();
console.log(today); | Java |
var RocketBoots = {
isInitialized : false,
readyFunctions : [],
components : {},
loadedScripts: [],
version: {full: "0.7.0", major: 0, minor: 7, patch: 0, codeName: "sun-master"},
_autoLoadRequirements: true,
_initTimer : null,
_MAX_ATTEMPTS : 300,
_BOOTING_ELEMENT_ID : "booting-up-rocket-boots",
_: null, // Lodash
$: null, // jQuery
//==== Classes
Component : function(c){
this.fileName = c;
this.name = null;
this.isLoaded = false;
this.isInstalled = false;
},
//==== General Functions
log : console.log,
loadScript : function(url, callback){
//console.log("Loading script", url);
// http://stackoverflow.com/a/7719185/1766230
var o = this;
var s = document.createElement('script');
var r = false;
var t;
s.type = 'text/javascript';
s.src = "scripts/" + url + ".js";
s.className = "rocketboots-script";
s.onload = s.onreadystatechange = function() {
//console.log( this.readyState ); //uncomment this line to see which ready states are called.
if ( !r && (!this.readyState || this.readyState == 'complete') )
{
r = true;
o.loadedScripts.push(url);
if (typeof callback == "function") callback();
}
};
t = document.getElementsByTagName('script')[0];
t.parentNode.insertBefore(s, t);
return this;
},
//==== Component Functions
hasComponent: function (componentClass) {
if (typeof RocketBoots[componentClass] == "function") {
return true;
} else {
return false;
}
},
installComponent : function (options, callback, attempt) {
// options = { fileName, classNames, requirements, description, credits }
var o = this;
var mainClassName = (typeof options.classNames === 'object' && options.classNames.length > 0) ? options.classNames[0] : (options.classNames || options.className);
var componentClass = options[mainClassName];
var requirements = options.requirements;
var fileName = options.fileName;
var callbacks = [];
var i;
// Setup array of callbacks
if (typeof callback === 'function') { callbacks.push(callback); }
if (typeof options.callback === 'function') { callbacks.push(options.callback); }
if (typeof options.callbacks === 'object') { callbacks.concat(options.callbacks); }
// Check for possible errors
if (typeof mainClassName !== 'string') {
console.error("Error installing component: mainClassName is not a string", mainClassName, options);
console.log("options", options);
return;
} else if (typeof componentClass !== 'function') {
console.error("Error installing component: class name", mainClassName, "not found on options:", options);
console.log("options", options);
return;
}
//console.log("Installing", fileName, " ...Are required components", requirements, " loaded?", o.areComponentsLoaded(requirements));
if (!o.areComponentsLoaded(requirements)) {
var tryAgainDelay, compTimer;
if (typeof attempt === "undefined") {
attempt = 1;
} else if (attempt > o._MAX_ATTEMPTS) {
console.error("Could not initialize RocketBoots: too many attempts");
return false;
} else {
attempt++;
}
if (o._autoLoadRequirements) {
console.log(fileName, "requires component(s)", requirements, " which aren't loaded. Autoloading...");
o.loadComponents(requirements);
tryAgainDelay = 100 * attempt;
} else {
console.warn(fileName, "requires component(s)", requirements, " which aren't loaded.");
tryAgainDelay = 5000;
}
compTimer = window.setTimeout(function(){
o.installComponent(options, callback, attempt);
}, tryAgainDelay);
} else {
if (typeof o.components[fileName] == "undefined") {
o.components[fileName] = new o.Component(fileName);
}
/*
for (i = 0; i < callbacks.length; i++) {
if (typeof callbacks[i] === "function") {
callbacks[i]();
}
}
*/
o.components[fileName].name = mainClassName;
o.components[fileName].isInstalled = true;
o.components[fileName].callbacks = callbacks;
// TODO: Add description and credits
//o.components[fileName].description = "";
//o.components[fileName].credits = "";
o[mainClassName] = componentClass;
}
return this;
},
getComponentByName: function (componentName) {
var o = this;
for (var cKey in o.components) {
if (o.components[cKey].name == componentName) {
return o.components[cKey];
}
};
return;
},
areComponentsLoaded: function (componentNameArr) {
var o = this, areLoaded = true;
if (typeof componentNameArr !== 'object') {
return areLoaded;
}
for (var i = 0; i < componentNameArr.length; i++) {
if (!o.isComponentInstalled(componentNameArr[i])) { areLoaded = false; }
};
return areLoaded;
},
isComponentInstalled: function (componentName) {
var comp = this.getComponentByName(componentName);
return (comp && comp.isInstalled);
},
loadComponents : function(arr, path){
var o = this;
var componentName;
path = (typeof path === 'undefined') ? "rocketboots/" : path;
for (var i = 0, al = arr.length; i < al; i++){
componentName = arr[i];
if (typeof o.components[componentName] == "undefined") {
o.components[componentName] = new o.Component(componentName);
o.loadScript(path + arr[i], function(){
o.components[componentName].isLoaded = true;
});
} else {
//console.warn("Trying to load", componentName, "component that already exists.");
}
}
return this;
},
loadCustomComponents : function (arr, path) {
path = (typeof path === 'undefined') ? "" : path;
return this.loadComponents(arr, path);
},
areAllComponentsLoaded : function(){
var o = this;
var componentCount = 0,
componentsInstalledCount = 0;
for (var c in o.components) {
// if (o.components.hasOwnProperty(c)) { do stuff }
componentCount++;
if (o.components[c].isInstalled) componentsInstalledCount++;
}
console.log("RB Components Installed: " + componentsInstalledCount + "/" + componentCount);
return (componentsInstalledCount >= componentCount);
},
//==== Ready and Init Functions
ready : function(callback){
if (typeof callback == "function") {
if (this.isInitialized) {
callback(this);
} else {
this.readyFunctions.push(callback);
}
} else {
console.error("Ready argument (callback) not a function");
}
return this;
},
runReadyFunctions : function(){
var o = this;
// Loop over readyFunctions and run each one
var f, fn;
for (var i = 0; o.readyFunctions.length > 0; i++){
f = o.readyFunctions.splice(i,1);
fn = f[0];
fn(o);
}
return this;
},
init : function(attempt){
var o = this;
// TODO: allow dependecies to be injected rather than forcing them to be on the window scope
var isJQueryUndefined = (typeof $ === "undefined");
var isLodashUndefined = (typeof _ === "undefined");
var areRequiredScriptsMissing = isJQueryUndefined || isLodashUndefined;
if (typeof attempt === "undefined") {
attempt = 1;
} else if (attempt > o._MAX_ATTEMPTS) {
console.error("Could not initialize RocketBoots: too many attempts");
return false;
} else {
attempt++;
}
//console.log("RB Init", attempt, (areRequiredScriptsMissing ? "Waiting on required objects from external scripts" : ""));
if (!isJQueryUndefined) {
o.$ = $;
o.$('#' + o._BOOTING_ELEMENT_ID).show();
}
if (!isLodashUndefined) {
o._ = _;
o.each = o.forEach = _.each;
}
function tryAgain () {
// Clear previous to stop multiple inits from happening
window.clearTimeout(o._initTimer);
o._initTimer = window.setTimeout(function(){
o.init(attempt);
}, (attempt * 10));
}
// On first time through, do some things
if (attempt === 1) {
// Create "rb" alias
if (typeof window.rb !== "undefined") {
o._rb = window.rb;
}
window.rb = o;
// Aliases
o.window = window;
o.document = window.document;
// Load default components
// TODO: make this configurable
this.loadComponents(["Game"]);
// Load required scripts
if (isJQueryUndefined) {
o.loadScript("libs/jquery-2.2.4.min", function(){
//o.init(1);
});
}
if (isLodashUndefined) {
o.loadScript("libs/lodash.min", function(){ });
}
}
if (o.areAllComponentsLoaded() && !areRequiredScriptsMissing) {
console.log("RB Init - All scripts and components are loaded.", o.loadedScripts, "\nRunning component callbacks...");
// TODO: These don't necessarily run in the correct order for requirements
o.each(o.components, function(component){
o.each(component.callbacks, function(callback){
console.log("Callback for", component.name);
callback(); // TODO: Make this run in the right context?
});
});
console.log("RB Init - Running Ready functions.\n");
o.$('#' + o._BOOTING_ELEMENT_ID).hide();
o.runReadyFunctions();
o.isInitialized = true;
return true;
}
tryAgain();
return false;
}
};
RocketBoots.init();
| Java |
<?php
namespace ErenMustafaOzdal\LaravelModulesBase;
use Illuminate\Database\Eloquent\Model;
class Neighborhood extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'neighborhoods';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['neighborhood'];
public $timestamps = false;
/*
|--------------------------------------------------------------------------
| Model Relations
|--------------------------------------------------------------------------
*/
/**
* Get the postal code of the district.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function postalCode()
{
return $this->hasOne('App\PostalCode');
}
/*
|--------------------------------------------------------------------------
| Model Set and Get Attributes
|--------------------------------------------------------------------------
*/
/**
* get the neighborhood uc first
*
* @return string
*/
public function getNeighborhoodUcFirstAttribute()
{
return ucfirst_tr($this->neighborhood);
}
}
| Java |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
// Key used by getwork/getblocktemplate miners.
// Allocated in StartRPCThreads, free'd in StopRPCThreads
CReserveKey* pMiningKey = NULL;
static std::string strRPCUserColonPass;
// These are created by StartRPCThreads, destroyed in StopRPCThreads
static asio::io_service* rpc_io_service = NULL;
static ssl::context* rpc_ssl_context = NULL;
static boost::thread_group* rpc_worker_group = NULL;
static inline unsigned short GetDefaultRPCPort()
{
return GetBoolArg("-testnet", false) ? 5745 : 13000;
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 12000000)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
// Accept the deprecated and ignored 'detach' boolean argument
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"Stop Netbits server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "Netbits server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name actor (function) okSafeMode threadSafe
// ------------------------ ----------------------- ---------- ----------
{ "help", &help, true, true },
{ "stop", &stop, true, true },
{ "getblockcount", &getblockcount, true, false },
{ "getconnectioncount", &getconnectioncount, true, false },
{ "getpeerinfo", &getpeerinfo, true, false },
{ "addnode", &addnode, true, true },
{ "getaddednodeinfo", &getaddednodeinfo, true, true },
{ "getdifficulty", &getdifficulty, true, false },
{ "getgenerate", &getgenerate, true, false },
{ "setgenerate", &setgenerate, true, false },
{ "gethashespersec", &gethashespersec, true, false },
{ "getinfo", &getinfo, true, false },
{ "getmininginfo", &getmininginfo, true, false },
{ "getnewaddress", &getnewaddress, true, false },
{ "getaccountaddress", &getaccountaddress, true, false },
{ "setaccount", &setaccount, true, false },
{ "getaccount", &getaccount, false, false },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false },
{ "sendtoaddress", &sendtoaddress, false, false },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false },
{ "backupwallet", &backupwallet, true, false },
{ "keypoolrefill", &keypoolrefill, true, false },
{ "walletpassphrase", &walletpassphrase, true, false },
{ "walletpassphrasechange", &walletpassphrasechange, false, false },
{ "walletlock", &walletlock, true, false },
{ "encryptwallet", &encryptwallet, false, false },
{ "validateaddress", &validateaddress, true, false },
{ "getbalance", &getbalance, false, false },
{ "move", &movecmd, false, false },
{ "sendfrom", &sendfrom, false, false },
{ "sendmany", &sendmany, false, false },
{ "addmultisigaddress", &addmultisigaddress, false, false },
{ "createmultisig", &createmultisig, true, true },
{ "getrawmempool", &getrawmempool, true, false },
{ "getblock", &getblock, false, false },
{ "getblockhash", &getblockhash, false, false },
{ "gettransaction", &gettransaction, false, false },
{ "listtransactions", &listtransactions, false, false },
{ "listaddressgroupings", &listaddressgroupings, false, false },
{ "signmessage", &signmessage, false, false },
{ "verifymessage", &verifymessage, false, false },
{ "getwork", &getwork, true, false },
{ "listaccounts", &listaccounts, false, false },
{ "settxfee", &settxfee, false, false },
{ "getblocktemplate", &getblocktemplate, true, false },
{ "submitblock", &submitblock, false, false },
{ "listsinceblock", &listsinceblock, false, false },
{ "dumpprivkey", &dumpprivkey, true, false },
{ "importprivkey", &importprivkey, false, false },
{ "listunspent", &listunspent, false, false },
{ "getrawtransaction", &getrawtransaction, false, false },
{ "createrawtransaction", &createrawtransaction, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false },
{ "signrawtransaction", &signrawtransaction, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false },
{ "gettxoutsetinfo", &gettxoutsetinfo, true, false },
{ "gettxout", &gettxout, true, false },
{ "lockunspent", &lockunspent, false, false },
{ "listlockunspent", &listlockunspent, false, false },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: netbits-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: netbits-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: netbits-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ServiceConnection(AcceptedConnection *conn);
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted && acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
else {
ServiceConnection(conn);
conn->close();
delete conn;
}
}
void StartRPCThreads()
{
// getwork/getblocktemplate mining rewards paid here:
pMiningKey = new CReserveKey(pwalletMain);
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if ((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"]))
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use netbitsd";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=netbitsrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"Netbits Alert\" admin@foo.com\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
assert(rpc_io_service == NULL);
rpc_io_service = new asio::io_service();
rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
const bool fUseSSL = GetBoolArg("-rpcssl");
if (fUseSSL)
{
rpc_ssl_context->set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
rpc_worker_group = new boost::thread_group();
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
}
void StopRPCThreads()
{
delete pMiningKey; pMiningKey = NULL;
if (rpc_io_service == NULL) return;
rpc_io_service->stop();
rpc_worker_group->join_all();
delete rpc_worker_group; rpc_worker_group = NULL;
delete rpc_ssl_context; rpc_ssl_context = NULL;
delete rpc_io_service; rpc_io_service = NULL;
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
void ServiceConnection(AcceptedConnection *conn)
{
bool fRun = true;
while (fRun)
{
int nProto = 0;
map<string, string> mapHeaders;
string strRequest, strMethod, strURI;
// Read HTTP request line
if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
break;
// Read HTTP message headers and body
ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
if (strURI != "/") {
conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
break;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->threadSafe)
result = pcmd->actor(params, false);
else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive HTTP reply status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Receive HTTP reply message headers and body
map<string, string> mapHeaders;
string strReply;
ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...) {
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| Java |
#!/usr/bin/env python3
# Copyright (c) 2015-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Utilities for manipulating blocks and transactions."""
import struct
import time
import unittest
from .address import (
key_to_p2sh_p2wpkh,
key_to_p2wpkh,
script_to_p2sh_p2wsh,
script_to_p2wsh,
)
from .messages import (
CBlock,
COIN,
COutPoint,
CTransaction,
CTxIn,
CTxInWitness,
CTxOut,
hash256,
ser_uint256,
tx_from_hex,
uint256_from_str,
)
from .script import (
CScript,
CScriptNum,
CScriptOp,
OP_1,
OP_CHECKMULTISIG,
OP_CHECKSIG,
OP_RETURN,
OP_TRUE,
)
from .script_util import (
key_to_p2wpkh_script,
script_to_p2wsh_script,
)
from .util import assert_equal
WITNESS_SCALE_FACTOR = 4
MAX_BLOCK_SIGOPS = 20000
MAX_BLOCK_SIGOPS_WEIGHT = MAX_BLOCK_SIGOPS * WITNESS_SCALE_FACTOR
# Genesis block time (regtest)
TIME_GENESIS_BLOCK = 1296688602
# Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
COINBASE_MATURITY = 100
# Soft-fork activation heights
DERSIG_HEIGHT = 102 # BIP 66
CLTV_HEIGHT = 111 # BIP 65
CSV_ACTIVATION_HEIGHT = 432
# From BIP141
WITNESS_COMMITMENT_HEADER = b"\xaa\x21\xa9\xed"
NORMAL_GBT_REQUEST_PARAMS = {"rules": ["segwit"]}
VERSIONBITS_LAST_OLD_BLOCK_VERSION = 4
def create_block(hashprev=None, coinbase=None, ntime=None, *, version=None, tmpl=None, txlist=None):
"""Create a block (with regtest difficulty)."""
block = CBlock()
if tmpl is None:
tmpl = {}
block.nVersion = version or tmpl.get('version') or VERSIONBITS_LAST_OLD_BLOCK_VERSION
block.nTime = ntime or tmpl.get('curtime') or int(time.time() + 600)
block.hashPrevBlock = hashprev or int(tmpl['previousblockhash'], 0x10)
if tmpl and not tmpl.get('bits') is None:
block.nBits = struct.unpack('>I', bytes.fromhex(tmpl['bits']))[0]
else:
block.nBits = 0x207fffff # difficulty retargeting is disabled in REGTEST chainparams
if coinbase is None:
coinbase = create_coinbase(height=tmpl['height'])
block.vtx.append(coinbase)
if txlist:
for tx in txlist:
if not hasattr(tx, 'calc_sha256'):
tx = tx_from_hex(tx)
block.vtx.append(tx)
block.hashMerkleRoot = block.calc_merkle_root()
block.calc_sha256()
return block
def get_witness_script(witness_root, witness_nonce):
witness_commitment = uint256_from_str(hash256(ser_uint256(witness_root) + ser_uint256(witness_nonce)))
output_data = WITNESS_COMMITMENT_HEADER + ser_uint256(witness_commitment)
return CScript([OP_RETURN, output_data])
def add_witness_commitment(block, nonce=0):
"""Add a witness commitment to the block's coinbase transaction.
According to BIP141, blocks with witness rules active must commit to the
hash of all in-block transactions including witness."""
# First calculate the merkle root of the block's
# transactions, with witnesses.
witness_nonce = nonce
witness_root = block.calc_witness_merkle_root()
# witness_nonce should go to coinbase witness.
block.vtx[0].wit.vtxinwit = [CTxInWitness()]
block.vtx[0].wit.vtxinwit[0].scriptWitness.stack = [ser_uint256(witness_nonce)]
# witness commitment is the last OP_RETURN output in coinbase
block.vtx[0].vout.append(CTxOut(0, get_witness_script(witness_root, witness_nonce)))
block.vtx[0].rehash()
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
def script_BIP34_coinbase_height(height):
if height <= 16:
res = CScriptOp.encode_op_n(height)
# Append dummy to increase scriptSig size above 2 (see bad-cb-length consensus rule)
return CScript([res, OP_1])
return CScript([CScriptNum(height)])
def create_coinbase(height, pubkey=None, extra_output_script=None, fees=0, nValue=50):
"""Create a coinbase transaction.
If pubkey is passed in, the coinbase output will be a P2PK output;
otherwise an anyone-can-spend output.
If extra_output_script is given, make a 0-value output to that
script. This is useful to pad block weight/sigops as needed. """
coinbase = CTransaction()
coinbase.vin.append(CTxIn(COutPoint(0, 0xffffffff), script_BIP34_coinbase_height(height), 0xffffffff))
coinbaseoutput = CTxOut()
coinbaseoutput.nValue = nValue * COIN
if nValue == 50:
halvings = int(height / 150) # regtest
coinbaseoutput.nValue >>= halvings
coinbaseoutput.nValue += fees
if pubkey is not None:
coinbaseoutput.scriptPubKey = CScript([pubkey, OP_CHECKSIG])
else:
coinbaseoutput.scriptPubKey = CScript([OP_TRUE])
coinbase.vout = [coinbaseoutput]
if extra_output_script is not None:
coinbaseoutput2 = CTxOut()
coinbaseoutput2.nValue = 0
coinbaseoutput2.scriptPubKey = extra_output_script
coinbase.vout.append(coinbaseoutput2)
coinbase.calc_sha256()
return coinbase
def create_tx_with_script(prevtx, n, script_sig=b"", *, amount, script_pub_key=CScript()):
"""Return one-input, one-output transaction object
spending the prevtx's n-th output with the given amount.
Can optionally pass scriptPubKey and scriptSig, default is anyone-can-spend output.
"""
tx = CTransaction()
assert n < len(prevtx.vout)
tx.vin.append(CTxIn(COutPoint(prevtx.sha256, n), script_sig, 0xffffffff))
tx.vout.append(CTxOut(amount, script_pub_key))
tx.calc_sha256()
return tx
def create_transaction(node, txid, to_address, *, amount):
""" Return signed transaction spending the first output of the
input txid. Note that the node must have a wallet that can
sign for the output that is being spent.
"""
raw_tx = create_raw_transaction(node, txid, to_address, amount=amount)
tx = tx_from_hex(raw_tx)
return tx
def create_raw_transaction(node, txid, to_address, *, amount):
""" Return raw signed transaction spending the first output of the
input txid. Note that the node must have a wallet that can sign
for the output that is being spent.
"""
psbt = node.createpsbt(inputs=[{"txid": txid, "vout": 0}], outputs={to_address: amount})
for _ in range(2):
for w in node.listwallets():
wrpc = node.get_wallet_rpc(w)
signed_psbt = wrpc.walletprocesspsbt(psbt)
psbt = signed_psbt['psbt']
final_psbt = node.finalizepsbt(psbt)
assert_equal(final_psbt["complete"], True)
return final_psbt['hex']
def get_legacy_sigopcount_block(block, accurate=True):
count = 0
for tx in block.vtx:
count += get_legacy_sigopcount_tx(tx, accurate)
return count
def get_legacy_sigopcount_tx(tx, accurate=True):
count = 0
for i in tx.vout:
count += i.scriptPubKey.GetSigOpCount(accurate)
for j in tx.vin:
# scriptSig might be of type bytes, so convert to CScript for the moment
count += CScript(j.scriptSig).GetSigOpCount(accurate)
return count
def witness_script(use_p2wsh, pubkey):
"""Create a scriptPubKey for a pay-to-witness TxOut.
This is either a P2WPKH output for the given pubkey, or a P2WSH output of a
1-of-1 multisig for the given pubkey. Returns the hex encoding of the
scriptPubKey."""
if not use_p2wsh:
# P2WPKH instead
pkscript = key_to_p2wpkh_script(pubkey)
else:
# 1-of-1 multisig
witness_script = CScript([OP_1, bytes.fromhex(pubkey), OP_1, OP_CHECKMULTISIG])
pkscript = script_to_p2wsh_script(witness_script)
return pkscript.hex()
def create_witness_tx(node, use_p2wsh, utxo, pubkey, encode_p2sh, amount):
"""Return a transaction (in hex) that spends the given utxo to a segwit output.
Optionally wrap the segwit output using P2SH."""
if use_p2wsh:
program = CScript([OP_1, bytes.fromhex(pubkey), OP_1, OP_CHECKMULTISIG])
addr = script_to_p2sh_p2wsh(program) if encode_p2sh else script_to_p2wsh(program)
else:
addr = key_to_p2sh_p2wpkh(pubkey) if encode_p2sh else key_to_p2wpkh(pubkey)
if not encode_p2sh:
assert_equal(node.getaddressinfo(addr)['scriptPubKey'], witness_script(use_p2wsh, pubkey))
return node.createrawtransaction([utxo], {addr: amount})
def send_to_witness(use_p2wsh, node, utxo, pubkey, encode_p2sh, amount, sign=True, insert_redeem_script=""):
"""Create a transaction spending a given utxo to a segwit output.
The output corresponds to the given pubkey: use_p2wsh determines whether to
use P2WPKH or P2WSH; encode_p2sh determines whether to wrap in P2SH.
sign=True will have the given node sign the transaction.
insert_redeem_script will be added to the scriptSig, if given."""
tx_to_witness = create_witness_tx(node, use_p2wsh, utxo, pubkey, encode_p2sh, amount)
if (sign):
signed = node.signrawtransactionwithwallet(tx_to_witness)
assert "errors" not in signed or len(["errors"]) == 0
return node.sendrawtransaction(signed["hex"])
else:
if (insert_redeem_script):
tx = tx_from_hex(tx_to_witness)
tx.vin[0].scriptSig += CScript([bytes.fromhex(insert_redeem_script)])
tx_to_witness = tx.serialize().hex()
return node.sendrawtransaction(tx_to_witness)
class TestFrameworkBlockTools(unittest.TestCase):
def test_create_coinbase(self):
height = 20
coinbase_tx = create_coinbase(height=height)
assert_equal(CScriptNum.decode(coinbase_tx.vin[0].scriptSig), height)
| Java |
#include "StdAfx.h"
#include "Distance Joint Description.h"
#include "Spring Description.h"
#include "Distance Joint.h"
#include <NxDistanceJointDesc.h>
using namespace StillDesign::PhysX;
DistanceJointDescription::DistanceJointDescription() : JointDescription( new NxDistanceJointDesc() )
{
}
DistanceJointDescription::DistanceJointDescription( NxDistanceJointDesc* desc ) : JointDescription( desc )
{
}
float DistanceJointDescription::MinimumDistance::get()
{
return this->UnmanagedPointer->minDistance;
}
void DistanceJointDescription::MinimumDistance::set( float value )
{
this->UnmanagedPointer->minDistance = value;
}
float DistanceJointDescription::MaximumDistance::get()
{
return this->UnmanagedPointer->maxDistance;
}
void DistanceJointDescription::MaximumDistance::set( float value )
{
this->UnmanagedPointer->maxDistance = value;
}
SpringDescription DistanceJointDescription::Spring::get()
{
return (SpringDescription)this->UnmanagedPointer->spring;
}
void DistanceJointDescription::Spring::set( SpringDescription value )
{
this->UnmanagedPointer->spring = (NxSpringDesc)value;
}
DistanceJointFlag DistanceJointDescription::Flags::get()
{
return (DistanceJointFlag)this->UnmanagedPointer->flags;
}
void DistanceJointDescription::Flags::set( DistanceJointFlag value )
{
this->UnmanagedPointer->flags = (NxDistanceJointFlag)value;
}
NxDistanceJointDesc* DistanceJointDescription::UnmanagedPointer::get()
{
return (NxDistanceJointDesc*)JointDescription::UnmanagedPointer;
} | Java |
using UnityEngine;
using UnityEditor;
using System.Collections;
using UForms.Attributes;
namespace UForms.Controls.Fields
{
/// <summary>
///
/// </summary>
[ExposeControl( "Object Field", "Fields" )]
public class ObjectField : AbstractField< Object >
{
/// <summary>
///
/// </summary>
protected override Vector2 DefaultSize
{
get { return new Vector2( 200.0f, 16.0f ); }
}
/// <summary>
///
/// </summary>
protected override bool UseBackingFieldChangeDetection
{
get { return true; }
}
/// <summary>
///
/// </summary>
public System.Type Type { get; set; }
/// <summary>
///
/// </summary>
public bool AllowSceneObjects { get; set; }
public ObjectField() : base ()
{
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="allowSceneObjects"></param>
/// <param name="value"></param>
/// <param name="label"></param>
public ObjectField( System.Type type, bool allowSceneObjects = false, Object value = null, string label = "" ) : base( value, label )
{
Type = type;
AllowSceneObjects = allowSceneObjects;
}
/// <summary>
///
/// </summary>
/// <param name="position"></param>
/// <param name="size"></param>
/// <param name="type"></param>
/// <param name="allowSceneObjects"></param>
/// <param name="value"></param>
/// <param name="label"></param>
public ObjectField( Vector2 position, Vector2 size, System.Type type, bool allowSceneObjects = false, Object value = null, string label = "" ) : base( position, size, value, label )
{
Type = type;
AllowSceneObjects = allowSceneObjects;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected override Object DrawAndUpdateValue()
{
return EditorGUI.ObjectField( ScreenRect, Label, m_cachedValue, Type, AllowSceneObjects );
}
/// <summary>
///
/// </summary>
/// <param name="oldval"></param>
/// <param name="newval"></param>
/// <returns></returns>
protected override bool TestValueEquality( Object oldval, Object newval )
{
if ( oldval == null || newval == null )
{
if ( oldval == null && newval == null )
{
return true;
}
return false;
}
return oldval.Equals( newval );
}
}
} | Java |
using Microsoft.AspNetCore.Http;
using System.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.Extensions.Primitives;
using System.Globalization;
namespace TCPServer.ServerImplemetation
{
class TCPRequest : HttpRequest
{
private TCPRequest()
{
}
public static async Task<TCPRequest> Parse(TCPStream input, bool includeHeaders)
{
var r = new TCPRequest();
await r.ParseCore(input, includeHeaders).ConfigureAwait(false);
return r;
}
private async Task ParseCore(TCPStream stream, bool includeHeaders)
{
Method = await stream.ReadStringAync().ConfigureAwait(false);
var requestUri = await stream.ReadStringAync().ConfigureAwait(false);
var uri = new Uri(requestUri);
Scheme = uri.Scheme;
IsHttps = false;
Host = new HostString(uri.Host, uri.Port);
PathBase = new PathString(uri.AbsolutePath);
Path = new PathString(uri.AbsolutePath);
QueryString = new QueryString(uri.Query);
Query = new QueryCollection(Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query));
Protocol = "http";
if(includeHeaders)
{
var headers = new List<Tuple<string, string>>();
var headersCount = await stream.ReadVarIntAsync().ConfigureAwait(false);
for(int i = 0; i < (int)headersCount; i++)
{
var key = await stream.ReadStringAync().ConfigureAwait(false);
var value = await stream.ReadStringAync().ConfigureAwait(false);
headers.Add(Tuple.Create(key, value));
}
foreach(var h in headers.GroupBy(g => g.Item1, g => g.Item2))
{
Headers.Add(h.Key, new StringValues(h.ToArray()));
}
}
var hasContent = (await stream.ReadVarIntAsync().ConfigureAwait(false)) == 1;
if(hasContent)
{
var buffer = await stream.ReadBytesAync(TCPStream.ReadType.ManagedPool).ConfigureAwait(false);
Body = new MemoryStream(buffer.Array);
Body.SetLength(buffer.Count);
ContentLength = buffer.Count;
}
}
HttpContext _HttpContext;
public void SetHttpContext(HttpContext context)
{
if(context == null)
throw new ArgumentNullException(nameof(context));
_HttpContext = context;
}
public override HttpContext HttpContext => _HttpContext;
public override string Method
{
get;
set;
}
public override string Scheme
{
get;
set;
}
public override bool IsHttps
{
get;
set;
}
public override HostString Host
{
get;
set;
}
public override PathString PathBase
{
get;
set;
}
public override PathString Path
{
get;
set;
}
public override QueryString QueryString
{
get;
set;
}
public override IQueryCollection Query
{
get;
set;
}
public override string Protocol
{
get;
set;
}
IHeaderDictionary _Headers = new HeaderDictionary();
public override IHeaderDictionary Headers => _Headers;
public override IRequestCookieCollection Cookies
{
get;
set;
} = new RequestCookieCollection();
public override long? ContentLength
{
get
{
StringValues value;
if(!Headers.TryGetValue("Content-Length", out value))
return null;
return long.Parse(value.FirstOrDefault(), CultureInfo.InvariantCulture);
}
set
{
Headers.Remove("Content-Length");
if(value != null)
Headers.Add("Content-Length", value.Value.ToString(CultureInfo.InvariantCulture));
}
}
public override string ContentType
{
get
{
StringValues value;
if(!Headers.TryGetValue("Content-Type", out value))
return null;
return value.FirstOrDefault();
}
set
{
Headers.Remove("Content-Type");
if(value != null)
Headers.Add("Content-Type", new StringValues(value));
}
}
public override Stream Body
{
get;
set;
}
public override bool HasFormContentType => false;
public override IFormCollection Form
{
get;
set;
}
FormCollection _ReadFormAsync = new FormCollection(new Dictionary<string, Microsoft.Extensions.Primitives.StringValues>());
public override Task<IFormCollection> ReadFormAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult<IFormCollection>(_ReadFormAsync);
}
}
}
| Java |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UnitTests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c5d231db-9fb7-42cc-843f-72f9ca4ef087")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Java |
<?php
namespace VirtualPersistAPI\VirtualPersistBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class VirtualPersistExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
}
}
| Java |
import { Selector } from 'testcafe'
import { ROOT_URL, login } from '../e2e/utils'
// eslint-disable-next-line
fixture`imported data check`.beforeEach(async (t /*: TestController */) => {
await t.setNativeDialogHandler(() => true)
await t.navigateTo(`${ROOT_URL}/login`)
await login(t)
})
test('wait entry', async (t /*: TestController */) => {
await t
.expect(Selector('a').withText('Ask HN: single comment').exists)
.ok({ timeout: 20000 })
})
| Java |
---
layout: post
date: '2016-12-21'
title: "Compelling Strapless Sleeveless Full Back Floor Length Satin Sheath Wedding Dress "
category: Wedding Dress
tags: ["dress","full","floor","length","bride"]
image: http://www.starbrideapparel.com/21326-thickbox_default/compelling-strapless-sleeveless-full-back-floor-length-satin-sheath-wedding-dress-.jpg
---
Compelling Strapless Sleeveless Full Back Floor Length Satin Sheath Wedding Dress
On Sales: **$195.594**
<a href="https://www.starbrideapparel.com/wedding-dress/8580-compelling-strapless-sleeveless-full-back-floor-length-satin-sheath-wedding-dress--1463394479084.html"><amp-img layout="responsive" width="600" height="600" src="//www.starbrideapparel.com/21326-thickbox_default/compelling-strapless-sleeveless-full-back-floor-length-satin-sheath-wedding-dress-.jpg" alt="Compelling Strapless Sleeveless Full Back Floor Length Satin Sheath Wedding Dress 0" /></a>
<a href="https://www.starbrideapparel.com/wedding-dress/8580-compelling-strapless-sleeveless-full-back-floor-length-satin-sheath-wedding-dress--1463394479084.html"><amp-img layout="responsive" width="600" height="600" src="//www.starbrideapparel.com/21327-thickbox_default/compelling-strapless-sleeveless-full-back-floor-length-satin-sheath-wedding-dress-.jpg" alt="Compelling Strapless Sleeveless Full Back Floor Length Satin Sheath Wedding Dress 1" /></a>
Buy it: [Compelling Strapless Sleeveless Full Back Floor Length Satin Sheath Wedding Dress ](https://www.starbrideapparel.com/wedding-dress/8580-compelling-strapless-sleeveless-full-back-floor-length-satin-sheath-wedding-dress--1463394479084.html "Compelling Strapless Sleeveless Full Back Floor Length Satin Sheath Wedding Dress ")
View more: [Wedding Dress](https://www.starbrideapparel.com/80-wedding-dress "Wedding Dress") | Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>vergerpc.config — Utilities for reading verge configuration files — verge-python 0.1.3 documentation</title>
<link rel="stylesheet" href="_static/default.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '0.1.3',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<link rel="top" title="verge-python 0.1.3 documentation" href="index.html" />
<link rel="up" title="API reference" href="apireference.html" />
<link rel="prev" title="vergerpc.data — VERGE RPC service, data objects" href="vergerpc.data.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="vergerpc.data.html" title="vergerpc.data — VERGE RPC service, data objects"
accesskey="P">previous</a> |</li>
<li><a href="index.html">verge-python 0.1.3 documentation</a> »</li>
<li><a href="apireference.html" accesskey="U">API reference</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="module-vergerpc.config">
<span id="vergerpc-config-utilities-for-reading-verge-configuration-files"></span><h1><a class="reference internal" href="#module-vergerpc.config" title="vergerpc.config"><tt class="xref py py-mod docutils literal"><span class="pre">vergerpc.config</span></tt></a> — Utilities for reading verge configuration files<a class="headerlink" href="#module-vergerpc.config" title="Permalink to this headline">¶</a></h1>
<p>Utilities for reading verge configuration files.</p>
<dl class="function">
<dt id="vergerpc.config.read_config_file">
<tt class="descclassname">vergerpc.config.</tt><tt class="descname">read_config_file</tt><big>(</big><em>filename</em><big>)</big><a class="headerlink" href="#vergerpc.config.read_config_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Read a simple <tt class="docutils literal"><span class="pre">'='</span></tt>-delimited config file.
Raises <tt class="xref py py-const docutils literal"><span class="pre">IOError</span></tt> if unable to open file, or <tt class="xref py py-const docutils literal"><span class="pre">ValueError</span></tt>
if an parse error occurs.</p>
</dd></dl>
<dl class="function">
<dt id="vergerpc.config.read_default_config">
<tt class="descclassname">vergerpc.config.</tt><tt class="descname">read_default_config</tt><big>(</big><em>filename=None</em><big>)</big><a class="headerlink" href="#vergerpc.config.read_default_config" title="Permalink to this definition">¶</a></dt>
<dd><p>Read verge default configuration from the current user’s home directory.</p>
<p>Arguments:</p>
<ul class="simple">
<li><cite>filename</cite>: Path to a configuration file in a non-standard location (optional)</li>
</ul>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="vergerpc.data.html"
title="previous chapter"><tt class="docutils literal"><span class="pre">vergerpc.data</span></tt> — VERGE RPC service, data objects</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/vergerpc.config.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="vergerpc.data.html" title="vergerpc.data — VERGE RPC service, data objects"
>previous</a> |</li>
<li><a href="index.html">verge-python 0.1.3 documentation</a> »</li>
<li><a href="apireference.html" >API reference</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2016, verge-python developers.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.1.
</div>
</body>
</html> | Java |
---
published: true
layout: post
title: "LAHacks: The most bizarre hackathon experience in my life"
quote: My 10th hackathon.
image:
url: "/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1685.jpg"
source: null
color: ""
posted: Published
video: false
comments: true
---
It was 2am, my team and I were wandering around the streets, looking for wifi.
We visited Starbucks before that opened 24/7 around the university area. Unfortunately it was crowded with homeless people and part of the area inside the coffee house was closed.
So we kept walking and explored the nearby hotels. Thanks to the very kind front desk staff, we crushed at Vintage Westwood Horizons’ hotel lobby at 3 in the morning because the WiFi connection got cut off at Pauley Pavilion. The internet was back at that time after LAHacks organizer announced it on Twitter, but we were too lazy to walk back so we pulled out our laptop and worked there.
I worked a little, and tried to get some sleep. The journey from Seattle - Los Angeles - UCLA was tiring. Dylan woke me up at 6am and we walked back to Pauley.
## We met on Twitter
Arik, Dylan, Cary and I formed our team through Twitter. I tweeted to LAHacks organizer and they retweeted my tweet. Arik is a student flying from Tel Aviv and LAHacks was his last event he attended in the United States; Cary and Dylan are both computer science major at Cal Poly Pomona. <br>
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/twitter.png" width="100%" description="" %}
## The Design behind SnapChess
Mystery guest speaker, Evan Spiegel, CEO of Snapchat made [a deep but great speech](https://twitter.com/adithyaiscool/status/454854832205996032) about privacy on the stage([Keynote available at Scribd](http://www.scribd.com/doc/217768898/2014-LA-Hacks-Keynote)). Our idea was to make a parody out of it — so we built Snapchess within 36 hours, a democracy-mode chess game matchmaking web application. You have 10 seconds to decide your next move with your alliance. To make it more interesting and relevant to the audience, I had the idea of putting UCLA and USC in this game, since there is a rivalry between the two. And even better, you can hack the game — play on behalf of your enemy, make all the wrong moves, and completely ruins your enemy’s game.
I was inspired by a [Dribbble shot](https://dribbble.com/shots/710449-ursa-delaunay) using [Delaunay Raster script](http://www.creatogether.com/ai-delaunay-brush/), but unfortunately Scriptographer is not available on CS6 due to [Adobe’s automatic wrapping of native API issue](http://scriptographer.org/news/the-future-of-scriptographer-is-paper-js/). I tweeted Tomás, the owner of the Dribbble shot. He responded promptly and suggested me to use [Dmesh](http://dmesh.thedofl.com/) instead. I explored to use the tool for the first time, and the result was surprisingly beautiful.
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Kodiak-Bear-small.jpg" width="100%" description="Original image of the bear I googled on the web. I do not own the copyright of this image." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-27 at 12.54.56 AM.png" width="100%" description="Process for converting in Dmesh." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-12 at 12.57.25 PM.png" width="100%" description="Working on Illustrator to take out the points and refine the design." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/bear-01.png" width="100%" description="Cleaned up version of the bear mascot for UCLA." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/bear-final.png" width="100%" description="Final version of the UCLA bear with color scheme tweaks." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Usc_football_logo.gif" width="50%" description="I asked a guy from USC and he told me the trojans are more famous about the traveller. Apparently no one cares about the traveller mascot but I decided to use it anyway." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-12 at 4.23.00 PM.png" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/trojan-final-01.png" width="100%" description="Color scheme is tweaked and here’s the final version for USC mascot." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/logo-01.png" width="100%" description="Final version of logo for Snapchess" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-12 at 11.53.31 PM.png" width="100%" description="Screenshot of the front page before I worked on the CSS styling. The links work." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-13 at 3.00.35 AM.png" width="100%" description="I used Bootplus framework and apply the design for the frontpage." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-12 at 5.23.39 PM.png" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-13 at 1.40.13 AM.png" width="100%" description="PHP master Arik was debugging on the game page. This was the screenshot before styling." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-27 at 1.04.29 AM.png" width="100%" description="Game page integrated with homepage design and CSS styling." %}
<iframe width="100%" height="360" src="//www.youtube.com/embed/guKuQJ4Qx_0" frameborder="0" allowfullscreen></iframe>
{% include image.html url="" width="0" description="Demo of Snapchess. I’m sorry if you don’t like Electronic Music :/ http://youtu.be/guKuQJ4Qx_0" %}
## The End
We had an expo after the hackathon was over and we were lining up on the table demoing our hacks. It was like a little SXSW at the event and I really like the idea. One of the feedback we received, which I think is helpful — is to create a login system which enables users to play based on weight and priority if you make the right moves most of the times.
We did not end up winning and I have expected that, since we did not use any of the sponsor’s API. Is SnapChess solving a big problem? No. But there’s currently no matchmaking for chess board game on the web right now([Twitch Plays Pokemon](http://www.twitch.tv/twitchplayspokemon) for Chess). Is it fun? I would say yes.
Crushing at the hotel lobby at 3 in the morning and sleeping under the staircase at Pauley Pavilion — I had the most bizarre yet fun experience by attending the largest hackathon in my life(hacking with 1400 people!). I am really thankful for the organizers to make the event all possible, especially the prompt respond on Twitter.
Achievement unlocked.
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1626.jpg" width="100%" description="Meeting Dylan and Arik for the first time after I flew in from Seattle on Friday afternoon." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1628.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1635.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1640.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1643.jpg" width="100%" description="From left to right: Arik, Cary, Dylan and Dylan’s cousin." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1644.jpg" width="100%" description="Waiting in the queue before entering Pauley." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1652.jpg" width="100%" description="LAHacks is the Disneyland of hackathons. Yes you need a wristband to go in." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1653.jpg" width="100%" description="Crushing and coding at the hotel lobby at 3 in the morning." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1654.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1662.jpg" width="100%" description="In-And-Out Burger near UCLA." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1663.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1664.jpg" width="100%" description="Having dinner with Arik at BBQ Chicken." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1665.jpg" width="100%" description="We skipped the Chipotle provided by LAHacks. That was worth it." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1667.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1672.jpg" width="100%" description="Alexis Ohanian and I founded Raddit, a redesigned version of Reddit 2.0 during LAHacks. It was pretty rad." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1673.jpg" width="100%" description="Just happy to get my book signed. When Alexis came to UW, I was at HackAtBrown hackathon. When he came to Brown University, I was back to UW. So finally we met." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1676.jpg" width="100%" description="Swallow pizza, drink red bull, and print all fibonacci number using python. “Disqualified, memory leaks.”" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1679.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1681.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1683.jpg" width="100%" description="Adib and I formed a team during the first hackathon in my life — Mega CodeDay Seattle and we won 1st place. Now is my 10th hackathon. Time flies." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1685.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1686.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1688.jpg" width="100%" description="Arik, the PHP master and me." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1690.jpg" width="100%" description="Demoing at the expo." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1691.jpg" width="100%" description="Tred team demoed the Oculus Rift Treadmill system to let you physically walk in your virtual world. They won 1st place at LAHacks and the team members are Shariq Hashme, Charlie Hulcher, and Jake Rye. Youtube video: http://youtu.be/XcX1uGFR6SE" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1692.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1693.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1694.jpg" width="100%" description="Table#38: 15 years old highschool freshman made Gorrila Warfare shooting game." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1695.jpg" width="100%" description="Table #31: Game maps your finger with touchdevelop using Makey makey and picks up potatoes." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1703.jpg" width="100%" description="Table #32: Moozik lets users to type in their favorite artist and explore new music with similar genre. Built w/ gracenote & @rdio api" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1706.jpg" width="100%" description="Table #28: Crowdbox crowsources songs by letting users to vote on songs to be played in events" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1708.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1710.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1711.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1713.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1715.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1747.jpg" width="100%" description="" %}
<br>
*This post is originally published at [Medium.com](https://medium.com/p/9ff0e33a98e3), but it is a shorter version with no additional pictures.*
*Feel free to send me a tweet on Twitter if you have any feedback for me ☺*
Demo: [http://snapchess.co](http://snapchess.co)
Feel free to fork: [https://github.com/lcdvirgo/snapchess](https://github.com/lcdvirgo/snapchess)
ChallengePost: [http://lahacks.challengepost.com/submissions/22803-snapchess](http://lahacks.challengepost.com/submissions/22803-snapchess)
LA Weekly coverage: [http://www.laweekly.com/informer/2014/04/12/ucla-hosts-biggest-hackathon-in-history](http://www.laweekly.com/informer/2014/04/12/ucla-hosts-biggest-hackathon-in-history)
| Java |
<div itemprop="description" class="col-12">
<div [innerHTML]="description | sanitizeHtml"></div>
</div>
| Java |
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; only version 2 of the License is applicable.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# This plugin is to monitor queue lengths in Redis. Based on redis_info.py by
# Garret Heaton <powdahound at gmail.com>, hence the GPL at the top.
import collectd
from contextlib import closing, contextmanager
import socket
# Host to connect to. Override in config by specifying 'Host'.
REDIS_HOST = 'localhost'
# Port to connect on. Override in config by specifying 'Port'.
REDIS_PORT = 6379
# Verbose logging on/off. Override in config by specifying 'Verbose'.
VERBOSE_LOGGING = False
# Queue names to monitor. Override in config by specifying 'Queues'.
QUEUE_NAMES = []
def fetch_queue_lengths(queue_names):
"""Connect to Redis server and request queue lengths.
Return a dictionary from queue names to integers.
"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((REDIS_HOST, REDIS_PORT))
log_verbose('Connected to Redis at %s:%s' % (REDIS_HOST, REDIS_PORT))
except socket.error, e:
collectd.error('redis_queues plugin: Error connecting to %s:%d - %r'
% (REDIS_HOST, REDIS_PORT, e))
return None
queue_lengths = {}
with closing(s) as redis_socket:
for queue_name in queue_names:
log_verbose('Requesting length of queue %s' % queue_name)
redis_socket.sendall('llen %s\r\n' % queue_name)
with closing(redis_socket.makefile('r')) as response_file:
response = response_file.readline()
if response.startswith(':'):
try:
queue_lengths[queue_name] = int(response[1:-1])
except ValueError:
log_verbose('Invalid response: %r' % response)
else:
log_verbose('Invalid response: %r' % response)
return queue_lengths
def configure_callback(conf):
"""Receive configuration block"""
global REDIS_HOST, REDIS_PORT, VERBOSE_LOGGING, QUEUE_NAMES
for node in conf.children:
if node.key == 'Host':
REDIS_HOST = node.values[0]
elif node.key == 'Port':
REDIS_PORT = int(node.values[0])
elif node.key == 'Verbose':
VERBOSE_LOGGING = bool(node.values[0])
elif node.key == 'Queues':
QUEUE_NAMES = list(node.values)
else:
collectd.warning('redis_queues plugin: Unknown config key: %s.'
% node.key)
log_verbose('Configured with host=%s, port=%s' % (REDIS_HOST, REDIS_PORT))
for queue in QUEUE_NAMES:
log_verbose('Watching queue %s' % queue)
if not QUEUE_NAMES:
log_verbose('Not watching any queues')
def read_callback():
log_verbose('Read callback called')
queue_lengths = fetch_queue_lengths(QUEUE_NAMES)
if queue_lengths is None:
# An earlier error, reported to collectd by fetch_queue_lengths
return
for queue_name, queue_length in queue_lengths.items():
log_verbose('Sending value: %s=%s' % (queue_name, queue_length))
val = collectd.Values(plugin='redis_queues')
val.type = 'gauge'
val.type_instance = queue_name
val.values = [queue_length]
val.dispatch()
def log_verbose(msg):
if not VERBOSE_LOGGING:
return
collectd.info('redis plugin [verbose]: %s' % msg)
# register callbacks
collectd.register_config(configure_callback)
collectd.register_read(read_callback)
| Java |
from .DiscreteFactor import State, DiscreteFactor
from .CPD import TabularCPD
from .JointProbabilityDistribution import JointProbabilityDistribution
__all__ = ['TabularCPD',
'DiscreteFactor',
'State'
]
| Java |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Dev to DevOps</title>
<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
<meta name="author" content="Hakim El Hattab">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="css/reveal.min.css">
<link rel="stylesheet" href="css/theme/sky.css" id="theme">
<link rel="stylesheet" href="css/dev2devops.css">
<!-- For syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- If the query includes 'print-pdf', use the PDF print sheet -->
<script>
document.write( '<link rel="stylesheet" href="css/print/' + ( window.location.search.match( /print-pdf/gi ) ? 'pdf' : 'paper' ) + '.css" type="text/css" media="print">' );
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class='screen-logo'>
<div style='position: absolute; left: 20px; bottom: 20px; opacity: 0.5;'>
<img src='img/constant-contact-logo.png' width='250'>
</div>
</div>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h3>Intro to DevOps</h3>
<p>Hi, my name is Dinshaw.</p>
</section>
<section>
<h2>Computers</h2>
<p>The cause of – and the solution to – all of life's problems.</p>
</section>
<section>
<h2>A Brief History of Computing</h2>
</section>
<section>
<img src="img/colosus.jpg">
<h3>Mainframe</h3>
</section>
<section>
<img src="img/punch-cards.jpg">
<h3>Punch Cards</h3>
</section>
<section>
<img src="img/computer.jpg">
<h3>Personal Computers</h3>
</section>
<section class='the-wall-goes-up'>
<h3><span>Users . . .</span> The Wall <span>. . . Operations</span></h3>
</section>
<section>
<img src="img/patrick.jpg">
<h3>Patrick Dubois</h3>
<p>The 'Godfather' of DevOps</p>
</section>
<section>
<h3>10+ Deploys Per Day:</h3>
<h3>Dev and Ops Cooperation at Flickr</h3>
<p>John Allspaw and Paul Hammond</p>
<p>@ Velocity Conference 2009, San Jose</p>
</section>
<section>
<img src="img/spock-scotty.jpg">
</section>
<section>
<h1>#devops</h1>
</section>
<section>
<img src='img/culture.jpg'>
<h3>Culture</h3>
</section>
<section>
<img src='img/computer.jpg'>
<h3>Tools</h3>
</section>
<section>
<h3>... habits [tools & culture] that allow us to survive in <em><strong>The Danger Zone</strong></em>.</h3>
</section>
<section>
<h3>TurboTax</h3>
<p>165 new-feature experiments in the 3 month tax season</p>
<p><a href="http://network.intuit.com/2011/04/20/leadership-in-the-agile-age/">Economist conference 2011</a></p>
</section>
<section>
<h3>Puppet: State of DevOps Report</h3>
<p>'DevOps' up 50% on Linkedin keyword searches</p>
</section>
<section>
<h3>Puppet: What is a DevOps Engineer?</h3>
<ul>
<li class='fragment'>Coding/Scripting</li>
<li class='fragment'>Strong grasp of automation tools</li>
<li class='fragment'>Process re-engineering</li>
<li class='fragment'>A focus on business outcomes</li>
<li class='fragment'>Communication & Collaboration</li>
</ul>
</section>
<section>
<h2>Questions?</h2>
</section>
<section>
<h2>Puppet & Chef</h2>
<ul>
<li>Configuration Management</li>
<li>Portable</li>
<li>Repeatable</li>
</ul>
</section>
<section>
<h2>Puppet</h2>
<ul>
<li>http://puppetlabs.com/</li>
<li>Ruby-like</li>
<li>Modules @ Puppet Forge</li>
</ul>
<pre>
<code>
package { "gtypist":
ensure => installed,
provider => homebrew,
}
package { "redis":
ensure => installed,
provider => homebrew,
}
</code>
</pre>
</section>
<section>
<h2>Chef</h2>
<ul>
<li>http://www.getchef.com/</li>
<li>Opscode</li>
<li>Ruby</li>
<li>Cookbooks @ Opscode Community</li>
</ul>
<pre>
<code>
package "mysql" do
action :install
end
package "redis" do
action :install
end
</code>
</pre>
</section>
<section>
<h2>Vagrant</h2>
<p>http://www.vagrantup.com/</p>
<pre>
<code>
Vagrant.configure do |config|
config.vm.provision "puppet" do |puppet|
puppet.manifests_path = "my_manifests"
puppet.manifest_file = "default.pp"
end
end
</code>
</pre>
</section>
<section>
<h2>You build it; you run it.</h2>
<p>Deliver working code AND the environment it runs in.</p>
</section>
<section>
<h2>T.D.D.</h2>
<div>
<blockquote>
"If you tell the truth, you don't have to remember anything."
</blockquote>
<small class="author">- Mark Twain</small>
</div>
<p>Dev and Test are no longer separable</p>
</section>
<section>
<h2>What we need from Ops</h2>
<ul>
<li class='fragment'>One button environment</li>
<li class='fragment'>One button deploy</li>
</ul>
</section>
<section>
<h3>First Steps:</h3>
<ul>
<li class='fragment'>Automate something simple</li>
<ul>
<li class='fragment'>White space</li>
<li class='fragment'>Dev Log rotation</li>
<li class='fragment'><a href="http://dotfiles.github.io/">.Dotfiles</a></li>
</ul>
<li class='fragment'>Automate something not-so-simple</li>
<ul>
<li class='fragment'>Development machine configuration</li>
<li class='fragment'>Production configuration</li>
</ul>
</ul>
</section>
<section>
<h3>Questions?</h3>
</section>
<section>
<h2>Google SRE</h2>
<p class='fragment'>Hand-off Readiness Review</p>
<ul>
<li class='fragment'>Types/Frequency of defects</li>
<li class='fragment'>Maturity of monitoring</li>
<li class='fragment'>Release process</li>
</ul>
</section>
<section>
<h2><a href="http://techblog.netflix.com/2012/07/chaos-monkey-released-into-wild.html">Netflix: Chaos Monkey</a></h2>
<p>April 21st, 2011 Amazon Web Service outage</p>
<p>Netfilx maintained availability</p>
</section>
<section>
<h2><a href="https://blog.twitter.com/2010/murder-fast-datacenter-code-deploys-using-bittorrent">Twitter Murder!</a></h2>
<p class='fragment'>40 minute to 12 seconds!</p>
</section>
<section>
<h2><a href="http://www.youtube.com/watch?v=-LxavzqLHj8">ChatOps at Github</a></h2>
<p>Automating common operational tasks with Hu-Bot</p>
<img src='img/hu-bot.jpg'>
</section>
<section>
<h3>
<a href='http://assets.en.oreilly.com/1/event/60/Velocity%20Culture%20Presentation.pdf'>Amazon @ O'rily Velocity Conf. 2011</a>
</h3>
<ul>
<li class='fragment'>A deploy every 11.6 seconds</li>
<li class='fragment'>Max deployments per hour: 10,000</li>
<li class='fragment'>30,000 hosts simultaneously receiving a deployment</li>
</ul>
</section>
<section class='links'>
<ul>
<li><a href="http://www.devopsdays.org/">DevOpsDays</a></li>
<li><a href='http://velocityconf.com/velocity2009'>Velocity Conference 2009, San Jose</a></li>
<li><a href='http://velocityconference.blip.tv/file/2284377/'>10+ Deploys Per Day: Dev and Ops Cooperation at Flickr</a></li>
<li><a href='http://continuousdelivery.com/2012/10/theres-no-such-thing-as-a-devops-team/'>No such thing as a DevOps team</a></li>
<li><a href='http://www.youtube.com/watch?v=disjFj4ruHg'>Why We Need DevOps Now</a></li>
<li><a href='http://info.puppetlabs.com/2013-state-of-devops-report.html'>State of DevOps 2013 - Puppet Report</a></li>
<li><a href="http://network.intuit.com/2011/04/20/leadership-in-the-agile-age/">Scott Cook on TurboTax @ Economist conference 2011</a></li>
<li><a href="http://dotfiles.github.io/">.Dotfiles</a></li>
<li><a href="http://docs.puppetlabs.com/learning/">Learning Puppet</a></li>
<li><a href="http://forge.puppetlabs.com/">Puppet Forge</a></li>
<li><a href='http://boxen.github.com/'>Boxen</a></li>
<li><a href="http://vimeo.com/61172067">Boxen presentation: Managing an army of laptops</a></li>
<li><a href='http://www.opscode.com/chef/'>Opscode</a></li>
<li><a href="http://docs.opscode.com/">Learning Chef</a></li>
<li><a href="https://github.com/opscode-cookbooks">Chef Cookbooks</a></li>
<li><a href='http://www.youtube.com/watch?v=ZC91gZv-Uao'>Chef intro: TDDing tmux</a></li>
<li><a href="http://techblog.netflix.com/2012/07/chaos-monkey-released-into-wild.html">Netflix: Chaos Monkey</a></li>
<li><a href="https://blog.twitter.com/2010/murder-fast-datacenter-code-deploys-using-bittorrent">Twitter Murder!</a></li>
<li><a href="http://www.youtube.com/watch?v=-LxavzqLHj8">ChatOps at Github</a></li>
<li><a href="http://assets.en.oreilly.com/1/event/60/Velocity%20Culture%20Presentation.pdf">Amazon: A deploy every 11 seconds slides</a></li>
<li><a href='http://vimeo.com/61172067'>Managing an Army of Laptops with Puppet</a></li>
<li><a href='http://www.youtube.com/watch?v=ZC91gZv-Uao'>TDDing tmux</a></li>
</ul>
</section>
<section>
<p>Intro to DevOps</p>
<p>Dinshaw Gobhai | <a href="mailto:dgobhai@constantcontact.com">dgobhai@constantcontact.com</a></p>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.min.js"></script>
<script>
// Full list of configuration options available here:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
theme: Reveal.getQueryHash().theme, // available themes are in /css/theme
transition: Reveal.getQueryHash().transition || 'default', // default/cube/page/concave/zoom/linear/fade/none
// Optional libraries used to extend on reveal.js
dependencies: [
{ src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
// { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
// { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
{ src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } },
// { src: 'plugin/search/search.js', async: true, condition: function() { return !!document.body.classList; } }
// { src: 'plugin/remotes/remotes.js', async: true, condition: function() { return !!document.body.classList; } }
]
});
</script>
</body>
</head>
</html>
| Java |
/*
Ql builtin and external frmt command.
format text
*/
package frmt
import (
"clive/cmd"
"clive/cmd/opt"
"clive/nchan"
"clive/zx"
"errors"
"fmt"
"io"
"strings"
"unicode"
)
type parFmt {
rc chan string
ec chan bool
}
func startPar(out io.Writer, indent0, indent string, max int) *parFmt {
rc := make(chan string)
ec := make(chan bool, 1)
wc := make(chan string)
pf := &parFmt{rc, ec}
go func() {
for s := range rc {
if s == "\n" {
wc <- s
continue
}
words := strings.Fields(strings.TrimSpace(s))
for _, w := range words {
wc <- w
}
}
close(wc)
}()
go func() {
pos, _ := fmt.Fprintf(out, "%s", indent0)
firstword := true
lastword := "x"
for w := range wc {
if len(w) == 0 {
continue
}
if w == "\n" {
fmt.Fprintf(out, "\n")
firstword = true
pos = 0
continue
}
if pos+len(w)+1 > max {
fmt.Fprintf(out, "\n")
pos, _ = fmt.Fprintf(out, "%s", indent)
firstword = true
}
if !firstword && len(w)>0 && !unicode.IsPunct(rune(w[0])) {
lastr := rune(lastword[len(lastword)-1])
if !strings.ContainsRune("([{", lastr) {
fmt.Fprintf(out, " ")
pos++
}
}
fmt.Fprintf(out, "%s", w)
pos += len(w)
firstword = false
lastword = w
}
if !firstword {
fmt.Fprintf(out, "\n")
}
close(ec)
}()
return pf
}
func (pf *parFmt) WriteString(s string) {
pf.rc <- s
}
func (pf *parFmt) Close() {
if pf == nil {
return
}
close(pf.rc)
<-pf.ec
}
type xCmd {
*cmd.Ctx
*opt.Flags
wid int
}
func tabsOf(s string) int {
for i := 0; i < len(s); i++ {
if s[i] != '\t' {
return i
}
}
return 0
}
func (x *xCmd) RunFile(d zx.Dir, dc <-chan []byte) error {
if dc == nil {
return nil
}
rc := nchan.Lines(dc, '\n')
var pf *parFmt
ntabs := 0
tabs := ""
doselect {
case <-x.Intrc:
close(rc, "interrupted")
pf.Close()
return errors.New("interrupted")
case s, ok := <-rc:
if !ok {
pf.Close()
return cerror(rc)
}
if s=="\n" || s=="" {
pf.Close()
pf = nil
x.Printf("\n")
continue
}
nt := tabsOf(s)
if nt != ntabs {
pf.Close()
pf = nil
ntabs = nt
tabs = strings.Repeat("\t", ntabs)
}
if pf == nil {
pf = startPar(x.Stdout, tabs, tabs, x.wid)
}
pf.WriteString(s)
}
pf.Close()
if err := cerror(rc); err != nil {
return err
}
return nil
}
func Run(c cmd.Ctx) (err error) {
argv := c.Args
x := &xCmd{Ctx: &c}
x.Flags = opt.New("{file}")
x.Argv0 = argv[0]
x.NewFlag("w", "wid: set max line width", &x.wid)
args, err := x.Parse(argv)
if err != nil {
x.Usage(x.Stderr)
return err
}
if x.wid < 10 {
x.wid = 70
}
if cmd.Ns == nil {
cmd.MkNS()
}
return cmd.RunFiles(x, args...)
}
| Java |
({
baseUrl: "../linesocial/public/js",
paths: {
jquery: "public/js/libs/jquery-1.9.1.js"
},
name: "main",
out: "main-built.js"
}) | Java |
<?php
namespace Usolv\TrackingBundle\Form\Model;
use Doctrine\Common\Collections\ArrayCollection;
class TimeRecordSearch
{
protected $project;
public function setProject($project)
{
$this->project = $project;
return $this;
}
public function getProject()
{
return $this->project;
}
}
| Java |
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Fieldset, Layout
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
from django.db import transaction
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from django_filters import FilterSet
from easy_select2 import Select2
from crispy_layout_mixin import form_actions, to_row
from utils import (TIPO_TELEFONE, YES_NO_CHOICES, get_medicos,
get_or_create_grupo)
from .models import Especialidade, EspecialidadeMedico, Usuario
class EspecialidadeMedicoFilterSet(FilterSet):
class Meta:
model = EspecialidadeMedico
fields = ['especialidade']
def __init__(self, *args, **kwargs):
super(EspecialidadeMedicoFilterSet, self).__init__(*args, **kwargs)
row1 = to_row([('especialidade', 12)])
self.form.helper = FormHelper()
self.form.helper.form_method = 'GET'
self.form.helper.layout = Layout(
Fieldset(_('Pesquisar Médico'),
row1, form_actions(save_label='Filtrar'))
)
class MudarSenhaForm(forms.Form):
nova_senha = forms.CharField(
label="Nova Senha", max_length=30,
widget=forms.PasswordInput(
attrs={'class': 'form-control form-control-lg',
'name': 'senha',
'placeholder': 'Nova Senha'}))
confirmar_senha = forms.CharField(
label="Confirmar Senha", max_length=30,
widget=forms.PasswordInput(
attrs={'class': 'form-control form-control-lg',
'name': 'confirmar_senha',
'placeholder': 'Confirmar Senha'}))
class LoginForm(AuthenticationForm):
username = forms.CharField(
label="Username", max_length=30,
widget=forms.TextInput(
attrs={'class': 'form-control form-control-lg',
'name': 'username',
'placeholder': 'Usuário'}))
password = forms.CharField(
label="Password", max_length=30,
widget=forms.PasswordInput(
attrs={'class': 'form-control',
'name': 'password',
'placeholder': 'Senha'}))
class UsuarioForm(ModelForm):
# Usuário
password = forms.CharField(
max_length=20,
label=_('Senha'),
widget=forms.PasswordInput())
password_confirm = forms.CharField(
max_length=20,
label=_('Confirmar Senha'),
widget=forms.PasswordInput())
class Meta:
model = Usuario
fields = ['username', 'email', 'nome', 'password', 'password_confirm',
'data_nascimento', 'sexo', 'plano', 'tipo', 'cep', 'end',
'numero', 'complemento', 'bairro', 'referencia',
'primeiro_telefone', 'segundo_telefone']
widgets = {'email': forms.TextInput(
attrs={'style': 'text-transform:lowercase;'})}
def __init__(self, *args, **kwargs):
super(UsuarioForm, self).__init__(*args, **kwargs)
self.fields['primeiro_telefone'].widget.attrs['class'] = 'telefone'
self.fields['segundo_telefone'].widget.attrs['class'] = 'telefone'
def valida_igualdade(self, texto1, texto2, msg):
if texto1 != texto2:
raise ValidationError(msg)
return True
def clean(self):
if ('password' not in self.cleaned_data or
'password_confirm' not in self.cleaned_data):
raise ValidationError(_('Favor informar senhas atuais ou novas'))
msg = _('As senhas não conferem.')
self.valida_igualdade(
self.cleaned_data['password'],
self.cleaned_data['password_confirm'],
msg)
try:
validate_password(self.cleaned_data['password'])
except ValidationError as error:
raise ValidationError(error)
return self.cleaned_data
@transaction.atomic
def save(self, commit=False):
usuario = super(UsuarioForm, self).save(commit)
# Cria User
u = User.objects.create(username=usuario.username, email=usuario.email)
u.set_password(self.cleaned_data['password'])
u.is_active = True
u.groups.add(get_or_create_grupo(self.cleaned_data['tipo'].descricao))
u.save()
usuario.user = u
usuario.save()
return usuario
class UsuarioEditForm(ModelForm):
# Primeiro Telefone
primeiro_tipo = forms.ChoiceField(
widget=forms.Select(),
choices=TIPO_TELEFONE,
label=_('Tipo Telefone'))
primeiro_ddd = forms.CharField(max_length=2, label=_('DDD'))
primeiro_numero = forms.CharField(max_length=10, label=_('Número'))
primeiro_principal = forms.TypedChoiceField(
widget=forms.Select(),
label=_('Telefone Principal?'),
choices=YES_NO_CHOICES)
# Primeiro Telefone
segundo_tipo = forms.ChoiceField(
required=False,
widget=forms.Select(),
choices=TIPO_TELEFONE,
label=_('Tipo Telefone'))
segundo_ddd = forms.CharField(required=False, max_length=2, label=_('DDD'))
segundo_numero = forms.CharField(
required=False, max_length=10, label=_('Número'))
segundo_principal = forms.ChoiceField(
required=False,
widget=forms.Select(),
label=_('Telefone Principal?'),
choices=YES_NO_CHOICES)
class Meta:
model = Usuario
fields = ['username', 'email', 'nome', 'data_nascimento', 'sexo',
'plano', 'tipo', 'cep', 'end', 'numero', 'complemento',
'bairro', 'referencia', 'primeiro_telefone',
'segundo_telefone']
widgets = {'username': forms.TextInput(attrs={'readonly': 'readonly'}),
'email': forms.TextInput(
attrs={'style': 'text-transform:lowercase;'}),
}
def __init__(self, *args, **kwargs):
super(UsuarioEditForm, self).__init__(*args, **kwargs)
self.fields['primeiro_telefone'].widget.attrs['class'] = 'telefone'
self.fields['segundo_telefone'].widget.attrs['class'] = 'telefone'
def valida_igualdade(self, texto1, texto2, msg):
if texto1 != texto2:
raise ValidationError(msg)
return True
def clean_primeiro_numero(self):
cleaned_data = self.cleaned_data
telefone = Telefone()
telefone.tipo = self.data['primeiro_tipo']
telefone.ddd = self.data['primeiro_ddd']
telefone.numero = self.data['primeiro_numero']
telefone.principal = self.data['primeiro_principal']
cleaned_data['primeiro_telefone'] = telefone
return cleaned_data
def clean_segundo_numero(self):
cleaned_data = self.cleaned_data
telefone = Telefone()
telefone.tipo = self.data['segundo_tipo']
telefone.ddd = self.data['segundo_ddd']
telefone.numero = self.data['segundo_numero']
telefone.principal = self.data['segundo_principal']
cleaned_data['segundo_telefone'] = telefone
return cleaned_data
@transaction.atomic
def save(self, commit=False):
usuario = super(UsuarioEditForm, self).save(commit)
# Primeiro telefone
tel = usuario.primeiro_telefone
tel.tipo = self.data['primeiro_tipo']
tel.ddd = self.data['primeiro_ddd']
tel.numero = self.data['primeiro_numero']
tel.principal = self.data['primeiro_principal']
tel.save()
usuario.primeiro_telefone = tel
# Segundo telefone
tel = usuario.segundo_telefone
if tel:
tel.tipo = self.data['segundo_tipo']
tel.ddd = self.data['segundo_ddd']
tel.numero = self.data['segundo_numero']
tel.principal = self.data['segundo_principal']
tel.save()
usuario.segundo_telefone = tel
# User
u = usuario.user
u.email = usuario.email
u.groups.remove(u.groups.first())
u.groups.add(get_or_create_grupo(self.cleaned_data['tipo'].descricao))
u.save()
usuario.save()
return usuario
class EspecialidadeMedicoForm(ModelForm):
medico = forms.ModelChoiceField(
queryset=get_medicos(),
widget=Select2(select2attrs={'width': '535px'}))
especialidade = forms.ModelChoiceField(
queryset=Especialidade.objects.all(),
widget=Select2(select2attrs={'width': '535px'}))
class Meta:
model = EspecialidadeMedico
fields = ['especialidade', 'medico']
| Java |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Freeform - Control Panel
*
* The Control Panel master class that handles all of the CP requests and displaying.
*
* @package Solspace:Freeform
* @author Solspace, Inc.
* @copyright Copyright (c) 2008-2014, Solspace, Inc.
* @link http://solspace.com/docs/freeform
* @license http://www.solspace.com/license_agreement
* @version 4.1.7
* @filesource freeform/mcp.freeform.php
*/
if ( ! class_exists('Module_builder_freeform'))
{
require_once 'addon_builder/module_builder.php';
}
class Freeform_mcp extends Module_builder_freeform
{
private $migration_batch_limit = 100;
private $pro_update = FALSE;
// --------------------------------------------------------------------
/**
* Constructor
*
* @access public
* @param bool Enable calling of methods based on URI string
* @return string
*/
public function __construct( $switch = TRUE )
{
parent::__construct();
// Install or Uninstall Request
if ((bool) $switch === FALSE) return;
if ( ! function_exists('lang'))
{
ee()->load->helper('language');
}
// --------------------------------------------
// Module Menu Items
// --------------------------------------------
$menu = array(
'module_forms' => array(
'link' => $this->base,
'title' => lang('forms')
),
'module_fields' => array(
'link' => $this->base . AMP . 'method=fields',
'title' => lang('fields')
),
'module_fieldtypes' => array(
'link' => $this->base . AMP . 'method=fieldtypes',
'title' => lang('fieldtypes')
),
'module_notifications' => array(
'link' => $this->base . AMP . 'method=notifications',
'title' => lang('notifications')
),
/*'module_export' => array(
'link' => $this->base . AMP . 'method=export',
'title' => lang('export')
),*/
'module_utilities' => array(
'link' => $this->base . AMP . 'method=utilities',
'title' => lang('utilities')
),
'module_preferences' => array(
'link' => $this->base . AMP . 'method=preferences',
'title' => lang('preferences')
),
'module_documentation' => array(
'link' => FREEFORM_DOCS_URL,
'title' => lang('help'),
'new_window' => TRUE
),
);
$this->cached_vars['lang_module_version'] = lang('freeform_module_version');
$this->cached_vars['module_version'] = FREEFORM_VERSION;
$this->cached_vars['module_menu_highlight'] = 'module_forms';
$this->cached_vars['inner_nav_links'] = array();
// -------------------------------------
// css includes. WOOT!
// -------------------------------------
$this->cached_vars['cp_stylesheet'] = array(
'chosen',
'standard_cp'
);
$this->cached_vars['cp_javascript'] = array(
'standard_cp.min',
'chosen.jquery.min'
);
// -------------------------------------
// custom CP?
// -------------------------------------
$debug_normal = (ee()->input->get_post('debug_normal') !== FALSE);
$is_crappy_ie_version = FALSE;
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if (stristr($ua, 'msie 6') OR
stristr($ua, 'msie 7') OR
stristr($ua, 'msie 8'))
{
//technically this should be true for any IE version, but...
$is_crappy_ie_version = TRUE;
}
if ( ! $debug_normal AND
! $is_crappy_ie_version AND
! $this->check_no($this->preference('use_solspace_mcp_style')))
{
$this->cached_vars['cp_stylesheet'][] = 'custom_cp';
}
//avoids AR collisions
$this->data->get_module_preferences();
$this->data->get_global_module_preferences();
$this->data->show_all_sites();
// -------------------------------------
// run upgrade or downgrade scripts
// -------------------------------------
if (FREEFORM_PRO AND $this->data->global_preference('ffp') === 'n' OR
! FREEFORM_PRO AND $this->data->global_preference('ffp') === 'y')
{
$_GET['method'] = 'freeform_module_update';
$this->pro_update = TRUE;
}
$this->cached_vars['module_menu'] = $menu;
}
// END Freeform_cp_base()
//---------------------------------------------------------------------
// begin views
//---------------------------------------------------------------------
// --------------------------------------------------------------------
/**
* Module's Main Homepage
*
* @access public
* @param string
* @return null
*/
public function index ($message='')
{
if ($message == '' AND ee()->input->get('msg') !== FALSE)
{
$message = lang(ee()->input->get('msg'));
}
return $this->forms($message);
}
// END index()
// --------------------------------------------------------------------
/**
* My Forms
*
* @access public
* @param string $message incoming message for flash data
* @return string html output
*/
public function forms($message = '')
{
// -------------------------------------
// Messages
// -------------------------------------
if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) )
{
$message = lang(ee()->input->get('msg'));
}
$this->cached_vars['message'] = $message;
//--------------------------------------------
// Crumbs and tab highlight
//--------------------------------------------
$new_form_link = $this->mod_link(array(
'method' => 'edit_form'
));
$this->cached_vars['new_form_link'] = $new_form_link;
$this->add_crumb( lang('forms') );
$this->freeform_add_right_link(lang('new_form'), $new_form_link);
$this->set_highlight('module_forms');
//--------------------------------------
// start vars
//--------------------------------------
$row_limit = $this->data->defaults['mcp_row_limit'];
$paginate = '';
$row_count = 0;
// -------------------------------------
// pagination?
// -------------------------------------
ee()->load->model('freeform_form_model');
if ( ! $this->data->show_all_sites())
{
ee()->freeform_form_model->where(
'site_id',
ee()->config->item('site_id')
);
}
$total_results = ee()->freeform_form_model->count(array(), FALSE);
// do we need pagination?
if ( $total_results > $row_limit )
{
$row_count = $this->get_post_or_zero('row');
$url = $this->mod_link(array(
'method' => 'forms'
));
//get pagination info
$pagination_data = $this->universal_pagination(array(
'total_results' => $total_results,
'limit' => $row_limit,
'current_page' => $row_count,
'pagination_config' => array('base_url' => $url),
'query_string_segment' => 'row'
));
ee()->freeform_form_model->limit(
$row_limit,
$pagination_data['pagination_page']
);
$paginate = $pagination_data['pagination_links'];
}
ee()->freeform_form_model->order_by('form_label');
$this->cached_vars['paginate'] = $paginate;
// -------------------------------------
// Did they upgrade from FF3?
// -------------------------------------
$this->cached_vars['legacy'] = FALSE;
$this->cached_vars['migrate_link'] = '';
ee()->load->library('freeform_migration');
if ( ee()->freeform_migration->legacy() === TRUE )
{
$this->cached_vars['legacy'] = TRUE;
$this->cached_vars['migrate_link'] = $this->mod_link(array('method' => 'utilities'));
}
// -------------------------------------
// data
// -------------------------------------
$rows = ee()->freeform_form_model->get();
$form_data = array();
if ($rows !== FALSE)
{
// -------------------------------------
// check for composer for each form
// -------------------------------------
$form_ids = array();
$potential_composer_ids = array();
foreach ($rows as $row)
{
$form_ids[] = $row['form_id'];
if ($this->is_positive_intlike($row['composer_id']))
{
$potential_composer_ids[$row['form_id']] = $row['composer_id'];
}
}
$has_composer = array();
if ( ! empty($potential_composer_ids))
{
ee()->load->model('freeform_composer_model');
$composer_ids = ee()->freeform_composer_model
->key('composer_id', 'composer_id')
->where('preview !=', 'y')
->where_in(
'composer_id',
array_values($potential_composer_ids)
)
->get();
if ( ! empty($composer_ids))
{
foreach ($potential_composer_ids as $form_id => $composer_id)
{
if (in_array($composer_id, $composer_ids))
{
$has_composer[$form_id] = $composer_id;
}
}
}
}
// -------------------------------------
// suppliment rows
// -------------------------------------
foreach ($rows as $row)
{
$row['submissions_count'] = (
$this->data->get_form_submissions_count($row['form_id'])
);
$row['moderate_count'] = (
$this->data->get_form_needs_moderation_count($row['form_id'])
);
$row['has_composer'] = isset(
$has_composer[$row['form_id']]
);
// -------------------------------------
// piles o' links
// -------------------------------------
$row['form_submissions_link'] = $this->mod_link(array(
'method' => 'entries',
'form_id' => $row['form_id']
));
$row['form_moderate_link'] = $this->mod_link(array(
'method' => 'moderate_entries',
'form_id' => $row['form_id'],
'search_status' => 'pending'
));
$row['form_edit_composer_link'] = $this->mod_link(array(
'method' => 'form_composer',
'form_id' => $row['form_id']
));
$row['form_settings_link'] = $this->mod_link(array(
'method' => 'edit_form',
'form_id' => $row['form_id']
));
$row['form_duplicate_link'] = $this->mod_link(array(
'method' => 'edit_form',
'duplicate_id' => $row['form_id']
));
$row['form_delete_link'] = $this->mod_link(array(
'method' => 'delete_confirm_form',
'form_id' => $row['form_id']
));
$form_data[] = $row;
}
}
$this->cached_vars['form_data'] = $form_data;
$this->cached_vars['form_url'] = $this->mod_link(array(
'method' => 'delete_confirm_form'
));
// ----------------------------------------
// Load vars
// ----------------------------------------
// -------------------------------------
// JS
// -------------------------------------
ee()->cp->add_js_script(
array('plugin' => array('tooltip', 'dataTables'))
);
// --------------------------------------------
// Load page
// --------------------------------------------
$this->cached_vars['current_page'] = $this->view(
'forms.html',
NULL,
TRUE
);
return $this->ee_cp_view('index.html');
}
//END forms
// --------------------------------------------------------------------
/**
* delete_confirm_form
*
* @access public
* @return string
*/
public function delete_confirm_form ()
{
$form_ids = ee()->input->get_post('form_id', TRUE);
if ( ! is_array($form_ids) AND
! $this->is_positive_intlike($form_ids) )
{
$this->actions()->full_stop(lang('no_form_ids_submitted'));
}
//already checked for numeric :p
if ( ! is_array($form_ids))
{
$form_ids = array($form_ids);
}
return $this->delete_confirm(
'delete_forms',
array('form_ids' => $form_ids),
'delete_form_confirmation'
);
}
//END delete_confirm_form
// --------------------------------------------------------------------
/**
* delete_forms
*
* @access public
* @return string
*/
public function delete_forms ($form_ids = array())
{
$message = 'delete_form_success';
if ( empty($form_ids) )
{
$form_ids = ee()->input->get_post('form_ids');
}
if ( ! is_array($form_ids) AND
$this->is_positive_intlike($form_ids))
{
$form_ids = array($form_ids);
}
//if everything is all nice and array like, DELORT
//but one last check on each item to make sure its a number
if ( is_array($form_ids))
{
ee()->load->library('freeform_forms');
foreach ($form_ids as $form_id)
{
if ($this->is_positive_intlike($form_id))
{
ee()->freeform_forms->delete_form($form_id);
}
}
}
//the voyage home
ee()->functions->redirect($this->mod_link(array(
'method' => 'index',
'msg' => $message
)));
}
//END delete_forms
// --------------------------------------------------------------------
/**
* Edit Form
*
* @access public
* @return string html output
*/
public function edit_form ()
{
// -------------------------------------
// form ID? we must be editing
// -------------------------------------
$form_id = $this->get_post_or_zero('form_id');
$update = $this->cached_vars['update'] = ($form_id != 0);
// -------------------------------------
// default data
// -------------------------------------
$inputs = array(
'form_id' => '0',
'form_name' => '',
'form_label' => '',
'default_status' => $this->data->defaults['default_form_status'],
'notify_admin' => 'n',
'notify_user' => 'n',
'user_email_field' => '',
'user_notification_id' => '0',
'admin_notification_id' => '0',
'admin_notification_email' => ee()->config->item('webmaster_email'),
'form_description' => '',
'template_id' => '0',
'composer_id' => '0',
'field_ids' => '',
'field_order' => '',
);
// -------------------------------------
// updating?
// -------------------------------------
if ($update)
{
$form_data = $this->data->get_form_info($form_id);
if ($form_data)
{
foreach ($form_data as $key => $value)
{
if ($key == 'admin_notification_email')
{
$value = str_replace('|', ', ', $value);
}
if ($key == 'field_ids')
{
$value = ( ! empty($value)) ? implode('|', $value) : '';
}
$inputs[$key] = form_prep($value);
}
}
else
{
$this->actions()->full_stop(lang('invalid_form_id'));
}
}
//--------------------------------------------
// Crumbs and tab highlight
//--------------------------------------------
$this->add_crumb(
lang('forms'),
$this->mod_link(array('method' => 'forms'))
);
$this->add_crumb(
$update ?
lang('update_form') . ': ' . $form_data['form_label'] :
lang('new_form')
);
$this->set_highlight('module_forms');
// -------------------------------------
// duplicating?
// -------------------------------------
$duplicate_id = $this->get_post_or_zero('duplicate_id');
$this->cached_vars['duplicate_id'] = $duplicate_id;
$this->cached_vars['duplicated'] = FALSE;
if ( ! $update AND $duplicate_id > 0)
{
$form_data = $this->data->get_form_info($duplicate_id);
if ($form_data)
{
foreach ($form_data as $key => $value)
{
if (in_array($key, array('form_id', 'form_label', 'form_name')))
{
continue;
}
if ($key == 'field_ids')
{
$value = ( ! empty($value)) ? implode('|', $value) : '';
}
if ($key == 'admin_notification_email')
{
$value = str_replace('|', ', ', $value);
}
$inputs[$key] = form_prep($value);
}
$this->cached_vars['duplicated'] = TRUE;
$this->cached_vars['duplicated_from'] = $form_data['form_label'];
}
}
if (isset($form_data['field_ids']) AND
! empty($form_data['field_ids']) AND
isset($form_data['field_order']) AND
! empty($form_data['field_order']))
{
$field_ids = $form_data['field_ids'];
if ( ! is_array($field_ids))
{
$field_ids = $this->actions()->pipe_split($field_ids);
}
$field_order = $form_data['field_order'];
if ( ! is_array($field_order))
{
$field_order = $this->actions()->pipe_split($field_order);
}
$missing_ids = array_diff($field_ids, $field_order);
$inputs['field_order'] = implode('|', array_merge($field_order, $missing_ids));
}
// -------------------------------------
// load inputs
// -------------------------------------
foreach ($inputs as $key => $value)
{
$this->cached_vars[$key] = $value;
}
// -------------------------------------
// select boxes
// -------------------------------------
$this->cached_vars['statuses'] = $this->data->get_form_statuses();
ee()->load->model('freeform_field_model');
$available_fields = ee()->freeform_field_model->get();
$available_fields = ($available_fields !== FALSE) ?
$available_fields :
array();
//fields
$this->cached_vars['available_fields'] = $available_fields;
//notifications
$this->cached_vars['notifications'] = $this->data->get_available_notification_templates();
// -------------------------------------
// user email fields
// -------------------------------------
$user_email_fields = array('' => lang('choose_user_email_field'));
$f_rows = ee()->freeform_field_model
->select('field_id, field_label, settings')
->get(array('field_type' => 'text'));
//we only want fields that are being validated as email
if ($f_rows)
{
foreach ($f_rows as $row)
{
$row_settings = json_decode($row['settings'], TRUE);
$row_settings = (is_array($row_settings)) ? $row_settings : array();
if (isset($row_settings['field_content_type']) AND
$row_settings['field_content_type'] == 'email')
{
$user_email_fields[$row['field_id']] = $row['field_label'];
}
}
}
$this->cached_vars['user_email_fields'] = $user_email_fields;
// ----------------------------------------
// Load vars
// ----------------------------------------
$this->cached_vars['form_uri'] = $this->mod_link(array(
'method' => 'save_form'
));
// -------------------------------------
// js libs
// -------------------------------------
$this->load_fancybox();
$this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min';
ee()->cp->add_js_script(array(
'ui' => array('draggable', 'droppable', 'sortable')
));
// --------------------------------------------
// Load page
// --------------------------------------------
$this->cached_vars['current_page'] = $this->view(
'edit_form.html',
NULL,
TRUE
);
return $this->ee_cp_view('index.html');
}
//END edit_form
// --------------------------------------------------------------------
/**
* form composer
*
* ajax form and field builder
*
* @access public
* @param string message lang line
* @return string html output
*/
public function form_composer ( $message = '' )
{
// -------------------------------------
// Messages
// -------------------------------------
if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) )
{
$message = lang(ee()->input->get('msg'));
}
$this->cached_vars['message'] = $message;
// -------------------------------------
// form_id
// -------------------------------------
$form_id = ee()->input->get_post('form_id', TRUE);
$form_data = $this->data->get_form_info($form_id);
if ( ! $form_data)
{
return $this->actions()->full_stop(lang('invalid_form_id'));
}
$update = $form_data['composer_id'] != 0;
//--------------------------------------------
// Crumbs and tab highlight
//--------------------------------------------
$this->add_crumb( lang('forms'), $this->base );
$this->add_crumb( lang('composer') . ': ' . $form_data['form_label'] );
$this->set_highlight('module_forms');
// -------------------------------------
// data
// -------------------------------------
$this->cached_vars['form_data'] = $form_data;
// -------------------------------------
// fields for composer
// -------------------------------------
ee()->load->model('freeform_field_model');
$available_fields = ee()->freeform_field_model
->where('composer_use', 'y')
->order_by('field_label')
->key('field_name')
->get();
$available_fields = ($available_fields !== FALSE) ?
$available_fields :
array();
// -------------------------------------
// templates
// -------------------------------------
ee()->load->model('freeform_template_model');
$available_templates = ee()->freeform_template_model
->where('enable_template', 'y')
->order_by('template_label')
->key('template_id', 'template_label')
->get();
$available_templates = ($available_templates !== FALSE) ?
$available_templates :
array();
// -------------------------------------
// get field output for composer
// -------------------------------------
ee()->load->library('freeform_fields');
$field_composer_output = array();
$field_id_list = array();
foreach ($available_fields as $field_name => $field_data)
{
$field_id_list[$field_data['field_id']] = $field_name;
//encode to keep JS from running
//camel case because its exposed in JS
$field_composer_output[$field_name] = $this->composer_field_data(
$field_data['field_id'],
$field_data,
TRUE
);
}
$this->cached_vars['field_id_list'] = $this->json_encode($field_id_list);
$this->cached_vars['field_composer_output_json'] = $this->json_encode($field_composer_output);
$this->cached_vars['available_fields'] = $available_fields;
$this->cached_vars['available_templates'] = $available_templates;
$this->cached_vars['prohibited_field_names'] = $this->data->prohibited_names;
$this->cached_vars['notifications'] = $this->data->get_available_notification_templates();
$this->cached_vars['disable_missing_submit_warning'] = $this->check_yes(
$this->preference('disable_missing_submit_warning')
);
// -------------------------------------
// previous composer data?
// -------------------------------------
$composer_data = '{}';
if ($form_data['composer_id'] > 0)
{
ee()->load->model('freeform_composer_model');
$composer = ee()->freeform_composer_model
->select('composer_data')
->where('composer_id', $form_data['composer_id'])
->get_row();
if ($composer !== FALSE)
{
$composer_data_test = $this->json_decode($composer['composer_data']);
if ($composer_data_test)
{
$composer_data = $composer['composer_data'];
}
}
}
$this->cached_vars['composer_layout_data'] = $composer_data;
// ----------------------------------------
// Load vars
// ----------------------------------------
$this->cached_vars['lang_allowed_html_tags'] = (
lang('allowed_html_tags') .
"<" . implode(">, <", $this->data->allowed_html_tags) . ">"
);
$this->cached_vars['captcha_dummy_url'] = $this->sc->addon_theme_url .
'images/captcha.png';
$this->cached_vars['new_field_url'] = $this->mod_link(array(
'method' => 'edit_field',
//this builds a URL, so yes this is intentionally a string
'modal' => 'true'
), TRUE);
$this->cached_vars['field_data_url'] = $this->mod_link(array(
'method' => 'composer_field_data'
), TRUE);
$this->cached_vars['composer_preview_url'] = $this->mod_link(array(
'method' => 'composer_preview',
'form_id' => $form_id
), TRUE);
$this->cached_vars['composer_ajax_save_url'] = $this->mod_link(array(
'method' => 'save_composer_data',
'form_id' => $form_id
), TRUE);
//
$this->cached_vars['composer_save_url'] = $this->mod_link(array(
'method' => 'save_composer_data',
'form_id' => $form_id
));
$this->cached_vars['allowed_html_tags'] = "'" .
implode("','", $this->data->allowed_html_tags) . "'";
// -------------------------------------
// js libs
// -------------------------------------
$this->load_fancybox();
ee()->cp->add_js_script(array(
'ui' => array('sortable', 'draggable', 'droppable'),
'file' => array('underscore', 'json2')
));
// --------------------------------------------
// Load page
// --------------------------------------------
$this->cached_vars['cp_javascript'][] = 'composer_cp.min';
$this->cached_vars['cp_javascript'][] = 'edit_field_cp.min';
$this->cached_vars['cp_javascript'][] = 'security.min';
$this->cached_vars['current_page'] = $this->view(
'composer.html',
NULL,
TRUE
);
return $this->ee_cp_view('index.html');
}
//END form_composer
// --------------------------------------------------------------------
/**
* Composer preview
*
* @access public
* @return mixed ajax return if detected or else html without cp
*/
public function composer_preview ()
{
$form_id = $this->get_post_or_zero('form_id');
$template_id = $this->get_post_or_zero('template_id');
$composer_id = $this->get_post_or_zero('composer_id');
$preview_id = $this->get_post_or_zero('preview_id');
$subpreview = (ee()->input->get_post('subpreview') !== FALSE);
$composer_page = $this->get_post_or_zero('composer_page');
if ( ! $this->data->is_valid_form_id($form_id))
{
$this->actions()->full_stop(lang('invalid_form_id'));
}
// -------------------------------------
// is this a preview?
// -------------------------------------
if ($preview_id > 0)
{
$preview_mode = TRUE;
$composer_id = $preview_id;
}
$page_count = 1;
// -------------------------------------
// main output or sub output?
// -------------------------------------
if ( ! $subpreview)
{
// -------------------------------------
// get composer data and build page count
// -------------------------------------
if ($composer_id > 0)
{
ee()->load->model('freeform_composer_model');
$composer = ee()->freeform_composer_model
->select('composer_data')
->where('composer_id', $composer_id)
->get_row();
if ($composer !== FALSE)
{
$composer_data = $this->json_decode(
$composer['composer_data'],
TRUE
);
if ($composer_data AND
isset($composer_data['rows']) AND
! empty($composer_data['rows']))
{
foreach ($composer_data['rows'] as $row)
{
if ($row == 'page_break')
{
$page_count++;
}
}
}
}
}
$page_url = array();
for ($i = 1, $l = $page_count; $i <= $l; $i++)
{
$page_url[] = $this->mod_link(array(
'method' => __FUNCTION__,
'form_id' => $form_id,
'template_id' => $template_id,
'preview_id' => $preview_id,
'subpreview' => 'true',
'composer_page' => $i
));
}
$this->cached_vars['page_url'] = $page_url;
$this->cached_vars['default_preview_css'] = $this->sc->addon_theme_url .
'css/default_composer.css';
$this->cached_vars['jquery_src'] = ee()->functions->fetch_site_index(0, 0) .
QUERY_MARKER . 'ACT=jquery';
$html = $this->view('composer_preview.html', NULL, TRUE);
}
else
{
$subhtml = "{exp:freeform:composer form_id='$form_id'";
$subhtml .= ($composer_page > 1) ? " multipage_page='" . $composer_page . "'" : '';
$subhtml .= ($template_id > 0) ? " composer_template_id='" . $template_id . "'" : '';
$subhtml .= ($preview_id > 0) ? " preview_id='" . $preview_id . "'" : '';
$subhtml .= "}";
$html = $this->actions()->template()->process_string_as_template($subhtml);
}
if ($this->is_ajax_request())
{
return $this->send_ajax_response(array(
'success' => TRUE,
'html' => $html
));
}
else
{
exit($html);
}
}
//end composer preview
// --------------------------------------------------------------------
/**
* entries
*
* @access public
* @param string $message message lang line
* @param bool $moderate are we moderating?
* @param bool $export export?
* @return string html output
*/
public function entries ( $message = '' , $moderate = FALSE, $export = FALSE)
{
// -------------------------------------
// Messages
// -------------------------------------
if ($message == '' AND
! in_array(ee()->input->get('msg'), array(FALSE, '')) )
{
$message = lang(ee()->input->get('msg', TRUE));
}
$this->cached_vars['message'] = $message;
// -------------------------------------
// moderate
// -------------------------------------
$search_status = ee()->input->get_post('search_status');
$moderate = (
$moderate AND
($search_status == 'pending' OR
$search_status === FALSE
)
);
//if moderate and search status was not submitted, fake into pending
if ($moderate AND $search_status === FALSE)
{
$_POST['search_status'] = 'pending';
}
$this->cached_vars['moderate'] = $moderate;
$this->cached_vars['method'] = $method = (
$moderate ? 'moderate_entries' : 'entries'
);
// -------------------------------------
// user using session id instead of cookies?
// -------------------------------------
$this->cached_vars['fingerprint'] = $this->get_session_id();
// -------------------------------------
// form data? legit? GTFO?
// -------------------------------------
$form_id = ee()->input->get_post('form_id');
ee()->load->library('freeform_forms');
ee()->load->model('freeform_form_model');
//form data does all of the proper id validity checks for us
$form_data = $this->data->get_form_info($form_id);
if ( ! $form_data)
{
$this->actions()->full_stop(lang('invalid_form_id'));
exit();
}
$this->cached_vars['form_id'] = $form_id;
$this->cached_vars['form_label'] = $form_data['form_label'];
//--------------------------------------------
// Crumbs and tab highlight
//--------------------------------------------
$this->add_crumb(
lang('forms'),
$this->mod_link(array('method' => 'forms'))
);
$this->add_crumb(
$form_data['form_label'] . ': ' .
lang($moderate ? 'moderate' : 'entries')
);
$this->set_highlight('module_forms');
$this->freeform_add_right_link(
lang('new_entry'),
$this->mod_link(array(
'method' => 'edit_entry',
'form_id' => $form_id
))
);
// -------------------------------------
// status prefs
// -------------------------------------
$form_statuses = $this->data->get_form_statuses();
$this->cached_vars['form_statuses'] = $form_statuses;
// -------------------------------------
// rest of models
// -------------------------------------
ee()->load->model('freeform_entry_model');
ee()->freeform_entry_model->id($form_id);
// -------------------------------------
// custom field labels
// -------------------------------------
$standard_columns = $this->get_standard_column_names();
//we want author instead of author id until we get data
$possible_columns = $standard_columns;
//key = value
$all_columns = array_combine($standard_columns, $standard_columns);
$column_labels = array();
$field_column_names = array();
//field prefix
$f_prefix = ee()->freeform_form_model->form_field_prefix;
//keyed labels for the front end
foreach ($standard_columns as $column_name)
{
$column_labels[$column_name] = lang($column_name);
}
// -------------------------------------
// check for fields with custom views for entry tables
// -------------------------------------
ee()->load->library('freeform_fields');
//fields in this form
foreach ($form_data['fields'] as $field_id => $field_data)
{
//outputs form_field_1, form_field_2, etc for ->select()
$field_id_name = $f_prefix . $field_id;
$field_column_names[$field_id_name] = $field_data['field_name'];
$all_columns[$field_id_name] = $field_data['field_name'];
$column_labels[$field_data['field_name']] = $field_data['field_label'];
$column_labels[$field_id_name] = $field_data['field_label'];
$possible_columns[] = $field_id;
$instance =& ee()->freeform_fields->get_field_instance(array(
'field_id' => $field_id,
'field_data' => $field_data
));
if ( ! empty($instance->entry_views))
{
foreach ($instance->entry_views as $e_lang => $e_method)
{
$this->freeform_add_right_link(
$e_lang,
$this->mod_link(array(
'method' => 'field_method',
'field_id' => $field_id,
'field_method' => $e_method,
'form_id' => $form_id
))
);
}
}
}
// -------------------------------------
// visible columns
// -------------------------------------
$visible_columns = $this->visible_columns($standard_columns, $possible_columns);
$this->cached_vars['visible_columns'] = $visible_columns;
$this->cached_vars['column_labels'] = $column_labels;
$this->cached_vars['possible_columns'] = $possible_columns;
$this->cached_vars['all_columns'] = $all_columns;
// -------------------------------------
// prep unused from from possible
// -------------------------------------
//so so used
$un_used = array();
foreach ($possible_columns as $pcid)
{
$check = ($this->is_positive_intlike($pcid)) ?
$f_prefix . $pcid :
$pcid;
if ( ! in_array($check, $visible_columns))
{
$un_used[] = $check;
}
}
$this->cached_vars['unused_columns'] = $un_used;
// -------------------------------------
// build query
// -------------------------------------
//base url for pagination
$pag_url = array(
'method' => $method,
'form_id' => $form_id
);
//cleans out blank keys from unset
$find_columns = array_merge(array(), $visible_columns);
$must_haves = array('entry_id');
// -------------------------------------
// search criteria
// building query
// -------------------------------------
$has_search = FALSE;
$search_vars = array(
'search_keywords',
'search_status',
'search_date_range',
'search_date_range_start',
'search_date_range_end',
'search_on_field'
);
foreach ($search_vars as $search_var)
{
$$search_var = ee()->input->get_post($search_var, TRUE);
//set for output
$this->cached_vars[$search_var] = (
($$search_var) ? trim($$search_var) : ''
);
}
// -------------------------------------
// search keywords
// -------------------------------------
if ($search_keywords AND
trim($search_keywords) !== '' AND
$search_on_field AND
in_array($search_on_field, $visible_columns))
{
ee()->freeform_entry_model->like(
$search_on_field,
$search_keywords
);
//pagination
$pag_url['search_keywords'] = $search_keywords;
$pag_url['search_on_field'] = $search_on_field;
$has_search = TRUE;
}
//no search on field? guess we had better search it all *gulp*
else if ($search_keywords AND trim($search_keywords) !== '')
{
$first = TRUE;
ee()->freeform_entry_model->group_like(
$search_keywords,
array_values($visible_columns)
);
$pag_url['search_keywords'] = $search_keywords;
$has_search = TRUE;
}
//status search?
if ($moderate)
{
ee()->freeform_entry_model->where('status', 'pending');
}
else if ($search_status AND in_array($search_status, array_flip( $form_statuses)))
{
ee()->freeform_entry_model->where('status', $search_status);
//pagination
$pag_url['search_status'] = $search_status;
$has_search = TRUE;
}
// -------------------------------------
// date range?
// -------------------------------------
//pagination
if ($search_date_range == 'date_range')
{
//if its the same date, lets set the time to the end of the day
if ($search_date_range_start == $search_date_range_end)
{
$search_date_range_end .= ' 23:59';
}
if ($search_date_range_start !== FALSE)
{
$pag_url['search_date_range_start'] = $search_date_range_start;
}
if ($search_date_range_end !== FALSE)
{
$pag_url['search_date_range_end'] = $search_date_range_end;
}
//pagination
if ($search_date_range_start OR $search_date_range_end)
{
$pag_url['search_date_range'] = 'date_range';
$has_search = TRUE;
}
}
else if ($search_date_range !== FALSE)
{
$pag_url['search_date_range'] = $search_date_range;
$has_search = TRUE;
}
ee()->freeform_entry_model->date_where(
$search_date_range,
$search_date_range_start,
$search_date_range_end
);
// -------------------------------------
// any searches?
// -------------------------------------
$this->cached_vars['has_search'] = $has_search;
// -------------------------------------
// data from all sites?
// -------------------------------------
if ( ! $this->data->show_all_sites())
{
ee()->freeform_entry_model->where(
'site_id',
ee()->config->item('site_id')
);
}
//we need the counts for exports and end results
$total_entries = ee()->freeform_entry_model->count(array(), FALSE);
// -------------------------------------
// orderby
// -------------------------------------
$order_by = 'entry_date';
$p_order_by = ee()->input->get_post('order_by');
if ($p_order_by !== FALSE AND in_array($p_order_by, $all_columns))
{
$order_by = $p_order_by;
$pag_url['order_by'] = $order_by;
}
// -------------------------------------
// sort
// -------------------------------------
$sort = ($order_by == 'entry_date') ? 'desc' : 'asc';
$p_sort = ee()->input->get_post('sort');
if ($p_sort !== FALSE AND
in_array(strtolower($p_sort), array('asc', 'desc')))
{
$sort = strtolower($p_sort);
$pag_url['sort'] = $sort;
}
ee()->freeform_entry_model->order_by($order_by, $sort);
$this->cached_vars['order_by'] = $order_by;
$this->cached_vars['sort'] = $sort;
// -------------------------------------
// export button
// -------------------------------------
if ($total_entries > 0)
{
$this->freeform_add_right_link(
lang('export_entries'),
'#export_entries'
);
}
// -------------------------------------
// export url
// -------------------------------------
$export_url = $pag_url;
$export_url['moderate'] = $moderate ? 'true' : 'false';
$export_url['method'] = 'export_entries';
$this->cached_vars['export_url'] = $this->mod_link($export_url);
// -------------------------------------
// export?
// -------------------------------------
if ($export)
{
$export_fields = ee()->input->get_post('export_fields');
$export_labels = $column_labels;
// -------------------------------------
// build possible select alls
// -------------------------------------
$select = array();
//are we sending just the selected fields?
if ($export_fields != 'all')
{
$select = array_unique(array_merge($must_haves, $find_columns));
foreach ($export_labels as $key => $value)
{
//clean export labels for json
if ( ! in_array($key, $select))
{
unset($export_labels[$key]);
}
}
//get real names
foreach ($select as $key => $value)
{
if (isset($field_column_names[$value]))
{
$select[$key] = $field_column_names[$value];
}
}
}
//sending all fields means we need to still clean some labels
else
{
foreach ($all_columns as $field_id_name => $field_name)
{
//clean export labels for json
if ($field_id_name != $field_name)
{
unset($export_labels[$field_id_name]);
}
$select[] = $field_name;
}
}
foreach ($export_labels as $key => $value)
{
//fix entities
$value = html_entity_decode($value, ENT_COMPAT, 'UTF-8');
$export_labels[$key] = $value;
if (isset($field_column_names[$key]))
{
$export_labels[$field_column_names[$key]] = $value;
}
}
ee()->freeform_entry_model->select(implode(', ', $select));
// -------------------------------------
// check for chunking, etc
// -------------------------------------
ee()->load->library('freeform_export');
ee()->freeform_export->format_dates = (ee()->input->get_post('format_dates') == 'y');
ee()->freeform_export->export(array(
'method' => ee()->input->get_post('export_method'),
'form_id' => $form_id,
'form_name' => $form_data['form_name'],
'output' => 'download',
'model' => ee()->freeform_entry_model,
'remove_entry_id' => ($export_fields != 'all' AND ! in_array('entry_id', $visible_columns)),
'header_labels' => $export_labels,
'total_entries' => $total_entries
));
}
//END if ($export)
// -------------------------------------
// selects
// -------------------------------------
$needed_selects = array_unique(array_merge($must_haves, $find_columns));
ee()->freeform_entry_model->select(implode(', ', $needed_selects));
//--------------------------------------
// pagination start vars
//--------------------------------------
$pag_url = $this->mod_link($pag_url);
$row_limit = $this->data->defaults['mcp_row_limit'];
$paginate = '';
$row_count = 0;
//moved above exports
//$total_entries = ee()->freeform_entry_model->count(array(), FALSE);
$current_page = 0;
// -------------------------------------
// pagination?
// -------------------------------------
// do we need pagination?
if ($total_entries > $row_limit )
{
$row_count = $this->get_post_or_zero('row');
//get pagination info
$pagination_data = $this->universal_pagination(array(
'total_results' => $total_entries,
'limit' => $row_limit,
'current_page' => $row_count,
'pagination_config' => array('base_url' => $pag_url),
'query_string_segment' => 'row'
));
$paginate = $pagination_data['pagination_links'];
$current_page = $pagination_data['pagination_page'];
ee()->freeform_entry_model->limit($row_limit, $current_page);
}
$this->cached_vars['paginate'] = $paginate;
// -------------------------------------
// get data
// -------------------------------------
$result_array = ee()->freeform_entry_model->get();
$count = $row_count;
$entries = array();
if ( ! $result_array)
{
$result_array = array();
}
$entry_ids = array();
foreach ($result_array as $row)
{
$entry_ids[] = $row['entry_id'];
}
// -------------------------------------
// allow pre_process
// -------------------------------------
ee()->freeform_fields->apply_field_method(array(
'method' => 'pre_process_entries',
'form_id' => $form_id,
'entry_id' => $entry_ids,
'form_data' => $form_data,
'field_data' => $form_data['fields']
));
foreach ( $result_array as $row)
{
//apply display_entry_cp to our field data
$field_parse = ee()->freeform_fields->apply_field_method(array(
'method' => 'display_entry_cp',
'form_id' => $form_id,
'entry_id' => $row['entry_id'],
'form_data' => $form_data,
'field_data' => $form_data['fields'],
'field_input_data' => $row
));
$row = array_merge($row, $field_parse['variables']);
$entry = array();
$entry['view_entry_link'] = $this->mod_link(array(
'method' => 'view_entry',
'form_id' => $form_id,
'entry_id' => $row['entry_id']
));
$entry['edit_entry_link'] = $this->mod_link(array(
'method' => 'edit_entry',
'form_id' => $form_id,
'entry_id' => $row['entry_id']
));
$entry['approve_link'] = $this->mod_link(array(
'method' => 'approve_entries',
'form_id' => $form_id,
'entry_ids' => $row['entry_id']
));
$entry['count'] = ++$count;
$entry['id'] = $row['entry_id'];
// -------------------------------------
// remove entry_id and author_id if we
// arent showing them
// -------------------------------------
if ( ! in_array('entry_id', $visible_columns))
{
unset($row['entry_id']);
}
// -------------------------------------
// dates
// -------------------------------------
if (in_array('entry_date', $visible_columns))
{
$row['entry_date'] = $this->format_cp_date($row['entry_date']);
}
if (in_array('edit_date', $visible_columns))
{
$row['edit_date'] = ($row['edit_date'] == 0) ? '' : $this->format_cp_date($row['edit_date']);
}
$entry['data'] = $row;
$entries[] = $entry;
}
$this->cached_vars['entries'] = $entries;
// -------------------------------------
// ajax request?
// -------------------------------------
if ($this->is_ajax_request())
{
$this->send_ajax_response(array(
'entries' => $entries,
'paginate' => $paginate,
'visibleColumns' => $visible_columns,
'allColumns' => $all_columns,
'columnLabels' => $column_labels,
'success' => TRUE
));
exit();
}
// -------------------------------------
// moderation count?
// -------------------------------------
//lets not waste the query if we are already moderating
$moderation_count = (
( ! $moderate) ?
$this->data->get_form_needs_moderation_count($form_id) :
0
);
if ($moderation_count > 0)
{
$this->cached_vars['lang_num_items_awaiting_moderation'] = str_replace(
array('%num%', '%form_label%'),
array($moderation_count, $form_data['form_label']),
lang('num_items_awaiting_moderation')
);
}
$this->cached_vars['moderation_count'] = $moderation_count;
$this->cached_vars['moderation_link'] = $this->mod_link(array(
'method' => 'moderate_entries',
'form_id' => $form_id,
'search_status' => 'pending'
));
// -------------------------------------
// is admin?
// -------------------------------------
$this->cached_vars['is_admin'] = $is_admin = (
ee()->session->userdata('group_id') == 1
);
// -------------------------------------
// can save field layout?
// -------------------------------------
//$this->cached_vars['can_edit_layout'] = $can_edit_layout = (
// $is_admin OR
// $this->check_yes($this->preference('allow_user_field_layout'))
//);
//just in case
$this->cached_vars['can_edit_layout'] = TRUE;
$this->freeform_add_right_link(
lang('edit_field_layout'),
'#edit_field_layout'
);
// -------------------------------------
// member groups
// -------------------------------------
$member_groups = array();
if ($is_admin)
{
ee()->db->select('group_id, group_title');
$member_groups = $this->prepare_keyed_result(
ee()->db->get('member_groups'),
'group_id',
'group_title'
);
}
$this->cached_vars['member_groups'] = $member_groups;
// -------------------------------------
// lang items
// -------------------------------------
// -------------------------------------
// no results lang
// -------------------------------------
$this->cached_vars['lang_no_results_for_form'] = (
($has_search) ?
lang('no_results_for_search') :
(
($moderate) ?
lang('no_entries_awaiting_approval') :
lang('no_entries_for_form')
)
);
// -------------------------------------
// moderation lang
// -------------------------------------
$this->cached_vars['lang_viewing_moderation'] = str_replace(
'%form_label%',
$form_data['form_label'],
lang('viewing_moderation')
);
// -------------------------------------
// other vars
// -------------------------------------
$this->cached_vars['form_url'] = $this->mod_link(array(
'method' => 'entries_action',
'return_method' => (($moderate) ? 'moderate_' : '' ) . 'entries'
));
$this->cached_vars['save_layout_url'] = $this->mod_link(array(
'method' => 'save_field_layout'
));
// -------------------------------------
// js libs
// -------------------------------------
$this->load_fancybox();
//$this->load_datatables();
ee()->cp->add_js_script(array(
'ui' => array('datepicker', 'sortable'),
'file' => 'underscore'
));
// --------------------------------------------
// Load page
// --------------------------------------------
$this->cached_vars['current_page'] = $this->view(
'entries.html',
NULL,
TRUE
);
return $this->ee_cp_view('index.html');
}
//END entries
// --------------------------------------------------------------------
/**
* Fire a field method as a page view
*
* @access public
* @param string $message lang line to load for a message
* @return string html output
*/
public function field_method ($message = '')
{
// -------------------------------------
// Messages
// -------------------------------------
if ($message == '' AND
! in_array(ee()->input->get('msg'), array(FALSE, '')) )
{
$message = lang(ee()->input->get('msg', TRUE));
}
$this->cached_vars['message'] = $message;
// -------------------------------------
// goods
// -------------------------------------
$form_id = $this->get_post_or_zero('form_id');
$field_id = $this->get_post_or_zero('field_id');
$field_method = ee()->input->get_post('field_method');
$instance = FALSE;
if ( $field_method == FALSE OR
! $this->data->is_valid_form_id($form_id) OR
$field_id == 0)
{
ee()->functions->redirect($this->mod_link(array('method' => 'forms')));
}
ee()->load->library('freeform_fields');
$instance =& ee()->freeform_fields->get_field_instance(array(
'form_id' => $form_id,
'field_id' => $field_id
));
//legit?
if ( ! is_object($instance) OR
empty($instance->entry_views) OR
//removed so you can post to this
//! in_array($field_method, $instance->entry_views) OR
! is_callable(array($instance, $field_method)))
{
ee()->functions->redirect($this->mod_link(array('method' => 'forms')));
}
$method_lang = lang('field_entry_view');
foreach ($instance->entry_views as $e_lang => $e_method)
{
if ($field_method == $e_method)
{
$method_lang = $e_lang;
}
}
//--------------------------------------------
// Crumbs and tab highlight
//--------------------------------------------
$this->add_crumb(
lang('entries'),
$this->mod_link(array(
'method' => 'entries',
'form_id' => $form_id
))
);
$this->add_crumb($method_lang);
$this->set_highlight('module_forms');
// --------------------------------------------
// Load page
// --------------------------------------------
$this->cached_vars['current_page'] = $instance->$field_method();
// -------------------------------------
// loading these after the instance
// incase the instance exits
// -------------------------------------
$this->load_fancybox();
return $this->ee_cp_view('index.html');
}
//END field_method
// --------------------------------------------------------------------
/**
* migrate collections
*
* @access public
* @return string
*/
public function migrate_collections ( $message = '' )
{
if ($message == '' AND ee()->input->get('msg') !== FALSE)
{
$message = lang(ee()->input->get('msg'));
}
$this->cached_vars['message'] = $message;
//--------------------------------------
// Title and Crumbs
//--------------------------------------
$this->add_crumb(lang('utilities'));
$this->set_highlight('module_utilities');
//--------------------------------------
// Library
//--------------------------------------
ee()->load->library('freeform_migration');
//--------------------------------------
// Variables
//--------------------------------------
$migrate_empty_fields = 'n';
$migrate_attachments = 'n';
$this->cached_vars['total'] = 0;
$this->cached_vars['collections'] = '';
$collections = ee()->input->post('collections');
if ( $collections !== FALSE )
{
$this->cached_vars['total'] = ee()->freeform_migration
->get_migration_count(
$collections
);
$this->cached_vars['collections'] = implode('|', $collections);
if ($this->check_yes( ee()->input->post('migrate_empty_fields') ) )
{
$migrate_empty_fields = 'y';
}
if ($this->check_yes( ee()->input->post('migrate_attachments') ) )
{
$migrate_attachments = 'y';
}
}
//--------------------------------------
// Migration ajax url
//--------------------------------------
$this->cached_vars['ajax_url'] = $this->base .
'&method=migrate_collections_ajax' .
'&migrate_empty_fields=' . $migrate_empty_fields .
'&migrate_attachments=' . $migrate_attachments .
'&collections=' .
urlencode( $this->cached_vars['collections'] ) .
'&total=' .
$this->cached_vars['total'] .
'&batch=0';
//--------------------------------------
// images
//--------------------------------------
//Success image
$this->cached_vars['success_png_url'] = $this->sc->addon_theme_url . 'images/success.png';
// Error image
$this->cached_vars['error_png_url'] = $this->sc->addon_theme_url . 'images/exclamation.png';
//--------------------------------------
// Javascript
//--------------------------------------
$this->cached_vars['cp_javascript'][] = 'migrate';
ee()->cp->add_js_script(
array('ui' => array('core', 'progressbar'))
);
//--------------------------------------
// Load page
//--------------------------------------
$this->cached_vars['current_page'] = $this->view(
'migrate.html',
NULL,
TRUE
);
return $this->ee_cp_view('index.html');
}
// End migrate collections
// --------------------------------------------------------------------
/**
* migrate collections ajax
*
* @access public
* @return string
*/
public function migrate_collections_ajax()
{
$upper_limit = 9999;
//--------------------------------------
// Base output
//--------------------------------------
$out = array(
'done' => FALSE,
'batch' => ee()->input->get('batch'),
'total' => ee()->input->get('total')
);
//--------------------------------------
// Libraries
//--------------------------------------
ee()->load->library('freeform_migration');
//--------------------------------------
// Validate
//--------------------------------------
$collections = ee()->input->get('collections');
if ( empty( $collections ) OR
ee()->input->get('batch') === FALSE )
{
$out['error'] = TRUE;
$out['errors'] = array( 'no_collections' => lang('no_collections') );
$this->send_ajax_response($out);
exit();
}
//--------------------------------------
// Done?
//--------------------------------------
if ( ee()->input->get('batch') !== FALSE AND
ee()->input->get('total') !== FALSE AND
ee()->input->get('batch') >= ee()->input->get('total') )
{
$out['done'] = TRUE;
$this->send_ajax_response($out);
exit();
}
//--------------------------------------
// Anything?
//--------------------------------------
$collections = $this->actions()->pipe_split(
urldecode(
ee()->input->get('collections')
)
);
$counts = ee()->freeform_migration->get_collection_counts($collections);
if (empty($counts))
{
$out['error'] = TRUE;
$out['errors'] = array( 'no_collections' => lang('no_collections') );
$this->send_ajax_response($out);
exit();
}
//--------------------------------------
// Do any of the submitted collections have unmigrated entries?
//--------------------------------------
$migrate = FALSE;
foreach ( $counts as $form_name => $val )
{
if ( ! empty( $val['unmigrated'] ) )
{
$migrate = TRUE;
}
}
if ( empty( $migrate ) )
{
$out['done'] = TRUE;
$this->send_ajax_response($out);
exit();
}
//--------------------------------------
// Master arrays
//--------------------------------------
$forms = array();
$form_fields = array();
//--------------------------------------
// Loop and process
//--------------------------------------
foreach ( $counts as $form_name => $val )
{
//--------------------------------------
// For each collection, create a form
//--------------------------------------
$form_data = ee()->freeform_migration->create_form($form_name);
if ( $form_data !== FALSE )
{
$forms[ $form_data['form_name'] ]['form_id'] = $form_data['form_id'];
$forms[ $form_data['form_name'] ]['form_label'] = $form_data['form_label'];
}
else
{
$errors = ee()->freeform_migration->get_errors();
if ( $errors !== FALSE )
{
$out['error'] = TRUE;
$out['errors'] = $errors;
$this->send_ajax_response($out);
exit();
}
}
//--------------------------------------
// For each collection, determine fields
//--------------------------------------
$migrate_empty_fields = (
$this->check_yes(ee()->input->get('migrate_empty_fields'))
) ? 'y': 'n';
$fields = ee()->freeform_migration->get_fields_for_collection(
$form_name,
$migrate_empty_fields
);
if ($fields !== FALSE)
{
$form_fields[ $form_name ]['fields'] = $fields;
}
else
{
$errors = ee()->freeform_migration->get_errors();
if ($errors !== FALSE)
{
$out['error'] = TRUE;
$out['errors'] = $errors;
$this->send_ajax_response($out);
exit();
}
}
//--------------------------------------
// For each collection, create necessary fields if they don't yet exist.
//--------------------------------------
$created_field_ids = array();
if ( ! empty( $form_fields[$form_name]['fields'] ) )
{
foreach ( $form_fields[$form_name]['fields'] as $name => $attr )
{
$field_id = ee()->freeform_migration->create_field(
$forms[$form_name]['form_id'],
$name,
$attr
);
if ($field_id !== FALSE )
{
$created_field_ids[] = $field_id;
}
else
{
$errors = ee()->freeform_migration->get_errors();
if ( $errors !== FALSE )
{
$out['error'] = TRUE;
$out['errors'] = $errors;
$this->send_ajax_response($out);
exit();
}
}
}
}
//--------------------------------------
// For each collection, create upload fields if needed.
//--------------------------------------
$attachment_profiles = ee()->freeform_migration->get_attachment_profiles( $form_name );
if ($this->check_yes( ee()->input->get('migrate_attachments') ) AND
$attachment_profiles !== FALSE )
{
foreach ( $attachment_profiles as $row )
{
$field_id = ee()->freeform_migration->create_upload_field(
$forms[ $form_name ]['form_id'],
$row['name'],
$row
);
if ($field_id !== FALSE)
{
$created_field_ids[] = $field_id;
$upload_pref_id_map[ $row['pref_id'] ] = array(
'field_id' => $field_id,
'field_name' => $row['name']
);
}
else
{
$errors = ee()->freeform_migration->get_errors();
if ( $errors !== FALSE )
{
$out['error'] = TRUE;
$out['errors'] = $errors;
$this->send_ajax_response($out);
exit();
}
}
}
if ( ! empty( $upload_pref_id_map ) )
{
ee()->freeform_migration->set_property(
'upload_pref_id_map',
$upload_pref_id_map
);
}
}
//--------------------------------------
// Assign the fields to our form.
//--------------------------------------
ee()->freeform_migration->assign_fields_to_form(
$forms[ $form_data['form_name'] ]['form_id'],
$created_field_ids
);
//--------------------------------------
// Safeguard?
//--------------------------------------
if ( ee()->input->get('batch') == $upper_limit )
{
$this->send_ajax_response(array('done' => TRUE ));
exit();
}
//--------------------------------------
// Pass attachments pref
//--------------------------------------
if ($this->check_yes( ee()->input->get('migrate_attachments') ) )
{
ee()->freeform_migration->set_property('migrate_attachments', TRUE);
}
//--------------------------------------
// Grab entries
//--------------------------------------
ee()->freeform_migration->set_property(
'batch_limit',
$this->migration_batch_limit
);
$entries = ee()->freeform_migration->get_legacy_entries($form_name);
if ( $entries !== FALSE )
{
foreach ( $entries as $entry )
{
//--------------------------------------
// Insert
//--------------------------------------
$entry_id = ee()->freeform_migration->set_legacy_entry(
$forms[ $form_name ]['form_id'],
$entry
);
if ( $entry_id === FALSE )
{
$errors = ee()->freeform_migration->get_errors();
if ( $errors !== FALSE )
{
$out['error'] = TRUE;
$out['errors'] = $errors;
$this->send_ajax_response($out);
exit();
}
}
else
{
$out['batch'] = $out['batch'] + 1;
}
}
}
}
//--------------------------------------
// Are we done?
//--------------------------------------
$this->send_ajax_response($out);
exit();
}
// End migrate collections ajax
// --------------------------------------------------------------------
/**
* moderate entries
*
* almost the same as entries but with some small modifications
*
* @access public
* @param string message lang line
* @return string html output
*/
public function moderate_entries ( $message = '' )
{
return $this->entries($message, TRUE);
}
//END moderate_entries
// --------------------------------------------------------------------
/**
* Action from submitted entries links
*
* @access public
* @return string html output
*/
public function entries_action ()
{
$action = ee()->input->get_post('submit_action');
if ($action == 'approve')
{
return $this->approve_entries();
}
else if ($action == 'delete')
{
return $this->delete_confirm_entries();
}
/*
else if ($action == 'edit')
{
$this->edit_entries();
}
*/
}
//END entries_action
// --------------------------------------------------------------------
/**
* [edit_entry description]
*
* @access public
* @return string parsed html
*/
public function edit_entry ($message = '')
{
// -------------------------------------
// Messages
// -------------------------------------
if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) )
{
$message = lang(ee()->input->get('msg'));
}
$this->cached_vars['message'] = $message;
// -------------------------------------
// edit?
// -------------------------------------
$form_id = $this->get_post_or_zero('form_id');
$entry_id = $this->get_post_or_zero('entry_id');
ee()->load->model('freeform_form_model');
ee()->load->model('freeform_entry_model');
$form_data = $this->data->get_form_info($form_id);
if ( ! $form_data)
{
return $this->actions()->full_stop(lang('invalid_form_id'));
}
$entry_data = array();
$edit = FALSE;
if ($entry_id > 0)
{
$entry_data = ee()->freeform_entry_model
->id($form_id)
->where('entry_id', $entry_id)
->get_row();
if ($entry_data == FALSE)
{
return $this->actions()->full_stop(lang('invalid_entry_id'));
}
$edit = TRUE;
}
//--------------------------------------------
// Crumbs and tab highlight
//--------------------------------------------
$this->add_crumb(
lang('forms'),
$this->mod_link(array('method' => 'forms'))
);
$this->add_crumb(
lang($edit ? 'edit_entry' : 'new_entry') . ': ' . $form_data['form_label']
);
$this->set_highlight('module_forms');
// -------------------------------------
// load the template library in case
// people get upset or something
// -------------------------------------
if ( ! isset(ee()->TMPL) OR ! is_object(ee()->TMPL))
{
ee()->load->library('template');
$globals['TMPL'] =& ee()->template;
ee()->TMPL =& ee()->template;
}
// -------------------------------------
// get fields
// -------------------------------------
ee()->load->library('freeform_fields');
$field_output_data = array();
$field_loop_ids = array_keys($form_data['fields']);
if ($form_data['field_order'] !== '')
{
$order_ids = $this->actions()->pipe_split($form_data['field_order']);
if ( ! empty($order_ids))
{
//this makes sure that any fields in 'fields' are in the
//order set as well. Will add missing at the end like this
$field_loop_ids = array_merge(
$order_ids,
array_diff($field_loop_ids, $order_ids)
);
}
}
foreach ($field_loop_ids as $field_id)
{
if ( ! isset($form_data['fields'][$field_id]))
{
continue;
}
$f_data = $form_data['fields'][$field_id];
$instance =& ee()->freeform_fields->get_field_instance(array(
'field_id' => $field_id,
'field_data' => $f_data,
'form_id' => $form_id,
'entry_id' => $entry_id,
'edit' => $edit,
'extra_settings' => array(
'entry_id' => $entry_id
)
));
$column_name = ee()->freeform_entry_model->form_field_prefix . $field_id;
$display_field_data = '';
if ($edit)
{
if (isset($entry_data[$column_name]))
{
$display_field_data = $entry_data[$column_name];
}
else if (isset($entry_data[$f_data['field_name']]))
{
$display_field_data = $entry_data[$f_data['field_name']];
}
}
$field_output_data[$field_id] = array(
'field_display' => $instance->display_edit_cp($display_field_data),
'field_label' => $f_data['field_label'],
'field_description' => $f_data['field_description']
);
}
$entry_data['screen_name'] = '';
$entry_data['group_title'] = '';
if (!empty($entry_data['author_id']))
{
$member_data = ee()->db
->select('group_title, screen_name')
->from('members')
->join('member_groups', 'members.group_id = member_groups.group_id', 'left')
->where('member_id', $entry_data['author_id'])
->limit(1)
->get();
if ($member_data->num_rows() > 0)
{
$entry_data['screen_name'] = $member_data->row('screen_name');
$entry_data['group_title'] = $member_data->row('group_title');
}
}
if ($entry_data['screen_name'] == '')
{
$entry_data['screen_name'] = lang('guest');
$entry_data['group_title'] = lang('guest');
$guest_data = ee()->db
->select('group_title')
->from('member_groups')
->where('group_id', 3)
->limit(1)
->get();
if ($guest_data->num_rows() > 0)
{
$entry_data['group_title'] = $guest_data->row('group_title');
}
}
$entry_data['entry_date'] = ( ! empty( $entry_data['entry_date'] ) ) ?
$entry_data['entry_date'] :
ee()->localize->now;
$entry_data['entry_date'] = $this->format_cp_date($entry_data['entry_date']);
$entry_data['edit_date'] = (!empty($entry_data['edit_date'])) ?
$this->format_cp_date($entry_data['edit_date']) :
lang('n_a');
$this->cached_vars['entry_data'] = $entry_data;
$this->cached_vars['field_output_data'] = $field_output_data;
$this->cached_vars['form_uri'] = $this->mod_link(array(
'method' => 'save_entry'
));
$this->cached_vars['form_id'] = $form_id;
$this->cached_vars['entry_id'] = $entry_id;
$this->cached_vars['statuses'] = $this->data->get_form_statuses();
// --------------------------------------------
// Load page
// --------------------------------------------
$this->load_fancybox();
$this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min';
$this->cached_vars['current_page'] = $this->view(
'edit_entry.html',
NULL,
TRUE
);
return $this->ee_cp_view('index.html');
}
//END edit_entry
// --------------------------------------------------------------------
/**
* fields
*
* @access public
* @param string message
* @return string
*/
public function fields ( $message = '' )
{
// -------------------------------------
// Messages
// -------------------------------------
if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) )
{
$message = lang(ee()->input->get('msg'));
}
$this->cached_vars['message'] = $message;
//--------------------------------------------
// Crumbs and tab highlight
//--------------------------------------------
$this->cached_vars['new_field_link'] = $this->mod_link(array(
'method' => 'edit_field'
));
$this->add_crumb( lang('fields') );
//optional
$this->freeform_add_right_link(lang('new_field'), $this->cached_vars['new_field_link']);
$this->set_highlight('module_fields');
// -------------------------------------
// data
// -------------------------------------
$this->cached_vars['fingerprint'] = $this->get_session_id();
$row_limit = $this->data->defaults['mcp_row_limit'];
$paginate = '';
$row_count = 0;
$field_data = array();
$paginate_url = array('method' => 'fields');
ee()->load->model('freeform_field_model');
ee()->freeform_field_model->select(
'field_label,
field_name,
field_type,
field_id,
field_description'
);
// -------------------------------------
// search?
// -------------------------------------
$field_search = '';
$field_search_on = '';
$search = ee()->input->get_post('field_search', TRUE);
if ($search)
{
$f_search_on = ee()->input->get_post('field_search_on');
if ($f_search_on == 'field_name')
{
ee()->freeform_field_model->like('field_name', $search);
$field_search_on = 'field_name';
}
else if ($f_search_on == 'field_label')
{
ee()->freeform_field_model->like('field_label', $search);
$field_search_on = 'field_label';
}
else if ($f_search_on == 'field_description')
{
ee()->freeform_field_model->like('field_description', $search);
$field_search_on = 'field_description';
}
else //if ($f_search_on == 'all')
{
ee()->freeform_field_model->like('field_name', $search);
ee()->freeform_field_model->or_like('field_label', $search);
ee()->freeform_field_model->or_like('field_description', $search);
$field_search_on = 'all';
}
$field_search = $search;
$paginate_url['field_search'] = $search;
$paginate_url['field_search_on'] = $field_search_on;
}
$this->cached_vars['field_search'] = $field_search;
$this->cached_vars['field_search_on'] = $field_search_on;
// -------------------------------------
// all sites?
// -------------------------------------
if ( ! $this->data->show_all_sites())
{
ee()->freeform_field_model->where(
'site_id',
ee()->config->item('site_id')
);
}
ee()->freeform_field_model->order_by('field_name', 'asc');
$total_results = ee()->freeform_field_model->count(array(), FALSE);
$row_count = 0;
// do we need pagination?
if ( $total_results > $row_limit )
{
$row_count = $this->get_post_or_zero('row');
//get pagination info
$pagination_data = $this->universal_pagination(array(
'total_results' => $total_results,
'limit' => $row_limit,
'current_page' => $row_count,
'pagination_config' => array('base_url' => $this->mod_link($paginate_url)),
'query_string_segment' => 'row'
));
$paginate = $pagination_data['pagination_links'];
ee()->freeform_field_model->limit(
$row_limit,
$pagination_data['pagination_page']
);
}
$query = ee()->freeform_field_model->get();
$count = $row_count;
if ($query !== FALSE)
{
foreach ($query as $row)
{
$row['count'] = ++$count;
$row['field_edit_link'] = $this->mod_link(array(
'method' => 'edit_field',
'field_id' => $row['field_id']
));
$row['field_duplicate_link'] = $this->mod_link(array(
'method' => 'edit_field',
'duplicate_id' => $row['field_id']
));
$row['field_delete_link'] = $this->mod_link(array(
'method' => 'delete_confirm_fields',
'field_id' => $row['field_id']
));
$field_data[] = $row;
}
}
$this->cached_vars['field_data'] = $field_data;
$this->cached_vars['paginate'] = $paginate;
// -------------------------------------
// ajax?
// -------------------------------------
if ($this->is_ajax_request())
{
return $this->send_ajax_response(array(
'success' => TRUE,
'field_data' => $field_data,
'paginate' => $paginate
));
}
// ----------------------------------------
// Load vars
// ----------------------------------------
$this->cached_vars['form_uri'] = $this->mod_link(array(
'method' => 'delete_confirm_fields'
));
// -------------------------------------
// js
// -------------------------------------
ee()->cp->add_js_script(array(
'file' => array('underscore', 'json2')
));
// --------------------------------------------
// Load page
// --------------------------------------------
$this->cached_vars['current_page'] = $this->view(
'fields.html',
NULL,
TRUE
);
return $this->ee_cp_view('index.html');
}
//END fields
// --------------------------------------------------------------------
/**
* Edit Field
*
* @access public
* @param bool $modal is this a modal version?
* @return string
*/
public function edit_field ($modal = FALSE)
{
// -------------------------------------
// field ID? we must be editing
// -------------------------------------
$field_id = $this->get_post_or_zero('field_id');
$update = ($field_id != 0);
$modal = ( ! $modal AND $this->check_yes(ee()->input->get_post('modal'))) ? TRUE : $modal;
$this->cached_vars['modal'] = $modal;
//--------------------------------------------
// Crumbs and tab highlight
//--------------------------------------------
$this->add_crumb( lang('fields') , $this->base . AMP . 'method=fields');
$this->add_crumb( lang(($update ? 'update_field' : 'new_field')) );
//optional
//$this->freeform_add_right_link(lang('home'), $this->base . AMP . 'method=some_method');
$this->set_highlight('module_fields');
// -------------------------------------
// default values
// -------------------------------------
$inputs = array(
'field_id' => '0',
'field_name' => '',
'field_label' => '',
'field_order' => '0',
'field_type' => $this->data->defaults['field_type'],
'field_length' => $this->data->defaults['field_length'],
'field_description' => '',
'submissions_page' => 'y',
'moderation_page' => 'y',
'composer_use' => 'y',
);
// -------------------------------------
// defaults
// -------------------------------------
$this->cached_vars['edit_warning'] = FALSE;
$field_in_forms = array();
$incoming_settings = FALSE;
if ($update)
{
$field_data = $this->data->get_field_info_by_id($field_id);
if (empty($field_data))
{
$this->actions()->full_stop(lang('invalid_field_id'));
}
foreach ($field_data as $key => $value)
{
$inputs[$key] = $value;
}
// -------------------------------------
// is this change going to affect any
// forms that use this field?
// -------------------------------------
$form_info = $this->data->get_form_info_by_field_id($field_id);
if ($form_info AND ! empty($form_info))
{
$this->cached_vars['edit_warning'] = TRUE;
$form_names = array();
foreach ($form_info as $row)
{
$field_in_forms[] = $row['form_id'];
$form_names[] = $row['form_label'];
}
$this->cached_vars['lang_field_edit_warning'] = lang('field_edit_warning');
$this->cached_vars['lang_field_edit_warning_desc'] = str_replace(
'%form_names%',
implode(', ', $form_names),
lang('field_edit_warning_desc')
);
}
}
$this->cached_vars['form_ids'] = implode('|', array_unique($field_in_forms));
// -------------------------------------
// duplicating?
// -------------------------------------
$duplicate_id = $this->get_post_or_zero('duplicate_id');
$duplicate = FALSE;
$this->cached_vars['duplicated'] = FALSE;
if ( ! $update AND $duplicate_id > 0)
{
$field_data = $this->data->get_field_info_by_id($duplicate_id);
if ($field_data)
{
$duplicate = TRUE;
foreach ($field_data as $key => $value)
{
if (in_array($key, array('field_id', 'field_label', 'field_name')))
{
continue;
}
$inputs[$key] = $value;
}
$this->cached_vars['duplicated'] = TRUE;
$this->cached_vars['duplicated_from'] = $field_data['field_label'];
}
}
// -------------------------------------
// get available field types
// -------------------------------------
ee()->load->library('freeform_fields');
$this->cached_vars['fieldtypes'] = ee()->freeform_fields->get_available_fieldtypes();
// -------------------------------------
// get available forms to add this to
// -------------------------------------
if ( ! $this->data->show_all_sites())
{
ee()->db->where('site_id', ee()->config->item('site_id'));
}
$this->cached_vars['available_forms'] = $this->prepare_keyed_result(
ee()->db->get('freeform_forms'),
'form_id'
);
// -------------------------------------
// add desc and lang for field types
// -------------------------------------
foreach($this->cached_vars['fieldtypes'] as $fieldtype => $field_data)
{
//settings?
$settings = (
($update OR $duplicate ) AND
$inputs['field_type'] == $fieldtype AND
isset($inputs['settings'])
) ? json_decode($inputs['settings'], TRUE) : array();
//we are encoding this and decoding in JS because leaving the
//fields intact while in storage in the html makes dupes of fields.
//I could do some html moving around, but that would keep running
//individual settings JS over and over again when it should
//only be run on display.
$this->cached_vars['fieldtypes'][$fieldtype]['settings_output'] = base64_encode(
ee()->freeform_fields->fieldtype_display_settings_output(
$fieldtype,
$settings
)
);
}
if (isset($inputs['field_label']))
{
$inputs['field_label'] = form_prep($inputs['field_label']);
}
if (isset($inputs['field_description']))
{
$inputs['field_description'] = form_prep($inputs['field_description']);
}
// -------------------------------------
// load inputs
// -------------------------------------
foreach ($inputs as $key => $value)
{
$this->cached_vars[$key] = $value;
}
$this->cached_vars['form_uri'] = $this->mod_link(array(
'method' => 'save_field'
));
//----------------------------------------
// Load vars
//----------------------------------------
$this->cached_vars['lang_submit_word'] = lang(
($update ? 'update_field' : 'create_field')
);
$this->cached_vars['prohibited_field_names'] = $this->data->prohibited_names;
// --------------------------------------------
// Load page
// --------------------------------------------
$this->cached_vars['cp_javascript'][] = 'edit_field_cp.min';
$this->cached_vars['current_page'] = $this->view(
'edit_field.html',
NULL,
TRUE
);
if ($modal)
{
exit($this->cached_vars['current_page']);
}
$this->load_fancybox();
$this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min';
return $this->ee_cp_view('index.html');
}
//END edit_field
// --------------------------------------------------------------------
/**
* Field Types
*
* @access public
* @param message
* @return string
*/
public function fieldtypes ( $message = '' )
{
// -------------------------------------
// Messages
// -------------------------------------
if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) )
{
$message = lang(ee()->input->get('msg'));
}
$this->cached_vars['message'] = $message;
//--------------------------------------------
// Crumbs and tab highlight
//--------------------------------------------
$this->add_crumb( lang('fieldtypes') );
$this->set_highlight('module_fieldtypes');
//--------------------------------------
// start vars
//--------------------------------------
$fieldtypes = array();
ee()->load->library('freeform_fields');
ee()->load->model('freeform_field_model');
ee()->load->model('freeform_fieldtype_model');
if ( ( $installed_fieldtypes = ee()->freeform_fieldtype_model->installed_fieldtypes() ) === FALSE )
{
$installed_fieldtypes = array();
}
$fieldtypes = ee()->freeform_fields->get_installable_fieldtypes();
// -------------------------------------
// missing fieldtype folders?
// -------------------------------------
$missing_fieldtypes = array();
foreach ($installed_fieldtypes as $name => $version)
{
if ( ! array_key_exists($name, $fieldtypes))
{
$missing_fieldtypes[] = $name;
}
}
// -------------------------------------
// add urls and crap
// -------------------------------------
$action_url = $this->base . AMP . 'method=freeform_fieldtype_action';
foreach ($fieldtypes as $name => $data)
{
$fieldtypes[$name]['installed_lang'] = lang($data['installed'] ? 'installed' : 'not_installed');
$action = ($data['installed'] ? 'uninstall' : 'install');
$fieldtypes[$name]['action_lang'] = lang($action);
$fieldtypes[$name]['action_url'] = $this->mod_link(array(
'method' => 'freeform_fieldtype_action',
'name' => $name,
'action' => $action,
//some other time -gf
//'folder' => base64_encode($data['folder'])
));
}
$this->cached_vars['fieldtypes'] = $fieldtypes;
$this->cached_vars['freeform_ft_docs_url'] = $this->data->doc_links['custom_fields'];
// --------------------------------------------
// Load page
// --------------------------------------------
$this->cached_vars['current_page'] = $this->view(
'fieldtypes.html',
NULL,
TRUE
);
return $this->ee_cp_view('index.html');
}
//END field_types
// --------------------------------------------------------------------
/**
* notifications
*
* @access public
* @param string message to output
* @return string outputted template
*/
public function notifications ( $message = '' )
{
// -------------------------------------
// Messages
// -------------------------------------
if ($message == '' AND
! in_array(ee()->input->get('msg'), array(FALSE, '')) )
{
$message = lang(ee()->input->get('msg'));
}
$this->cached_vars['message'] = $message;
//--------------------------------------------
// Crumbs and tab highlight
//--------------------------------------------
$this->cached_vars['new_notification_link'] = $this->mod_link(array(
'method' => 'edit_notification'
));
$this->add_crumb( lang('notifications') );
$this->freeform_add_right_link(
lang('new_notification'),
$this->cached_vars['new_notification_link']
);
$this->set_highlight('module_notifications');
// -------------------------------------
// data
// -------------------------------------
$row_limit = $this->data->defaults['mcp_row_limit'];
$paginate = '';
$row_count = 0;
$notification_data = array();
ee()->db->start_cache();
ee()->db->order_by('notification_name', 'asc');
if ( ! $this->data->show_all_sites())
{
ee()->db->where('site_id', ee()->config->item('site_id'));
}
ee()->db->from('freeform_notification_templates');
ee()->db->stop_cache();
$total_results = ee()->db->count_all_results();
// do we need pagination?
if ( $total_results > $row_limit )
{
$row_count = $this->get_post_or_zero('row');
$url = $this->mod_link(array(
'method' => 'notifications'
));
//get pagination info
$pagination_data = $this->universal_pagination(array(
'total_results' => $total_results,
'limit' => $row_limit,
'current_page' => $row_count,
'pagination_config' => array('base_url' => $url),
'query_string_segment' => 'row'
));
$paginate = $pagination_data['pagination_links'];
ee()->db->limit($row_limit, $pagination_data['pagination_page']);
}
$query = ee()->db->get();
ee()->db->flush_cache();
if ($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
$row['notification_edit_link'] = $this->mod_link(array(
'method' => 'edit_notification',
'notification_id' => $row['notification_id'],
));
$row['notification_duplicate_link'] = $this->mod_link(array(
'method' => 'edit_notification',
'duplicate_id' => $row['notification_id'],
));
$row['notification_delete_link'] = $this->mod_link(array(
'method' => 'delete_confirm_notification',
'notification_id' => $row['notification_id'],
));
$notification_data[] = $row;
}
}
$this->cached_vars['notification_data'] = $notification_data;
$this->cached_vars['paginate'] = $paginate;
// ----------------------------------------
// Load vars
// ----------------------------------------
$this->cached_vars['form_uri'] = $this->mod_link(array(
'method' => 'delete_confirm_notification'
));
// --------------------------------------------
// Load page
// --------------------------------------------
$this->cached_vars['current_page'] = $this->view(
'notifications.html',
NULL,
TRUE
);
return $this->ee_cp_view('index.html');
}
//END notifications
// --------------------------------------------------------------------
/**
* edit_notification
*
* @access public
* @return string
*/
public function edit_notification ()
{
// -------------------------------------
// notification ID? we must be editing
// -------------------------------------
$notification_id = $this->get_post_or_zero('notification_id');
$update = ($notification_id != 0);
//--------------------------------------
// Title and Crumbs
//--------------------------------------
$this->add_crumb(
lang('notifications'),
$this->base . AMP . 'method=notifications'
);
$this->add_crumb(
lang(($update ? 'update_notification' : 'new_notification'))
);
$this->set_highlight('module_notifications');
// -------------------------------------
// data items
// -------------------------------------
$inputs = array(
'notification_id' => '0',
'notification_name' => '',
'notification_label' => '',
'notification_description' => '',
'wordwrap' => $this->data->defaults['wordwrap'],
'allow_html' => $this->data->defaults['allow_html'],
'from_name' => form_prep(ee()->config->item('webmaster_name')),
'from_email' => ee()->config->item('webmaster_email'),
'reply_to_email' => ee()->config->item('webmaster_email'),
'email_subject' => '',
'template_data' => '',
'include_attachments' => 'n'
);
// -------------------------------------
// defaults
// -------------------------------------
$this->cached_vars['edit_warning'] = FALSE;
if ($update)
{
$notification_data = $this->data->get_notification_info_by_id($notification_id);
foreach ($notification_data as $key => $value)
{
$inputs[$key] = form_prep($value);
}
// -------------------------------------
// is this change going to affect any
// forms that use this field?
// -------------------------------------
$form_info = $this->data->get_form_info_by_notification_id($notification_id);
if ($form_info AND ! empty($form_info))
{
$this->cached_vars['edit_warning'] = TRUE;
$form_names = array();
foreach ($form_info as $row)
{
$form_names[] = $row['form_label'];
}
$this->cached_vars['lang_notification_edit_warning'] = str_replace(
'%form_names%',
implode(', ', $form_names),
lang('notification_edit_warning')
);
}
}
// -------------------------------------
// duplicating?
// -------------------------------------
$duplicate_id = $this->get_post_or_zero('duplicate_id');
$this->cached_vars['duplicated'] = FALSE;
if ( ! $update AND $duplicate_id > 0)
{
$notification_data = $this->data->get_notification_info_by_id($duplicate_id);
if ($notification_data)
{
foreach ($notification_data as $key => $value)
{
//TODO: remove other items that dont need to be duped?
if (in_array($key, array(
'notification_id',
'notification_label',
'notification_name'
)))
{
continue;
}
$inputs[$key] = form_prep($value);
}
$this->cached_vars['duplicated'] = TRUE;
$this->cached_vars['duplicated_from'] = $notification_data['notification_label'];
}
}
// -------------------------------------
// get available fields
// -------------------------------------
ee()->load->model('freeform_field_model');
$this->cached_vars['available_fields'] = array();
if ( ( $fields = ee()->freeform_field_model->get() ) !== FALSE )
{
$this->cached_vars['available_fields'] = $fields;
}
$this->cached_vars['standard_tags'] = $this->data->standard_notification_tags;
// -------------------------------------
// load inputs
// -------------------------------------
foreach ($inputs as $key => $value)
{
$this->cached_vars[$key] = $value;
}
$this->cached_vars['form_uri'] = $this->base . AMP .
'method=save_notification';
// ----------------------------------------
// Load vars
// ----------------------------------------
$this->cached_vars['lang_submit_word'] = lang(
($update ? 'update_notification' : 'create_notification')
);
$this->load_fancybox();
$this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min';
// --------------------------------------------
// Load page
// --------------------------------------------
$this->cached_vars['current_page'] = $this->view(
'edit_notification.html',
NULL,
TRUE
);
return $this->ee_cp_view('index.html');
}
//END edit_notification
// --------------------------------------------------------------------
/**
* preferences
*
* @access public
* @return string
*/
public function preferences ( $message = '' )
{
if ($message == '' AND ee()->input->get('msg') !== FALSE)
{
$message = lang(ee()->input->get('msg'));
}
$this->cached_vars['message'] = $message;
//--------------------------------------
// Title and Crumbs
//--------------------------------------
$this->add_crumb(lang('preferences'));
$this->set_highlight('module_preferences');
// -------------------------------------
// global prefs
// -------------------------------------
$this->cached_vars['msm_enabled'] = $msm_enabled = $this->data->msm_enabled;
$is_admin = (ee()->session->userdata('group_id') == 1);
$this->cached_vars['show_global_prefs'] = ($is_admin AND $msm_enabled);
$global_pref_data = array();
$global_prefs = $this->data->get_global_module_preferences();
$default_global_prefs = array_keys($this->data->default_global_preferences);
//dynamically get prefs and lang so we can just add them to defaults
foreach( $global_prefs as $key => $value )
{
//this skips things that don't need to be shown on this page
//so we can use the prefs table for other areas of the addon
if ( ! in_array($key, $default_global_prefs))
{
continue;
}
$pref = array();
$pref['name'] = $key;
$pref['lang_label'] = lang($key);
$key_desc = $key . '_desc';
$pref['lang_desc'] = (lang($key_desc) == $key_desc) ? '' : lang($key_desc);
$pref['value'] = form_prep($value);
$pref['type'] = $this->data->default_global_preferences[$key]['type'];
$global_pref_data[] = $pref;
}
$this->cached_vars['global_pref_data'] = $global_pref_data;
// -------------------------------------
// these two will only be used if MSM
// is enabled, but setting them
// anyway to avoid potential PHP errors
// -------------------------------------
$prefs_all_sites = ! $this->check_no(
$this->data->global_preference('prefs_all_sites')
);
$this->cached_vars['lang_site_prefs_for_site'] = (
lang('site_prefs_for') . ' ' . (
($prefs_all_sites) ?
lang('all_sites') :
ee()->config->item('site_label')
)
);
//--------------------------------------
// per site prefs
//--------------------------------------
$pref_data = array();
$prefs = $this->data->get_module_preferences();
$default_prefs = array_keys($this->data->default_preferences);
//dynamically get prefs and lang so we can just add them to defaults
foreach( $prefs as $key => $value )
{
//this skips things that don't need to be shown on this page
//so we can use the prefs table for other areas of the addon
if ( ! in_array($key, $default_prefs))
{
continue;
}
//admin only pref?
//MSM pref and no MSM?
if (
(ee()->session->userdata('group_id') != 1 AND
in_array($key, $this->data->admin_only_prefs)) OR
( ! $msm_enabled AND
in_array($key, $this->data->msm_only_prefs))
)
{
continue;
}
$pref = array();
$pref['name'] = $key;
$pref['lang_label'] = lang($key);
$key_desc = $key . '_desc';
$pref['lang_desc'] = (lang($key_desc) == $key_desc) ? '' : lang($key_desc);
$pref['value'] = form_prep($value);
$pref['type'] = $this->data->default_preferences[$key]['type'];
$pref_data[] = $pref;
}
$this->cached_vars['pref_data'] = $pref_data;
// ----------------------------------------
// Load vars
// ----------------------------------------
$this->cached_vars['form_uri'] = $this->mod_link(array(
'method' => 'save_preferences'
));
// --------------------------------------------
// Load page
// --------------------------------------------
$this->cached_vars['current_page'] = $this->view(
'preferences.html',
NULL,
TRUE
);
return $this->ee_cp_view('index.html');
}
//END preferences
// --------------------------------------------------------------------
/**
* delete confirm page abstractor
*
* @access private
* @param string method you want to post data to after confirm
* @param array all of the values you want to carry over to post
* @param string the lang line of the warning message to display
* @param string the lang line of the submit button for confirm
* @param bool $message_use_lang use the lang wrapper for the message?
* @return string
*/
private function delete_confirm ($method, $hidden_values,
$message_line, $submit_line = 'delete',
$message_use_lang = TRUE)
{
$this->cached_vars = array_merge($this->cached_vars, array(
'hidden_values' => $hidden_values,
'lang_message' => ($message_use_lang ? lang($message_line) : $message_line),
'lang_submit' => lang($submit_line),
'form_url' => $this->mod_link(array('method' => $method))
));
$this->cached_vars['current_page'] = $this->view(
'delete_confirm.html',
NULL,
TRUE
);
return $this->ee_cp_view('index.html');
}
//END delete_confirm
//--------------------------------------------------------------------
// end views
//--------------------------------------------------------------------
// --------------------------------------------------------------------
/**
* Clean up inputted paragraph html
*
* @access public
* @param string $string string to clean
* @return mixed string if html or json if not
*/
public function clean_paragraph_html ($string = '', $allow_ajax = TRUE)
{
if ( ! $string OR trim($string == ''))
{
$string = ee()->input->get_post('clean_string');
if ( $string === FALSE OR trim($string) === '')
{
$string = '';
}
}
$allowed_tags = '<' . implode('><', $this->data->allowed_html_tags) . '>';
$string = strip_tags($string, $allowed_tags);
$string = ee()->security->xss_clean($string);
return $string;
}
//END clean_paragraph_html
// --------------------------------------------------------------------
/**
* Fieldtype Actions
*
* this installs or uninstalles depending on the sent action
* this will redirect no matter what
*
* @access public
* @return null
*/
public function freeform_fieldtype_action ()
{
$return_url = array('method' => 'fieldtypes');
$name = ee()->input->get_post('name', TRUE);
$action = ee()->input->get_post('action');
if ($name AND $action)
{
ee()->load->library('freeform_fields');
if ($action === 'install')
{
if (ee()->freeform_fields->install_fieldtype($name))
{
$return_url['msg'] = 'fieldtype_installed';
}
else
{
return $this->actions()->full_stop(lang('fieldtype_install_error'));
}
}
else if ($action === 'uninstall')
{
$uninstall = $this->uninstall_confirm_fieldtype($name);
//if its not a boolean true, its a confirmation
if ($uninstall !== TRUE)
{
return $uninstall;
}
else
{
$return_url['msg'] = 'fieldtype_uninstalled';
}
}
}
if ($this->is_ajax_request())
{
return $this->send_ajax_response(array(
'success' => TRUE,
'message' => lang('fieldtype_uninstalled')
));
}
else
{
ee()->functions->redirect($this->mod_link($return_url));
}
}
//END freeform_fieldtype_action
// --------------------------------------------------------------------
/**
* save field layout
*
* ajax called method for saving field layout in the entries screen
*
* @access public
* @return string
*/
public function save_field_layout ()
{
ee()->load->library('freeform_forms');
ee()->load->model('freeform_form_model');
$save_for = ee()->input->get_post('save_for', TRUE);
$shown_fields = ee()->input->get_post('shown_fields', TRUE);
$form_id = $this->get_post_or_zero('form_id');
$form_data = $this->data->get_form_info($form_id);
// -------------------------------------
// valid
// -------------------------------------
if (
! $this->is_ajax_request() OR
! is_array($save_for) OR
! is_array($shown_fields) OR
! $form_data
)
{
return $this->send_ajax_response(array(
'success' => FALSE,
'message' => lang('invalid_input')
));
}
// -------------------------------------
// permissions?
// -------------------------------------
//if (ee()->session->userdata('group_id') != 1 AND
// ! $this->check_yes($this->preference('allow_user_field_layout'))
//)
//{
// return $this->send_ajax_response(array(
// 'success' => FALSE,
// 'message' => lang('invalid_permissions')
// ));
//}
// -------------------------------------
// save
// -------------------------------------
$field_layout_prefs = $this->preference('field_layout_prefs');
$original_prefs = (
is_array($field_layout_prefs) ?
$field_layout_prefs :
array()
);
// -------------------------------------
// who is it for?
// -------------------------------------
$for = array();
foreach ($save_for as $item)
{
//if this is for everyone, we can stop
if (in_array($item, array('just_me', 'everyone')))
{
$for = $item;
break;
}
if ($this->is_positive_intlike($item))
{
$for[] = $item;
}
}
// -------------------------------------
// what do they want to see?
// -------------------------------------
$standard_columns = $this->get_standard_column_names();
$possible_columns = $standard_columns;
//build possible columns
foreach ($form_data['fields'] as $field_id => $field_data)
{
$possible_columns[] = $field_id;
}
$data = array();
$prefix = ee()->freeform_form_model->form_field_prefix;
//check for field validity, no funny business
foreach ($shown_fields as $field_name)
{
$field_id = str_replace($prefix, '', $field_name);
if (in_array($field_name, $standard_columns))
{
$data[] = $field_name;
unset(
$possible_columns[
array_search(
$field_name,
$possible_columns
)
]
);
}
else if (in_array($field_id , array_keys($form_data['fields'])))
{
$data[] = $field_id;
unset(
$possible_columns[
array_search(
$field_id,
$possible_columns
)
]
);
}
}
//removes holes
sort($possible_columns);
// -------------------------------------
// insert the data per group or all
// -------------------------------------
$settings = array(
'visible' => $data,
'hidden' => $possible_columns
);
if ($for == 'just_me')
{
$id = ee()->session->userdata('member_id');
$original_prefs['entry_layout_prefs']['member'][$id] = $settings;
}
else if ($for == 'everyone')
{
$original_prefs['entry_layout_prefs']['all']['visible'] = $settings;
}
else
{
foreach ($for as $who)
{
$original_prefs['entry_layout_prefs']['group'][$who]['visible'] = $settings;
}
}
// -------------------------------------
// save
// -------------------------------------
$this->data->set_module_preferences(array(
'field_layout_prefs' => json_encode($original_prefs)
));
// -------------------------------------
// success!
// -------------------------------------
//TODO test for ajax request or redirect back
//don't want JS erorrs preventing this from
//working
$this->send_ajax_response(array(
'success' => TRUE,
'message' => lang('layout_saved'),
'update_fields' => array()
));
//prevent EE CP default spit out
exit();
}
//END save_field_layout
// --------------------------------------------------------------------
/**
* save_form
*
* @access public
* @return null
*/
public function save_form ()
{
// -------------------------------------
// form ID? we must be editing
// -------------------------------------
$form_id = $this->get_post_or_zero('form_id');
$update = ($form_id != 0);
// -------------------------------------
// default status
// -------------------------------------
$default_status = ee()->input->get_post('default_status', TRUE);
$default_status = ($default_status AND trim($default_status) != '') ?
$default_status :
$this->data->defaults['default_form_status'];
// -------------------------------------
// composer return?
// -------------------------------------
$do_composer = (FREEFORM_PRO AND ee()->input->get_post('ret') == 'composer');
$composer_save_finish = (FREEFORM_PRO AND ee()->input->get_post('ret') == 'composer_save_finish');
if ($composer_save_finish)
{
$do_composer = TRUE;
}
// -------------------------------------
// error on empty items or bad data
// (doing this via ajax in the form as well)
// -------------------------------------
$errors = array();
// -------------------------------------
// field name
// -------------------------------------
$form_name = ee()->input->get_post('form_name', TRUE);
//if the field label is blank, make one for them
//we really dont want to do this, but here we are
if ( ! $form_name OR ! trim($form_name))
{
$errors['form_name'] = lang('form_name_required');
}
else
{
$form_name = strtolower(trim($form_name));
if ( in_array($form_name, $this->data->prohibited_names ) )
{
$errors['form_name'] = str_replace(
'%name%',
$form_name,
lang('reserved_form_name')
);
}
//if the form_name they submitted isn't like how a URL title may be
//also, cannot be numeric
if (preg_match('/[^a-z0-9\_\-]/i', $form_name) OR
is_numeric($form_name))
{
$errors['form_name'] = lang('form_name_can_only_contain');
}
ee()->load->model('freeform_form_model');
//get dupe from field names
$dupe_data = ee()->freeform_form_model->get_row(array(
'form_name' => $form_name
));
//if we are updating, we don't want to error on the same field id
if ( ! empty($dupe_data) AND
! ($update AND $dupe_data['form_id'] == $form_id))
{
$errors['form_name'] = str_replace(
'%name%',
$form_name,
lang('form_name_exists')
);
}
}
// -------------------------------------
// form label
// -------------------------------------
$form_label = ee()->input->get_post('form_label', TRUE);
if ( ! $form_label OR ! trim($form_label) )
{
$errors['form_label'] = lang('form_label_required');
}
// -------------------------------------
// admin notification email
// -------------------------------------
$admin_notification_email = ee()->input->get_post('admin_notification_email', TRUE);
if ($admin_notification_email AND
trim($admin_notification_email) != '')
{
ee()->load->helper('email');
$emails = preg_split(
'/(\s+)?\,(\s+)?/',
$admin_notification_email,
-1,
PREG_SPLIT_NO_EMPTY
);
$errors['admin_notification_email'] = array();
foreach ($emails as $key => $email)
{
$emails[$key] = trim($email);
if ( ! valid_email($email))
{
$errors['admin_notification_email'][] = str_replace('%email%', $email, lang('non_valid_email'));
}
}
if (empty($errors['admin_notification_email']))
{
unset($errors['admin_notification_email']);
}
$admin_notification_email = implode('|', $emails);
}
else
{
$admin_notification_email = '';
}
// -------------------------------------
// user email field
// -------------------------------------
$user_email_field = ee()->input->get_post('user_email_field');
ee()->load->model('freeform_field_model');
$field_ids = ee()->freeform_field_model->key('field_id', 'field_id')->get();
if ($user_email_field AND
$user_email_field !== '--' AND
trim($user_email_field) !== '' AND
! in_array($user_email_field, $field_ids ))
{
$errors['user_email_field'] = lang('invalid_user_email_field');
}
// -------------------------------------
// errors? For shame :(
// -------------------------------------
if ( ! empty($errors))
{
return $this->actions()->full_stop($errors);
}
//send ajax response exists
//but this is in case someone is using a replacer
//that uses
if ($this->check_yes(ee()->input->get_post('validate_only')))
{
if ($this->is_ajax_request())
{
$this->send_ajax_response(array(
'success' => TRUE,
'errors' => array()
));
}
exit();
}
// -------------------------------------
// field ids
// -------------------------------------
$field_ids = array_filter(
$this->actions()->pipe_split(
ee()->input->get_post('field_ids', TRUE)
),
array($this, 'is_positive_intlike')
);
$sorted_field_ids = $field_ids;
sort($sorted_field_ids);
// -------------------------------------
// insert data
// -------------------------------------
$data = array(
'form_name' => strip_tags($form_name),
'form_label' => strip_tags($form_label),
'default_status' => $default_status,
'user_notification_id' => $this->get_post_or_zero('user_notification_id'),
'admin_notification_id' => $this->get_post_or_zero('admin_notification_id'),
'admin_notification_email' => $admin_notification_email,
'form_description' => strip_tags(ee()->input->get_post('form_description', TRUE)),
'author_id' => ee()->session->userdata('member_id'),
'field_ids' => implode('|', $sorted_field_ids),
'field_order' => implode('|', $field_ids),
'notify_admin' => (
(ee()->input->get_post('notify_admin') == 'y') ? 'y' : 'n'
),
'notify_user' => (
(ee()->input->get_post('notify_user') == 'y') ? 'y' : 'n'
),
'user_email_field' => $user_email_field,
);
//load the forms model if its not been already
ee()->load->library('freeform_forms');
if ($do_composer)
{
unset($data['field_ids']);
unset($data['field_order']);
}
if ($update)
{
unset($data['author_id']);
if ( ! $do_composer)
{
$data['composer_id'] = 0;
}
ee()->freeform_forms->update_form($form_id, $data);
}
else
{
//we don't want this running on update, will only happen for dupes
$composer_id = $this->get_post_or_zero('composer_id');
//this is a dupe and they want composer to dupe too?
if ($do_composer AND $composer_id > 0)
{
ee()->load->model('freeform_composer_model');
$composer_data = ee()->freeform_composer_model
->select('composer_data')
->where('composer_id', $composer_id)
->get_row();
if ($composer_data !== FALSE)
{
$data['composer_id'] = ee()->freeform_composer_model->insert(
array(
'composer_data' => $composer_data['composer_data'],
'site_id' => ee()->config->item('site_id')
)
);
}
}
$form_id = ee()->freeform_forms->create_form($data);
}
// -------------------------------------
// return
// -------------------------------------
if ( ! $composer_save_finish AND $do_composer)
{
ee()->functions->redirect($this->mod_link(array(
'method' => 'form_composer',
'form_id' => $form_id,
'msg' => 'edit_form_success'
)));
}
//'save and finish, default'
else
{
ee()->functions->redirect($this->mod_link(array(
'method' => 'forms',
'msg' => 'edit_form_success'
)));
}
}
//END save_form
// --------------------------------------------------------------------
/**
* Save Entry
*
* @access public
* @return null redirect
*/
public function save_entry ()
{
// -------------------------------------
// edit?
// -------------------------------------
$form_id = $this->get_post_or_zero('form_id');
$entry_id = $this->get_post_or_zero('entry_id');
ee()->load->model('freeform_form_model');
ee()->load->model('freeform_entry_model');
ee()->load->library('freeform_forms');
ee()->load->library('freeform_fields');
$form_data = $this->data->get_form_info($form_id);
// -------------------------------------
// valid form id
// -------------------------------------
if ( ! $form_data)
{
return $this->actions()->full_stop(lang('invalid_form_id'));
}
$previous_inputs = array();
if ( $entry_id > 0)
{
$entry_data = ee()->freeform_entry_model
->id($form_id)
->where('entry_id', $entry_id)
->get_row();
if ( ! $entry_data)
{
return $this->actions()->full_stop(lang('invalid_entry_id'));
}
$previous_inputs = $entry_data;
}
// -------------------------------------
// form data
// -------------------------------------
$field_labels = array();
$valid_fields = array();
foreach ( $form_data['fields'] as $row)
{
$field_labels[$row['field_name']] = $row['field_label'];
$valid_fields[] = $row['field_name'];
}
// -------------------------------------
// is this an edit? entry_id
// -------------------------------------
$edit = ($entry_id AND $entry_id != 0);
// -------------------------------------
// for hooks
// -------------------------------------
$this->edit = $edit;
$this->multipage = FALSE;
$this->last_page = TRUE;
// -------------------------------------
// prevalidate hook
// -------------------------------------
$errors = array();
//to assist backward compat
$this->field_errors = array();
if (ee()->extensions->active_hook('freeform_module_validate_begin') === TRUE)
{
$backup_errors = $errors;
$errors = ee()->extensions->universal_call(
'freeform_module_validate_begin',
$errors,
$this
);
if (ee()->extensions->end_script === TRUE) return;
//valid data?
if ( ! is_array($errors) AND
$this->check_yes($this->preference('hook_data_protection')))
{
$errors = $backup_errors;
}
}
// -------------------------------------
// validate
// -------------------------------------
$field_input_data = array();
$field_list = array();
// -------------------------------------
// status?
// -------------------------------------
$available_statuses = $this->data->get_form_statuses();
$status = ee()->input->get_post('status');
if ( ! array_key_exists($status, $available_statuses))
{
$field_input_data['status'] = $this->data->defaults['default_form_status'];
}
else
{
$field_input_data['status'] = $status;
}
foreach ($form_data['fields'] as $field_id => $field_data)
{
$field_list[$field_data['field_name']] = $field_data['field_label'];
$field_post = ee()->input->get_post($field_data['field_name']);
//if it's not even in $_POST or $_GET, lets skip input
//unless its an uploaded file, then we'll send false anyway
//because its fieldtype will handle the rest of that work
if ($field_post !== FALSE OR
isset($_FILES[$field_data['field_name']]))
{
$field_input_data[$field_data['field_name']] = $field_post;
}
}
//form fields do thier own validation,
//so lets just get results! (sexy results?)
$this->field_errors = array_merge(
$this->field_errors,
ee()->freeform_fields->validate(
$form_id,
$field_input_data
)
);
// -------------------------------------
// post validate hook
// -------------------------------------
if (ee()->extensions->active_hook('freeform_module_validate_end') === TRUE)
{
$backup_errors = $errors;
$errors = ee()->extensions->universal_call(
'freeform_module_validate_end',
$errors,
$this
);
if (ee()->extensions->end_script === TRUE) return;
//valid data?
if ( ! is_array($errors) AND
$this->check_yes($this->preference('hook_data_protection')))
{
$errors = $backup_errors;
}
}
$errors = array_merge($errors, $this->field_errors);
// -------------------------------------
// halt on errors
// -------------------------------------
if (count($errors) > 0)
{
$this->actions()->full_stop($errors);
}
//send ajax response exists
//but this is in case someone is using a replacer
//that uses
if ($this->check_yes(ee()->input->get_post('validate_only')))
{
if ($this->is_ajax_request())
{
$this->send_ajax_response(array(
'success' => TRUE,
'errors' => array()
));
}
exit();
}
// -------------------------------------
// entry insert begin hook
// -------------------------------------
if (ee()->extensions->active_hook('freeform_module_insert_begin') === TRUE)
{
$backup_field_input_data = $field_input_data;
$field_input_data = ee()->extensions->universal_call(
'freeform_module_insert_begin',
$field_input_data,
$entry_id,
$form_id,
$this
);
if (ee()->extensions->end_script === TRUE) return;
//valid data?
if ( ! is_array($field_input_data) AND
$this->check_yes($this->preference('hook_data_protection')))
{
$field_input_data = $backup_field_input_data;
}
}
// -------------------------------------
// insert/update data into db
// -------------------------------------
if ($edit)
{
ee()->freeform_forms->update_entry(
$form_id,
$entry_id,
$field_input_data
);
}
else
{
$entry_id = ee()->freeform_forms->insert_new_entry(
$form_id,
$field_input_data
);
}
// -------------------------------------
// entry insert begin hook
// -------------------------------------
if (ee()->extensions->active_hook('freeform_module_insert_end') === TRUE)
{
ee()->extensions->universal_call(
'freeform_module_insert_end',
$field_input_data,
$entry_id,
$form_id,
$this
);
if (ee()->extensions->end_script === TRUE) return;
}
// -------------------------------------
// return
// -------------------------------------
$success_line = ($edit) ? 'edit_entry_success' : 'new_entry_success';
if ($this->is_ajax_request())
{
return $this->send_ajax_response(array(
'form_id' => $form_id,
'entry_id' => $entry_id,
'message' => lang($success_line),
'success' => TRUE
));
}
//'save and finish, default'
else
{
ee()->functions->redirect($this->mod_link(array(
'method' => 'entries',
'form_id' => $form_id,
'msg' => $success_line
)));
}
}
//END edit_entry
// --------------------------------------------------------------------
/**
* approve entries
*
* accepts ajax call to approve entries
* or can be called via another view function on post
*
* @access public
* @param int form id
* @param mixed array or int of entry ids to approve
* @return string
*/
public function approve_entries ($form_id = 0, $entry_ids = array())
{
// -------------------------------------
// valid form id?
// -------------------------------------
if ( ! $form_id OR $form_id <= 0)
{
$form_id = $this->get_post_form_id();
}
if ( ! $form_id)
{
$this->actions()->full_stop(lang('invalid_form_id'));
}
// -------------------------------------
// entry ids?
// -------------------------------------
if ( ! $entry_ids OR empty($entry_ids) )
{
$entry_ids = $this->get_post_entry_ids();
}
//check
if ( ! $entry_ids)
{
$this->actions()->full_stop(lang('invalid_entry_id'));
}
// -------------------------------------
// approve!
// -------------------------------------
$updates = array();
foreach($entry_ids as $entry_id)
{
$updates[] = array(
'entry_id' => $entry_id,
'status' => 'open'
);
}
ee()->load->model('freeform_form_model');
ee()->db->update_batch(
ee()->freeform_form_model->table_name($form_id),
$updates,
'entry_id'
);
// -------------------------------------
// success
// -------------------------------------
if ($this->is_ajax_request())
{
$this->send_ajax_response(array(
'success' => TRUE
));
exit();
}
else
{
$method = ee()->input->get_post('return_method');
$method = ($method AND is_callable(array($this, $method))) ?
$method :
'moderate_entries';
ee()->functions->redirect($this->mod_link(array(
'method' => $method,
'form_id' => $form_id,
'msg' => 'entries_approved'
)));
}
}
//END approve_entry
// --------------------------------------------------------------------
/**
* get/post form_id
*
* gets and validates the current form_id possibly passed
*
* @access private
* @param bool validate form_id
* @return mixed integer of passed in form_id or bool false
*/
private function get_post_form_id ($validate = TRUE)
{
$form_id = $this->get_post_or_zero('form_id');
if ($form_id == 0 OR
($validate AND
! $this->data->is_valid_form_id($form_id))
)
{
return FALSE;
}
return $form_id;
}
//ENd get_post_form_id
// --------------------------------------------------------------------
/**
* get/post entry_ids
*
* gets and validates the current entry possibly passed
*
* @access private
* @return mixed array of passed in entry_ids or bool false
*/
private function get_post_entry_ids ()
{
$entry_ids = ee()->input->get_post('entry_ids');
if ( ! is_array($entry_ids) AND
! $this->is_positive_intlike($entry_ids))
{
return FALSE;
}
if ( ! is_array($entry_ids))
{
$entry_ids = array($entry_ids);
}
//clean and validate each as int
$entry_ids = array_filter($entry_ids, array($this, 'is_positive_intlike'));
if (empty($entry_ids))
{
return FALSE;
}
return $entry_ids;
}
//END get_post_entry_ids
// --------------------------------------------------------------------
/**
* delete_confirm_entries
*
* accepts ajax call to delete entry
* or can be called via another view function on post
*
* @access public
* @param int form id
* @param mixed array or int of entry ids to delete
* @return string
*/
public function delete_confirm_entries ($form_id = 0, $entry_ids = array())
{
// -------------------------------------
// ajax requests should be doing front
// end delete confirm. This also handles
// the ajax errors properly
// -------------------------------------
if ( $this->is_ajax_request())
{
return $this->delete_entries();
}
// -------------------------------------
// form id?
// -------------------------------------
if ( ! $form_id OR $form_id <= 0)
{
$form_id = $this->get_post_form_id();
}
if ( ! $form_id)
{
$this->show_error(lang('invalid_form_id'));
}
// -------------------------------------
// entry ids?
// -------------------------------------
if ( ! $entry_ids OR empty($entry_ids) )
{
$entry_ids = $this->get_post_entry_ids();
}
//check
if ( ! $entry_ids)
{
$this->show_error(lang('invalid_entry_id'));
}
// -------------------------------------
// return method?
// -------------------------------------
$return_method = ee()->input->get_post('return_method');
$return_method = ($return_method AND
is_callable(array($this, $return_method))) ?
$return_method :
'entries';
// -------------------------------------
// confirmation page
// -------------------------------------
return $this->delete_confirm(
'delete_entries',
array(
'form_id' => $form_id,
'entry_ids' => $entry_ids,
'return_method' => $return_method
),
'confirm_delete_entries'
);
}
//END delete_confirm_entries
// --------------------------------------------------------------------
/**
* delete entries
*
* accepts ajax call to delete entry
* or can be called via another view function on post
*
* @access public
* @param int form id
* @param mixed array or int of entry ids to delete
* @return string
*/
public function delete_entries ($form_id = 0, $entry_ids = array())
{
// -------------------------------------
// valid form id?
// -------------------------------------
if ( ! $this->is_positive_intlike($form_id))
{
$form_id = $this->get_post_form_id();
}
if ( ! $form_id)
{
$this->actions()->full_stop(lang('invalid_form_id'));
}
// -------------------------------------
// entry ids?
// -------------------------------------
if ( ! $entry_ids OR empty($entry_ids) )
{
$entry_ids = $this->get_post_entry_ids();
}
//check
if ( ! $entry_ids)
{
$this->actions()->full_stop(lang('invalid_entry_id'));
}
ee()->load->library('freeform_forms');
$success = ee()->freeform_forms->delete_entries($form_id, $entry_ids);
// -------------------------------------
// success
// -------------------------------------
if ($this->is_ajax_request())
{
$this->send_ajax_response(array(
'success' => $success
));
}
else
{
$method = ee()->input->get_post('return_method');
$method = ($method AND is_callable(array($this, $method))) ?
$method : 'entries';
ee()->functions->redirect($this->mod_link(array(
'method' => $method,
'form_id' => $form_id,
'msg' => 'entries_deleted'
)));
}
}
//END delete_entries
// --------------------------------------------------------------------
/**
* Confirm Delete Fields
*
* @access public
* @return html
*/
public function delete_confirm_fields ()
{
//the following fields will be deleted
//the following forms will be affected
//they contain the forms..
$field_ids = ee()->input->get_post('field_id', TRUE);
if ( ! is_array($field_ids) AND
! $this->is_positive_intlike($field_ids) )
{
$this->actions()->full_stop(lang('no_field_ids_submitted'));
}
//already checked for numeric :p
if ( ! is_array($field_ids))
{
$field_ids = array($field_ids);
}
$delete_field_confirmation = '';
$clean_field_ids = array();
foreach ($field_ids as $field_id)
{
if ($this->is_positive_intlike($field_id))
{
$clean_field_ids[] = $field_id;
}
}
if (empty($clean_field_ids))
{
$this->actions()->full_stop(lang('no_field_ids_submitted'));
}
// -------------------------------------
// build a list of forms affected by fields
// -------------------------------------
ee()->db->where_in('field_id', $clean_field_ids);
$all_field_data = ee()->db->get('freeform_fields');
$delete_field_confirmation = lang('delete_field_confirmation');
$extra_form_data = '';
foreach ($all_field_data->result_array() as $row)
{
//this doesn't get field data, so we had to above;
$field_form_data = $this->data->get_form_info_by_field_id($row['field_id']);
// -------------------------------------
// get each form affected by each field listed
// and show the user what forms will be affected
// -------------------------------------
if ( $field_form_data !== FALSE )
{
$freeform_affected = array();
foreach ($field_form_data as $form_id => $form_data)
{
$freeform_affected[] = $form_data['form_label'];
}
$extra_form_data .= '<p>' .
'<strong>' .
$row['field_label'] .
'</strong>: ' .
implode(', ', $freeform_affected) .
'</p>';
}
}
//if we have anything, add some extra warnings
if ($extra_form_data != '')
{
$delete_field_confirmation .= '<p>' .
lang('freeform_will_lose_data') .
'</p>' .
$extra_form_data;
}
return $this->delete_confirm(
'delete_fields',
array('field_id' => $clean_field_ids),
$delete_field_confirmation,
'delete',
FALSE
);
}
//END delete_confirm_fields
// --------------------------------------------------------------------
/**
* utilities
*
* @access public
* @return string
*/
public function utilities ( $message = '' )
{
if ($message == '' AND ee()->input->get('msg') !== FALSE)
{
$message = lang(ee()->input->get('msg'));
}
$this->cached_vars['message'] = $message;
//--------------------------------------
// Title and Crumbs
//--------------------------------------
$this->add_crumb(lang('utilities'));
$this->set_highlight('module_utilities');
//--------------------------------------
// Counts
//--------------------------------------
ee()->load->library('freeform_migration');
$this->cached_vars['counts'] = ee()->freeform_migration->get_collection_counts();
// $test = ee()->freeform_migration->create_upload_field( 1, 'goff', array( 'file_upload_location' => '1' ) );
// print_r( $test ); print_r( ee()->freeform_migration->get_errors() );
//--------------------------------------
// File upload field installed?
//--------------------------------------
$this->cached_vars['file_upload_installed'] = ee()->freeform_migration->get_field_type_installed('file_upload');
$query = ee()->db->query( "SELECT * FROM exp_freeform_fields WHERE field_type = 'file_upload'" );
//--------------------------------------
// Load vars
//--------------------------------------
$this->cached_vars['form_uri'] = $this->mod_link(array(
'method' => 'migrate_collections'
));
//--------------------------------------
// Load page
//--------------------------------------
$this->cached_vars['current_page'] = $this->view(
'utilities.html',
NULL,
TRUE
);
return $this->ee_cp_view('index.html');
}
// End utilities
// --------------------------------------------------------------------
/**
* Confirm Uninstall Fieldtypes
*
* @access public
* @return html
*/
public function uninstall_confirm_fieldtype ($name = '')
{
$name = trim($name);
if ($name == '')
{
ee()->functions->redirect($this->base);
}
ee()->load->model('freeform_field_model');
$items = ee()->freeform_field_model
->key('field_label', 'field_label')
->get(array('field_type' => $name));
if ($items == FALSE)
{
return $this->uninstall_fieldtype($name);
}
else
{
$confirmation = '<p>' . lang('following_fields_converted') . ': <strong>';
$confirmation .= implode(', ', $items) . '</strong></p>';
return $this->delete_confirm(
'uninstall_fieldtype',
array('fieldtype' => $name),
$confirmation,
'uninstall',
FALSE
);
}
}
//END uninstall_confirm_fieldtype
// --------------------------------------------------------------------
/**
* Uninstalls fieldtypes
*
* @access public
* @param string $name fieldtype name to remove
* @return void
*/
public function uninstall_fieldtype ($name = '', $redirect = TRUE)
{
if ($name == '')
{
$name = ee()->input->get_post('fieldtype', TRUE);
}
if ( ! $name)
{
$this->actions()->full_stop(lang('no_fieldtypes_submitted'));
}
ee()->load->library('freeform_fields');
$success = ee()->freeform_fields->uninstall_fieldtype($name);
if ( ! $redirect)
{
return $success;
}
if ($this->is_ajax_request())
{
$this->send_ajax_response(array(
'success' => $success,
'message' => lang('fieldtype_uninstalled'),
));
}
else
{
ee()->functions->redirect($this->mod_link(array(
'method' => 'fieldtypes',
'msg' => 'fieldtype_uninstalled'
)));
}
}
//END uninstall_fieldtype
// --------------------------------------------------------------------
/**
* Delete Fields
*
* @access public
* @return void
*/
public function delete_fields ()
{
// -------------------------------------
// safety goggles
// -------------------------------------
//
$field_ids = ee()->input->get_post('field_id', TRUE);
if ( ! is_array($field_ids) AND
! $this->is_positive_intlike($field_ids) )
{
$this->actions()->full_stop(lang('no_field_ids_submitted'));
}
//already checked for numeric :p
if ( ! is_array($field_ids))
{
$field_ids = array($field_ids);
}
// -------------------------------------
// delete fields
// -------------------------------------
ee()->load->library('freeform_fields');
ee()->freeform_fields->delete_field($field_ids);
// -------------------------------------
// success
// -------------------------------------
if ($this->is_ajax_request())
{
$this->send_ajax_response(array(
'success' => TRUE
));
}
else
{
ee()->functions->redirect($this->mod_link(array(
'method' => 'fields',
'msg' => 'fields_deleted'
)));
}
}
//END delete_fields
// --------------------------------------------------------------------
/**
* Confirm deletion of notifications
*
* accepts ajax call to delete notification
*
* @access public
* @param int form id
* @param mixed array or int of notification ids to delete
* @return string
*/
public function delete_confirm_notification ($notification_id = 0)
{
// -------------------------------------
// ajax requests should be doing front
// end delete confirm. This also handles
// the ajax errors properly
// -------------------------------------
if ( $this->is_ajax_request())
{
return $this->delete_notification();
}
// -------------------------------------
// entry ids?
// -------------------------------------
if ( ! is_array($notification_id) AND
! $this->is_positive_intlike($notification_id))
{
$notification_id = ee()->input->get_post('notification_id');
}
if ( ! is_array($notification_id) AND
! $this->is_positive_intlike($notification_id))
{
$this->actions()->full_stop(lang('invalid_notification_id'));
}
if ( is_array($notification_id))
{
$notification_id = array_filter(
$notification_id,
array($this, 'is_positive_intlike')
);
}
else
{
$notification_id = array($notification_id);
}
// -------------------------------------
// confirmation page
// -------------------------------------
return $this->delete_confirm(
'delete_notification',
array(
'notification_id' => $notification_id,
'return_method' => 'notifications'
),
'confirm_delete_notification'
);
}
//END delete_confirm_notification
// --------------------------------------------------------------------
/**
* Delete Notifications
*
* @access public
* @param integer $notification_id notification
* @return null
*/
public function delete_notification ($notification_id = 0)
{
// -------------------------------------
// entry ids?
// -------------------------------------
if ( ! is_array($notification_id) AND
! $this->is_positive_intlike($notification_id))
{
$notification_id = ee()->input->get_post('notification_id');
}
if ( ! is_array($notification_id) AND
! $this->is_positive_intlike($notification_id))
{
$this->actions()->full_stop(lang('invalid_notification_id'));
}
if ( is_array($notification_id))
{
$notification_id = array_filter(
$notification_id,
array($this, 'is_positive_intlike')
);
}
else
{
$notification_id = array($notification_id);
}
ee()->load->model('freeform_notification_model');
$success = ee()->freeform_notification_model
->where_in('notification_id', $notification_id)
->delete();
// -------------------------------------
// success
// -------------------------------------
if ($this->is_ajax_request())
{
$this->send_ajax_response(array(
'success' => $success
));
}
else
{
$method = ee()->input->get_post('return_method');
$method = ($method AND is_callable(array($this, $method))) ?
$method : 'notifications';
ee()->functions->redirect($this->mod_link(array(
'method' => $method,
'msg' => 'delete_notification_success'
)));
}
}
//END delete_notification
// --------------------------------------------------------------------
/**
* save_field
*
* @access public
* @return void (redirect)
*/
public function save_field ()
{
// -------------------------------------
// field ID? we must be editing
// -------------------------------------
$field_id = $this->get_post_or_zero('field_id');
$update = ($field_id != 0);
// -------------------------------------
// yes or no items (all default yes)
// -------------------------------------
$y_or_n = array('submissions_page', 'moderation_page', 'composer_use');
foreach ($y_or_n as $item)
{
//set as local var
$$item = $this->check_no(ee()->input->get_post($item)) ? 'n' : 'y';
}
// -------------------------------------
// field instance
// -------------------------------------
$field_type = ee()->input->get_post('field_type', TRUE);
ee()->load->library('freeform_fields');
ee()->load->model('freeform_field_model');
$available_fieldtypes = ee()->freeform_fields->get_available_fieldtypes();
//get the update with previous settings if this is an edit
if ($update)
{
$field = ee()->freeform_field_model
->where('field_id', $field_id)
->where('field_type', $field_type)
->count();
//make sure that we have the correct type just in case they
//are changing type like hooligans
if ($field)
{
$field_instance =& ee()->freeform_fields->get_field_instance($field_id);
}
else
{
$field_instance =& ee()->freeform_fields->get_fieldtype_instance($field_type);
}
}
else
{
$field_instance =& ee()->freeform_fields->get_fieldtype_instance($field_type);
}
// -------------------------------------
// error on empty items or bad data
// (doing this via ajax in the form as well)
// -------------------------------------
$errors = array();
// -------------------------------------
// field name
// -------------------------------------
$field_name = ee()->input->get_post('field_name', TRUE);
//if the field label is blank, make one for them
//we really dont want to do this, but here we are
if ( ! $field_name OR ! trim($field_name))
{
$errors['field_name'] = lang('field_name_required');
}
else
{
$field_name = strtolower(trim($field_name));
if ( in_array($field_name, $this->data->prohibited_names ) )
{
$errors['field_name'] = str_replace(
'%name%',
$field_name,
lang('freeform_reserved_field_name')
);
}
//if the field_name they submitted isn't like how a URL title may be
//also, cannot be numeric
if (preg_match('/[^a-z0-9\_\-]/i', $field_name) OR
is_numeric($field_name))
{
$errors['field_name'] = lang('field_name_can_only_contain');
}
//get dupe from field names
$f_query = ee()->db->select('field_name, field_id')->get_where(
'freeform_fields',
array('field_name' => $field_name)
);
//if we are updating, we don't want to error on the same field id
if ($f_query->num_rows() > 0 AND
! ($update AND $f_query->row('field_id') == $field_id))
{
$errors['field_name'] = str_replace(
'%name%',
$field_name,
lang('field_name_exists')
);
}
}
// -------------------------------------
// field label
// -------------------------------------
$field_label = ee()->input->get_post('field_label', TRUE);
if ( ! $field_label OR ! trim($field_label) )
{
$errors['field_label'] = lang('field_label_required');
}
// -------------------------------------
// field type
// -------------------------------------
if ( ! $field_type OR ! array_key_exists($field_type, $available_fieldtypes))
{
$errors['field_type'] = lang('invalid_fieldtype');
}
// -------------------------------------
// field settings errors?
// -------------------------------------
$field_settings_validate = $field_instance->validate_settings();
if ( $field_settings_validate !== TRUE)
{
if (is_array($field_settings_validate))
{
$errors['field_settings'] = $field_settings_validate;
}
else if (! empty($field_instance->errors))
{
$errors['field_settings'] = $field_instance->errors;
}
else
{
$errors['field_settings'] = lang('field_settings_error');
}
}
// -------------------------------------
// errors? For shame :(
// -------------------------------------
if ( ! empty($errors))
{
return $this->actions()->full_stop($errors);
}
if ($this->check_yes(ee()->input->get_post('validate_only')) AND
$this->is_ajax_request())
{
$this->send_ajax_response(array(
'success' => TRUE
));
}
// -------------------------------------
// insert data
// -------------------------------------
$data = array(
'field_name' => strip_tags($field_name),
'field_label' => strip_tags($field_label),
'field_type' => $field_type,
'edit_date' => '0', //overridden if update
'field_description' => strip_tags(ee()->input->get_post('field_description', TRUE)),
'submissions_page' => $submissions_page,
'moderation_page' => $moderation_page,
'composer_use' => $composer_use,
'settings' => json_encode($field_instance->save_settings())
);
if ($update)
{
ee()->freeform_field_model->update(
array_merge(
$data,
array(
'edit_date' => ee()->localize->now
)
),
array('field_id' => $field_id)
);
}
else
{
$field_id = ee()->freeform_field_model->insert(
array_merge(
$data,
array(
'author_id' => ee()->session->userdata('member_id'),
'entry_date' => ee()->localize->now,
'site_id' => ee()->config->item('site_id')
)
)
);
}
$field_instance->field_id = $field_id;
$field_instance->post_save_settings();
$field_in_forms = array();
if ($update)
{
$field_in_forms = $this->data->get_form_info_by_field_id($field_id);
if ($field_in_forms)
{
$field_in_forms = array_keys($field_in_forms);
}
else
{
$field_in_forms = array();
}
}
$form_ids = ee()->input->get_post('form_ids');
if ($form_ids !== FALSE)
{
$form_ids = preg_split(
'/\|/',
$form_ids,
-1,
PREG_SPLIT_NO_EMPTY
);
}
else
{
$form_ids = array();
}
if ( ! (empty($form_ids) AND empty($field_in_forms)))
{
$remove = array_unique(array_diff($field_in_forms, $form_ids));
$add = array_unique(array_diff($form_ids, $field_in_forms));
ee()->load->library('freeform_forms');
foreach ($add as $add_id)
{
ee()->freeform_forms->add_field_to_form($add_id, $field_id);
}
foreach ($remove as $remove_id)
{
ee()->freeform_forms->remove_field_from_form($remove_id, $field_id);
}
}
// -------------------------------------
// success
// -------------------------------------
if ($this->is_ajax_request())
{
$return = array(
'success' => TRUE,
'field_id' => $field_id,
);
if ($this->check_yes(ee()->input->get_post('include_field_data')))
{
$return['composerFieldData'] = $this->composer_field_data($field_id, NULL, TRUE);
}
$this->send_ajax_response($return);
}
else
{
//redirect back to fields on success
ee()->functions->redirect($this->mod_link(array(
'method' => 'fields',
'msg' => 'edit_field_success'
)));
}
}
//END save_field
// --------------------------------------------------------------------
/**
* save_notification
*
* @access public
* @return null (redirect)
*/
public function save_notification ()
{
// -------------------------------------
// notification ID? we must be editing
// -------------------------------------
$notification_id = $this->get_post_or_zero('notification_id');
$update = ($notification_id != 0);
// -------------------------------------
// yes or no items (default yes)
// -------------------------------------
$y_or_n = array('wordwrap');
foreach ($y_or_n as $item)
{
//set as local var
$$item = $this->check_no(ee()->input->get_post($item)) ? 'n' : 'y';
}
// -------------------------------------
// yes or no items (default no)
// -------------------------------------
$n_or_y = array('allow_html', 'include_attachments');
foreach ($n_or_y as $item)
{
//set as local var
$$item = $this->check_yes(ee()->input->get_post($item)) ? 'y' : 'n';
}
// -------------------------------------
// error on empty items or bad data
// (doing this via ajax in the form as well)
// -------------------------------------
$errors = array();
// -------------------------------------
// notification name
// -------------------------------------
$notification_name = ee()->input->get_post('notification_name', TRUE);
//if the field label is blank, make one for them
//we really dont want to do this, but here we are
if ( ! $notification_name OR ! trim($notification_name))
{
$errors['notification_name'] = lang('notification_name_required');
}
else
{
$notification_name = strtolower(trim($notification_name));
if ( in_array($notification_name, $this->data->prohibited_names ) )
{
$errors['notification_name'] = str_replace(
'%name%',
$notification_name,
lang('reserved_notification_name')
);
}
//if the field_name they submitted isn't like how a URL title may be
//also, cannot be numeric
if (preg_match('/[^a-z0-9\_\-]/i', $notification_name) OR
is_numeric($notification_name))
{
$errors['notification_name'] = lang('notification_name_can_only_contain');
}
//get dupe from field names
ee()->db->select('notification_name, notification_id');
$f_query = ee()->db->get_where(
'freeform_notification_templates',
array(
'notification_name' => $notification_name
)
);
//if we are updating, we don't want to error on the same field id
if ($f_query->num_rows() > 0 AND
! ($update AND $f_query->row('notification_id') == $notification_id))
{
$errors['notification_name'] = str_replace(
'%name%',
$notification_name,
lang('notification_name_exists')
);
}
}
// -------------------------------------
// notification label
// -------------------------------------
$notification_label = ee()->input->get_post('notification_label', TRUE);
if ( ! $notification_label OR ! trim($notification_label) )
{
$errors['notification_label'] = lang('notification_label_required');
}
ee()->load->helper('email');
// -------------------------------------
// notification email
// -------------------------------------
$from_email = ee()->input->get_post('from_email', TRUE);
if ($from_email AND trim($from_email) != '')
{
$from_email = trim($from_email);
//allow tags
if ( ! preg_match('/' . LD . '([a-zA-Z0-9\_]+)' . RD . '/is', $from_email))
{
if ( ! valid_email($from_email))
{
$errors['from_email'] = str_replace(
'%email%',
$from_email,
lang('non_valid_email')
);
}
}
}
// -------------------------------------
// from name
// -------------------------------------
$from_name = ee()->input->get_post('from_name', TRUE);
if ( ! $from_name OR ! trim($from_name) )
{
//$errors['from_name'] = lang('from_name_required');
}
// -------------------------------------
// reply to email
// -------------------------------------
$reply_to_email = ee()->input->get_post('reply_to_email', TRUE);
if ($reply_to_email AND trim($reply_to_email) != '')
{
$reply_to_email = trim($reply_to_email);
//allow tags
if ( ! preg_match('/' . LD . '([a-zA-Z0-9\_]+)' . RD . '/is', $reply_to_email))
{
if ( ! valid_email($reply_to_email))
{
$errors['reply_to_email'] = str_replace(
'%email%',
$reply_to_email,
lang('non_valid_email')
);
}
}
}
else
{
$reply_to_email = '';
}
// -------------------------------------
// email subject
// -------------------------------------
$email_subject = ee()->input->get_post('email_subject', TRUE);
if ( ! $email_subject OR ! trim($email_subject) )
{
$errors['email_subject'] = lang('email_subject_required');
}
// -------------------------------------
// errors? For shame :(
// -------------------------------------
if ( ! empty($errors))
{
return $this->actions()->full_stop($errors);
}
//ajax checking?
else if ($this->check_yes(ee()->input->get_post('validate_only')))
{
return $this->send_ajax_response(array(
'success' => TRUE
));
}
// -------------------------------------
// insert data
// -------------------------------------
$data = array(
'notification_name' => strip_tags($notification_name),
'notification_label' => strip_tags($notification_label),
'notification_description' => strip_tags(ee()->input->get_post('notification_description', TRUE)),
'wordwrap' => $wordwrap,
'allow_html' => $allow_html,
'from_name' => $from_name,
'from_email' => $from_email,
'reply_to_email' => $reply_to_email,
'email_subject' => strip_tags($email_subject),
'template_data' => ee()->input->get_post('template_data'),
'include_attachments' => $include_attachments
);
ee()->load->model('freeform_notification_model');
if ($update)
{
ee()->freeform_notification_model->update(
$data,
array('notification_id' => $notification_id)
);
}
else
{
$notification_id = ee()->freeform_notification_model->insert(
array_merge(
$data,
array(
'site_id' => ee()->config->item('site_id')
)
)
);
}
// -------------------------------------
// ajax?
// -------------------------------------
if ($this->is_ajax_request())
{
$this->send_ajax_response(array(
'success' => TRUE,
'notification_id' => $notification_id
));
}
else
{
//redirect back to fields on success
ee()->functions->redirect($this->mod_link(array(
'method' => 'notifications',
'msg' => 'edit_notification_success'
)));
}
}
//END save_notification
// --------------------------------------------------------------------
/**
* Sets the menu highlight and assists with permissions (Freeform Pro)
*
* @access protected
* @param string $menu_item The menu item to highlight
*/
protected function set_highlight($menu_item = 'module_forms')
{
$this->cached_vars['module_menu_highlight'] = $menu_item;
}
//END set_highlight
// --------------------------------------------------------------------
/**
* save_preferences
*
* @access public
* @return null (redirect)
*/
public function save_preferences()
{
//defaults are in data.freeform.php
$prefs = array();
$all_prefs = array_merge(
$this->data->default_preferences,
$this->data->default_global_preferences
);
//check post input for all existing prefs and default if not present
foreach($all_prefs as $pref_name => $data)
{
$input = ee()->input->get_post($pref_name, TRUE);
//default
$output = $data['value'];
//int
if ($data['type'] == 'int' AND
$this->is_positive_intlike($input, -1))
{
$output = $input;
}
//yes or no
elseif ($data['type'] == 'y_or_n' AND
in_array(trim($input), array('y', 'n'), TRUE))
{
$output = trim($input);
}
//list of items
//this seems nutty, but this serializes the list of items
elseif ($data['type'] == 'list')
{
//lotses?
if (is_array($input))
{
$temp_input = array();
foreach ($input as $key => $value)
{
if (trim($value) !== '')
{
$temp_input[] = trim($value);
}
}
$output = json_encode($temp_input);
}
//just one :/
else if (trim($input) !== '')
{
$output = json_encode(array(trim($input)));
}
}
//text areas
elseif ($data['type'] == 'text' OR
$data['type'] == 'textarea' )
{
$output = trim($input);
}
$prefs[$pref_name] = $output;
}
//send all prefs to DB
$this->data->set_module_preferences($prefs);
// ----------------------------------
// Redirect to Homepage with Message
// ----------------------------------
ee()->functions->redirect(
$this->base .
AMP . 'method=preferences' .
AMP . 'msg=preferences_updated'
);
}
//END save_preferences
// --------------------------------------------------------------------
/**
* Export Entries
*
* Calls entries with proper flags to cue export
*
* @access public
* @return mixed forces a download of the exported items or error
*/
public function export_entries ()
{
$moderate = (ee()->input->get_post('moderate') == 'true');
return $this->entries(NULL, $moderate, TRUE);
}
//END export_entries
// --------------------------------------------------------------------
/**
* get_standard_column_names
*
* gets the standard column names and replaces author_id with author
*
* @access private
* @return null
*/
private function get_standard_column_names()
{
$standard_columns = array_keys(
ee()->freeform_form_model->default_form_table_columns
);
array_splice(
$standard_columns,
array_search('author_id', $standard_columns),
1,
'author'
);
return $standard_columns;
}
//END get_standard_column_names
// --------------------------------------------------------------------
/**
* mod_link
*
* makes $this->base . AMP . 'key=value' out of arrays
*
* @access public
* @param array key value pair of get vars to add to base
* @param bool $real_amp use a real ampersand?
* @return string
*/
private function mod_link ($vars = array(), $real_amp = FALSE)
{
$link = $this->base;
$amp = $real_amp ? '&' : AMP;
if ($real_amp)
{
$link = str_replace(AMP, '&', $link);
}
else
{
//Swap all to regular amp first so we don't get false
//positives. Could do this with negative lookups, but
//those are spottier than this.
$link = str_replace('&', AMP, str_replace(AMP, '&', $link));
}
if ( ! empty($vars))
{
foreach ($vars as $key => $value)
{
$link .= $amp . $key . '=' . $value;
}
}
return $link;
}
//END mod_link
// --------------------------------------------------------------------
/**
* load_fancybox
*
* loads fancybox jquery UI plugin and its needed css
*
* @access private
* @return null
*/
private function load_fancybox()
{
//so currently the fancybox setup inlucded in EE doesn't get built
//automaticly and requires relying on the current CP theme.
//Dislike. Inlcuding our own version instead.
//Seems fancy box has also been removed from some later versions
//of EE, so instinct here was correct.
$css_link = $this->sc->addon_theme_url . 'fancybox/jquery.fancybox-1.3.4.css';
$js_link = $this->sc->addon_theme_url . 'fancybox/jquery.fancybox-1.3.4.pack.js';
ee()->cp->add_to_head('<link href="' . $css_link . '" type="text/css" rel="stylesheet" media="screen" />');
ee()->cp->add_to_foot('<script src="' . $js_link . '" type="text/javascript"></script>');
}
//END load_fancybox
// --------------------------------------------------------------------
/**
* freeform_add_right_link
*
* abstractor for cp add_right_link so freeform can move it how it needs
* when an alternate style is chosen
*
* @access private
* @param string words of link to display
* @param string link to display
* @return null
*/
private function freeform_add_right_link ($lang, $link)
{
$this->cached_vars['inner_nav_links'][$lang] = $link;
//return $this->add_right_link($lang, $link);
}
//END freeform_add_right_link
// --------------------------------------------------------------------
/**
* Module Upgrading
*
* This function is not required by the 1.x branch of ExpressionEngine by default. However,
* as the install and deinstall ones are, we are just going to keep the habit and include it
* anyhow.
* - Originally, the $current variable was going to be passed via parameter, but as there might
* be a further use for such a variable throughout the module at a later date we made it
* a class variable.
*
*
* @access public
* @return bool
*/
public function freeform_module_update()
{
if ( ! isset($_POST['run_update']) OR $_POST['run_update'] != 'y')
{
$this->add_crumb(lang('update_freeform_module'));
$this->build_crumbs();
$this->cached_vars['form_url'] = $this->base . '&msg=update_successful';
if ($this->pro_update)
{
$this->cached_vars['form_url'] .= "&update_pro=true";
}
$this->cached_vars['current_page'] = $this->view(
'update_module.html',
NULL,
TRUE
);
return $this->ee_cp_view('index.html');
}
require_once $this->addon_path . 'upd.freeform.php';
$U = new Freeform_upd();
if ($U->update() !== TRUE)
{
return ee()->functions->redirect($this->mod_link(array(
'method' => 'index',
'msg' => lang('update_failure')
)));
}
else
{
return ee()->functions->redirect($this->mod_link(array(
'method' => 'index',
'msg' => lang('update_successful')
)));
}
}
// END freeform_module_update()
// --------------------------------------------------------------------
/**
* Visible Columns
*
* @access protected
* @param $possible_columns possible columns
* @return array array of visible columns
*/
protected function visible_columns ($standard_columns = array(),
$possible_columns = array())
{
// -------------------------------------
// get column settings
// -------------------------------------
$column_settings = array();
ee()->load->model('freeform_form_model');
$field_layout_prefs = $this->preference('field_layout_prefs');
$member_id = ee()->session->userdata('member_id');
$group_id = ee()->session->userdata('group_id');
$f_prefix = ee()->freeform_form_model->form_field_prefix;
//¿existe? Member? Group? all?
if ($field_layout_prefs)
{
//$field_layout_prefs = json_decode($field_layout_prefs, TRUE);
$entry_layout_prefs = (
isset($field_layout_prefs['entry_layout_prefs']) ?
$field_layout_prefs['entry_layout_prefs'] :
FALSE
);
if ($entry_layout_prefs)
{
if (isset($entry_layout_prefs['member'][$member_id]))
{
$column_settings = $entry_layout_prefs['member'][$member_id];
}
else if (isset($entry_layout_prefs['all']))
{
$column_settings = $entry_layout_prefs['all'];
}
else if (isset($entry_layout_prefs['group'][$group_id]))
{
$column_settings = $entry_layout_prefs['group'][$group_id];
}
}
}
//if a column is missing, we don't want to error
//and if its newer than the settings, show it by default
//settings are also in order of appearence here.
//we also store the field ids without the prefix
//in case someone changed it. That would probably
//hose everything, but who knows? ;)
if ( ! empty($column_settings))
{
$to_sort = array();
//we are going over possible instead of settings in case something
//is new or an old column is missing
foreach ($possible_columns as $cid)
{
//if these are new, put them at the end
if (! in_array($cid, $column_settings['visible']) AND
! in_array($cid, $column_settings['hidden'])
)
{
$to_sort[$cid] = $cid;
}
}
//now we want columns from the settings order to go first
//this way stuff thats not been removed gets to keep settings
foreach ($column_settings['visible'] as $ecid)
{
if (in_array($ecid, $possible_columns))
{
//since we are getting our real results now
//we can add the prefixes
if ( ! in_array($ecid, $standard_columns) )
{
$ecid = $f_prefix . $ecid;
}
$visible_columns[] = $ecid;
}
}
//and if we have anything left over (new fields probably)
//its at the end
if (! empty($to_sort))
{
foreach ($to_sort as $tsid)
{
//since we are getting our real results now
//we can add the prefixes
if ( ! in_array($tsid, $standard_columns) )
{
$tsid = $f_prefix . $tsid;
}
$visible_columns[] = $tsid;
}
}
}
//if we don't have any settings, just toss it all in in order
else
{
foreach ($possible_columns as $pcid)
{
if ( ! in_array($pcid, $standard_columns) )
{
$pcid = $f_prefix . $pcid;
}
$visible_columns[] = $pcid;
}
//in theory it should always be there if prefs are empty ...
$default_hide = array('site_id', 'entry_id', 'complete');
foreach ($default_hide as $hide_me_seymour)
{
if (in_array($hide_me_seymour, $visible_columns))
{
unset(
$visible_columns[
array_search(
$hide_me_seymour,
$visible_columns
)
]
);
}
}
//fix keys, but preserve order
$visible_columns = array_merge(array(), $visible_columns);
}
return $visible_columns;
}
//END visible_columns
// --------------------------------------------------------------------
/**
* Format CP date
*
* @access public
* @param mixed $date unix time
* @return string unit time formatted to cp date formatting pref
*/
public function format_cp_date($date)
{
return $this->actions()->format_cp_date($date);
}
//END format_cp_date
// --------------------------------------------------------------------
/**
* Send AJAX response
*
* Outputs and exit either an HTML string or a
* JSON array with the Profile disabled and correct
* headers sent.
*
* @access public
* @param string|array String is sent as HTML, Array is sent as JSON
* @param bool Is this an error message?
* @param bool bust cache for JSON?
* @return void
*/
public function send_ajax_response($msg, $error = FALSE, $cache_bust = TRUE)
{
$this->restore_xid();
parent::send_ajax_response($msg, $error, $cache_bust);
}
//END send_ajax_response
// --------------------------------------------------------------------
/**
* EE 2.7+ restore xid with version check
* @access public
* @return voic
*/
public function restore_xid()
{
//deprecated in 2.8. Weeee!
if (version_compare($this->ee_version, '2.7', '>=') &&
version_compare($this->ee_version, '2.8', '<'))
{
ee()->security->restore_xid();
}
}
//END restore_xid
}
// END CLASS Freeform | Java |
<!DOCTYPE html><html><head><meta charset=utf-8><meta itemprop=name content=ESS_在线考试系统><meta name=keywords content="在线考试, 随机试题"><meta name=description content="在线考试系统, 支持随机生成试题, 随机选项, 在线考试"><meta name=viewport content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0"><link rel=icon href=./logo.png><link href=/static/css/app.78dc4afeba3d5b1ec39077e72921911d.css rel=stylesheet></head><body><div id=app></div><script type=text/javascript src=/static/js/manifest.56aba6cf9a8f01b185dd.js></script><script type=text/javascript src=/static/js/vendor.e209ba326b65a769a57a.js></script><script type=text/javascript src=/static/js/app.534dfddb4177c561540f.js></script></body><script src=//at.alicdn.com/t/font_455702_omc7om53zyk138fr.js></script></html> | Java |
/* exported Qualifications */
function Qualifications(skills, items) {
var requirements = {
'soldier': {
meta: {
passPercentage: 100
},
classes: {
'Heavy Assault': {
certifications: [
{ skill: skills.heavyAssault.flakArmor, level: 3 }
],
equipment: []
},
'Light Assault': {
certifications: [
{ skill: skills.lightAssault.flakArmor, level: 3 }
],
equipment: []
},
'Engineer': {
certifications: [
{ skill: skills.engineer.flakArmor, level: 3 },
{ skill: skills.engineer.nanoArmorKit, level: 4 },
{ skill: skills.engineer.tankMine, level: 1 }
],
equipment: []
},
'Medic': {
certifications: [
{ skill: skills.medic.flakArmor, level: 3 },
{ skill: skills.medic.medicalApplicator, level: 4 }
],
equipment: []
},
'Infiltrator': {
certifications: [
{ skill: skills.infiltrator.flakArmor, level: 3 }
],
equipment: []
},
'Sunderer': {
certifications: [
{ skill: skills.sunderer.advancedMobileStation, level: 1 }
],
equipment: []
},
'Squad Leader': {
certifications: [
{ skill: skills.squadLeader.priorityDeployment, level: 0 }
],
equipment: []
}
}
},
'veteran': {
meta: {
passPercentage: 100
},
classes: {
'Heavy Assault': {
certifications: [
{ skill: skills.heavyAssault.resistShield, level: 1 },
{ skill: skills.heavyAssault.antiVehicleGrenade, level: 1 },
{ skill: skills.universal.medicalKit, level: 1 }
],
equipment: []
},
'Light Assault': {
certifications: [
{ skill: skills.lightAssault.c4, level: 2 },
{ skill: skills.lightAssault.drifterJumpJets, level: 2 }
],
equipment: []
},
'Engineer': {
certifications: [
{ skill: skills.engineer.nanoArmorKit, level: 6 },
{ skill: skills.engineer.claymoreMine, level: 2 },
{ skill: skills.engineer.tankMine, level: 2 },
{ skill: skills.engineer.ammunitionPackage, level: 3 },
{ skill: skills.engineer.stickyGrenade, level: 1 }
],
equipment: [
items.weapon.trac5s,
items.engineer.avManaTurret
]
},
'Medic': {
certifications: [
{ skill: skills.medic.medicalApplicator, level: 6 },
{ skill: skills.medic.nanoRegenDevice, level: 6 }
],
equipment: []
},
'Infiltrator': {
certifications: [
{ skill: skills.infiltrator.advancedEquipmentTerminalHacking, level: 3 }
],
equipment: []
},
'Sunderer': {
certifications: [
{ skill: skills.sunderer.vehicleAmmoDispenser, level: 1 },
{ skill: skills.sunderer.blockadeArmor, level: 3 },
{ skill: skills.sunderer.gateShieldDiffuser, level: 2 }
],
equipment: []
},
'Squad Leader': {
certifications: [
{ skill: skills.squadLeader.priorityDeployment, level: 2 }
],
equipment: []
}
}
},
'medic': {
meta: {
passPercentage: 100
},
classes: {
'Loadout: Offensive Medic': {
certifications: [
{ skill: skills.medic.grenadeBandolier, level: 2 },
{ skill: skills.medic.naniteReviveGrenade, level: 1 },
{ skill: skills.medic.nanoRegenDevice, level: 6 },
{ skill: skills.universal.medicalKit, level: 3 }
],
equipment: []
},
'Loadout: Defensive Medic': {
certifications: [
{ skill: skills.medic.flakArmor, level: 4 },
{ skill: skills.medic.naniteReviveGrenade, level: 1 },
{ skill: skills.medic.regenerationField, level: 5 },
{ skill: skills.universal.medicalKit, level: 3 }
],
equipment: []
}
}
},
'engineer': {
meta: {
passPercentage: 100
},
classes: {
'Loadout: Anti-Infantry MANA Turret': {
certifications: [
{ skill: skills.engineer.flakArmor, level: 4 },
{ skill: skills.engineer.claymoreMine, level: 2 }
],
equipment: [
items.weapon.trac5s
]
},
'Loadout: Anti-Vehicle MANA Turret': {
certifications: [
{ skill: skills.engineer.flakArmor, level: 4 },
{ skill: skills.engineer.tankMine, level: 2 },
{ skill: skills.engineer.avManaTurret, level: 1 }
],
equipment: [
items.weapon.trac5s,
items.engineer.avManaTurret
]
}
}
},
'lightAssault': {
meta: {
passPercentage: 100
},
classes: {
'Loadout: Bounty Hunter': {
certifications: [
{ skill: skills.lightAssault.flakArmor, level: 4 },
{ skill: skills.lightAssault.jumpJets, level: 6 },
{ skill: skills.lightAssault.flashGrenade, level: 1 }
],
equipment: []
},
'Loadout: Death From Above': {
certifications: [
{ skill: skills.lightAssault.grenadeBandolier, level: 2 },
{ skill: skills.lightAssault.drifterJumpJets, level: 5 },
{ skill: skills.lightAssault.smokeGrenade, level: 1 }
],
equipment: []
}
}
},
'infiltrator': {
meta: {
passPercentage: 100
},
classes: {
'Loadout: Close Quarters': {
certifications: [
{ skill: skills.infiltrator.flakArmor, level: 4 },
{ skill: skills.infiltrator.grenadeBandolier, level: 2 },
{ skill: skills.infiltrator.reconDetectDevice, level: 6 },
{ skill: skills.infiltrator.claymoreMine, level: 2 },
{ skill: skills.infiltrator.empGrenade, level: 1 }
],
equipment: [
items.weapon.ns7pdw
]
},
'Loadout: Assassin': {
certifications: [
{ skill: skills.infiltrator.ammunitionBelt, level: 3 },
{ skill: skills.infiltrator.motionSpotter, level: 5 },
{ skill: skills.infiltrator.claymoreMine, level: 2 },
{ skill: skills.infiltrator.decoyGrenade, level: 1 },
{ skill: skills.universal.medicalKit, level: 3 }
],
equipment: [
items.weapon.rams
]
}
}
},
'heavyAssault': {
meta: {
passPercentage: 100
},
classes: {
'Loadout: Anti-Infantry': {
certifications: [
{ skill: skills.heavyAssault.grenadeBandolier, level: 2 },
{ skill: skills.heavyAssault.flakArmor, level: 4 },
{ skill: skills.heavyAssault.resistShield, level: 1 },
{ skill: skills.heavyAssault.concussionGrenade, level: 1 },
{ skill: skills.universal.medicalKit, level: 3 }
],
equipment: [
items.weapon.decimator
]
},
'Loadout: Anti-Armor': {
certifications: [
{ skill: skills.heavyAssault.flakArmor, level: 4 },
{ skill: skills.heavyAssault.resistShield, level: 1 },
{ skill: skills.heavyAssault.c4, level: 1 },
{ skill: skills.heavyAssault.antiVehicleGrenade, level: 1 }
],
equipment: [
items.weapon.skep,
items.weapon.grounder
]
}
}
},
'maxUnit': {
meta: {
passPercentage: 100
},
classes: {
'Loadout: Anti-Infantry': {
certifications: [
{ skill: skills.max.kineticArmor, level: 5 },
{ skill: skills.max.lockdown, level: 2 }
],
equipment: [
items.max.leftMercy,
items.max.rightMercy
]
},
'Loadout: Anti-Armor': {
certifications: [
{ skill: skills.max.flakArmor, level: 5 },
{ skill: skills.max.kineticArmor, level: 5 },
{ skill: skills.max.lockdown, level: 2 }
],
equipment: [
items.max.leftPounder,
items.max.rightPounder
]
},
'Loadout: Anti-Air': {
certifications: [
{ skill: skills.max.flakArmor, level: 5 },
{ skill: skills.max.lockdown, level: 2 }
],
equipment: [
items.max.leftBurster,
items.max.rightBurster
]
}
}
},
'basicTanks': {
meta: {
passPercentage: 100
},
classes: {
'Prowler': {
certifications: [
{ skill: skills.prowler.anchoredMode, level: 1 }
],
equipment: [
items.prowler.walker
]
},
'Sunderer': {
certifications: [
{ skill: skills.sunderer.vehicleAmmoDispenser, level: 1 },
{ skill: skills.sunderer.gateShieldDiffuser, level: 2 }
],
equipment: []
}
}
},
'sunderer': {
meta: {
passPercentage: 100
},
classes: {
'Sunderer': {
certifications: [
{ skill: skills.sunderer.mineGuard, level: 4 },
{ skill: skills.sunderer.blockadeArmor, level: 4 },
{ skill: skills.sunderer.gateShieldDiffuser, level: 3 },
{ skill: skills.sunderer.naniteProximityRepairSystem, level: 6 }
],
equipment: []
}
}
},
'prowler': {
meta: {
passPercentage: 100
},
classes: {
'Prowler': {
certifications: [
{ skill: skills.prowler.anchoredMode, level: 4 },
{ skill: skills.prowler.mineGuard, level: 4 }
],
equipment: [
items.prowler.p2120ap,
items.prowler.halberd
]
}
}
},
'lightning': {
meta: {
passPercentage: 100
},
classes: {
'Lightning': {
certifications: [
{ skill: skills.lightning.reinforcedTopArmor, level: 1 }
],
equipment: [
items.lightning.skyguard
]
}
}
},
'harasser': {
meta: {
passPercentage: 100
},
classes: {
'Harasser': {
certifications: [
{ skill: skills.harasser.fireSuppressionSystem, level: 4 },
{ skill: skills.harasser.compositeArmor, level: 4 },
{ skill: skills.harasser.turbo, level: 5 }
],
equipment: [
items.harasser.halberd
]
}
}
},
'commander': {
meta: {
passPercentage: 100
},
classes: {
'Squad Leader': {
certifications: [
{ skill: skills.squadLeader.commandCommChannel, level: 1 },
{ skill: skills.squadLeader.requestReinforcements, level: 1 },
{ skill: skills.squadLeader.rallyPointGreen, level: 1 },
{ skill: skills.squadLeader.rallyPointOrange, level: 1 },
{ skill: skills.squadLeader.rallyPointPurple, level: 1 },
{ skill: skills.squadLeader.rallyPointYellow, level: 1 },
{ skill: skills.squadLeader.priorityDeployment, level: 4 }
],
equipment: []
}
}
}
},
echoHavoc = qual('Echo Havoc', null, null, true),
max = qual('MAX', echoHavoc, requirements.maxUnit),
heavyAssault = qual('Heavy Assault', max, requirements.heavyAssault),
echoCovertOps = qual('Echo Covert Ops', null, null, true),
infiltrator = qual('Infiltrator', echoCovertOps, requirements.infiltrator),
lightAssault = qual('Light Assault', infiltrator, requirements.lightAssault),
echoSpecialist = qual('Echo Specialist', null, null, true),
engineer = qual('Engineer', echoSpecialist, requirements.engineer),
combatMedic = qual('Combat Medic', engineer, requirements.medic),
commander = qual('Commander', null, requirements.commander, true),
sunderer = qual('Sunderer', [ echoSpecialist, echoCovertOps, echoHavoc ], requirements.sunderer),
harasser = qual('Harasser', null, requirements.harasser),
lightning = qual('Lightning', harasser, requirements.lightning),
prowler = qual('Prowler', lightning, requirements.prowler),
basicTanks = qual('Basic Tanks', [ sunderer, prowler ], requirements.basicTanks),
veteran = qual('Veteran', [ combatMedic, lightAssault, heavyAssault, commander ], requirements.veteran, true),
soldier = qual('Soldier', [ veteran, basicTanks ], requirements.soldier, true);
addParentRelationships(soldier);
return soldier;
function qual(name, child, certs, isRank) {
var obj = {};
obj.name = name;
if (child) {
if ($.isArray(child)) {
obj.child = child;
} else {
obj.child = [ child ];
}
}
if (certs) {
obj.cert = certs;
}
if (isRank) {
obj.isRank = true;
}
return obj;
}
function addParentRelationships(rank, parent) {
if (parent) {
if (rank.parent) {
rank.parent.push(parent);
} else {
rank.parent = [ parent ];
}
}
if (rank.child) {
$.each(rank.child, function() {
addParentRelationships(this, rank);
});
}
}
}
| Java |
package addonloader.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
/**
* Simple wrapper around {@link Properites},
* allowing to easily access objects.
* @author Enginecrafter77
*/
public class ObjectSettings extends Properties{
private static final long serialVersionUID = -8939834947658913650L;
private final File path;
public ObjectSettings(File path) throws FileNotFoundException, IOException
{
this.path = path;
this.load(new FileReader(path));
}
public ObjectSettings(String path) throws FileNotFoundException, IOException
{
this(new File(path));
}
public boolean getBoolean(String key, boolean def)
{
return Boolean.parseBoolean(this.getProperty(key, String.valueOf(def)));
}
public int getInteger(String key, int def)
{
return Integer.parseInt(this.getProperty(key, String.valueOf(def)));
}
public float getFloat(String key, float def)
{
return Float.parseFloat(this.getProperty(key, String.valueOf(def)));
}
public void set(String key, Object val)
{
this.setProperty(key, val.toString());
}
public void store(String comment)
{
try
{
this.store(new FileOutputStream(path), comment);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
| Java |
print ARGF.read.gsub!(/\B[a-z]+\B/) {|x| x.split('').sort_by{rand}.join}
| Java |
require 'minitest/autorun'
require 'minitest/pride'
require 'bundler/setup'
Bundler.require(:default)
require 'active_record'
require File.dirname(__FILE__) + '/../lib/where_exists'
ActiveRecord::Base.default_timezone = :utc
ActiveRecord::Base.time_zone_aware_attributes = true
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => File.dirname(__FILE__) + "/db/test.db"
)
| Java |
/*
* This file is part of the easy framework.
*
* (c) Julien Sergent <sergent.julien@icloud.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const ConfigLoader = require( 'easy/core/ConfigLoader' )
const EventsEmitter = require( 'events' )
/**
* @class Database
*/
class Database {
/**
* @constructor
*/
constructor( config ) {
this._config = config
this.stateEmitter = new EventsEmitter()
this.name = config.config.name
this.init()
}
/**
* init - init attributes
*/
init() {
this._instance = null
this._connector = this._config.connector
this.resetProperties()
}
/**
* Reset instance and connected state
*
* @memberOf Database
*/
resetProperties() {
this._connected = false
this._connectionError = null
}
/**
* load - load database config
*/
async start() {
await this.connect()
}
/**
* restart - restart database component
*/
async restart() {
this.resetProperties()
await this.start()
}
/**
* connect - connect database to instance
*/
async connect() {
const { instance, connected, error } = await this.config.connector()
const oldConnected = this.connected
this.instance = instance
this.connected = connected
this.connectionError = error
if ( this.connected !== oldConnected ) {
this.stateEmitter.emit( 'change', this.connected )
}
if ( error ) {
throw new Error( error )
}
}
/**
* Reset database connection and instance
*
* @memberOf Database
*/
disconnect() {
const oldConnected = this.connected
this.resetProperties()
if ( this.connected !== oldConnected ) {
this.stateEmitter.emit( 'change', this.connected )
}
}
/**
* verifyConnectionHandler - handler called by daemon which indicates if database still available or not
*
* @returns {Promise}
*
* @memberOf Database
*/
verifyConnectionHandler() {
return this.config.verifyConnectionHandler()
}
/**
* Branch handler on database state events
*
* @param {Function} handler
*
* @memberOf Database
*/
connectToStateEmitter( handler ) {
this.stateEmitter.on( 'change', handler )
}
/**
* get - get database instance
*
* @returns {Object}
*/
get instance() {
return this._instance
}
/**
* set - set database instance
*
* @param {Object} instance
* @returns {Object}
*/
set instance( instance ) {
this._instance = instance
return this._instance
}
/**
* get - get database connection state
*
* @returns {Object}
*/
get connected() {
return this._connected
}
/**
* set - set database connection state
*
* @param {boolean} connected
* @returns {Database}
*/
set connected( connected ) {
this._connected = connected
return this
}
/**
* get - get database configurations
*
* @returns {Object}
*/
get config() {
return this._config
}
/**
* Get connection error
*
* @readonly
*
* @memberOf Database
*/
get connectionError() {
return this._connectionError
}
/**
* Set connection error
*
* @returns {Database}
*
* @memberOf Database
*/
set connectionError( error ) {
this._connectionError = error
return this
}
}
module.exports = Database
| Java |
import { useEffect, useRef, useState } from "react"
import * as React from "react"
import {
RelayPaginationProp,
RelayRefetchProp,
createPaginationContainer,
} from "react-relay"
import { graphql } from "relay-runtime"
import Waypoint from "react-waypoint"
import { Box, Flex, Spacer, Spinner } from "@artsy/palette"
import compact from "lodash/compact"
import styled from "styled-components"
import { extractNodes } from "v2/Utils/extractNodes"
import { ItemFragmentContainer } from "./Item"
import { Reply } from "./Reply"
import { ConversationMessagesFragmentContainer as ConversationMessages } from "./ConversationMessages"
import { ConversationHeader } from "./ConversationHeader"
import { ConfirmArtworkModalQueryRenderer } from "./ConfirmArtworkModal"
import { BuyerGuaranteeMessage } from "./BuyerGuaranteeMessage"
import { returnOrderModalDetails } from "../Utils/returnOrderModalDetails"
import { OrderModal } from "./OrderModal"
import { UnreadMessagesToastQueryRenderer } from "./UnreadMessagesToast"
import useOnScreen from "../Utils/useOnScreen"
import { UpdateConversation } from "../Mutation/UpdateConversationMutation"
import { Conversation_conversation } from "v2/__generated__/Conversation_conversation.graphql"
import { useRouter } from "v2/System/Router/useRouter"
export interface ConversationProps {
conversation: Conversation_conversation
showDetails: boolean
setShowDetails: (showDetails: boolean) => void
relay: RelayPaginationProp
refetch: RelayRefetchProp["refetch"]
}
export const PAGE_SIZE: number = 15
const Loading: React.FC = () => (
<SpinnerContainer>
<Spinner />
</SpinnerContainer>
)
const Conversation: React.FC<ConversationProps> = props => {
const { conversation, relay, showDetails, setShowDetails } = props
const liveArtwork = conversation?.items?.[0]?.liveArtwork
const artwork = liveArtwork?.__typename === "Artwork" ? liveArtwork : null
const isOfferable = !!artwork && !!artwork?.isOfferableFromInquiry
const [showConfirmArtworkModal, setShowConfirmArtworkModal] = useState<
boolean
>(false)
const inquiryItemBox = compact(conversation.items).map((i, idx) => {
const isValidType =
i.item?.__typename === "Artwork" || i.item?.__typename === "Show"
return (
<ItemFragmentContainer
item={i.item!}
key={isValidType ? i.item?.id : idx}
/>
)
})
// ORDERS
const [showOrderModal, setShowOrderModal] = useState<boolean>(false)
const activeOrder = extractNodes(conversation.orderConnection)[0]
let orderID
let kind
if (activeOrder) {
kind = activeOrder.buyerAction
orderID = activeOrder.internalID
}
const { url, modalTitle } = returnOrderModalDetails({
kind: kind!,
orderID: orderID,
})
// SCROLLING AND FETCHING
// States and Refs
const bottomOfMessageContainer = useRef<HTMLElement>(null)
const initialMount = useRef(true)
const initialScroll = useRef(true)
const scrollContainer = useRef<HTMLDivElement>(null)
const [fetchingMore, setFetchingMore] = useState<boolean>(false)
const [lastMessageID, setLastMessageID] = useState<string | null>()
const [lastOrderUpdate, setLastOrderUpdate] = useState<string | null>()
const isBottomVisible = useOnScreen(bottomOfMessageContainer)
// Functions
const loadMore = (): void => {
if (relay.isLoading() || !relay.hasMore() || !initialMount.current) return
setFetchingMore(true)
const scrollCursor = scrollContainer.current
? scrollContainer.current?.scrollHeight -
scrollContainer.current?.scrollTop
: 0
relay.loadMore(PAGE_SIZE, error => {
if (error) console.error(error)
setFetchingMore(false)
if (scrollContainer.current) {
// Scrolling to former position
scrollContainer.current?.scrollTo({
top: scrollContainer.current?.scrollHeight - scrollCursor,
behavior: "smooth",
})
}
})
}
const { match } = useRouter()
const conversationID = match?.params?.conversationID
// TODO: refactor
useEffect(() => {
initialScroll.current = false
}, [conversationID])
useEffect(() => {
initialScroll.current = !fetchingMore
}, [fetchingMore])
useEffect(() => {
if (!fetchingMore && !initialScroll.current) {
scrollToBottom()
}
})
const scrollToBottom = () => {
if (!!bottomOfMessageContainer?.current) {
bottomOfMessageContainer.current?.scrollIntoView?.({
block: "end",
inline: "nearest",
behavior: initialMount.current ? "auto" : "smooth",
})
if (isBottomVisible) initialMount.current = false
setLastMessageID(conversation?.lastMessageID)
setOrderKey()
}
}
const refreshData = () => {
props.refetch({ conversationID: conversation.internalID }, null, error => {
if (error) console.error(error)
scrollToBottom()
})
}
const setOrderKey = () => {
setLastOrderUpdate(activeOrder?.updatedAt)
}
const [toastBottom, setToastBottom] = useState(0)
// Behaviours
// -Navigation
useEffect(() => {
setLastMessageID(conversation?.fromLastViewedMessageID)
initialMount.current = true
setOrderKey()
}, [
conversation.internalID,
conversation.fromLastViewedMessageID,
setOrderKey,
])
// -Last message opened
useEffect(() => {
// Set on a timeout so the user sees the "new" flag
setTimeout(
() => {
UpdateConversation(relay.environment, conversation)
},
!!conversation.isLastMessageToUser ? 3000 : 0
)
}, [lastMessageID])
// -Workaround Reply render resizing race condition
useEffect(() => {
if (initialMount.current) scrollToBottom()
const rect = scrollContainer.current?.getBoundingClientRect()
setToastBottom(window.innerHeight - (rect?.bottom ?? 0) + 30)
}, [scrollContainer?.current?.clientHeight])
// -On scroll down
useEffect(() => {
if (isBottomVisible) refreshData()
}, [isBottomVisible])
return (
<Flex flexDirection="column" flexGrow={1}>
<ConversationHeader
partnerName={conversation.to.name}
showDetails={showDetails}
setShowDetails={setShowDetails}
/>
<NoScrollFlex flexDirection="column" width="100%">
<MessageContainer ref={scrollContainer as any}>
<Box pb={[6, 6, 6, 0]} pr={1}>
<Spacer mt={["75px", "75px", 2]} />
<Flex flexDirection="column" width="100%" px={1}>
{isOfferable && <BuyerGuaranteeMessage />}
{inquiryItemBox}
<Waypoint onEnter={loadMore} />
{fetchingMore ? <Loading /> : null}
<ConversationMessages
messages={conversation.messagesConnection!}
events={conversation.orderConnection}
lastViewedMessageID={conversation?.fromLastViewedMessageID}
setShowDetails={setShowDetails}
/>
<Box ref={bottomOfMessageContainer as any} />
</Flex>
</Box>
<UnreadMessagesToastQueryRenderer
conversationID={conversation?.internalID!}
lastOrderUpdate={lastOrderUpdate}
bottom={toastBottom}
hasScrolled={!isBottomVisible}
onClick={scrollToBottom}
refreshCallback={refreshData}
/>
</MessageContainer>
<Reply
onScroll={scrollToBottom}
conversation={conversation}
refetch={props.refetch}
environment={relay.environment}
openInquiryModal={() => setShowConfirmArtworkModal(true)}
openOrderModal={() => setShowOrderModal(true)}
/>
</NoScrollFlex>
{isOfferable && (
<ConfirmArtworkModalQueryRenderer
artworkID={artwork?.internalID!}
conversationID={conversation.internalID!}
show={showConfirmArtworkModal}
closeModal={() => setShowConfirmArtworkModal(false)}
/>
)}
{isOfferable && (
<OrderModal
path={url!}
orderID={orderID}
title={modalTitle!}
show={showOrderModal}
closeModal={() => {
refreshData()
setShowOrderModal(false)
}}
/>
)}
</Flex>
)
}
const MessageContainer = styled(Box)`
flex-grow: 1;
overflow-y: auto;
`
const NoScrollFlex = styled(Flex)`
overflow: hidden;
flex-grow: 1;
`
const SpinnerContainer = styled.div`
width: 100%;
height: 100px;
position: relative;
`
export const ConversationPaginationContainer = createPaginationContainer(
Conversation,
{
conversation: graphql`
fragment Conversation_conversation on Conversation
@argumentDefinitions(
count: { type: "Int", defaultValue: 30 }
after: { type: "String" }
) {
id
internalID
from {
name
email
}
to {
name
initials
}
initialMessage
lastMessageID
fromLastViewedMessageID
isLastMessageToUser
unread
orderConnection(
first: 10
states: [APPROVED, FULFILLED, SUBMITTED, REFUNDED, CANCELED]
participantType: BUYER
) {
edges {
node {
internalID
updatedAt
... on CommerceOfferOrder {
buyerAction
}
}
}
...ConversationMessages_events
}
unread
messagesConnection(first: $count, after: $after, sort: DESC)
@connection(key: "Messages_messagesConnection", filters: []) {
pageInfo {
startCursor
endCursor
hasPreviousPage
hasNextPage
}
edges {
node {
id
}
}
totalCount
...ConversationMessages_messages
}
items {
item {
__typename
... on Artwork {
id
isOfferableFromInquiry
internalID
}
...Item_item
}
liveArtwork {
... on Artwork {
isOfferableFromInquiry
internalID
__typename
}
}
}
...ConversationCTA_conversation
}
`,
},
{
direction: "forward",
getConnectionFromProps(props) {
return props.conversation?.messagesConnection
},
getFragmentVariables(prevVars, count) {
return {
...prevVars,
count,
}
},
getVariables(props, { cursor, count }) {
return {
count,
cursor,
after: cursor,
conversationID: props.conversation.id,
}
},
query: graphql`
query ConversationPaginationQuery(
$count: Int
$after: String
$conversationID: ID!
) {
node(id: $conversationID) {
...Conversation_conversation @arguments(count: $count, after: $after)
}
}
`,
}
)
| Java |
---
layout: post
title: Hybrid重构框架
color: blue
width: 3
height: 1
category: hybrid
---
#### Hybrid重构框架结构

框架结构是基于业务模型定制的 分为 【公共模块】 和 【业务模块】
#### 公共模块(Common ) 组成
公共模块 由两部分组成 分别是 【Scss】 和 【Widget】

***
**Scss 放着框架公用代码**
【component】
* _button(按钮)
* _list-item(列表 包括带箭头的)
* _name-gender(性别样式 主要用在理财师业务模块中)
* _notice-bar(小黄条)
* _value(代表收益涨、跌的公共色值类)
【mixins】
* _border-line(兼容ios9 和 Android 关于1px显示的粗细问题 现已统一采用1px/*no*/)
* _button(按钮 + 状态)
* _clearfix(清除浮动)
* _cus-font-height(自定义字号 高度 和button 合作用的)
* _ellipse(省略号缩写)
* _list-item(列表样式 供 component里的的list-item调用)
* _value(涨跌样式 供 component里的的value调用)
* _way-step-v(类似时间轴一样的 竖列步骤结构)
【themes】 定义了全站通用的颜色值
* 字体
* 基本色 橙色、白色、蓝色
* 蓝色、灰色的灰度级
* 线条色
* 文本色
* 按钮色
* 收益涨跌色值
【core】是以上通用 样式的集合出口
***
**Widget 存放框架组件样式代码**
暂时抽出的组件有
* animate(动画)
* banner(广告banner)
* baseloading(加载样式)
* fundItem(基金模块)
* indexCrowdfunding(理财首页的众筹模块)
* newsItem(发现频道的 新闻模块)
* prodfixItem (固收页的 产品模块 包括新手 和 加息类产品)
* slick (轮播组件样式)
* tab ( tab 导航)
***
#### 业务模块(Pages) 组成
目前业务模块 有众筹、白拿、基金、理财、发现、积分商城、新手引导、邀请、理财师 后续会根据业务内容的增加而变化
 | Java |
<?php
class LinterTests extends PHPUnit_Framework_TestCase
{
/**
* @param string $source
* @param \Superbalist\Money\Linter\Tests\LinterTestInterface $test
*/
protected function assertLinterThrowsWarnings($source, \Superbalist\Money\Linter\Tests\LinterTestInterface $test)
{
$result = $test->analyse($source);
$this->assertNotEmpty($result);
}
/**
*
*/
public function testMatchesAbsFunctionCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php echo abs(-37);',
new \Superbalist\Money\Linter\Tests\AbsFunctionCallTest()
);
}
/**
*
*/
public function testMatchesArraySumFunctionCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php $values = array(0, 1, 2, 3); $sum = array_sum($values);',
new \Superbalist\Money\Linter\Tests\ArraySumFunctionCallTest()
);
}
/**
*
*/
public function testMatchesCeilFunctionCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php echo ceil(3.3);',
new \Superbalist\Money\Linter\Tests\CeilFunctionCallTest()
);
}
/**
*
*/
public function testMatchesDivideOperatorTest()
{
$this->assertLinterThrowsWarnings(
'<?php $test = 1 / 0.1;',
new \Superbalist\Money\Linter\Tests\DivideOperatorTest()
);
}
/**
*
*/
public function testMatchesFloatCastTest()
{
$this->assertLinterThrowsWarnings(
'<?php $test = "3.3"; echo (float) $test;',
new \Superbalist\Money\Linter\Tests\FloatCastTest()
);
}
/**
*
*/
public function testMatchesFloatParamDocBlockTest()
{
$source = <<<'EOT'
<?php
/**
* @param float $number this is a test
* @return float test
*/
public function getFloatNumber($number)
{
return $number;
}
EOT;
$this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\FloatParamDocBlockTest());
}
/**
*
*/
public function testMatchesFloatReturnDocBlockTest()
{
$source = <<<'EOT'
<?php
/**
* @param float $number this is a test
* @return float test
*/
public function getFloatNumber($number)
{
return $number;
}
EOT;
$this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\FloatReturnDocBlockTest());
}
/**
*
*/
public function testMatchesFloatvalFunctionCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php echo floatval("3.3");',
new \Superbalist\Money\Linter\Tests\FloatvalFunctionCallTest()
);
}
/**
*
*/
public function testMatchesFloatVarDocBlockTest()
{
$source = <<<'EOT'
<?php
/**
* @var float
*/
protected $number = 0.0;
EOT;
$this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\FloatVarDocBlockTest());
}
/**
*
*/
public function testMatchesFloorFunctionCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php echo floor(3.3);',
new \Superbalist\Money\Linter\Tests\FloorFunctionCallTest()
);
}
/**
*
*/
public function testMatchesGreaterThanOperatorTest()
{
$this->assertLinterThrowsWarnings(
'<?php if (4 > 3) { echo "true"; } else { echo "false"; }',
new \Superbalist\Money\Linter\Tests\GreaterThanOperatorTest()
);
}
/**
*
*/
public function testMatchesGreaterThanOrEqualsOperatorTest()
{
$this->assertLinterThrowsWarnings(
'<?php if (4 >= 3) { echo "true"; } else { echo "false"; }',
new \Superbalist\Money\Linter\Tests\GreaterThanOrEqualsOperatorTest()
);
}
/**
*
*/
public function testMatchesIntCastTest()
{
$this->assertLinterThrowsWarnings(
'<?php $test = "3.3"; echo (int) $test;',
new \Superbalist\Money\Linter\Tests\IntCastTest()
);
}
/**
*
*/
public function testMatchesIntParamDocBlockTest()
{
$source = <<<'EOT'
<?php
/**
* @param int $number this is a test
* @return int test
*/
public function getIntNumber($number)
{
return $number;
}
EOT;
$this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\IntParamDocBlockTest());
}
/**
*
*/
public function testMatchesIntReturnDocBlockTest()
{
$source = <<<'EOT'
<?php
/**
* @param int $number this is a test
* @return int test
*/
public function getIntNumber($number)
{
return $number;
}
EOT;
$this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\IntReturnDocBlockTest());
}
/**
*
*/
public function testMatchesIntvalFunctionCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php echo intval("3.3");',
new \Superbalist\Money\Linter\Tests\IntvalFunctionCallTest()
);
}
/**
*
*/
public function testMatchesIntVarDocBlockTest()
{
$source = <<<'EOT'
<?php
/**
* @var int
*/
protected $number = 0;
EOT;
$this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\IntVarDocBlockTest());
}
/**
*
*/
public function testMatchesIsFloatFunctionCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php $a = 3.3; var_dump(is_float($a));',
new \Superbalist\Money\Linter\Tests\IsFloatFunctionCallTest()
);
}
/**
*
*/
public function testMatchesIsIntegerFunctionCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php $a = 3; var_dump(is_integer($a));',
new \Superbalist\Money\Linter\Tests\IsIntegerFunctionCallTest()
);
}
/**
*
*/
public function testMatchesIsIntFunctionCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php $a = 3; var_dump(is_int($a));',
new \Superbalist\Money\Linter\Tests\IsIntFunctionCallTest()
);
}
/**
*
*/
public function testMatchesIsNumericFunctionCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php $a = 3; var_dump(is_numeric($a));',
new \Superbalist\Money\Linter\Tests\IsNumericFunctionCallTest()
);
}
/**
*
*/
public function testMatchesMaxFunctionCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php echo max(0, 3.3);',
new \Superbalist\Money\Linter\Tests\MaxFunctionCallTest()
);
}
/**
*
*/
public function testMatchesMinFunctionCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php echo min(0, 3.3);',
new \Superbalist\Money\Linter\Tests\MinFunctionCallTest()
);
}
/**
*
*/
public function testMatchesMinusOperatorTest()
{
$this->assertLinterThrowsWarnings(
'<?php $test = 1 - 0.1;',
new \Superbalist\Money\Linter\Tests\MinusOperatorTest()
);
}
/**
*
*/
public function testMatchesModOperatorTest()
{
$this->assertLinterThrowsWarnings(
'<?php $test = 4 % 2;',
new \Superbalist\Money\Linter\Tests\ModOperatorTest()
);
}
/**
*
*/
public function testMatchesMoneyFormatCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php echo money_format("%.2n", 2.4562)',
new \Superbalist\Money\Linter\Tests\MoneyFormatCallTest()
);
}
/**
*
*/
public function testMatchesMultiplyOperatorTest()
{
$this->assertLinterThrowsWarnings(
'<?php $test = 1 * 0.1;',
new \Superbalist\Money\Linter\Tests\MultiplyOperatorTest()
);
}
/**
*
*/
public function testMatchesNumberFloatTest()
{
$this->assertLinterThrowsWarnings(
'<?php $test = 0.2 + 0.1;',
new \Superbalist\Money\Linter\Tests\NumberFloatTest()
);
}
/**
*
*/
public function testMatchesNumberFormatCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php echo number_format(1.3, 2)',
new \Superbalist\Money\Linter\Tests\NumberFormatCallTest()
);
}
/**
*
*/
public function testMatchesNumberIntTest()
{
$this->assertLinterThrowsWarnings(
'<?php $test = 1 + 0.1;',
new \Superbalist\Money\Linter\Tests\NumberIntTest()
);
}
/**
*
*/
public function testMatchesPlusOperatorTest()
{
$this->assertLinterThrowsWarnings(
'<?php $test = 1 + 0.1;',
new \Superbalist\Money\Linter\Tests\PlusOperatorTest()
);
}
/**
*
*/
public function testMatchesPowFunctionCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php echo pow(2, 8);',
new \Superbalist\Money\Linter\Tests\PowFunctionCallTest()
);
}
/**
*
*/
public function testMatchesRoundFunctionCallTest()
{
$this->assertLinterThrowsWarnings(
'<?php echo round(9.93434, 2);',
new \Superbalist\Money\Linter\Tests\RoundFunctionCallTest()
);
}
/**
*
*/
public function testMatchesSmallerThanOperatorTest()
{
$this->assertLinterThrowsWarnings(
'<?php if (4 < 3) { echo "true"; } else { echo "false"; }',
new \Superbalist\Money\Linter\Tests\SmallerThanOperatorTest()
);
}
/**
*
*/
public function testMatchesSmallerThanOrEqualsOperatorTest()
{
$this->assertLinterThrowsWarnings(
'<?php if (4 <= 3) { echo "true"; } else { echo "false"; }',
new \Superbalist\Money\Linter\Tests\SmallerThanOrEqualsOperatorTest()
);
}
/**
*
*/
public function testMatchesSprintfFormatFloatTest()
{
$this->assertLinterThrowsWarnings(
'<?php echo sprintf("%f", 4.55555);',
new \Superbalist\Money\Linter\Tests\SprintfFormatFloatTest()
);
$this->assertLinterThrowsWarnings(
'<?php echo sprintf("%.2f %s", 4.55555, "test");',
new \Superbalist\Money\Linter\Tests\SprintfFormatFloatTest()
);
$this->assertLinterThrowsWarnings(
'<?php echo sprintf("%.2f %s", 4.55555, sprintf("%s", "test")); $test = intval(1.1);',
new \Superbalist\Money\Linter\Tests\SprintfFormatFloatTest()
);
}
/**
*
*/
public function testMatchesVariableDecrementTest()
{
$this->assertLinterThrowsWarnings(
'<?php $n = 3; $n--;',
new \Superbalist\Money\Linter\Tests\VariableDecrementTest()
);
}
/**
*
*/
public function testMatchesVariableDivideEqualsTest()
{
$this->assertLinterThrowsWarnings(
'<?php $n = 21; $n /= 3;',
new \Superbalist\Money\Linter\Tests\VariableDivideEqualsTest()
);
}
/**
*
*/
public function testMatchesVariableIncrementTest()
{
$this->assertLinterThrowsWarnings(
'<?php $n = 3; $n++;',
new \Superbalist\Money\Linter\Tests\VariableIncrementTest()
);
}
/**
*
*/
public function testMatchesVariableMinusEqualsTest()
{
$this->assertLinterThrowsWarnings(
'<?php $n = 21; $n -= 2;',
new \Superbalist\Money\Linter\Tests\VariableMinusEqualsTest()
);
}
/**
*
*/
public function testMatchesVariableModEqualsTest()
{
$this->assertLinterThrowsWarnings(
'<?php $n = 24; $n %= 2;',
new \Superbalist\Money\Linter\Tests\VariableModEqualsTest()
);
}
/**
*
*/
public function testMatchesVariablePlusEqualsTest()
{
$this->assertLinterThrowsWarnings(
'<?php $n = 21; $n += 2;',
new \Superbalist\Money\Linter\Tests\VariablePlusEqualsTest()
);
}
/**
*
*/
public function testMatchesVariableTimesEqualsTest()
{
$this->assertLinterThrowsWarnings(
'<?php $n = 21; $n *= 2;',
new \Superbalist\Money\Linter\Tests\VariableTimesEqualsTest()
);
}
}
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>hammer: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.8.1 / hammer - 1.3+8.12</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
hammer
<small>
1.3+8.12
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-02-10 07:56:43 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-10 07:56:43 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.8.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "palmskog@gmail.com"
homepage: "https://github.com/lukaszcz/coqhammer"
dev-repo: "git+https://github.com/lukaszcz/coqhammer.git"
bug-reports: "https://github.com/lukaszcz/coqhammer/issues"
license: "LGPL-2.1-only"
synopsis: "General-purpose automated reasoning hammer tool for Coq"
description: """
A general-purpose automated reasoning hammer tool for Coq that combines
learning from previous proofs with the translation of problems to the
logics of automated systems and the reconstruction of successfully found proofs.
"""
build: [make "-j%{jobs}%" {ocaml:version >= "4.06"} "plugin"]
install: [
[make "install-plugin"]
[make "test-plugin"] {with-test}
]
depends: [
"ocaml"
"coq" {>= "8.12" & < "8.13~"}
("conf-g++" {build} | "conf-clang" {build})
"coq-hammer-tactics" {= version}
]
tags: [
"category:Miscellaneous/Coq Extensions"
"keyword:automation"
"keyword:hammer"
"logpath:Hammer.Plugin"
"date:2020-07-28"
]
authors: [
"Lukasz Czajka <lukaszcz@mimuw.edu.pl>"
"Cezary Kaliszyk <cezary.kaliszyk@uibk.ac.at>"
]
url {
src: "https://github.com/lukaszcz/coqhammer/archive/v1.3-coq8.12.tar.gz"
checksum: "sha512=666ea825c122319e398efb7287f429ebfb5d35611b4cabe4b88732ffb5c265ef348b53d5046c958831ac0b7a759b44ce1ca04220ca68b1915accfd23435b479c"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-hammer.1.3+8.12 coq.8.8.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.8.1).
The following dependencies couldn't be met:
- coq-hammer -> coq >= 8.12
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-hammer.1.3+8.12</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| Java |
package ch.bisi.koukan.job;
import ch.bisi.koukan.provider.XMLExchangeRatesProvider;
import ch.bisi.koukan.repository.DataAccessException;
import ch.bisi.koukan.repository.ExchangeRatesRepository;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* Executes scheduled tasks for updating the in memory exchange rates
* by querying the European Central Bank endpoints.
*/
@Component
public class ECBDataLoaderScheduler {
private static final Logger logger = LoggerFactory.getLogger(ECBDataLoaderScheduler.class);
private final XMLExchangeRatesProvider xmlExchangeRatesProvider;
private final ExchangeRatesRepository exchangeRatesRepository;
private final URL dailyEndpoint;
private final URL pastDaysEndpoint;
/**
* Instantiates a new {@link ECBDataLoaderScheduler}.
*
* @param xmlExchangeRatesProvider the provider of exchange rates
* @param exchangeRatesRepository the repository
* @param dailyEndpoint the ECB daily endpoint {@link URL}
* @param pastDaysEndpoint the ECB endpoint {@link URL} for retrieving past days data
*/
@Autowired
public ECBDataLoaderScheduler(
@Qualifier("ECBProvider") final XMLExchangeRatesProvider xmlExchangeRatesProvider,
final ExchangeRatesRepository exchangeRatesRepository,
@Qualifier("dailyEndpoint") final URL dailyEndpoint,
@Qualifier("pastDaysEndpoint") final URL pastDaysEndpoint) {
this.xmlExchangeRatesProvider = xmlExchangeRatesProvider;
this.exchangeRatesRepository = exchangeRatesRepository;
this.dailyEndpoint = dailyEndpoint;
this.pastDaysEndpoint = pastDaysEndpoint;
}
/**
* Retrieves the whole exchange rates daily data.
*
* @throws IOException in case of the problems accessing the ECB endpoint
* @throws XMLStreamException in case of problems parsing the ECB XML
* @throws DataAccessException in case of problems accessing the underlying data
*/
@Scheduled(initialDelay = 0, fixedRateString = "${daily.rates.update.rate}")
public void loadDailyData() throws IOException, XMLStreamException, DataAccessException {
try (final InputStream inputStream = dailyEndpoint.openStream()) {
logger.info("Updating ECB daily exchange rates data");
loadData(inputStream);
}
}
/**
* Retrieves the whole exchange rates data for past days.
*
* @throws IOException in case of the problems accessing the ECB endpoint
* @throws XMLStreamException in case of problems parsing the ECB XML
* @throws DataAccessException in case of problems accessing the underlying data
*/
@Scheduled(initialDelay = 0, fixedRateString = "${past.days.rates.update.rate}")
public void loadPastDaysData() throws IOException, XMLStreamException, DataAccessException {
try (final InputStream inputStream = pastDaysEndpoint.openStream()) {
logger.info("Updating ECB exchange rates data for the past 90 days");
loadData(inputStream);
}
}
/**
* Loads exchange rates data from the given {@link InputStream}.
*
* @param inputStream the {@link InputStream}
* @throws XMLStreamException in case of problems parsing the ECB XML
* @throws DataAccessException in case of problems accessing the underlying data
*/
private void loadData(final InputStream inputStream)
throws XMLStreamException, DataAccessException {
final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance()
.createXMLStreamReader(inputStream);
exchangeRatesRepository.save(xmlExchangeRatesProvider.retrieveAll(xmlStreamReader));
}
}
| Java |
<?php namespace JetMinds\Job\Updates;
use Schema;
use October\Rain\Database\Schema\Blueprint;
use October\Rain\Database\Updates\Migration;
class CreateResumesTable extends Migration
{
public function up()
{
Schema::create('jetminds_job_resumes', function(Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->string('email')->nullable();
$table->string('phone')->nullable();
$table->string('position')->nullable();
$table->longText('location')->nullable();
$table->string('resume_category')->nullable();
$table->string('resume_education')->nullable();
$table->longText('education_note')->nullable();
$table->string('resume_experience')->nullable();
$table->longText('experience_note')->nullable();
$table->string('resume_language')->nullable();
$table->string('resume_skill')->nullable();
$table->longText('resume_note')->nullable();
$table->boolean('is_invite')->default(1);
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('jetminds_job_resumes');
}
}
| Java |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace SpartaHack
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public static ObservableValue<string> Title { get; set; }
public static ObservableValue<bool> LoggedIn { get; set; }
public static ObservableValue<string> Time { get; set; }
public static MainPage root;
private DateTime DoneTime;
public MainPage(Frame frame)
{
this.InitializeComponent();
Title = new ObservableValue<string>();
LoggedIn = new ObservableValue<bool>();
Time = new ObservableValue<string>();
this.MySplitView.Content = frame;
DataContext = this;
DoneTime = DateTime.Parse("1/22/2017 17:00:00 GMT");
DispatcherTimer dt = new DispatcherTimer();
dt.Interval = TimeSpan.FromSeconds(1);
dt.Tick += Dt_Tick;
this.Loaded += (s,e) =>
{
rdAnnouncements.IsChecked = true;
dt.Start();
};
MySplitView.PaneClosed += (s, e) =>
{
grdHideView.Visibility = Visibility.Collapsed;
bgPane.Margin = new Thickness(MySplitView.IsPaneOpen ? MySplitView.OpenPaneLength : MySplitView.CompactPaneLength, bgPane.Margin.Top, bgPane.Margin.Right, bgPane.Margin.Bottom);
};
}
private void Dt_Tick(object sender, object e)
{
TimeSpan dt = DoneTime.ToUniversalTime().Subtract(DateTime.Now.ToUniversalTime());
if (dt.TotalSeconds <= 0)
Time.Value = "FINISHED";
else
//txtCountDown.Text = dt.ToString(@"hh\:mm\:ss");
//Time.Value = $"{(int)dt.TotalHours}H {dt.Minutes}M {dt.Seconds}S";
Time.Value= string.Format("{0:##}h {1:##}m {2:##}s", ((int)dt.TotalHours), dt.Minutes.ToString(), dt.Seconds.ToString());
}
private void OnAnnouncementsChecked(object sender, RoutedEventArgs e)
{
try
{
MySplitView.IsPaneOpen = false;
if (MySplitView.Content != null)
((Frame)MySplitView.Content).Navigate(typeof(AnnouncementsPage));
}
catch { }
}
private void OnScheduleChecked(object sender, RoutedEventArgs e)
{
try
{
MySplitView.IsPaneOpen = false;
if (MySplitView.Content != null)
((Frame)MySplitView.Content).Navigate(typeof(SchedulePage));
}
catch { }
}
private void OnTicketChecked(object sender, RoutedEventArgs e)
{
try
{
MySplitView.IsPaneOpen = false;
if (MySplitView.Content != null)
((Frame)MySplitView.Content).Navigate(typeof(TicketPage));
}
catch { }
}
private void OnMapChecked(object sender, RoutedEventArgs e)
{
try
{
MySplitView.IsPaneOpen = false;
if (MySplitView.Content != null)
((Frame)MySplitView.Content).Navigate(typeof(MapPage));
}
catch { }
}
private void OnSponsorChecked(object sender, RoutedEventArgs e)
{
try
{
MySplitView.IsPaneOpen = false;
if (MySplitView.Content != null)
((Frame)MySplitView.Content).Navigate(typeof(SponsorPage));
}
catch { }
}
private void OnPrizeChecked(object sender, RoutedEventArgs e)
{
try
{
MySplitView.IsPaneOpen = false;
if (MySplitView.Content != null)
((Frame)MySplitView.Content).Navigate(typeof(PrizePage));
}
catch { }
}
private void OnLoginChecked(object sender, RoutedEventArgs e)
{
try
{
MySplitView.IsPaneOpen = false;
if (MySplitView.Content != null)
((Frame)MySplitView.Content).Navigate(typeof(ProfilePage));
}
catch { }
}
private void HambButton_Click(object sender, RoutedEventArgs e)
{
try
{
grdHideView.Visibility = grdHideView.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
MySplitView.IsPaneOpen = !MySplitView.IsPaneOpen;
bgPane.Margin = new Thickness(MySplitView.IsPaneOpen ? MySplitView.OpenPaneLength : MySplitView.CompactPaneLength, bgPane.Margin.Top, bgPane.Margin.Right, bgPane.Margin.Bottom);
}
catch { }
}
private void grdHideView_Tapped(object sender, TappedRoutedEventArgs e)
{
try
{
grdHideView.Visibility = grdHideView.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
MySplitView.IsPaneOpen = !MySplitView.IsPaneOpen;
bgPane.Margin = new Thickness(MySplitView.IsPaneOpen ? MySplitView.OpenPaneLength : MySplitView.CompactPaneLength, bgPane.Margin.Top, bgPane.Margin.Right, bgPane.Margin.Bottom);
}
catch { }
}
}
}
| Java |
using System;
using System.Diagnostics;
namespace Oragon.Architecture.IO.Path
{
partial class PathHelpers
{
#region Private Classes
private sealed class RelativeFilePath : RelativePathBase, IRelativeFilePath
{
#region Internal Constructors
internal RelativeFilePath(string pathString)
: base(pathString)
{
Debug.Assert(pathString != null);
Debug.Assert(pathString.Length > 0);
Debug.Assert(pathString.IsValidRelativeFilePath());
}
#endregion Internal Constructors
#region Public Properties
public string FileExtension { get { return FileNameHelpers.GetFileNameExtension(m_PathString); } }
//
// File Name and File Name Extension
//
public string FileName { get { return FileNameHelpers.GetFileName(m_PathString); } }
public string FileNameWithoutExtension { get { return FileNameHelpers.GetFileNameWithoutExtension(m_PathString); } }
//
// IsFilePath ; IsDirectoryPath
//
public override bool IsDirectoryPath { get { return false; } }
public override bool IsFilePath { get { return true; } }
#endregion Public Properties
#region Public Methods
public override IAbsolutePath GetAbsolutePathFrom(IAbsoluteDirectoryPath path)
{
return (this as IRelativeFilePath).GetAbsolutePathFrom(path);
}
public IRelativeDirectoryPath GetBrotherDirectoryWithName(string directoryName)
{
Debug.Assert(directoryName != null); // Enforced by contract
Debug.Assert(directoryName.Length > 0); // Enforced by contract
IDirectoryPath path = PathBrowsingHelpers.GetBrotherDirectoryWithName(this, directoryName);
var pathTyped = path as IRelativeDirectoryPath;
Debug.Assert(pathTyped != null);
return pathTyped;
}
public IRelativeFilePath GetBrotherFileWithName(string fileName)
{
Debug.Assert(fileName != null); // Enforced by contract
Debug.Assert(fileName.Length > 0); // Enforced by contract
IFilePath path = PathBrowsingHelpers.GetBrotherFileWithName(this, fileName);
var pathTyped = path as IRelativeFilePath;
Debug.Assert(pathTyped != null);
return pathTyped;
}
public bool HasExtension(string extension)
{
// All these 3 assertions have been checked by contract!
Debug.Assert(extension != null);
Debug.Assert(extension.Length >= 2);
Debug.Assert(extension[0] == '.');
return FileNameHelpers.HasExtension(m_PathString, extension);
}
IDirectoryPath IFilePath.GetBrotherDirectoryWithName(string directoryName)
{
Debug.Assert(directoryName != null); // Enforced by contract
Debug.Assert(directoryName.Length > 0); // Enforced by contract
return this.GetBrotherDirectoryWithName(directoryName);
}
// Explicit Impl methods
IFilePath IFilePath.GetBrotherFileWithName(string fileName)
{
Debug.Assert(fileName != null); // Enforced by contract
Debug.Assert(fileName.Length > 0); // Enforced by contract
return this.GetBrotherFileWithName(fileName);
}
IFilePath IFilePath.UpdateExtension(string newExtension)
{
// All these 3 assertions have been checked by contract!
Debug.Assert(newExtension != null);
Debug.Assert(newExtension.Length >= 2);
Debug.Assert(newExtension[0] == '.');
return this.UpdateExtension(newExtension);
}
//
// Absolute/Relative pathString conversion
//
IAbsoluteFilePath IRelativeFilePath.GetAbsolutePathFrom(IAbsoluteDirectoryPath path)
{
Debug.Assert(path != null); // Enforced by contracts!
string pathAbsolute, failureReason;
if (!AbsoluteRelativePathHelpers.TryGetAbsolutePathFrom(path, this, out pathAbsolute, out failureReason))
{
throw new ArgumentException(failureReason);
}
Debug.Assert(pathAbsolute != null);
Debug.Assert(pathAbsolute.Length > 0);
return (pathAbsolute + MiscHelpers.DIR_SEPARATOR_CHAR + this.FileName).ToAbsoluteFilePath();
}
//
// Path Browsing facilities
//
public IRelativeFilePath UpdateExtension(string newExtension)
{
// All these 3 assertions have been checked by contract!
Debug.Assert(newExtension != null);
Debug.Assert(newExtension.Length >= 2);
Debug.Assert(newExtension[0] == '.');
string pathString = PathBrowsingHelpers.UpdateExtension(this, newExtension);
Debug.Assert(pathString.IsValidRelativeFilePath());
return new RelativeFilePath(pathString);
}
#endregion Public Methods
}
#endregion Private Classes
}
} | Java |
---
layout: page
title: Guardian Quality Technologies Award Ceremony
date: 2016-05-24
author: Peter Simmons
tags: weekly links, java
status: published
summary: Sed consequat quis sapien eget malesuada. Morbi semper tempor nunc.
banner: images/banner/meeting-01.jpg
booking:
startDate: 12/25/2019
endDate: 12/28/2019
ctyhocn: MSLOHHX
groupCode: GQTAC
published: true
---
Aliquam bibendum sit amet nibh et feugiat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam feugiat dictum sapien, eget vestibulum mauris tincidunt ut. Quisque suscipit diam vel aliquet suscipit. Donec at sollicitudin orci. Integer est nulla, elementum quis viverra non, semper nec nibh. Mauris pellentesque ligula ac nisl mollis, sit amet semper sapien luctus. Aenean dignissim in lacus sed convallis. Quisque ac dignissim tellus, vel blandit diam. Maecenas consequat ligula ut purus semper, a condimentum tellus volutpat.
Aliquam quis lorem ante. Quisque tempus pretium urna. Proin justo nisi, maximus et velit vitae, dictum pretium dui. Ut ut luctus magna. Phasellus lectus justo, varius sed ultrices nec, malesuada id massa. Mauris nulla justo, finibus commodo lobortis sed, pulvinar id ipsum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla fermentum lobortis arcu, id elementum diam tempor vitae. Aliquam erat volutpat. Nulla lacinia metus sit amet cursus lacinia.
* Suspendisse congue velit sed varius malesuada
* Nulla et ante luctus, sollicitudin justo ullamcorper, aliquet nulla
* Proin tincidunt sem quis venenatis cursus
* Pellentesque a ipsum tincidunt nisi aliquet varius in sit amet metus
* Vestibulum eu ante sit amet lectus vestibulum pretium ut et libero.
Nullam molestie felis quis nunc tincidunt, at vestibulum enim tempus. Vivamus imperdiet nec est non tempor. Curabitur at scelerisque leo. Morbi tempor arcu at ex finibus pulvinar. Curabitur ullamcorper tincidunt hendrerit. Donec quam nibh, viverra non feugiat sit amet, dictum ac libero. Ut dignissim neque sit amet tortor lobortis efficitur. Curabitur id consectetur turpis, quis facilisis augue. Interdum et malesuada fames ac ante ipsum primis in faucibus. Maecenas sit amet rhoncus erat, nec pulvinar metus.
| Java |
---
layout: page
title: Protector Purple Group Show
date: 2016-05-24
author: Barbara Riddle
tags: weekly links, java
status: published
summary: In lacinia libero vitae ullamcorper malesuada.
banner: images/banner/wedding.jpg
booking:
startDate: 05/06/2019
endDate: 05/07/2019
ctyhocn: PTNHHHX
groupCode: PPGS
published: true
---
Quisque fermentum nibh lorem, non feugiat nunc dignissim nec. Praesent sed neque sollicitudin, fermentum purus a, porttitor urna. Nullam placerat varius ipsum, quis porttitor sem gravida et. Pellentesque porta interdum luctus. Cras dolor tellus, tristique non efficitur id, ultrices vel nisi. Pellentesque viverra quam vitae est tincidunt, ac lobortis nulla dictum. Vestibulum ornare turpis erat, et porta magna imperdiet sed. Phasellus auctor dui sed ipsum venenatis, ornare porttitor magna varius.
* Aliquam porttitor elit at ipsum feugiat, in vehicula elit hendrerit
* Morbi quis ligula non nulla sollicitudin sollicitudin eu sed mi
* Ut accumsan nisi nec nisl varius, at euismod mi sodales
* Nulla tristique magna nec accumsan posuere.
Cras ultricies tellus in elit congue pretium. Sed efficitur quam feugiat orci tincidunt finibus. Praesent consectetur sed purus ut condimentum. Suspendisse tincidunt condimentum viverra. In porta rhoncus arcu, a lacinia risus maximus non. Pellentesque et gravida velit. Suspendisse a aliquet mauris. Pellentesque tempor interdum elit sed aliquam. Praesent semper est a metus aliquet, nec ornare nunc sollicitudin. Aliquam non orci dictum, bibendum mi eu, pellentesque mi. Nulla risus odio, blandit in auctor vel, sagittis eu nisi. Curabitur porttitor purus nisi. In eget accumsan erat.
| Java |
---
layout: page
title: Liberated Peace Electronics Party
date: 2016-05-24
author: Charles Hunt
tags: weekly links, java
status: published
summary: Sed sit amet facilisis elit.
banner: images/banner/leisure-01.jpg
booking:
startDate: 11/07/2018
endDate: 11/12/2018
ctyhocn: NCLHXHX
groupCode: LPEP
published: true
---
Ut consequat tortor non eros interdum consectetur. Vestibulum porta gravida nisi, ac laoreet sem imperdiet sit amet. Curabitur dictum elit nisl. Fusce sit amet nulla magna. Nulla risus erat, aliquam sit amet mattis in, placerat sed massa. In dolor ante, ornare at tristique non, rhoncus ac diam. In augue urna, ultrices sed commodo in, pellentesque ut dolor. Vestibulum cursus consectetur odio, lobortis malesuada lectus. Nullam dignissim gravida tristique.
1 Donec eleifend neque blandit enim auctor, ut pellentesque est pulvinar
1 In vitae erat efficitur, rhoncus sem ac, auctor leo
1 Nulla eget est non metus vestibulum convallis
1 Aenean eu purus malesuada, mollis enim nec, aliquet lectus
1 Phasellus nec nisi efficitur, accumsan neque ut, mollis dolor.
Praesent tincidunt vulputate elit. Aliquam erat volutpat. Proin placerat nisi ut diam posuere, a laoreet enim luctus. Vestibulum luctus urna a nisi commodo congue. Donec sit amet sem et augue placerat sodales a eget nibh. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vestibulum vel ullamcorper urna. Donec cursus imperdiet erat, at finibus velit egestas iaculis. Duis malesuada laoreet leo, in aliquam neque faucibus in. Praesent faucibus diam eget odio lobortis, iaculis laoreet ligula rhoncus. Aliquam erat volutpat. Curabitur hendrerit nibh in orci volutpat egestas.
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In volutpat semper mattis. Sed euismod quam id mi consequat, nec consectetur turpis imperdiet. Nunc tristique ultricies enim, vel venenatis quam porta quis. Sed ligula tortor, fringilla ac ultrices vel, vulputate eu nunc. Duis laoreet suscipit turpis ac tempus. Pellentesque nunc nisi, interdum sed bibendum ac, rutrum eu magna. Praesent ac lacinia purus. Phasellus facilisis consequat finibus. Etiam semper dolor nec neque egestas, sed tincidunt odio interdum. Etiam ut ipsum pellentesque, rutrum urna non, pharetra mi. Sed in diam non mauris sodales iaculis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi quis aliquam arcu, eget euismod arcu. Aenean et efficitur nisi. Morbi eu magna ut ligula tempus maximus eu quis nulla.
| Java |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.05.03 at 03:15:27 PM EDT
//
package API.amazon.mws.xml.JAXB;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="value">
* <complexType>
* <simpleContent>
* <extension base="<>String200Type">
* </extension>
* </simpleContent>
* </complexType>
* </element>
* </sequence>
* <attribute name="delete" type="{}BooleanType" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
@XmlRootElement(name = "cdrh_classification")
public class CdrhClassification {
@XmlElement(required = true)
protected CdrhClassification.Value value;
@XmlAttribute(name = "delete")
protected BooleanType delete;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link CdrhClassification.Value }
*
*/
public CdrhClassification.Value getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link CdrhClassification.Value }
*
*/
public void setValue(CdrhClassification.Value value) {
this.value = value;
}
/**
* Gets the value of the delete property.
*
* @return
* possible object is
* {@link BooleanType }
*
*/
public BooleanType getDelete() {
return delete;
}
/**
* Sets the value of the delete property.
*
* @param value
* allowed object is
* {@link BooleanType }
*
*/
public void setDelete(BooleanType value) {
this.delete = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <simpleContent>
* <extension base="<>String200Type">
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
public static class Value {
@XmlValue
protected String value;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
}
}
| Java |
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com>
namespace Marius.Html.Hap
{
/// <summary>
/// Represents a base class for fragments in a mixed code document.
/// </summary>
public abstract class MixedCodeDocumentFragment
{
#region Fields
internal MixedCodeDocument Doc;
private string _fragmentText;
internal int Index;
internal int Length;
private int _line;
internal int _lineposition;
internal MixedCodeDocumentFragmentType _type;
#endregion
#region Constructors
internal MixedCodeDocumentFragment(MixedCodeDocument doc, MixedCodeDocumentFragmentType type)
{
Doc = doc;
_type = type;
switch (type)
{
case MixedCodeDocumentFragmentType.Text:
Doc._textfragments.Append(this);
break;
case MixedCodeDocumentFragmentType.Code:
Doc._codefragments.Append(this);
break;
}
Doc._fragments.Append(this);
}
#endregion
#region Properties
/// <summary>
/// Gets the fragement text.
/// </summary>
public string FragmentText
{
get
{
if (_fragmentText == null)
{
_fragmentText = Doc._text.Substring(Index, Length);
}
return FragmentText;
}
internal set { _fragmentText = value; }
}
/// <summary>
/// Gets the type of fragment.
/// </summary>
public MixedCodeDocumentFragmentType FragmentType
{
get { return _type; }
}
/// <summary>
/// Gets the line number of the fragment.
/// </summary>
public int Line
{
get { return _line; }
internal set { _line = value; }
}
/// <summary>
/// Gets the line position (column) of the fragment.
/// </summary>
public int LinePosition
{
get { return _lineposition; }
}
/// <summary>
/// Gets the fragment position in the document's stream.
/// </summary>
public int StreamPosition
{
get { return Index; }
}
#endregion
}
} | Java |
import React from 'react'
import { User } from '../../lib/accounts/users'
import styled from '../../lib/styled'
import MdiIcon from '@mdi/react'
import { mdiAccount } from '@mdi/js'
import { SectionPrimaryButton } from './styled'
import { useTranslation } from 'react-i18next'
interface UserProps {
user: User
signout: (user: User) => void
}
const Container = styled.div`
margin-bottom: 8px;
`
export default ({ user, signout }: UserProps) => {
const { t } = useTranslation()
return (
<Container>
<MdiIcon path={mdiAccount} size='80px' />
<p>{user.name}</p>
<SectionPrimaryButton onClick={() => signout(user)}>
{t('general.signOut')}
</SectionPrimaryButton>
</Container>
)
}
| Java |
#include "TextItem.h"
#include <QPainter>
#include <QFont>
#include <QDebug>
////////////////////////////////////////////////////////////////
TextItem::TextItem(const QString& text, QGraphicsLayoutItem *parent)
: BaseItem(parent)
{
_text = text;
QFont font;
font.setPointSize(11);
font.setBold(false);
setFont(font);
}
////////////////////////////////////////////////////////////////
TextItem::~TextItem()
{
}
////////////////////////////////////////////////////////////////
void TextItem::setFont(const QFont &font)
{
_font = font;
QFontMetrics fm(_font);
}
////////////////////////////////////////////////////////////////
QSizeF TextItem::measureSize() const
{
QFontMetrics fm(_font);
const QSizeF& size = fm.size(Qt::TextExpandTabs, _text);
// NOTE: flag Qt::TextSingleLine ignores newline characters.
return size;
}
////////////////////////////////////////////////////////////////
void TextItem::draw(QPainter *painter, const QRectF& bounds)
{
painter->setFont(_font);
// TODO: mozno bude treba specialne handlovat novy riadok
painter->drawText(bounds, _text);
}
| Java |
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved
*/
#ifndef _Stroika_Foundation_Containers_DataStructures_STLContainerWrapper_h_
#define _Stroika_Foundation_Containers_DataStructures_STLContainerWrapper_h_
#include "../../StroikaPreComp.h"
#include "../../Configuration/Common.h"
#include "../../Configuration/Concepts.h"
#include "../../Debug/AssertExternallySynchronizedMutex.h"
#include "../Common.h"
/**
* \file
*
* Description:
* This module genericly wraps STL containers (such as map, vector etc), and facilitates
* using them as backends for Stroika containers.
*
* TODO:
*
* @todo Replace Contains() with Lookup () - as we did for LinkedList<T>
*
* @todo Redo Contains1 versus Contains using partial template specialization of STLContainerWrapper - easy
* cuz such a trivial class. I can use THAT trick to handle the case of forward_list too. And size...
*
* @todo Add special subclass of ForwardIterator that tracks PREVPTR - and use to cleanup stuff
* that uses forward_list code...
*
*/
namespace Stroika::Foundation::Containers::DataStructures {
namespace Private_ {
template <typename T>
using has_erase_t = decltype (declval<T&> ().erase (begin (declval<T&> ()), end (declval<T&> ())));
template <typename T>
constexpr inline bool has_erase_v = Configuration::is_detected_v<has_erase_t, T>;
}
/**
* Use this to wrap an underlying stl container (like std::vector or stl:list, etc) to adapt
* it for Stroika containers.
*
* \note \em Thread-Safety <a href="Thread-Safety.md#C++-Standard-Thread-Safety">C++-Standard-Thread-Safety</a>
*
*/
template <typename STL_CONTAINER_OF_T>
class STLContainerWrapper : public STL_CONTAINER_OF_T, public Debug::AssertExternallySynchronizedMutex {
private:
using inherited = STL_CONTAINER_OF_T;
public:
using value_type = typename STL_CONTAINER_OF_T::value_type;
using iterator = typename STL_CONTAINER_OF_T::iterator;
using const_iterator = typename STL_CONTAINER_OF_T::const_iterator;
public:
/**
* Basic (mostly internal) element used by ForwardIterator. Abstract name so can be referenced generically across 'DataStructure' objects
*/
using UnderlyingIteratorRep = const_iterator;
public:
/**
* pass through CTOR args to underlying container
*/
template <typename... EXTRA_ARGS>
STLContainerWrapper (EXTRA_ARGS&&... args);
public:
class ForwardIterator;
public:
/*
* Take iteartor 'pi' which is originally a valid iterator from 'movedFrom' - and replace *pi with a valid
* iterator from 'this' - which points at the same logical position. This requires that this container
* was just 'copied' from 'movedFrom' - and is used to produce an eqivilennt iterator (since iterators are tied to
* the container they were iterating over).
*/
nonvirtual void MoveIteratorHereAfterClone (ForwardIterator* pi, const STLContainerWrapper* movedFrom) const;
public:
nonvirtual bool Contains (ArgByValueType<value_type> item) const;
public:
/**
* \note Complexity:
* Always: O(N)
*/
template <typename FUNCTION>
nonvirtual void Apply (FUNCTION doToElement) const;
public:
/**
* \note Complexity:
* Worst Case: O(N)
* Typical: O(N), but can be less if systematically finding entries near start of container
*/
template <typename FUNCTION>
nonvirtual iterator Find (FUNCTION doToElement);
template <typename FUNCTION>
nonvirtual const_iterator Find (FUNCTION doToElement) const;
public:
template <typename PREDICATE>
nonvirtual bool FindIf (PREDICATE pred) const;
public:
nonvirtual void Invariant () const noexcept;
public:
nonvirtual iterator remove_constness (const_iterator it);
};
/**
* STLContainerWrapper::ForwardIterator is a private utility class designed
* to promote source code sharing among the patched iterator implementations.
*
* \note ForwardIterator takes a const-pointer the the container as argument since this
* iterator never MODIFIES the container.
*
* However, it does a const-cast to maintain a non-const pointer since that is needed to
* option a non-const iterator pointer, which is needed by some classes that use this, and
* there is no zero (or even low for forward_list) cost way to map from const to non const
* iterators (needed to perform the update).
*
* @see https://stroika.atlassian.net/browse/STK-538
*/
template <typename STL_CONTAINER_OF_T>
class STLContainerWrapper<STL_CONTAINER_OF_T>::ForwardIterator {
public:
/**
*/
explicit ForwardIterator (const STLContainerWrapper* data);
explicit ForwardIterator (const STLContainerWrapper* data, UnderlyingIteratorRep startAt);
explicit ForwardIterator (const ForwardIterator& from) = default;
public:
nonvirtual bool Done () const noexcept;
public:
nonvirtual ForwardIterator& operator++ () noexcept;
public:
nonvirtual value_type Current () const;
public:
/**
* Only legal to call if underlying iterator is random_access
*/
nonvirtual size_t CurrentIndex () const;
public:
nonvirtual UnderlyingIteratorRep GetUnderlyingIteratorRep () const;
public:
nonvirtual void SetUnderlyingIteratorRep (UnderlyingIteratorRep l);
public:
nonvirtual bool Equals (const ForwardIterator& rhs) const;
public:
nonvirtual const STLContainerWrapper* GetReferredToData () const;
private:
const STLContainerWrapper* fData_;
const_iterator fStdIterator_;
private:
friend class STLContainerWrapper;
};
}
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "STLContainerWrapper.inl"
#endif /*_Stroika_Foundation_Containers_DataStructures_STLContainerWrapper_h_ */
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>LCOV - coverage.infosrc/core</title>
<link rel="stylesheet" type="text/css" href="../../gcov.css">
</head>
<body>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="title">LCOV - code coverage report</td></tr>
<tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr>
<tr>
<td width="100%">
<table cellpadding=1 border=0 width="100%">
<tr>
<td width="10%" class="headerItem">Current view:</td>
<td width="35%" class="headerValue"><a href="../../index.html">top level</a> - src/core</td>
<td width="5%"></td>
<td width="15%"></td>
<td width="10%" class="headerCovTableHead">Hit</td>
<td width="10%" class="headerCovTableHead">Total</td>
<td width="15%" class="headerCovTableHead">Coverage</td>
</tr>
<tr>
<td class="headerItem">Test:</td>
<td class="headerValue">coverage.info</td>
<td></td>
<td class="headerItem">Lines:</td>
<td class="headerCovTableEntry">193</td>
<td class="headerCovTableEntry">220</td>
<td class="headerCovTableEntryMed">87.7 %</td>
</tr>
<tr>
<td class="headerItem">Date:</td>
<td class="headerValue">2013-01-10</td>
<td></td>
<td class="headerItem">Functions:</td>
<td class="headerCovTableEntry">23</td>
<td class="headerCovTableEntry">26</td>
<td class="headerCovTableEntryMed">88.5 %</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td class="headerItem">Branches:</td>
<td class="headerCovTableEntry">20</td>
<td class="headerCovTableEntry">24</td>
<td class="headerCovTableEntryMed">83.3 %</td>
</tr>
<tr><td><img src="../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
</td>
</tr>
<tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
<center>
<table width="80%" cellpadding=1 cellspacing=1 border=0>
<tr>
<td width="44%"><br></td>
<td width="8%"></td>
<td width="8%"></td>
<td width="8%"></td>
<td width="8%"></td>
<td width="8%"></td>
<td width="8%"></td>
<td width="8%"></td>
</tr>
<tr>
<td class="tableHead">Filename <span class="tableHeadSort"><img src="../../glass.png" width=10 height=14 alt="Sort by name" title="Sort by name" border=0></span></td>
<td class="tableHead" colspan=3>Line Coverage <span class="tableHeadSort"><a href="index-sort-l.html"><img src="../../updown.png" width=10 height=14 alt="Sort by line coverage" title="Sort by line coverage" border=0></a></span></td>
<td class="tableHead" colspan=2>Functions <span class="tableHeadSort"><a href="index-sort-f.html"><img src="../../updown.png" width=10 height=14 alt="Sort by function coverage" title="Sort by function coverage" border=0></a></span></td>
<td class="tableHead" colspan=2>Branches <span class="tableHeadSort"><a href="index-sort-b.html"><img src="../../updown.png" width=10 height=14 alt="Sort by branch coverage" title="Sort by branch coverage" border=0></a></span></td>
</tr>
<tr>
<td class="coverFile"><a href="dvm.c.gcov.html">dvm.c</a></td>
<td class="coverBar" align="center">
<table border=0 cellspacing=0 cellpadding=1><tr><td class="coverBarOutline"><img src="../../emerald.png" width=91 height=10 alt="91.4%"><img src="../../snow.png" width=9 height=10 alt="91.4%"></td></tr></table>
</td>
<td class="coverPerHi">91.4 %</td>
<td class="coverNumHi">128 / 140</td>
<td class="coverPerHi">92.3 %</td>
<td class="coverNumHi">12 / 13</td>
<td class="coverPerMed">88.9 %</td>
<td class="coverNumMed">16 / 18</td>
</tr>
<tr>
<td class="coverFile"><a href="vmbase.c.gcov.html">vmbase.c</a></td>
<td class="coverBar" align="center">
<table border=0 cellspacing=0 cellpadding=1><tr><td class="coverBarOutline"><img src="../../amber.png" width=81 height=10 alt="81.2%"><img src="../../snow.png" width=19 height=10 alt="81.2%"></td></tr></table>
</td>
<td class="coverPerMed">81.2 %</td>
<td class="coverNumMed">65 / 80</td>
<td class="coverPerMed">84.6 %</td>
<td class="coverNumMed">11 / 13</td>
<td class="coverPerLo">66.7 %</td>
<td class="coverNumLo">4 / 6</td>
</tr>
</table>
</center>
<br>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr>
<tr><td class="versionInfo">Generated by: <a href="http://ltp.sourceforge.net/coverage/lcov.php">LCOV version 1.9</a></td></tr>
</table>
<br>
</body>
</html>
| Java |
import {writeFile} from 'fs-promise';
import {get, has, merge, set} from 'lodash/fp';
import flatten from 'flat';
import fs from 'fs';
import path from 'path';
const data = new WeakMap();
const initial = new WeakMap();
export default class Config {
constructor(d) {
data.set(this, d);
initial.set(this, Object.assign({}, d));
}
clone() {
return Object.assign({}, data.get(this));
}
get(keypath) {
return get(keypath, data.get(this));
}
has(keypath) {
return has(keypath, data.get(this));
}
inspect() {
return data.get(this);
}
merge(extra) {
data.set(this, merge(data.get(this), extra));
}
set(keypath, value) {
return set(keypath, data.get(this), value);
}
async save() {
const out = this.toString();
return await writeFile(`.boilerizerc`, out);
}
toJSON() {
const keys = Object.keys(flatten(data.get(this), {safe: true}));
const init = initial.get(this);
let target;
try {
const filepath = path.join(process.cwd(), `.boilerizerc`);
// Using sync here because toJSON can't have async functions in it
// eslint-disable-next-line no-sync
const raw = fs.readFileSync(filepath, `utf8`);
target = JSON.parse(raw);
}
catch (e) {
if (e.code !== `ENOENT`) {
console.error(e);
throw e;
}
target = {};
}
return keys.reduce((acc, key) => {
if (!has(key, init) || has(key, target)) {
const val = this.get(key);
acc = set(key, val, acc);
}
return acc;
}, target);
}
toString() {
return JSON.stringify(this, null, 2);
}
}
| Java |
/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.dfa.report;
public class ClassNode extends AbstractReportNode {
private String className;
public ClassNode(String className) {
this.className = className;
}
public String getClassName() {
return className;
}
public boolean equalsNode(AbstractReportNode arg0) {
if (!(arg0 instanceof ClassNode)) {
return false;
}
return ((ClassNode) arg0).getClassName().equals(className);
}
}
| Java |
<?php namespace Helpers;
/**
*This class handles rendering of view files
*
*@author Geoffrey Oliver <geoffrey.oliver2@gmail.com>
*@copyright Copyright (c) 2015 - 2020 Geoffrey Oliver
*@link http://libraries.gliver.io
*@category Core
*@package Core\Helpers\View
*/
use Drivers\Templates\Implementation;
use Exceptions\BaseException;
use Drivers\Cache\CacheBase;
use Drivers\Registry;
class View {
/**
*This is the constructor class. We make this private to avoid creating instances of
*this object
*
*@param null
*@return void
*/
private function __construct() {}
/**
*This method stops creation of a copy of this object by making it private
*
*@param null
*@return void
*
*/
private function __clone(){}
/**
*This method parses the input variables and loads the specified views
*
*@param string $filePath the string that specifies the view file to load
*@param array $data an array with variables to be passed to the view file
*@return void This method does not return anything, it directly loads the view file
*@throws
*/
public static function render($filePath, array $data = null)
{
//this try block is excecuted to enable throwing and catching of errors as appropriate
try {
//get the variables passed and make them available to the view
if ( $data != null)
{
//loop through the array setting the respective variables
foreach ($data as $key => $value)
{
$$key = $value;
}
}
//get the parsed contents of the template file
$contents = self::getContents($filePath);
//start the output buffer
ob_start();
//evaluate the contents of this view file
eval("?>" . $contents . "<?");
//get the evaluated contents
$contents = ob_get_contents();
//clean the output buffer
ob_end_clean();
//return the evaluated contents
echo $contents;
//stop further script execution
exit();
}
catch(BaseException $e) {
//echo $e->getMessage();
$e->show();
}
catch(Exception $e) {
echo $e->getMessage();
}
}
/**
*This method converts the code into valid php code
*
*@param string $file The name of the view whose contant is to be parsed
*@return string $parsedContent The parsed content of the template file
*/
public static function getContents($filePath)
{
//compose the file full path
$path = Path::view($filePath);
//get an instance of the view template class
$template = Registry::get('template');
//get the compiled file contents
$contents = $template->compiled($path);
//return the compiled template file contents
return $contents;
}
} | Java |
package pl.mmorpg.prototype.server.objects.monsters.properties.builders;
import pl.mmorpg.prototype.clientservercommon.packets.monsters.properties.MonsterProperties;
public class SnakePropertiesBuilder extends MonsterProperties.Builder
{
@Override
public MonsterProperties build()
{
experienceGain(100)
.hp(100)
.strength(5)
.level(1);
return super.build();
}
}
| Java |
using Microsoft.DataTransfer.AzureTable.Source;
using System;
using System.Globalization;
namespace Microsoft.DataTransfer.AzureTable
{
/// <summary>
/// Contains dynamic resources for data adapters configuration.
/// </summary>
public static class DynamicConfigurationResources
{
/// <summary>
/// Gets the description for source internal fields configuration property.
/// </summary>
public static string Source_InternalFields
{
get
{
return Format(ConfigurationResources.Source_InternalFieldsFormat, Defaults.Current.SourceInternalFields,
String.Join(", ", Enum.GetNames(typeof(AzureTableInternalFields))));
}
}
private static string Format(string format, params object[] args)
{
return String.Format(CultureInfo.InvariantCulture, format, args);
}
}
}
| Java |
// Karma configuration
// Generated on Thu Aug 21 2014 10:24:39 GMT+0200 (CEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai-jquery', 'jquery-1.8.3', 'sinon-chai'],
plugins: [
'karma-mocha',
'karma-chai',
'karma-sinon-chai',
'karma-chrome-launcher',
'karma-phantomjs-launcher',
'karma-jquery',
'karma-chai-jquery',
'karma-mocha-reporter'
],
// list of files / patterns to load in the browser
files: [
'bower/angular/angular.js',
'bower/angular-sanitize/angular-sanitize.js',
'bower/angular-mocks/angular-mocks.js',
'dist/ac-components.min.js',
'test/unit/**/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
| Java |
#! python3
"""
GUI for Ultrasonic Temperature Controller
Copyright (c) 2015 by Stefan Lehmann
"""
import os
import datetime
import logging
import json
import serial
from qtpy.QtWidgets import QAction, QDialog, QMainWindow, QMessageBox, \
QDockWidget, QLabel, QFileDialog, QApplication
from qtpy.QtGui import QIcon
from qtpy.QtCore import QSettings, QCoreApplication, Qt, QThread, \
Signal
from serial.serialutil import SerialException
from jsonwatch.jsonitem import JsonItem
from jsonwatch.jsonnode import JsonNode
from jsonwatchqt.logger import LoggingWidget
from pyqtconfig.config import QSettingsManager
from jsonwatchqt.plotsettings import PlotSettingsWidget
from jsonwatchqt.objectexplorer import ObjectExplorer
from jsonwatchqt.plotwidget import PlotWidget
from jsonwatchqt.serialdialog import SerialDialog, PORT_SETTING, \
BAUDRATE_SETTING
from jsonwatchqt.utilities import critical, pixmap
from jsonwatchqt.recorder import RecordWidget
from jsonwatchqt.csvsettings import CSVSettingsDialog, DECIMAL_SETTING, \
SEPARATOR_SETTING
logger = logging.getLogger("jsonwatchqt.mainwindow")
WINDOWSTATE_SETTING = "mainwindow/windowstate"
GEOMETRY_SETTING = "mainwindow/geometry"
FILENAME_SETTING = "mainwindow/filename"
def strip(s):
return s.strip()
def utf8_to_bytearray(x):
return bytearray(x, 'utf-8')
def bytearray_to_utf8(x):
return x.decode('utf-8')
def set_default_settings(settings: QSettingsManager):
settings.set_defaults({
DECIMAL_SETTING: ',',
SEPARATOR_SETTING: ';'
})
class SerialWorker(QThread):
data_received = Signal(datetime.datetime, str)
def __init__(self, ser: serial.Serial, parent=None):
super().__init__(parent)
self.serial = ser
self._quit = False
def run(self):
while not self._quit:
try:
if self.serial.isOpen() and self.serial.inWaiting():
self.data_received.emit(
datetime.datetime.now(),
strip(bytearray_to_utf8(self.serial.readline()))
)
except SerialException:
pass
def quit(self):
self._quit = True
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.recording_enabled = False
self.serial = serial.Serial()
self.rootnode = JsonNode('')
self._connected = False
self._dirty = False
self._filename = None
# settings
self.settings = QSettingsManager()
set_default_settings(self.settings)
# Controller Settings
self.settingsDialog = None
# object explorer
self.objectexplorer = ObjectExplorer(self.rootnode, self)
self.objectexplorer.nodevalue_changed.connect(self.send_serialdata)
self.objectexplorer.nodeproperty_changed.connect(self.set_dirty)
self.objectexplorerDockWidget = QDockWidget(self.tr("object explorer"),
self)
self.objectexplorerDockWidget.setObjectName(
"objectexplorer_dockwidget")
self.objectexplorerDockWidget.setWidget(self.objectexplorer)
# plot widget
self.plot = PlotWidget(self.rootnode, self.settings, self)
# plot settings
self.plotsettings = PlotSettingsWidget(self.settings, self.plot, self)
self.plotsettingsDockWidget = QDockWidget(self.tr("plot settings"),
self)
self.plotsettingsDockWidget.setObjectName("plotsettings_dockwidget")
self.plotsettingsDockWidget.setWidget(self.plotsettings)
# log widget
self.loggingWidget = LoggingWidget(self)
self.loggingDockWidget = QDockWidget(self.tr("logger"), self)
self.loggingDockWidget.setObjectName("logging_dockwidget")
self.loggingDockWidget.setWidget(self.loggingWidget)
# record widget
self.recordWidget = RecordWidget(self.rootnode, self)
self.recordDockWidget = QDockWidget(self.tr("data recording"), self)
self.recordDockWidget.setObjectName("record_dockwidget")
self.recordDockWidget.setWidget(self.recordWidget)
# actions and menus
self._init_actions()
self._init_menus()
# statusbar
statusbar = self.statusBar()
statusbar.setVisible(True)
self.connectionstateLabel = QLabel(self.tr("Not connected"))
statusbar.addPermanentWidget(self.connectionstateLabel)
statusbar.showMessage(self.tr("Ready"))
# layout
self.setCentralWidget(self.plot)
self.addDockWidget(Qt.LeftDockWidgetArea,
self.objectexplorerDockWidget)
self.addDockWidget(Qt.LeftDockWidgetArea, self.plotsettingsDockWidget)
self.addDockWidget(Qt.BottomDockWidgetArea, self.loggingDockWidget)
self.addDockWidget(Qt.BottomDockWidgetArea, self.recordDockWidget)
self.load_settings()
def _init_actions(self):
# Serial Dialog
self.serialdlgAction = QAction(self.tr("Serial Settings..."), self)
self.serialdlgAction.setShortcut("F6")
self.serialdlgAction.setIcon(QIcon(pixmap("configure.png")))
self.serialdlgAction.triggered.connect(self.show_serialdlg)
# Connect
self.connectAction = QAction(self.tr("Connect"), self)
self.connectAction.setShortcut("F5")
self.connectAction.setIcon(QIcon(pixmap("network-connect-3.png")))
self.connectAction.triggered.connect(self.toggle_connect)
# Quit
self.quitAction = QAction(self.tr("Quit"), self)
self.quitAction.setShortcut("Alt+F4")
self.quitAction.setIcon(QIcon(pixmap("window-close-3.png")))
self.quitAction.triggered.connect(self.close)
# Save Config as
self.saveasAction = QAction(self.tr("Save as..."), self)
self.saveasAction.setShortcut("Ctrl+Shift+S")
self.saveasAction.setIcon(QIcon(pixmap("document-save-as-5.png")))
self.saveasAction.triggered.connect(self.show_savecfg_dlg)
# Save file
self.saveAction = QAction(self.tr("Save"), self)
self.saveAction.setShortcut("Ctrl+S")
self.saveAction.setIcon(QIcon(pixmap("document-save-5.png")))
self.saveAction.triggered.connect(self.save_file)
# Load file
self.loadAction = QAction(self.tr("Open..."), self)
self.loadAction.setShortcut("Ctrl+O")
self.loadAction.setIcon(QIcon(pixmap("document-open-7.png")))
self.loadAction.triggered.connect(self.show_opencfg_dlg)
# New
self.newAction = QAction(self.tr("New"), self)
self.newAction.setShortcut("Ctrl+N")
self.newAction.setIcon(QIcon(pixmap("document-new-6.png")))
self.newAction.triggered.connect(self.new)
# start recording
self.startrecordingAction = QAction(self.tr("Start recording"), self)
self.startrecordingAction.setShortcut("F9")
self.startrecordingAction.setIcon(QIcon(pixmap("media-record-6.png")))
self.startrecordingAction.triggered.connect(self.start_recording)
# stop recording
self.stoprecordingAction = QAction(self.tr("Stop recording"), self)
self.stoprecordingAction.setShortcut("F10")
self.stoprecordingAction.setIcon(QIcon(pixmap("media-playback-stop-8.png")))
self.stoprecordingAction.setEnabled(False)
self.stoprecordingAction.triggered.connect(self.stop_recording)
# clear record
self.clearrecordAction = QAction(self.tr("Clear"), self)
self.clearrecordAction.setIcon(QIcon(pixmap("editclear.png")))
self.clearrecordAction.triggered.connect(self.clear_record)
# export record
self.exportcsvAction = QAction(self.tr("Export to csv..."), self)
self.exportcsvAction.setIcon(QIcon(pixmap("text_csv.png")))
self.exportcsvAction.triggered.connect(self.export_csv)
# show record settings
self.recordsettingsAction = QAction(self.tr("Settings..."), self)
self.recordsettingsAction.setIcon(QIcon(pixmap("configure.png")))
self.recordsettingsAction.triggered.connect(self.show_recordsettings)
# Info
self.infoAction = QAction(self.tr("Info"), self)
self.infoAction.setShortcut("F1")
self.infoAction.triggered.connect(self.show_info)
def _init_menus(self):
# file menu
self.fileMenu = self.menuBar().addMenu(self.tr("File"))
self.fileMenu.addAction(self.newAction)
self.fileMenu.addAction(self.loadAction)
self.fileMenu.addAction(self.saveAction)
self.fileMenu.addAction(self.saveasAction)
self.fileMenu.addSeparator()
self.fileMenu.addAction(self.connectAction)
self.fileMenu.addAction(self.serialdlgAction)
self.fileMenu.addSeparator()
self.fileMenu.addAction(self.quitAction)
# view menu
self.viewMenu = self.menuBar().addMenu(self.tr("View"))
self.viewMenu.addAction(
self.objectexplorerDockWidget.toggleViewAction())
self.viewMenu.addAction(self.plotsettingsDockWidget.toggleViewAction())
self.viewMenu.addAction(self.loggingDockWidget.toggleViewAction())
self.viewMenu.addAction(self.recordDockWidget.toggleViewAction())
# record menu
self.recordMenu = self.menuBar().addMenu(self.tr("Record"))
self.recordMenu.addAction(self.startrecordingAction)
self.recordMenu.addAction(self.stoprecordingAction)
self.recordMenu.addAction(self.exportcsvAction)
self.recordMenu.addSeparator()
self.recordMenu.addAction(self.clearrecordAction)
self.recordMenu.addSeparator()
self.recordMenu.addAction(self.recordsettingsAction)
# info menu
self.menuBar().addAction(self.infoAction)
def show_info(self):
QMessageBox.about(
self, QApplication.applicationName(),
"%s %s\n"
"Copyright (c) by %s" %
(
QCoreApplication.applicationName(),
QCoreApplication.applicationVersion(),
QCoreApplication.organizationName(),
)
)
def load_file(self, filename):
old_filename = self.filename if self.filename != filename else None
self.filename = filename
try:
with open(filename, 'rb') as f:
try:
self.objectexplorer.model().beginResetModel()
self.rootnode.load(bytearray_to_utf8(f.read()))
self.objectexplorer.model().endResetModel()
except ValueError as e:
critical(self, "File '%s' is not a valid config file."
% filename)
logger.error(str(e))
if old_filename is not None:
self.load_file(old_filename)
else:
self.filename = None
except FileNotFoundError as e:
logger.error(str(e))
self.filename = None
self.objectexplorer.refresh()
def load_settings(self):
settings = QSettings()
# window geometry
try:
self.restoreGeometry(settings.value(GEOMETRY_SETTING))
except:
logger.debug("error restoring window geometry")
# window state
try:
self.restoreState(settings.value(WINDOWSTATE_SETTING))
except:
logger.debug("error restoring window state")
# filename
self.filename = settings.value(FILENAME_SETTING)
if self.filename is not None:
self.load_file(self.filename)
def save_settings(self):
settings = QSettings()
settings.setValue(WINDOWSTATE_SETTING, self.saveState())
settings.setValue(GEOMETRY_SETTING, self.saveGeometry())
settings.setValue(FILENAME_SETTING, self.filename)
def closeEvent(self, event):
if self.dirty:
res = QMessageBox.question(
self,
QCoreApplication.applicationName(),
self.tr("Save changes to file '%s'?" %
self.filename
if self.filename is not None else "unknown"),
QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel
)
if res == QMessageBox.Cancel:
event.ignore()
return
elif res == QMessageBox.Yes:
self.save_file()
self.save_settings()
try:
self.worker.quit()
except AttributeError:
pass
try:
self.serial.close()
except (SerialException, AttributeError):
pass
def new(self):
self.objectexplorer.model().beginResetModel()
self.rootnode.clear()
self.objectexplorer.model().endResetModel()
def send_reset(self):
jsonstring = json.dumps({"resetpid": 1})
self.serial.write(bytearray(jsonstring, 'utf-8'))
def receive_serialdata(self, time, data):
self.loggingWidget.log_input(data)
try:
self.rootnode.from_json(data)
except ValueError as e:
logger.error(str(e))
# refresh widgets
self.objectexplorer.refresh()
self.plot.refresh(time)
if self.recording_enabled:
self.recordWidget.add_data(time, self.rootnode)
def send_serialdata(self, node):
if isinstance(node, JsonItem):
if self.serial.isOpen():
s = node.to_json()
self.serial.write(utf8_to_bytearray(s + '\n'))
self.loggingWidget.log_output(s.strip())
def show_serialdlg(self):
dlg = SerialDialog(self.settings, self)
dlg.exec_()
def toggle_connect(self):
if self.serial.isOpen():
self.disconnect()
else:
self.connect()
def connect(self):
# Load port setting
port = self.settings.get(PORT_SETTING)
baudrate = self.settings.get(BAUDRATE_SETTING)
# If no port has been selected before show serial settings dialog
if port is None:
if self.show_serialdlg() == QDialog.Rejected:
return
port = self.settings.get(PORT_SETTING)
baudrate = self.settings.get(BAUDRATE_SETTING)
# Serial connection
try:
self.serial.port = port
self.serial.baudrate = baudrate
self.serial.open()
except ValueError:
QMessageBox.critical(
self, QCoreApplication.applicationName(),
self.tr("Serial parameters e.g. baudrate, databits are out "
"of range.")
)
except SerialException:
QMessageBox.critical(
self, QCoreApplication.applicationName(),
self.tr("The device '%s' can not be found or can not be "
"configured." % port)
)
else:
self.worker = SerialWorker(self.serial, self)
self.worker.data_received.connect(self.receive_serialdata)
self.worker.start()
self.connectAction.setText(self.tr("Disconnect"))
self.connectAction.setIcon(QIcon(pixmap("network-disconnect-3.png")))
self.serialdlgAction.setEnabled(False)
self.connectionstateLabel.setText(
self.tr("Connected to %s") % port)
self._connected = True
self.objectexplorer.refresh()
def disconnect(self):
self.worker.quit()
self.serial.close()
self.connectAction.setText(self.tr("Connect"))
self.connectAction.setIcon(QIcon(pixmap("network-connect-3.png")))
self.serialdlgAction.setEnabled(True)
self.connectionstateLabel.setText(self.tr("Not connected"))
self._connected = False
self.objectexplorer.refresh()
def show_savecfg_dlg(self):
filename, _ = QFileDialog.getSaveFileName(
self, self.tr("Save configuration file..."),
directory=os.path.expanduser("~"),
filter="Json file (*.json)"
)
if filename:
self.filename = filename
self.save_file()
def save_file(self):
if self.filename is not None:
config_string = self.rootnode.dump()
with open(self.filename, 'w') as f:
f.write(config_string)
self.dirty = False
else:
self.show_savecfg_dlg()
def show_opencfg_dlg(self):
# show file dialog
filename, _ = QFileDialog.getOpenFileName(
self, self.tr("Open configuration file..."),
directory=os.path.expanduser("~"),
filter=self.tr("Json file (*.json);;All files (*.*)")
)
# load config file
if filename:
self.load_file(filename)
def refresh_window_title(self):
s = "%s %s" % (QCoreApplication.applicationName(),
QCoreApplication.applicationVersion())
if self.filename is not None:
s += " - " + self.filename
if self.dirty:
s += "*"
self.setWindowTitle(s)
def start_recording(self):
self.recording_enabled = True
self.startrecordingAction.setEnabled(False)
self.stoprecordingAction.setEnabled(True)
def stop_recording(self):
self.recording_enabled = False
self.startrecordingAction.setEnabled(True)
self.stoprecordingAction.setEnabled(False)
def export_csv(self):
filename, _ = QFileDialog.getSaveFileName(
self, QCoreApplication.applicationName(),
filter="CSV files(*.csv);;All files (*.*)"
)
if filename == "":
return
# get current dataframe and export to csv
df = self.recordWidget.dataframe
decimal = self.settings.get(DECIMAL_SETTING)
df = df.applymap(lambda x: str(x).replace(".", decimal))
df.to_csv(
filename, index_label="time",
sep=self.settings.get(SEPARATOR_SETTING)
)
def clear_record(self):
self.recordWidget.clear()
def show_recordsettings(self):
dlg = CSVSettingsDialog(self)
dlg.exec_()
# filename property
@property
def filename(self):
return self._filename
@filename.setter
def filename(self, value=""):
self._filename = value
self.refresh_window_title()
# dirty property
@property
def dirty(self):
return self._dirty
@dirty.setter
def dirty(self, value):
self._dirty = value
self.refresh_window_title()
def set_dirty(self):
self.dirty = True
# connected property
@property
def connected(self):
return self._connected
| Java |
This returns the resolution of the cone (rather than the cap)
| Java |
using System.Threading;
using CodeTiger;
using Xunit;
namespace UnitTests.CodeTiger
{
public class LazyTests
{
public class Create1
{
[Fact]
public void SetsIsValueCreatedToFalse()
{
var target = Lazy.Create<object>();
Assert.False(target.IsValueCreated);
}
[Fact]
public void ReturnsDefaultValueOfObject()
{
var target = Lazy.Create<object>();
Assert.NotNull(target.Value);
Assert.Equal(typeof(object), target.Value.GetType());
}
[Fact]
public void ReturnsDefaultValueOfBoolean()
{
var target = Lazy.Create<bool>();
Assert.Equal(new bool(), target.Value);
}
[Fact]
public void ReturnsDefaultValueOfDecimal()
{
var target = Lazy.Create<decimal>();
Assert.Equal(new decimal(), target.Value);
}
}
public class Create1_Boolean
{
[Theory]
[InlineData(false)]
[InlineData(true)]
public void SetsIsValueCreatedToFalse(bool isThreadSafe)
{
var target = Lazy.Create<object>(isThreadSafe);
Assert.False(target.IsValueCreated);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ReturnsDefaultValueOfObject(bool isThreadSafe)
{
var target = Lazy.Create<object>(isThreadSafe);
Assert.NotNull(target.Value);
Assert.Equal(typeof(object), target.Value.GetType());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ReturnsDefaultValueOfBoolean(bool isThreadSafe)
{
var target = Lazy.Create<bool>(isThreadSafe);
Assert.Equal(new bool(), target.Value);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ReturnsDefaultValueOfDecimal(bool isThreadSafe)
{
var target = Lazy.Create<decimal>(isThreadSafe);
Assert.Equal(new decimal(), target.Value);
}
}
public class Create1_LazyThreadSafetyMode
{
[Theory]
[InlineData(LazyThreadSafetyMode.None)]
[InlineData(LazyThreadSafetyMode.PublicationOnly)]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
public void SetsIsValueCreatedToFalse(LazyThreadSafetyMode mode)
{
var target = Lazy.Create<object>(mode);
Assert.False(target.IsValueCreated);
}
[Theory]
[InlineData(LazyThreadSafetyMode.None)]
[InlineData(LazyThreadSafetyMode.PublicationOnly)]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
public void CreatesTaskWhichReturnsDefaultValueOfObject(LazyThreadSafetyMode mode)
{
var target = Lazy.Create<object>(mode);
Assert.NotNull(target.Value);
Assert.Equal(typeof(object), target.Value.GetType());
}
[Theory]
[InlineData(LazyThreadSafetyMode.None)]
[InlineData(LazyThreadSafetyMode.PublicationOnly)]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
public void CreatesTaskWhichReturnsDefaultValueOfBoolean(LazyThreadSafetyMode mode)
{
var target = Lazy.Create<bool>(mode);
Assert.Equal(new bool(), target.Value);
}
[Theory]
[InlineData(LazyThreadSafetyMode.None)]
[InlineData(LazyThreadSafetyMode.PublicationOnly)]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
public void CreatesTaskWhichReturnsDefaultValueOfDecimal(LazyThreadSafetyMode mode)
{
var target = Lazy.Create<decimal>(mode);
Assert.Equal(new decimal(), target.Value);
}
}
public class Create1_FuncOfTaskOfT1
{
[Fact]
public void SetsIsValueCreatedToFalse()
{
object expected = new object();
var target = Lazy.Create(() => expected);
Assert.False(target.IsValueCreated);
}
[Fact]
public void SetsValueToProvidedObject()
{
object expected = new object();
var target = Lazy.Create(() => expected);
Assert.Same(expected, target.Value);
}
}
public class Create1_FuncOfTaskOfT1_Boolean
{
[Theory]
[InlineData(false)]
[InlineData(true)]
public void SetsIsValueCreatedToFalse(bool isThreadSafe)
{
object expected = new object();
var target = Lazy.Create(() => expected, isThreadSafe);
Assert.False(target.IsValueCreated);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void SetsValueToProvidedTask(bool isThreadSafe)
{
object expected = new object();
var target = Lazy.Create(() => expected, isThreadSafe);
Assert.Same(expected, target.Value);
}
}
public class Create1_FuncOfTaskOfT1_LazyThreadSafetyMode
{
[Theory]
[InlineData(LazyThreadSafetyMode.None)]
[InlineData(LazyThreadSafetyMode.PublicationOnly)]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
public void SetsIsValueCreatedToFalse(LazyThreadSafetyMode mode)
{
object expected = new object();
var target = Lazy.Create(() => expected, mode);
Assert.False(target.IsValueCreated);
}
[Theory]
[InlineData(LazyThreadSafetyMode.None)]
[InlineData(LazyThreadSafetyMode.PublicationOnly)]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
public void SetsValueToProvidedTask(LazyThreadSafetyMode mode)
{
object expected = new object();
var target = Lazy.Create(() => expected, mode);
Assert.Same(expected, target.Value);
}
}
}
} | Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/><!-- using block title in layout.dt--><!-- using block ddox.defs in ddox.layout.dt--><!-- using block ddox.title in ddox.layout.dt-->
<title>Function awe_webview_set_callback_change_target_url</title>
<link rel="stylesheet" type="text/css" href="../../styles/ddox.css"/>
<link rel="stylesheet" href="../../prettify/prettify.css" type="text/css"/>
<script type="text/javascript" src="../../scripts/jquery.js">/**/</script>
<script type="text/javascript" src="../../prettify/prettify.js">/**/</script>
<script type="text/javascript" src="../../scripts/ddox.js">/**/</script>
</head>
<body onload="prettyPrint(); setupDdox();">
<nav id="main-nav"><!-- using block navigation in layout.dt-->
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">components</a>
<ul class="tree-view">
<li>
<a href="../../components/animation.html" class=" module">animation</a>
</li>
<li>
<a href="../../components/assets.html" class=" module">assets</a>
</li>
<li>
<a href="../../components/camera.html" class=" module">camera</a>
</li>
<li>
<a href="../../components/component.html" class=" module">component</a>
</li>
<li>
<a href="../../components/lights.html" class=" module">lights</a>
</li>
<li>
<a href="../../components/material.html" class=" module">material</a>
</li>
<li>
<a href="../../components/mesh.html" class=" module">mesh</a>
</li>
<li>
<a href="../../components/userinterface.html" class=" module">userinterface</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">core</a>
<ul class="tree-view">
<li>
<a href="../../core/dgame.html" class=" module">dgame</a>
</li>
<li>
<a href="../../core/gameobject.html" class=" module">gameobject</a>
</li>
<li>
<a href="../../core/prefabs.html" class=" module">prefabs</a>
</li>
<li>
<a href="../../core/properties.html" class=" module">properties</a>
</li>
<li>
<a href="../../core/reflection.html" class=" module">reflection</a>
</li>
<li>
<a href="../../core/scene.html" class=" module">scene</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">graphics</a>
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">adapters</a>
<ul class="tree-view">
<li>
<a href="../../graphics/adapters/adapter.html" class=" module">adapter</a>
</li>
<li>
<a href="../../graphics/adapters/linux.html" class=" module">linux</a>
</li>
<li>
<a href="../../graphics/adapters/mac.html" class=" module">mac</a>
</li>
<li>
<a href="../../graphics/adapters/win32.html" class=" module">win32</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">shaders</a>
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">glsl</a>
<ul class="tree-view">
<li>
<a href="../../graphics/shaders/glsl/ambientlight.html" class=" module">ambientlight</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/animatedgeometry.html" class=" module">animatedgeometry</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/directionallight.html" class=" module">directionallight</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/geometry.html" class=" module">geometry</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/pointlight.html" class=" module">pointlight</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/shadowmap.html" class=" module">shadowmap</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/userinterface.html" class=" module">userinterface</a>
</li>
</ul>
</li>
<li>
<a href="../../graphics/shaders/glsl.html" class=" module">glsl</a>
</li>
<li>
<a href="../../graphics/shaders/shaders.html" class=" module">shaders</a>
</li>
</ul>
</li>
<li>
<a href="../../graphics/adapters.html" class=" module">adapters</a>
</li>
<li>
<a href="../../graphics/graphics.html" class=" module">graphics</a>
</li>
<li>
<a href="../../graphics/shaders.html" class=" module">shaders</a>
</li>
</ul>
</li>
<li class=" tree-view">
<a href="#" class="package">utility</a>
<ul class="tree-view">
<li>
<a href="../../utility/awesomium.html" class="selected module">awesomium</a>
</li>
<li>
<a href="../../utility/concurrency.html" class=" module">concurrency</a>
</li>
<li>
<a href="../../utility/config.html" class=" module">config</a>
</li>
<li>
<a href="../../utility/filepath.html" class=" module">filepath</a>
</li>
<li>
<a href="../../utility/input.html" class=" module">input</a>
</li>
<li>
<a href="../../utility/output.html" class=" module">output</a>
</li>
<li>
<a href="../../utility/resources.html" class=" module">resources</a>
</li>
<li>
<a href="../../utility/string.html" class=" module">string</a>
</li>
<li>
<a href="../../utility/tasks.html" class=" module">tasks</a>
</li>
<li>
<a href="../../utility/time.html" class=" module">time</a>
</li>
</ul>
</li>
<li>
<a href="../../components.html" class=" module">components</a>
</li>
<li>
<a href="../../core.html" class=" module">core</a>
</li>
<li>
<a href="../../graphics.html" class=" module">graphics</a>
</li>
<li>
<a href="../../utility.html" class=" module">utility</a>
</li>
</ul>
<noscript>
<p style="color: red">The search functionality needs JavaScript enabled</p>
</noscript>
<div id="symbolSearchPane" style="display: none">
<p>
<input id="symbolSearch" type="text" placeholder="Search for symbols" onchange="performSymbolSearch(24);" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/>
</p>
<ul id="symbolSearchResults" style="display: none"></ul>
<script type="application/javascript" src="../../symbols.js"></script>
<script type="application/javascript">
//<![CDATA[
var symbolSearchRootDir = "../../"; $('#symbolSearchPane').show();
//]]>
</script>
</div>
</nav>
<div id="main-contents">
<h1>Function awe_webview_set_callback_change_target_url</h1><!-- using block body in layout.dt--><!-- Default block ddox.description in ddox.layout.dt--><!-- Default block ddox.sections in ddox.layout.dt--><!-- using block ddox.members in ddox.layout.dt-->
<p> Assign a <a href="../../utility/awesomium/awe_webview_set_callback_change_target_url.html#callback"><code class="prettyprint lang-d">callback</code></a> function to be notified when the target URL has changed.
This is usually the result of hovering over a link on the page.
</p>
<section>
<p> @param <a href="../../utility/awesomium/awe_webview_set_callback_change_target_url.html#webview"><code class="prettyprint lang-d">webview</code></a> The WebView instance.
</p>
<p> @param <a href="../../utility/awesomium/awe_webview_set_callback_change_target_url.html#callback"><code class="prettyprint lang-d">callback</code></a> A function pointer to the <a href="../../utility/awesomium/awe_webview_set_callback_change_target_url.html#callback"><code class="prettyprint lang-d">callback</code></a>.
</p>
</section>
<section>
<h2>Prototype</h2>
<pre class="code prettyprint lang-d prototype">
void awe_webview_set_callback_change_target_url(
<a href="../../utility/awesomium/awe_webview.html">awe_webview</a>* webview,
extern(C) void function(<a href="../../utility/awesomium/awe_webview.html">awe_webview</a>*, const(<a href="../../utility/awesomium/awe_string.html">awe_string</a>)*) callback
) extern(C);</pre>
</section>
<section>
<h2>Authors</h2><!-- using block ddox.authors in ddox.layout.dt-->
</section>
<section>
<h2>Copyright</h2><!-- using block ddox.copyright in ddox.layout.dt-->
</section>
<section>
<h2>License</h2><!-- using block ddox.license in ddox.layout.dt-->
</section>
</div>
</body>
</html> | Java |
all:
g++ lpf.cpp -o lpf.o
.PHONY:
clean
clean:
rm *.o
| Java |
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
n := nextInt(sc)
a := nextInt(sc)
b := nextInt(sc)
answer := 0
for i := 1; i <= n; i++ {
sum := 0
for _, s := range fmt.Sprintf("%d", i) {
x, _ := strconv.Atoi(string(s))
sum = sum + x
}
if a <= sum && sum <= b {
answer = answer + i
}
}
fmt.Println(answer)
}
// ----------
func nextString(sc *bufio.Scanner) string {
sc.Scan()
return sc.Text()
}
func nextNumber(sc *bufio.Scanner) float64 {
sc.Scan()
f, err := strconv.ParseFloat(sc.Text(), 32)
if err != nil {
panic(err)
}
return f
}
func nextInt(sc *bufio.Scanner) int {
sc.Scan()
n, err := strconv.Atoi(sc.Text())
if err != nil {
panic(err)
}
return n
}
func printArray(xs []int) {
fmt.Println(strings.Trim(fmt.Sprint(xs), "[]"))
}
func debugPrintf(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, format, a...)
}
| Java |
export default function _isString(obj) {
return toString.call(obj) === '[object String]'
}
| Java |
# cortex-ls [](http://badge.fury.io/js/cortex-ls) [](https://travis-ci.org/cortexjs/cortex-ls) [](https://gemnasium.com/cortexjs/cortex-ls)
<!-- description -->
## Install
```bash
$ npm install cortex-ls --save
```
## Usage
```js
var cortex_ls = require('cortex-ls);
```
## Licence
MIT
<!-- do not want to make nodeinit to complicated, you can edit this whenever you want. -->
| Java |
import Vue from 'vue'
import Router from 'vue-router'
import index from '../components/index'
import project from '../components/project/index'
import proAdd from '../components/project/proAdd'
import proList from '../components/project/proList'
import apiList from '../components/project/apiList'
import apiView from '../components/project/apiView'
import apiEdit from '../components/project/apiEdit'
import apiHistory from '../components/project/apiHistory'
import test from '../components/test'
import message from '../components/message'
import member from '../components/member'
import doc from '../components/doc'
import set from '../components/set'
import userSet from '../components/user/set'
import login from '../components/user/login'
Vue.use(Router)
const router:any = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'index',
component: index
},
{
path: '/project',
name: 'project',
component: project,
children: [
{
path: 'list',
name: 'proList',
component: proList,
meta: {
requireLogin: true
}
},
{
path: 'add',
name: 'proAdd',
component: proAdd,
meta: {
requireLogin: true
}
},
{
path: ':proId/edit',
name: 'proEdit',
component: proAdd,
meta: {
requireLogin: true
}
},
{
path: ':proId/api',
name: 'proApiList',
component: apiList,
children: [
{
path: 'add',
name: 'apiAdd',
component: apiEdit,
meta: {
requireLogin: true
}
},
{
path: ':apiId/detail',
name: 'apiView',
component: apiView,
meta: {
requireLogin: true
},
},
{
path: ':apiId/edit',
name: 'apiEdit',
component: apiEdit,
meta: {
requireLogin: true
}
},
{
path: ':apiId/history',
name: 'apiHistory',
component: apiHistory,
meta: {
requireLogin: true
}
}
]
}
]
},
{
path: '/test',
name: 'test',
component: test,
meta: {
requireLogin: true
}
},
{
path: '/message',
name: 'message',
component: message,
meta: {
requireLogin: true
}
},
{
path: '/member',
name: 'member',
component: member,
meta: {
requireLogin: true
}
},
{
path: '/doc',
name: 'doc',
component: doc
},
{
path: '/set',
name: 'set',
component: set,
meta: {
requireLogin: true
}
},
{
path: '/user/set',
name: 'userSet',
component: userSet,
meta: {
requireLogin: true
}
},
{
path: '/user/login',
name: 'login',
component: login
}
]
})
router.beforeEach((to:any, from:any, next:any) => {
if (to.matched.some((res:any) => res.meta.requireLogin)) {
if (localStorage.getItem('token')) {
next()
} else {
next('/user/login')
}
} else {
next()
}
})
export default router
| Java |
var class_mock =
[
[ "Mock", "class_mock.html#a2b9528f2e7fcf9738201a5ea667c1998", null ],
[ "Mock", "class_mock.html#a2b9528f2e7fcf9738201a5ea667c1998", null ],
[ "MOCK_METHOD0", "class_mock.html#ae710f23cafb1a2f17772e8805d6312d2", null ],
[ "MOCK_METHOD1", "class_mock.html#ada59eea6991953353f332e3ea1e74444", null ],
[ "MOCK_METHOD1", "class_mock.html#a2db4d82b6f92b4e462929f651ac4c3b1", null ],
[ "MOCK_METHOD1", "class_mock.html#ae73b4ee90bf6d84205d2b1c17f0b8433", null ],
[ "MOCK_METHOD1", "class_mock.html#a2cece30a3ea92b34f612f8032fe3a0f9", null ],
[ "MOCK_METHOD1", "class_mock.html#ac70c052254fa9816bd759c006062dc47", null ],
[ "MOCK_METHOD1", "class_mock.html#ae2379efbc030f1adf8b032be3bdf081d", null ],
[ "MOCK_METHOD1", "class_mock.html#a3fd62026610c5d3d3aeaaf2ade3e18aa", null ],
[ "MOCK_METHOD1", "class_mock.html#a890668928abcd28d4d39df164e7b6dd8", null ],
[ "MOCK_METHOD1", "class_mock.html#a50e2bda4375a59bb89fd5652bd33eb0f", null ]
]; | Java |
#include "StdAfx.h"
#include ".\datawriter.h"
using namespace std;
DataWriter::DataWriter(const std::string &fileName)
{
this->fileName = fileName;
fileStream = NULL;
//Initialize the filestream
fileStream = new fstream(fileName.c_str(), ios::out|ios::binary|ios::trunc);
}
void DataWriter::Write(int data, const size_t size)
{
if (fileStream)
{
if (fileStream->is_open())
{
int sizeCount = 0;
while (data > 0)
{
fileStream->put(char(data%256));
data /= 256;
++sizeCount;
}
while (sizeCount < size) //Fill the remaining characters
{
fileStream->put(char(0));
++sizeCount;
}
}
}
}
void DataWriter::Write(const char data)
{
if (fileStream)
{
if (fileStream->is_open())
{
fileStream->put(data);
}
}
}
void DataWriter::Write(const char* data, const size_t size)
{
if (!data)
{
std::cout << "Warning: attempted to write null pointer\n";
return;
}
if (fileStream)
{
if (fileStream->is_open())
{
if (strlen(data) > size)
{
cout << "Warning: Attempting to write data to area larger than specified size\n";
return;
}
fileStream->write(data,strlen(data));
if (strlen(data) < size)
{
for (unsigned int i = 0; i < size - strlen(data); ++i)
{
fileStream->put(char(0));//The files we're dealing with are little-endian, so fill after the placement of the data
}
}
}
}
}
| Java |
# Material-UI Versions
<p class="description">You can come back to this page and switch the version of the docs you're reading at any time.</p>
## Stable versions
The most recent version is recommended in production.
{{"demo": "pages/versions/StableVersions.js", "hideHeader": true}}
## Последние версии
Here you can find the latest unreleased documentation and code. You can use it to see what changes are coming and provide better feedback to Material-UI contributors.
{{"demo": "pages/versions/LatestVersion.js", "hideHeader": true}}
## Versioning strategy
We recognize that you need **stability** from the Material-UI library. Stability ensures that reusable components and libraries, tutorials, tools, and learned practices don't become obsolete unexpectedly. Stability is essential for the ecosystem around Material-UI to thrive.
This document contains **the practices that we follow** to provide you with a leading-edge UI library, balanced with stability. We strive to ensure that future changes are always introduced in a predictable way. We want everyone who depends on Material-UI to know when and how new features are added, and to be well-prepared when obsolete ones are removed.
Material-UI strictly follows [Semantic Versioning 2.0.0](https://semver.org/). Material-UI version numbers have three parts: `major.minor.patch`. The version number is incremented based on the level of change included in the release.
- **Major releases** contain significant new features, some but minimal developer assistance is expected during the update. When updating to a new major release, you may need to run update scripts, refactor code, run additional tests, and learn new APIs.
- **Minor releases** contain important new features. Minor releases are fully backward-compatible; no developer assistance is expected during update, but you can optionally modify your apps and libraries to begin using new APIs, features, and capabilities that were added in the release.
- **Patch releases** are low risk, contain bug fixes and small new features. No developer assistance is expected during update.
## Release frequency
We work toward a regular schedule of releases, so that you can plan and coordinate your updates with the continuing evolution of Material-UI.
In general, you can expect the following release cycle:
- A **major** release every 6 months.
- 1-3 **minor** releases for each major release.
- A **patch** release every week (anytime for urgent bugfix).
## Release schedule
> Disclaimer: The dates are offered as general guidance and may be adjusted by us when necessary to ensure delivery of a high-quality code.
| Date | Version |
|:------------- |:-------------------------- |
| May 2019 | `@material-ui/core` v4.0.0 |
| December 2019 | `@material-ui/core` v5.0.0 |
You can follow [our milestones](https://github.com/mui-org/material-ui/milestones) for a more detailed overview.
## Support policy
We only support the latest version of Material-UI. We don't yet have the resources to offer [LTS](https://en.wikipedia.org/wiki/Long-term_support) releases.
## Deprecation practices
Sometimes **"breaking changes"**, such as the removal of support for select APIs and features, are necessary.
To make these transitions as easy as possible, we make two commitments to you:
- We work hard to minimize the number of breaking changes and to provide migration tools when possible.
- We follow the deprecation policy described here, so you have time to update your apps to the latest APIs and best practices.
To help ensure that you have sufficient time and a clear path to update, this is our deprecation policy:
- We announce deprecated features in the changelog, and when possible, with warnings at runtime.
- When we announce a deprecation, we also announce a recommended update path.
- We support existing use of a stable API during the deprecation period, so your code will keep working during that period.
- We only make peer dependency updates (React) that require changes to your apps in a major release. | Java |
namespace mazes.Core.Grids {
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using mazes.Core.Cells;
using mazes.Core.Grids.Cartesian;
public class WeaveGrid : Grid {
private readonly List<UnderCell> _underCells = new List<UnderCell>();
public WeaveGrid(int rows, int cols) : base(rows, cols) {
PrepareGrid();
ConfigureCells();
}
private void PrepareGrid() {
var rows = new List<List<Cell>>();
for (var row = 0; row < Rows; row++) {
var newRow = new List<Cell>();
for (var column = 0; column < Columns; column++) {
newRow.Add(new OverCell(row, column, this));
}
rows.Add(newRow);
}
_grid = rows;
}
private void ConfigureCells() {
foreach (var cell in Cells.Cast<OverCell>()) {
var row = cell.Row;
var col = cell.Column;
cell.North = (OverCell)this[row - 1, col];
cell.South = (OverCell)this[row + 1, col];
cell.West = (OverCell)this[row, col - 1];
cell.East = (OverCell)this[row, col + 1];
}
}
public void TunnelUnder(OverCell overCell) {
var underCell = new UnderCell(overCell);
_underCells.Add(underCell);
}
public override IEnumerable<Cell> Cells => base.Cells.Union(_underCells);
public override Image ToImg(int cellSize = 50, float insetPrc = 0) {
return base.ToImg(cellSize, insetPrc == 0 ? 0.1f : insetPrc);
}
protected override void ToImgWithInset(Graphics g, CartesianCell cell, DrawMode mode, int cellSize, int x, int y, int inset) {
if (cell is UnderCell) {
var (x1, x2, x3, x4, y1, y2, y3, y4) = CellCoordinatesWithInset(x, y, cellSize, inset);
if (cell.VerticalPassage) {
g.DrawLine(Pens.Black, x2, y1, x2, y2);
g.DrawLine(Pens.Black, x3, y1, x3, y2);
g.DrawLine(Pens.Black, x2, y3, x2, y4);
g.DrawLine(Pens.Black, x3, y3, x3, y4);
} else {
g.DrawLine(Pens.Black, x1, y2, x2, y2);
g.DrawLine(Pens.Black, x1, y3, x2, y3);
g.DrawLine(Pens.Black, x3, y2, x4, y2);
g.DrawLine(Pens.Black, x3, y3, x4, y3);
}
} else {
base.ToImgWithInset(g, cell, mode, cellSize, x, y, inset);
}
}
}
} | Java |
package stream.flarebot.flarebot.mod.modlog;
public enum ModAction {
BAN(true, ModlogEvent.USER_BANNED),
SOFTBAN(true, ModlogEvent.USER_SOFTBANNED),
FORCE_BAN(true, ModlogEvent.USER_BANNED),
TEMP_BAN(true, ModlogEvent.USER_TEMP_BANNED),
UNBAN(false, ModlogEvent.USER_UNBANNED),
KICK(true, ModlogEvent.USER_KICKED),
TEMP_MUTE(true, ModlogEvent.USER_TEMP_MUTED),
MUTE(true, ModlogEvent.USER_MUTED),
UNMUTE(false, ModlogEvent.USER_UNMUTED),
WARN(true, ModlogEvent.USER_WARNED);
private boolean infraction;
private ModlogEvent event;
ModAction(boolean infraction, ModlogEvent modlogEvent) {
this.infraction = infraction;
this.event = modlogEvent;
}
public boolean isInfraction() {
return infraction;
}
@Override
public String toString() {
return name().charAt(0) + name().substring(1).toLowerCase().replaceAll("_", " ");
}
public String getLowercaseName() {
return toString().toLowerCase();
}
public ModlogEvent getEvent() {
return event;
}
}
| Java |
<?php
/**
* @package Update
* @category modules
* @author Nazar Mokrynskyi <nazar@mokrynskyi.com>
* @copyright Copyright (c) 2013-2014, Nazar Mokrynskyi
* @license MIT License, see license.txt
*/
namespace cs;
use h;
$Config = Config::instance();
$db = DB::instance();
$Index = Index::instance();
$module_object = $Config->module('Update');
if (!$module_object->version) {
$module_object->version = 0;
}
if (isset($Config->route[0]) && $Config->route[0] == 'process') {
$version = (int)$module_object->version;
for ($i = 1; file_exists(MFOLDER."/sql/$i.sql") || file_exists(MFOLDER."/php/$i.php"); ++$i) {
if ($version < $i) {
if (file_exists(MFOLDER."/sql/$i.sql")) {
foreach (explode(';', file_get_contents(MFOLDER."/sql/$i.sql")) as $s) {
if ($s) {
$db->{'0'}()->q($s);
}
}
}
if (file_exists(MFOLDER."/php/$i.php")) {
include MFOLDER."/php/$i.php";
}
$module_object->version = $i;
}
}
$Index->save(true);
}
$Index->buttons = false;
$Index->content(
h::{'p.cs-center'}("Current revision: $module_object->version").
h::{'a.cs-button.cs-center'}(
'Update System structure',
[
'href' => 'admin/Update/process'
]
)
);
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.6.0_18) on Thu Dec 18 17:18:41 PST 2014 -->
<title>Uses of Class javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction (Java Platform SE 7 )";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../javax/swing/plaf/basic/BasicFileChooserUI.UpdateAction.html" title="class in javax.swing.plaf.basic">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><strong>Java™ Platform<br>Standard Ed. 7</strong></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?javax/swing/plaf/basic/class-use/BasicFileChooserUI.UpdateAction.html" target="_top">Frames</a></li>
<li><a href="BasicFileChooserUI.UpdateAction.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction" class="title">Uses of Class<br>javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction</h2>
</div>
<div class="classUseContainer">No usage of javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../javax/swing/plaf/basic/BasicFileChooserUI.UpdateAction.html" title="class in javax.swing.plaf.basic">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><strong>Java™ Platform<br>Standard Ed. 7</strong></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?javax/swing/plaf/basic/class-use/BasicFileChooserUI.UpdateAction.html" target="_top">Frames</a></li>
<li><a href="BasicFileChooserUI.UpdateAction.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://docs.oracle.com/javase/7/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../../../legal/cpyr.html">Copyright</a> © 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p>
</body>
</html>
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.