text stringlengths 2 1.04M | meta dict |
|---|---|
<p style="text-align: center">{{photo}}</p>
<img class="img-responsive img-thumbnail img" ng-click="controller.show(photo)" ng-src="albums/{{controller.album.path}}/t_{{photo}}">
<div class="checkbox">
<label>
<input type="checkbox" ng-model="controller.checked[photo]" value="">
<span translate="CHECKBOX"></span>
</label>
</div> | {
"content_hash": "39e181dd25efca94349d794b0575ddce",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 134,
"avg_line_length": 44.25,
"alnum_prop": 0.6497175141242938,
"repo_name": "Grisu118/image-shop",
"id": "1328fcd3726fed488a02e843d5e57b8ec7940fa2",
"size": "354",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/views/public/album/photoElement.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "72"
},
{
"name": "HTML",
"bytes": "34200"
},
{
"name": "JavaScript",
"bytes": "38318"
},
{
"name": "PHP",
"bytes": "104437"
}
],
"symlink_target": ""
} |
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you 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.
-->
<axisconfig name="AxisJava2.0">
<!-- ================================================= -->
<!-- Parameters -->
<!-- ================================================= -->
<parameter name="hotdeployment">true</parameter>
<parameter name="hotupdate">false</parameter>
<parameter name="enableMTOM">false</parameter>
<parameter name="enableSwA">false</parameter>
<!--Uncomment if you want to enable file caching for attachments -->
<!--parameter name="cacheAttachments">true</parameter>
<parameter name="attachmentDIR"></parameter>
<parameter name="sizeThreshold">4000</parameter-->
<!--This will give out the timout of the configuration contexts, in milliseconds-->
<parameter name="ConfigContextTimeoutInterval">30000</parameter>
<!--During a fault, stacktrace can be sent with the fault message. The following flag will control -->
<!--that behavior.-->
<parameter name="sendStacktraceDetailsWithFaults">false</parameter>
<!--If there aren't any information available to find out the fault reason, we set the message of the exception-->
<!--as the faultreason/Reason. But when a fault is thrown from a service or some where, it will be -->
<!--wrapped by different levels. Due to this the initial exception message can be lost. If this flag-->
<!--is set, then Axis2 tries to get the first exception and set its message as the faultreason/Reason.-->
<parameter name="DrillDownToRootCauseForFaultReason">false</parameter>
<parameter name="userName">admin</parameter>
<parameter name="password">axis2</parameter>
<!--To override repository/services you need to uncomment following parameter and value SHOULD be absolute file path.-->
<!--ServicesDirectory only works on the following cases-->
<!---File based configurator and in that case the value should be a file URL (http:// not allowed)-->
<!---When creating URL Based configurator with URL "file://" -->
<!--- War based configurator with expanded case , -->
<!--All the other scenarios it will be ignored.-->
<!--<parameter name="ServicesDirectory">service</parameter>-->
<!--To override repository/modules you need to uncomment following parameter and value SHOULD be absolute file path-->
<!--<parameter name="ModulesDirectory">modules</parameter>-->
<!--Following params will set the proper context paths for invocations. All the endpoints will have a commons context-->
<!--root which can configured using the following contextRoot parameter-->
<!--<parameter name="contextRoot">axis2</parameter>-->
<!--Our HTTP endpoints can handle both REST and SOAP. Following parameters can be used to distinguiush those endpoints-->
<!--In case of a servlet, if you change this you have to manually change the settings of your servlet container to map this -->
<!--context path to proper Axis2 servlets-->
<parameter name="servicePath" locked="false">services</parameter>
<parameter name="restPath" locked="false">rest</parameter>
<!-- Following parameter will completely disable REST handling in Axis2-->
<parameter name="disableREST" locked="true">false</parameter>
<!--POJO deployer , this will alow users to drop .class file and make that into a service-->
<deployer extension=".class" directory="pojo" class="org.apache.axis2.deployment.POJODeployer"/>
<!-- Following parameter will set the host name for the epr-->
<!--<parameter name="hostname" locked="true">myhost.com</parameter>-->
<!-- If you have a frontend host which exposes this webservice using a different public URL -->
<!-- use this parameter to override autodetected url -->
<!--<parameter name="httpFrontendHostUrl">https://someotherhost/context</parameter>-->
<!-- The way of adding listener to the system-->
<!-- <listener class="org.apache.axis2.ObserverIMPL">-->
<!-- <parameter name="RSS_URL">http://127.0.0.1/rss</parameter>-->
<!-- </listener>-->
<!-- ================================================= -->
<!-- Message Receivers -->
<!-- ================================================= -->
<!--This is the deafult MessageReceiver for the system , if you want to have MessageReceivers for -->
<!--all the other MEP implement it and add the correct entry to here , so that you can refer from-->
<!--any operation -->
<!--Note : You can ovrride this for a particular service by adding the same element with your requirement-->
<messageReceivers>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"
class="org.apache.axis2.receivers.RawXMLINOnlyMessageReceiver"/>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
<messageReceiver mep="http://www.w3.org/2006/01/wsdl/in-only"
class="org.apache.axis2.receivers.RawXMLINOnlyMessageReceiver"/>
<messageReceiver mep="http://www.w3.org/2006/01/wsdl/in-out"
class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
</messageReceivers>
<!-- ================================================= -->
<!-- Message Formatter -->
<!-- ================================================= -->
<!--Following content type to message formatter mapping can be used to implement support for different message -->
<!--format serialization in Axis2. These message formats are expected to be resolved based on the content type. -->
<messageFormatters>
<messageFormatter contentType="application/x-www-form-urlencoded"
class="org.apache.axis2.transport.http.XFormURLEncodedFormatter"/>
<messageFormatter contentType="multipart/form-data"
class="org.apache.axis2.transport.http.MultipartFormDataFormatter"/>
<messageFormatter contentType="application/xml"
class="org.apache.axis2.transport.http.ApplicationXMLFormatter"/>
</messageFormatters>
<!-- ================================================= -->
<!-- Message Builders -->
<!-- ================================================= -->
<!--Following content type to builder mapping can be used to implement support for different message -->
<!--formats in Axis2. These message formats are expected to be resolved based on the content type. -->
<messageBuilders>
<messageBuilder contentType="application/xml"
class="org.apache.axis2.builder.ApplicationXMLBuilder"/>
<messageBuilder contentType="application/x-www-form-urlencoded"
class="org.apache.axis2.builder.XFormURLEncodedBuilder"/>
<messageBuilder contentType="multipart/form-data"
class="org.apache.axis2.builder.MultipartFormDataBuilder"/>
</messageBuilders>
<!-- ================================================= -->
<!-- Transport Ins -->
<!-- ================================================= -->
<transportReceiver name="http"
class="org.apache.axis2.transport.http.SimpleHTTPServer">
<parameter name="port">8200</parameter>
<!-- Here is the complete list of supported parameters (see example settings further below):
port: the port to listen on (default 6060)
hostname: if non-null, url prefix used in reply-to endpoint references (default null)
originServer: value of http Server header in outgoing messages (default "Simple-Server/1.1")
requestTimeout: value in millis of time that requests can wait for data (default 20000)
requestTcpNoDelay: true to maximize performance and minimize latency (default true)
false to minimize bandwidth consumption by combining segments
requestCoreThreadPoolSize: number of threads available for request processing (unless queue fills up) (default 25)
requestMaxThreadPoolSize: number of threads available for request processing if queue fills up (default 150)
note that default queue never fills up: see HttpFactory
threadKeepAliveTime: time to keep threads in excess of core size alive while inactive (default 180)
note that no such threads can exist with default unbounded request queue
threadKeepAliveTimeUnit: TimeUnit of value in threadKeepAliveTime (default SECONDS) (default SECONDS)
-->
<!-- <parameter name="hostname">http://www.myApp.com/ws</parameter> -->
<!-- <parameter name="originServer">My-Server/1.1</parameter> -->
<!-- <parameter name="requestTimeout">10000</parameter> -->
<!-- <parameter name="requestTcpNoDelay">false</parameter> -->
<!-- <parameter name="requestCoreThreadPoolSize">50</parameter> -->
<!-- <parameter name="RequestMaxThreadPoolSize">100</parameter> -->
<!-- <parameter name="threadKeepAliveTime">240000</parameter> -->
<!-- <parameter name="threadKeepAliveTimeUnit">MILLISECONDS</parameter> -->
</transportReceiver>
<!--Uncomment this and configure as appropriate for JMS transport support, after setting up your JMS environment (e.g. ActiveMQ)
<transportReceiver name="jms" class="org.apache.axis2.transport.jms.JMSListener">
<parameter name="myTopicConnectionFactory">
<parameter name="java.naming.factory.initial">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter>
<parameter name="java.naming.provider.url">tcp://localhost:61616</parameter>
<parameter name="transport.jms.ConnectionFactoryJNDIName">TopicConnectionFactory</parameter>
<parameter name="transport.jms.ConnectionFactoryType" locked="false">topic</parameter>
</parameter>
<parameter name="myQueueConnectionFactory">
<parameter name="java.naming.factory.initial">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter>
<parameter name="java.naming.provider.url">tcp://localhost:61616</parameter>
<parameter name="transport.jms.ConnectionFactoryJNDIName">QueueConnectionFactory</parameter>
<parameter name="transport.jms.ConnectionFactoryType" locked="false">queue</parameter>
</parameter>
<parameter name="default">
<parameter name="java.naming.factory.initial">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter>
<parameter name="java.naming.provider.url">tcp://localhost:61616</parameter>
<parameter name="transport.jms.ConnectionFactoryJNDIName">QueueConnectionFactory</parameter>
<parameter name="transport.jms.ConnectionFactoryType" locked="false">queue</parameter>
</parameter>
</transportReceiver>-->
<transportReceiver name="mailto" class="org.apache.axis2.transport.mail.MailTransportListener">
<!-- configure any optional POP3/IMAP properties
check com.sun.mail.pop3 and com.sun.mail.imap package documentation for more details-->
</transportReceiver>
<!--Uncomment if you want to have TCP transport support-->
<!--transportReceiver name="tcp"
class="org.apache.axis2.transport.tcp.TCPServer">
<parameter name="port">6060</parameter-->>
<!--If you want to give your own host address for EPR generation-->
<!--uncomment the following paramter , and set it as you required.-->
<!--<parameter name="hostname">tcp://myApp.com/ws</parameter>-->
<!-- /transportReceiver -->
<!-- ================================================= -->
<!-- Transport Outs -->
<!-- ================================================= -->
<!-- transportSender name="tcp"
class="org.apache.axis2.transport.tcp.TCPTransportSender"/>
<transportSender name="udp"
class="org.apache.axis2.transport.udp.UDPSender"/>
<transportSender name="local"
class="org.apache.axis2.transport.local.LocalTransportSender"/ -->
<transportSender name="http"
class="org.apache.axis2.transport.http.CommonsHTTPTransportSender">
<parameter name="PROTOCOL">HTTP/1.1</parameter>
<parameter name="Transfer-Encoding">chunked</parameter>
<!-- If following is set to 'true', optional action part of the Content-Type will not be added to the SOAP 1.2 messages -->
<!-- <parameter name="OmitSOAP12Action">true</parameter> -->
</transportSender>
<transportSender name="https"
class="org.apache.axis2.transport.http.CommonsHTTPTransportSender">
<parameter name="PROTOCOL">HTTP/1.1</parameter>
<parameter name="Transfer-Encoding">chunked</parameter>
</transportSender>
<transportSender name="jms"
class="org.apache.axis2.transport.jms.JMSSender"/>
<!-- configure the SMTP server information
check com.sun.mail.smtp package documentation for descriptions of properties-->
<transportSender name="mailto" class="org.apache.axis2.transport.mail.MailTransportSender">
<parameter name="mail.smtp.host">smtp.gmail.com</parameter>
<parameter name="mail.smtp.port">587</parameter>
<parameter name="mail.smtp.starttls.enable">true</parameter>
<parameter name="mail.smtp.auth">true</parameter>
<parameter name="mail.smtp.user">synapse.demo.0</parameter>
<parameter name="mail.smtp.password">mailpassword</parameter>
<parameter name="mail.smtp.from">synapse.demo.0@gmail.com</parameter>
</transportSender>
<!-- ================================================= -->
<!-- Global Modules -->
<!-- ================================================= -->
<!-- Comment this to disable Addressing -->
<module ref="addressing"/>
<!--Configuring module , providing parameters for modules whether they refer or not-->
<!--<moduleConfig name="addressing">-->
<!--<parameter name="addressingPara">N/A</parameter>-->
<!--</moduleConfig>-->
<!-- ================================================= -->
<!-- Clustering -->
<!-- ================================================= -->
<!-- Configure and uncomment following for preparing Axis2 to a clustered environment -->
<!--
<cluster class="org.apache.axis2.cluster.tribes.TribesClusterManager">
<parameter name="param1">value1</parameter>
<parameter name="domain">apache.axis2.domain</parameter>
<configurationManager class="org.apache.axis2.cluster.configuration.TribesConfigurationManager">
<listener class="org.apache.axis2.cluster.configuration.DefaultConfigurationManagerListener"/>
</configurationManager>
<contextManager class="org.apache.axis2.cluster.context.TribesContextManager">
<listener class="org.apache.axis2.cluster.context.DefaultContextManagerListener"/>
</contextManager>
</cluster>
-->
<!-- ================================================= -->
<!-- Phases -->
<!-- ================================================= -->
<phaseOrder type="InFlow">
<!-- System pre defined phases -->
<phase name="Transport">
<handler name="RequestURIBasedDispatcher"
class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher">
<order phase="Transport"/>
</handler>
<handler name="SOAPActionBasedDispatcher"
class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher">
<order phase="Transport"/>
</handler>
</phase>
<phase name="Addressing">
<handler name="AddressingBasedDispatcher"
class="org.apache.axis2.dispatchers.AddressingBasedDispatcher">
<order phase="Addressing"/>
</handler>
</phase>
<phase name="Security"/>
<phase name="PreDispatch"/>
<phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase">
<handler name="RequestURIBasedDispatcher"
class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"/>
<handler name="SOAPActionBasedDispatcher"
class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"/>
<handler name="RequestURIOperationDispatcher"
class="org.apache.axis2.dispatchers.RequestURIOperationDispatcher"/>
<handler name="SOAPMessageBodyBasedDispatcher"
class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher"/>
<handler name="HTTPLocationBasedDispatcher"
class="org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher"/>
</phase>
<phase name="RMPhase"/>
<!-- System predefined phases -->
<!-- After Postdispatch phase module author or service author can add any phase he want -->
<phase name="OperationInPhase"/>
<phase name="soapmonitorPhase"/>
</phaseOrder>
<phaseOrder type="OutFlow">
<!-- user can add his own phases to this area -->
<phase name="soapmonitorPhase"/>
<phase name="OperationOutPhase"/>
<!--system predefined phase-->
<!--these phase will run irrespective of the service-->
<phase name="RMPhase"/>
<phase name="PolicyDetermination"/>
<phase name="MessageOut"/>
<phase name="Security"/>
</phaseOrder>
<phaseOrder type="InFaultFlow">
<phase name="Addressing">
<handler name="AddressingBasedDispatcher"
class="org.apache.axis2.dispatchers.AddressingBasedDispatcher">
<order phase="Addressing"/>
</handler>
</phase>
<phase name="Security"/>
<phase name="PreDispatch"/>
<phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase">
<handler name="RequestURIBasedDispatcher"
class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"/>
<handler name="SOAPActionBasedDispatcher"
class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"/>
<handler name="RequestURIOperationDispatcher"
class="org.apache.axis2.dispatchers.RequestURIOperationDispatcher"/>
<handler name="SOAPMessageBodyBasedDispatcher"
class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher"/>
<handler name="HTTPLocationBasedDispatcher"
class="org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher"/>
</phase>
<phase name="RMPhase"/>
<!-- user can add his own phases to this area -->
<phase name="OperationInFaultPhase"/>
<phase name="soapmonitorPhase"/>
</phaseOrder>
<phaseOrder type="OutFaultFlow">
<!-- user can add his own phases to this area -->
<phase name="soapmonitorPhase"/>
<phase name="OperationOutFaultPhase"/>
<phase name="RMPhase"/>
<phase name="PolicyDetermination"/>
<phase name="MessageOut"/>
<phase name="Security"/>
</phaseOrder>
</axisconfig>
| {
"content_hash": "0c10901f615e4c852fe0d9064b551122",
"timestamp": "",
"source": "github",
"line_count": 362,
"max_line_length": 145,
"avg_line_length": 56.748618784530386,
"alnum_prop": 0.6213308669619821,
"repo_name": "ayyoob/carbon-apimgt",
"id": "6023150384db291c7218bfccd9f0c63dfaf6985b",
"size": "20543",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "dependencies/synapse/repository/conf/sample/resources/misc/client/axis2.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "72417"
},
{
"name": "Batchfile",
"bytes": "7251"
},
{
"name": "CSS",
"bytes": "1694146"
},
{
"name": "HTML",
"bytes": "342541"
},
{
"name": "Java",
"bytes": "3655118"
},
{
"name": "JavaScript",
"bytes": "14540423"
},
{
"name": "PLSQL",
"bytes": "88321"
},
{
"name": "PLpgSQL",
"bytes": "29272"
},
{
"name": "Shell",
"bytes": "19726"
},
{
"name": "Thrift",
"bytes": "1730"
},
{
"name": "XSLT",
"bytes": "94760"
}
],
"symlink_target": ""
} |
class Group::Update
def initialize(group, params)
@group, @params = group, params
end
def call
if group.update params
group
else
raise GroupsController::NotValidGroup, group.errors.as_json(full_messages: true)
end
end
private
attr_reader :group, :params
end
| {
"content_hash": "589806e397e490569faa0a5e1a53fa34",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 86,
"avg_line_length": 16.833333333333332,
"alnum_prop": 0.6732673267326733,
"repo_name": "lrosskamp/makealist-public",
"id": "ae1d00439fe63f11590220382f66981afda9e7ac",
"size": "303",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/services/group/update.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "673"
},
{
"name": "HTML",
"bytes": "61223"
},
{
"name": "JavaScript",
"bytes": "122729"
},
{
"name": "Ruby",
"bytes": "188742"
}
],
"symlink_target": ""
} |
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
const animationDuration = Ember.$.fn.accordion.settings.duration + 100;
moduleForComponent('flexberry-toggler', 'Integration | Component | flexberry toggler', {
integration: true
});
// Common expand/collapse test method.
let expandCollapseTogglerWithStateChecks = function(assert, captions) {
assert.expect(10);
let content = 'Toggler\'s content';
captions = captions || {};
let caption = captions.caption || '';
let expandedCaption = captions.expandedCaption || caption;
let collapsedCaption = captions.collapsedCaption || caption;
this.set('content', content);
this.set('caption', caption);
this.set('expandedCaption', expandedCaption);
this.set('collapsedCaption', collapsedCaption);
this.render(hbs`
{{#flexberry-toggler
caption=caption
expandedCaption=expandedCaption
collapsedCaption=collapsedCaption
}}
{{content}}
{{/flexberry-toggler}}`);
// Retrieve component, it's inner <input>.
let $component = this.$().children();
let $componentTitle = $component.children('div .title');
let $componentCaption = $componentTitle.children('span');
let $componentContent = $component.children('div .content');
// Check that component is collapsed by default.
assert.strictEqual($componentTitle.hasClass('active'), false);
assert.strictEqual($componentContent.hasClass('active'), false);
assert.strictEqual(Ember.$.trim($componentCaption.text()), collapsedCaption);
let expandAnimationCompleted = new Ember.RSVP.Promise((resolve, reject) => {
// Try to expand component.
// Semantic UI will start asynchronous animation after click, so we need Ember.run here.
Ember.run(() => {
$componentTitle.click();
});
// Check that component is animating now.
assert.strictEqual($componentContent.hasClass('animating'), true);
// Wait for expand animation to be completed & check component's state.
Ember.run(() => {
let animationCompleted = assert.async();
setTimeout(() => {
// Check that component is expanded now.
assert.strictEqual($componentTitle.hasClass('active'), true);
assert.strictEqual($componentContent.hasClass('active'), true);
assert.strictEqual(Ember.$.trim($componentCaption.text()), expandedCaption);
// Tell to test method that asynchronous operation completed.
animationCompleted();
// Resolve 'expandAnimationCompleted' promise.
resolve();
}, animationDuration);
});
});
// Wait for expand animation to be completed (when resolve will be called inside previous timeout).
// Then try to collapse component.
expandAnimationCompleted.then(() => {
// Semantic UI will start asynchronous animation after click, so we need Ember.run here.
Ember.run(() => {
$componentTitle.click();
});
// Wait for collapse animation to be completed & check component's state.
Ember.run(() => {
let animationCompleted = assert.async();
setTimeout(() => {
// Check that component is expanded now.
assert.strictEqual($componentTitle.hasClass('active'), false);
assert.strictEqual($componentContent.hasClass('active'), false);
assert.strictEqual(Ember.$.trim($componentCaption.text()), collapsedCaption);
animationCompleted();
}, animationDuration);
});
});
};
test('component renders properly', function(assert) {
assert.expect(22);
this.render(hbs`
{{#flexberry-toggler
class=class
}}
{{/flexberry-toggler}}`);
// Retrieve component, it's inner <input>.
let $component = this.$().children();
let $togglerTitle = $component.children('.title');
let $togglerIcon = $togglerTitle.children('i');
let $togglerCaption = $togglerTitle.children('span');
let $togglerContent = $component.children('.content');
// Check wrapper.
assert.strictEqual($component.prop('tagName'), 'DIV', 'Component\'s wrapper is a <div>');
assert.strictEqual($component.hasClass('flexberry-toggler'), true, 'Component\'s wrapper has \'flexberry-toggler\' css-class');
assert.strictEqual($component.hasClass('ui'), true, 'Component\'s wrapper has \'ui\' css-class');
assert.strictEqual($component.hasClass('accordion'), true, 'Component\'s wrapper has \'accordion\' css-class');
assert.strictEqual($component.hasClass('fluid'), true, 'Component\'s wrapper has \'fluid\' css-class');
// Check title's <div>.
assert.strictEqual($togglerTitle.length === 1, true, 'Component has inner title block');
assert.strictEqual($togglerTitle.prop('tagName'), 'DIV', 'Component\'s inner title block is a <div>');
assert.strictEqual($togglerTitle.hasClass('title'), true, 'Component\'s inner title block has \'title\' css-class');
// Check title's icon <i>.
assert.strictEqual($togglerIcon.length === 1, true, 'Component\'s title has icon block');
assert.strictEqual($togglerIcon.prop('tagName'), 'I', 'Component\'s icon block is a <i>');
assert.strictEqual($togglerIcon.hasClass('dropdown icon'), true, 'Component\'s icon block has \'dropdown icon\' css-class');
// Check title's caption <span>.
assert.strictEqual($togglerCaption.length === 1, true, 'Component has inner caption block');
assert.strictEqual($togglerCaption.prop('tagName'), 'SPAN', 'Component\'s caption block is a <span>');
assert.strictEqual($togglerCaption.hasClass('flexberry-toggler-caption'), true, 'Component\'s caption block has \'flexberry-toggler-caption\' css-class');
// Check content's <div>.
assert.strictEqual($togglerContent.length === 1, true, 'Component has inner content block');
assert.strictEqual($togglerContent.prop('tagName'), 'DIV', 'Component\'s content block is a <div>');
assert.strictEqual($togglerContent.hasClass('content'), true, 'Component\'s content block has \'content\' css-class');
assert.strictEqual($togglerContent.hasClass('flexberry-toggler-content'), true, 'Component\'s content block has \'flexberry-toggler-content\' css-class');
// Check component's additional CSS-classes.
let additioanlCssClasses = 'firstClass secondClass';
this.set('class', additioanlCssClasses);
Ember.A(additioanlCssClasses.split(' ')).forEach((cssClassName, index) => {
assert.strictEqual(
$component.hasClass(cssClassName),
true,
'Component\'s wrapper has additional css class \'' + cssClassName + '\'');
});
this.set('class', '');
Ember.A(additioanlCssClasses.split(' ')).forEach((cssClassName, index) => {
assert.strictEqual(
$component.hasClass(cssClassName),
false,
'Component\'s wrapper hasn\'t additional css class \'' + cssClassName + '\'');
});
});
test('component\'s icon can be customized', function(assert) {
assert.expect(2);
this.render(hbs`
{{#flexberry-toggler
iconClass=iconClass
}}
{{/flexberry-toggler}}`);
// Retrieve component, it's inner <input>.
let $component = this.$().children();
let $togglerTitle = $component.children('.title');
let $togglerIcon = $togglerTitle.children('i');
// Change default icon class.
let defaultIconClass = 'dropdown icon';
assert.strictEqual($togglerIcon.attr('class'), defaultIconClass, 'Component\'s icon is \'dropdown icon\' by default');
// Change icon class & check again.
let iconClass = 'marker icon';
this.set('iconClass', iconClass);
assert.strictEqual($togglerIcon.attr('class'), iconClass, 'Component\'s icon is \'dropdown icon\' by default');
});
test('component expands/collapses with defined \'expandedCaption\' & \'collapsedCaption\'', function(assert) {
expandCollapseTogglerWithStateChecks.call(this, assert, {
expandedCaption: 'Toggler\'s expanded caption',
collapsedCaption: 'Toggler\'s collapsed caption'
});
});
test('component expands/collapses with defined \'caption\' & \'collapsedCaption\'', function(assert) {
expandCollapseTogglerWithStateChecks.call(this, assert, {
caption: 'Toggler\'s caption',
collapsedCaption: 'Toggler\'s collapsed caption'
});
});
test('component expands/collapses with defined \'caption\' & \'expandedCaption\'', function(assert) {
expandCollapseTogglerWithStateChecks.call(this, assert, {
caption: 'Toggler\'s caption',
expandedCaption: 'Toggler\'s expanded caption'
});
});
test('component expands/collapses with only \'caption\' defined', function(assert) {
expandCollapseTogglerWithStateChecks.call(this, assert, {
caption: 'Toggler\'s caption'
});
});
test('component expands/collapses with only \'expandedCaption\' defined', function(assert) {
expandCollapseTogglerWithStateChecks.call(this, assert, {
expandedCaption: 'Toggler\'s expanded caption'
});
});
test('component expands/collapses with only \'collapsedCaption\' defined', function(assert) {
expandCollapseTogglerWithStateChecks.call(this, assert, {
collapsedCaption: 'Toggler\'s collapsed caption'
});
});
test('component expands/collapses without defined captions', function(assert) {
expandCollapseTogglerWithStateChecks.call(this, assert, {
});
});
test('changes in \'expanded\' property causes changing of component\'s expand/collapse state', function(assert) {
assert.expect(9);
let content = 'Toggler\'s content';
let collapsedCaption = 'Toggler\'s collapsed caption';
let expandedCaption = 'Toggler\'s expanded caption';
this.set('content', content);
this.set('collapsedCaption', collapsedCaption);
this.set('expandedCaption', expandedCaption);
this.render(hbs`
{{#flexberry-toggler
expanded=expanded
collapsedCaption=collapsedCaption
expandedCaption=expandedCaption
}}
{{content}}
{{/flexberry-toggler}}`);
// Retrieve component, it's inner <input>.
let $component = this.$().children();
let $togglerTitle = $component.children('.title');
let $togglerCaption = $togglerTitle.children('span');
let $togglerContent = $component.children('.content');
// Check that component is collapsed by default.
assert.strictEqual($togglerTitle.hasClass('active'), false);
assert.strictEqual($togglerContent.hasClass('active'), false);
assert.strictEqual(Ember.$.trim($togglerCaption.text()), collapsedCaption);
// Expand & check that component is expanded.
this.set('expanded', true);
assert.strictEqual($togglerTitle.hasClass('active'), true);
assert.strictEqual($togglerContent.hasClass('active'), true);
assert.strictEqual(Ember.$.trim($togglerCaption.text()), expandedCaption);
// Collapse & check that component is collapsed.
this.set('expanded', false);
assert.strictEqual($togglerTitle.hasClass('active'), false);
assert.strictEqual($togglerContent.hasClass('active'), false);
assert.strictEqual(Ember.$.trim($togglerCaption.text()), collapsedCaption);
});
test('disabled animation', function(assert) {
this.render(hbs`
{{#flexberry-toggler
caption="Click me!"
duration=0}}
Hello!
{{/flexberry-toggler}}`);
assert.notOk(this.$('.flexberry-toggler .content').hasClass('active'));
this.$('.flexberry-toggler .title').click();
assert.ok(this.$('.flexberry-toggler .content').hasClass('active'));
});
test('loong animation speed', function(assert) {
assert.expect(3);
let done = assert.async();
this.render(hbs`
{{#flexberry-toggler
caption="Click me!"
duration=750}}
Hello!
{{/flexberry-toggler}}`);
this.$('.flexberry-toggler .title').click();
assert.ok(this.$('.flexberry-toggler .content').hasClass('animating'));
Ember.run.later(() => {
assert.ok(this.$('.flexberry-toggler .content').hasClass('animating'));
}, 400);
Ember.run.later(() => {
assert.notOk(this.$('.flexberry-toggler .content').hasClass('animating'));
done();
}, 1000);
});
test('Components property hasShadow works properly', function(assert) {
this.set('hasShadow', true);
this.render(hbs`
{{#flexberry-toggler
caption="Click me!"
hasShadow=hasShadow
}}
Hello!
{{/flexberry-toggler}}`);
assert.ok(this.$('.flexberry-toggler').hasClass('has-shadow'));
this.set('hasShadow', false);
assert.notOk(this.$('.flexberry-toggler').hasClass('has-shadow'));
});
test('Components property hasBorder works properly', function(assert) {
this.set('hasBorder', true);
this.render(hbs`
{{#flexberry-toggler
caption="Click me!"
hasBorder=hasBorder
}}
Hello!
{{/flexberry-toggler}}`);
assert.ok(this.$('.flexberry-toggler').hasClass('has-border'));
this.set('hasBorder', false);
assert.notOk(this.$('.flexberry-toggler').hasClass('has-border'));
});
| {
"content_hash": "73bf002f797abef3709f36c5653cdfc8",
"timestamp": "",
"source": "github",
"line_count": 340,
"max_line_length": 156,
"avg_line_length": 37.226470588235294,
"alnum_prop": 0.6951884332780279,
"repo_name": "Flexberry/ember-flexberry",
"id": "c34b750f3340c10e971728b410a142d0ac552d64",
"size": "12657",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tests/integration/components/flexberry-toggler-test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1882"
},
{
"name": "Handlebars",
"bytes": "458142"
},
{
"name": "JavaScript",
"bytes": "2528680"
},
{
"name": "Less",
"bytes": "6426"
},
{
"name": "Shell",
"bytes": "7536"
},
{
"name": "TypeScript",
"bytes": "101585"
}
],
"symlink_target": ""
} |
import sys
import os
import time
speed = sys.argv[1]
t = sys.argv[2] #time
os.system('python driveM1.py -%s'% speed)
os.system('python driveM3.py %s'% speed)
time.sleep(float(t))
os.system('python driveM1.py 0')
os.system('python driveM3.py 0')
| {
"content_hash": "c44ebbe9ad34b7d8a3e71e8b2cc1e512",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 41,
"avg_line_length": 19.076923076923077,
"alnum_prop": 0.7016129032258065,
"repo_name": "cletusw/goal-e",
"id": "8fa8ac7c8dc3eb5bddaafb963b2077885413e46a",
"size": "248",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "misc/drive_straight.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1130"
},
{
"name": "C++",
"bytes": "62145"
},
{
"name": "Python",
"bytes": "69360"
}
],
"symlink_target": ""
} |
__author__ = 'q00222219@huawei'
import time
from heat.openstack.common import log as logging
import commonutils
import constant
import exception
LOG = logging.getLogger(__name__)
class CascadingConfiger(object):
def __init__(self, cascading_ip, user, password, cascaded_domain,
cascaded_api_ip, v2v_gw):
self.cascading_ip = cascading_ip
self.user = user
self.password = password
self.cascaded_domain = cascaded_domain
self.cascaded_ip = cascaded_api_ip
self.v2v_gw = v2v_gw
def do_config(self):
start_time = time.time()
LOG.info("start config cascading, cascading: %s" % self.cascading_ip)
# modify dns server address
address = "/%(cascaded_domain)s/%(cascaded_ip)s" \
% {"cascaded_domain": self.cascaded_domain,
"cascaded_ip": self.cascaded_ip}
for i in range(3):
try:
commonutils.execute_cmd_without_stdout(
host=self.cascading_ip,
user=self.user,
password=self.password,
cmd='cd %(dir)s; sh %(script)s add %(address)s'
% {"dir": constant.Cascading.REMOTE_SCRIPTS_DIR,
"script": constant.PublicConstant.
MODIFY_DNS_SERVER_ADDRESS,
"address": address})
break
except exception.SSHCommandFailure as e:
LOG.error("modify cascading dns address error, cascaded: "
"%s, error: %s"
% (self.cascaded_domain, e.format_message()))
time.sleep(1)
LOG.info(
"config cascading dns address success, cascading: %s"
% self.cascading_ip)
# config keystone
for i in range(3):
try:
commonutils.execute_cmd_without_stdout(
host=self.cascading_ip,
user=self.user,
password=self.password,
cmd='cd %(dir)s;'
'sh %(script)s %(cascaded_domain)s'
% {"dir": constant.RemoveConstant.REMOTE_SCRIPTS_DIR,
"script":
constant.RemoveConstant.REMOVE_KEYSTONE_SCRIPT,
"cascaded_domain": self.cascaded_domain})
commonutils.execute_cmd_without_stdout(
host=self.cascading_ip,
user=self.user,
password=self.password,
cmd='cd %(dir)s;'
'sh %(script)s %(cascaded_domain)s %(v2v_gw)s'
% {"dir": constant.Cascading.REMOTE_SCRIPTS_DIR,
"script":
constant.Cascading.KEYSTONE_ENDPOINT_SCRIPT,
"cascaded_domain": self.cascaded_domain,
"v2v_gw": self.v2v_gw})
break
except exception.SSHCommandFailure as e:
LOG.error(
"create keystone endpoint error, cascaded: %s, error: %s"
% (self.cascaded_domain, e.format_message()))
time.sleep(1)
LOG.info("config cascading keystone success, cascading: %s"
% self.cascading_ip)
for i in range(3):
try:
commonutils.execute_cmd_without_stdout(
host=self.cascading_ip,
user=self.user,
password=self.password,
cmd='cd %(dir)s; sh %(script)s %(cascaded_domain)s'
% {"dir": constant.Cascading.REMOTE_SCRIPTS_DIR,
"script":
constant.Cascading.ENABLE_OPENSTACK_SERVICE,
"cascaded_domain": self.cascaded_domain})
break
except exception.SSHCommandFailure as e:
LOG.error(
"enable openstack service error, cascaded: %s, error: %s"
% (self.cascaded_domain, e.format_message()))
time.sleep(1)
LOG.info("enable openstack service success, cascading: %s"
% self.cascading_ip)
cost_time = time.time() - start_time
LOG.info("config cascading success, cascading: %s, cost time: %d"
% (self.cascading_ip, cost_time))
| {
"content_hash": "a779d5549c329061da8ca25e953612bb",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 78,
"avg_line_length": 41.74311926605505,
"alnum_prop": 0.49164835164835163,
"repo_name": "Hybrid-Cloud/orchard",
"id": "88ee9f64656062720879c717b7f921eb8dc15ef2",
"size": "4573",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "code/cloudmanager/cascading_configer.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "1067396"
},
{
"name": "Shell",
"bytes": "49859"
}
],
"symlink_target": ""
} |
export declare class MdcGlidTile {
private element;
imgSrc: string;
imgClass: string;
supportIcon: string;
supportText: string;
actionIcon: string;
private log;
private elementGridTile;
private elementShowTitle;
private isImg;
private isClass;
private isTitle;
private isSupport;
private isSupportIcon;
private isSupportText;
private isActionIcon;
private isSecondary;
constructor(element: Element);
private bind();
private unbind();
private attached();
private onClick();
private onSecondaryAction();
private imgSrcChanged(newValue);
private imgClassChanged(newValue);
private showPrimary();
private supportIconChanged(newValue);
private supportTextChanged(newValue);
private actionIconChanged(newValue);
private showSecondary();
}
| {
"content_hash": "d2dc19b73c4e0b5d49d0eba1f1c4950b",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 41,
"avg_line_length": 26.65625,
"alnum_prop": 0.7069167643610785,
"repo_name": "Ullfis/aurelia-mdc-bridge",
"id": "01c787cdb95199e961fe66c8bd8da5704d3b586c",
"size": "853",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "dist/es2015/grid-list/grid-tile.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17937"
},
{
"name": "HTML",
"bytes": "207419"
},
{
"name": "TypeScript",
"bytes": "153768"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SteamKit2;
using SteamKit2.Internal;
using SteamChatBot.Triggers.TriggerOptions;
namespace SteamChatBot.Triggers
{
class UnlockChatTrigger : BaseTrigger
{
public UnlockChatTrigger(TriggerType type, string name, TriggerOptionsBase options) : base(type, name, options)
{ }
public override bool respondToChatMessage(SteamID roomID, SteamID chatterId, string message)
{
return Respond(roomID, message);
}
private bool Respond(SteamID roomID, string message)
{
string[] query = StripCommand(message, Options.ChatCommand.Command);
if (query != null)
{
var msg = new ClientMsg<MsgClientChatAction>();
msg.Body.SteamIdChat = SteamHelper.ToChatID(roomID);
msg.Body.SteamIdUserToActOn = SteamHelper.ToChatID(roomID);
msg.Body.ChatAction = EChatAction.UnlockChat;
Bot.steamClient.Send(msg);
return true;
}
return false;
}
}
}
| {
"content_hash": "04710f8288bf13ca6a3c9ba07d33a7b2",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 119,
"avg_line_length": 29.7,
"alnum_prop": 0.6313131313131313,
"repo_name": "dragonbanshee/SteamChatBot",
"id": "3a42cc68166d9cfbf295d87a1d57c405817a4142",
"size": "1190",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "SteamChatBot/Triggers/UnlockChatTrigger.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "134346"
}
],
"symlink_target": ""
} |
package de.jcup.egradle.eclipse.api;
import java.util.Map;
import org.eclipse.ui.IEditorInput;
/**
* The provider simply proves a map containing data for current variables.
*
* @author Albert Tregnaghi
*
*/
public interface VariableProvider {
/**
* Returns a map containing variable keys as key element, values as value. E.g.
* "rootProject.projectDir" is the key and
* "/usr/home/dev/projects/myGradleProject" is the value
*
* @param editorInput input so provider can determine for which file the
* parameters shall be supported.
*
* @return unmodifiable map or <code>null</code>
*/
Map<String, String> getVariables(IEditorInput editorInput);
}
| {
"content_hash": "c78d03a32329f80161612af2fe2cf3d2",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 83,
"avg_line_length": 26.142857142857142,
"alnum_prop": 0.6734972677595629,
"repo_name": "de-jcup/egradle",
"id": "15b3118b3cef3375ff3afc4f69539f76a886bd65",
"size": "1328",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "egradle-plugin-main/src/main/java-eclipse/de/jcup/egradle/eclipse/api/VariableProvider.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2674"
},
{
"name": "HTML",
"bytes": "71126"
},
{
"name": "Java",
"bytes": "3312182"
},
{
"name": "Shell",
"bytes": "21544"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<!-- meta information -->
<meta charset="utf-8">
<meta name="description" content="There’s a somewhat morbid charm to cute things being violent. No story or purpose behind this one, just thought it wo...">
<meta name="author" content="Jack Haydock">
<meta name="image" content="http://www.jackhaydock.co.uk/public/post-thumbnails/2017/RabbitThumb.png">
<meta name="og:image" content="http://www.jackhaydock.co.uk/public/post-thumbnails/2017/RabbitThumb.png">
<!---->
<!-- Twitter Meta -->
<meta name="twitter:title" content="Killer Rabbit">
<meta name="twitter:description" content="There’s a somewhat morbid charm to cute things being violent. No story or purpose behind this one, just thought it wo...">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://www.jackhaydock.co.uk/public/post-thumbnails/2017/RabbitThumb.png">
<meta name="twitter:domain" content="http://www.jackhaydock.co.uk/posts/2017/killerabbit">
<!---->
<!-- Enable responsiveness on mobile devices-->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<!-- title -->
<title>Killer Rabbit · Jack Haydock</title>
<!-- icons -->
<link rel="shortcut icon" href="/public/images/favicon.ico" />
<!-- stylesheets -->
<link rel="stylesheet" href="/public/css/responsive.gs.12col.css">
<link rel="stylesheet" href="/public/css/animate.min.css">
<link rel="stylesheet" href="/public/css/main.css">
<!-- Google fonts -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,400italic&subset=latin-ext">
<!-- feed links -->
<link rel="alternate" href="http://www.jackhaydock.co.uk/feed.xml" type="application/rss+xml" title="">
</head>
<body>
<div class="container azul">
<header class="top row gutters">
<div class="col span_2 center">
<!-- TODO: add baseurl to the logo link -->
<a href="/" id="logo" title="Jack Haydock"
style="background-image: url(/public/images/logo.png);">
</a>
</div><nav class="col span_10 top-navbar">
<a href="/" title="Home"
>Home</a>
<a href="/projects/" title="Projects"
>Projects</a>
<a href="/art/" title="Art"
>Art</a>
<a href="/blog/" title="Misc"
>Misc</a>
<a href="/about/" title="About"
>About</a>
</nav>
</header>
<article class="single row gutters">
<time class="published" datetime="2017-01-22">22 January 2017</time>
<h2>Killer Rabbit</h2>
<p>There’s a somewhat morbid charm to cute things being violent. No story or purpose behind this one, just thought it would be fun.</p>
<p><a href="/public/post-images/2017/Rabbit01-code.png">
<img src="/public/post-images/2017/Rabbit01-code.png" alt="Bloody Rabbit!" />
</a></p>
<p><a href="/public/post-images/2017/Rabbit02.png">
<img src="/public/post-images/2017/Rabbit02.png" alt="Bloody Rabbit!" />
</a></p>
<p><a href="/public/post-images/2017/Rabbit03.png">
<img src="/public/post-images/2017/Rabbit03.png" alt="Cute Rabbit" />
</a></p>
<h6 id="click-image-to-see-larger-version">Click image to see larger version</h6>
<p><a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/">Creative Commons Attribution-NonCommercial 4.0 International License</a>.</p>
<h5>Share this page</h5>
<a href=
'http://twitter.com/share?url=
http://www.jackhaydock.co.uk/posts/2017/killerabbit&text=Killer Rabbit'
target="_blank"
class='button'>
<img src="/public/images/twitter.png" alt="Twitter"
height=50px width=50px>
</a>
<a href=
"https://www.facebook.com/sharer/sharer.php?u=
http://www.jackhaydock.co.uk/posts/2017/killerabbit"
target="_blank">
<img src="/public/images/facebook.png" alt="Facebook"
height=50px width=50px>
</a>
<a href=
"https://plus.google.com/share?url=
http://www.jackhaydock.co.uk/posts/2017/killerabbit"
target="_blank">
<img src="/public/images/google.png" alt="Google+"
height=50px width=50px>
</a>
<h2> Comments </h2>
Don't be too mean...please?
<br>
You don't need to sign in to use the comments, simply click the 'Name' input and you will see an option 'I'd rather post as a guest'. You can use a phony email if it really bothers you.
<div id="disqus_thread"></div>
<script>
/**
* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//jackhaydock.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</article>
<footer>
<p>
Contact me:
<br>jwhaydock@jackhaydock.co.uk
<br>
<br>
This website is hosted on
<a href="https://github.com/jackhaydock/jackhaydock2.github.io" target="blank">GitHub</a>
and was originally created using
<a href="https://jekyllrb.com/" target="blank">Jekyll</a>
and the
<a href="http://jekyllthemes.org/themes/brume/" target="blank">brume</a>
theme
created by Aigars Dzerviniks, licensed under an
<a rel="license" href="https://github.com/aigarsdz/brume/blob/master/LICENSE.md" target="blank">MIT License</a>.
</p>
</footer>
</div>
<!-- scripts -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="/public/js/jquery.fitvids.js"></script>
<script>
$(document).ready(function(){
$("article").fitVids();
});
</script>
</body>
</html>
| {
"content_hash": "b3561be742c2631d40eee0f08bfbdfa8",
"timestamp": "",
"source": "github",
"line_count": 213,
"max_line_length": 381,
"avg_line_length": 29.802816901408452,
"alnum_prop": 0.6759609325771897,
"repo_name": "jackhaydock/jackhaydock.co.uk-Jekyll-Files",
"id": "139020419bab7d242b63874be5e712af33a943f6",
"size": "6354",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "posts/2017/killerabbit.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15178"
},
{
"name": "HTML",
"bytes": "1186289"
},
{
"name": "JavaScript",
"bytes": "5396"
},
{
"name": "Ruby",
"bytes": "968"
}
],
"symlink_target": ""
} |
package com.wlangiewicz
import java.io.File
import org.bitcoinj.core._
import org.bitcoinj.kits.WalletAppKit
import org.bitcoinj.params.{MainNetParams, TestNet3Params}
import org.bitcoinj.script.Script
/**
* The following example shows how to use the by bitcoinj provided WalletAppKit.
* The WalletAppKit class wraps the boilerplate (Peers, BlockChain, BlockStorage, Wallet) needed to set up a new SPV bitcoinj app.
*
* In this example we also define a WalletEventListener class with implementors that are called when the wallet changes (for example sending/receiving money)
*
* Usage example:
* sbt "run-main com.wlangiewicz.KitMainNet"
*/
object KitMainNet extends App {
override def main(args: Array[String]): Unit = {
// First we configure the network we want to use.
// The available options are:
// - MainNetParams
// - TestNet3Params
// - RegTestParams
// While developing your application you probably want to use the Regtest mode and run your local bitcoin network. Run bitcoind with the -regtest flag
// To test you app with a real network you can use the testnet. The testnet is an alternative bitcoin network that follows the same rules as main network. Coins are worth nothing and you can get coins for example from http://faucet.xeno-genesis.com/
//
// For more information have a look at: https://bitcoinj.github.io/testing and https://bitcoin.org/en/developer-examples#testing-applications
val params: NetworkParameters = MainNetParams.get
// Now we initialize a new WalletAppKit. The kit handles all the boilerplate for us and is the easiest way to get everything up and running.
// Have a look at the WalletAppKit documentation and its source to understand what's happening behind the scenes: https://github.com/bitcoinj/bitcoinj/blob/master/core/src/main/java/org/bitcoinj/kits/WalletAppKit.java
val kit: WalletAppKit = new WalletAppKit(params, new File("."), "walletappkit-example")
// In case you want to connect with your local bitcoind tell the kit to connect to localhost.
// You must do that in reg test mode.
//kit.connectToLocalHost();
//In main network mode you don't have to specify any hosts to connect to
// Now we start the kit and sync the blockchain.
// bitcoinj is working a lot with the Google Guava libraries. The WalletAppKit extends the AbstractIdleService. Have a look at the introduction to Guava services: https://code.google.com/p/guava-libraries/wiki/ServiceExplained
kit.startAsync
kit.awaitRunning
// To observe wallet events (like coins received) we implement a EventListener class that extends the AbstractWalletEventListener bitcoinj then calls the different functions from the EventListener class
val wListener: KitMainNet.WalletListener = new KitMainNet.WalletListener
kit.wallet.addEventListener(wListener)
// Ready to run. The kit syncs the blockchain and our wallet event listener gets notified when something happens.
// To test everything we create and print a fresh receiving address. Send some coins to that address and see if everything works.
Console.println("send money to: " + kit.wallet.freshReceiveAddress.toString)
// Make sure to properly shut down all the running services when you manually want to stop the kit. The WalletAppKit registers a runtime ShutdownHook so we actually do not need to worry about that when our application is stopping.
//System.out.println("shutting down again");
//kit.stopAsync();
//kit.awaitTerminated();
}
// The Wallet event listener its implementations get called on wallet changes.
private class WalletListener extends AbstractWalletEventListener {
override def onCoinsReceived(wallet: Wallet, tx: Transaction, prevBalance: Coin, newBalance: Coin) {
Console.println("-----> coins resceived: " + tx.getHashAsString)
Console.println("received: " + tx.getValue(wallet))
}
override def onTransactionConfidenceChanged(wallet: Wallet, tx: Transaction) {
Console.println("-----> confidence changed: " + tx.getHashAsString)
val confidence: TransactionConfidence = tx.getConfidence
Console.println("new block depth: " + confidence.getDepthInBlocks)
}
override def onCoinsSent(wallet: Wallet, tx: Transaction, prevBalance: Coin, newBalance: Coin) {
Console.println("coins sent")
}
override def onReorganize(wallet: Wallet) {
}
override def onWalletChanged(wallet: Wallet) {
}
def onKeysAdded(keys: List[ECKey]) {
Console.println("new key added")
}
def onScriptsAdded(wallet: Wallet, scripts: List[Script]) {
Console.println("new script added")
}
}
}
| {
"content_hash": "1d5c9a9280ee9e15e1f4598c03774af1",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 253,
"avg_line_length": 55.916666666666664,
"alnum_prop": 0.7455822865658931,
"repo_name": "wlk/bitcoinj-scala-examples",
"id": "f4b5c52e1542f79b6a2f16b47fb8e4347c6756bd",
"size": "4697",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/KitMainNet.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "40904"
}
],
"symlink_target": ""
} |
This module provides integration with [Phalcon framework](http://www.phalconphp.com/) (3.x).
Please try it and leave your feedback.
## Demo Project
<https://github.com/Codeception/phalcon-demo>
## Status
* Maintainer: **Serghei Iakovlev**
* Stability: **stable**
* Contact: serghei@phalconphp.com
## Config
The following configurations are required for this module:
* bootstrap: `string`, default `app/config/bootstrap.php` - relative path to app.php config file
* cleanup: `boolean`, default `true` - all database queries will be run in a transaction,
which will be rolled back at the end of each test
* savepoints: `boolean`, default `true` - use savepoints to emulate nested transactions
The application bootstrap file must return Application object but not call its handle() method.
## API
* di - `Phalcon\Di\Injectable` instance
* client - `BrowserKit` client
## Parts
By default all available methods are loaded, but you can specify parts to select only needed
actions and avoid conflicts.
* `orm` - include only `haveRecord/grabRecord/seeRecord/dontSeeRecord` actions.
* `services` - allows to use `grabServiceFromContainer` and `addServiceToContainer`.
Usage example:
Sample bootstrap (`app/config/bootstrap.php`):
``` php
<?php
$config = include __DIR__ . "/config.php";
include __DIR__ . "/loader.php";
$di = new \Phalcon\DI\FactoryDefault();
include __DIR__ . "/services.php";
return new \Phalcon\Mvc\Application($di);
?>
```
```yaml
class_name: AcceptanceTester
modules:
enabled:
- Phalcon:
part: services
bootstrap: 'app/config/bootstrap.php'
cleanup: true
savepoints: true
- WebDriver:
url: http://your-url.com
browser: phantomjs
```
## Actions
### _findElements
*hidden API method, expected to be used from Helper classes*
Locates element using available Codeception locator types:
* XPath
* CSS
* Strict Locator
Use it in Helpers or GroupObject or Extension classes:
```php
<?php
$els = $this->getModule('Phalcon')->_findElements('.items');
$els = $this->getModule('Phalcon')->_findElements(['name' => 'username']);
$editLinks = $this->getModule('Phalcon')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs
```
WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances
PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances
* `param` $locator
* `return` array of interactive elements
### _getResponseContent
*hidden API method, expected to be used from Helper classes*
Returns content of the last response
Use it in Helpers when you want to retrieve response of request performed by another module.
```php
<?php
// in Helper class
public function seeResponseContains($text)
{
$this->assertContains($text, $this->getModule('Phalcon')->_getResponseContent(), "response contains");
}
?>
```
* `return` string
@throws ModuleException
### _loadPage
*hidden API method, expected to be used from Helper classes*
Opens a page with arbitrary request parameters.
Useful for testing multi-step forms on a specific step.
```php
<?php
// in Helper class
public function openCheckoutFormStep2($orderId) {
$this->getModule('Phalcon')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]);
}
?>
```
* `param` $method
* `param` $uri
* `param array` $parameters
* `param array` $files
* `param array` $server
* `param null` $content
### _request
*hidden API method, expected to be used from Helper classes*
Send custom request to a backend using method, uri, parameters, etc.
Use it in Helpers to create special request actions, like accessing API
Returns a string with response body.
```php
<?php
// in Helper class
public function createUserByApi($name) {
$userData = $this->getModule('Phalcon')->_request('POST', '/api/v1/users', ['name' => $name]);
$user = json_decode($userData);
return $user->id;
}
?>
```
Does not load the response into the module so you can't interact with response page (click, fill forms).
To load arbitrary page for interaction, use `_loadPage` method.
* `param` $method
* `param` $uri
* `param array` $parameters
* `param array` $files
* `param array` $server
* `param null` $content
* `return` mixed|Crawler
@throws ExternalUrlException
@see `_loadPage`
### _savePageSource
*hidden API method, expected to be used from Helper classes*
Saves page source of to a file
```php
$this->getModule('Phalcon')->_savePageSource(codecept_output_dir().'page.html');
```
* `param` $filename
### addServiceToContainer
Registers a service in the services container and resolve it. This record will be erased after the test.
Recommended to use for unit testing.
``` php
<?php
$filter = $I->addServiceToContainer('filter', ['className' => '\Phalcon\Filter']);
$filter = $I->addServiceToContainer('answer', function () {
return rand(0, 1) ? 'Yes' : 'No';
}, true);
?>
```
* `param string` $name
* `param mixed` $definition
* `param boolean` $shared
* `return` mixed|null
* `[Part]` services
### amHttpAuthenticated
Authenticates user for HTTP_AUTH
* `param` $username
* `param` $password
### amOnPage
Opens the page for the given relative URI.
``` php
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
```
* `param` $page
### amOnRoute
Opens web page using route name and parameters.
``` php
<?php
$I->amOnRoute('posts.create');
?>
```
* `param string` $routeName
* `param array` $params
### attachFile
Attaches a file relative to the Codeception data directory to the given file upload field.
``` php
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
```
* `param` $field
* `param` $filename
### checkOption
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
``` php
<?php
$I->checkOption('#agree');
?>
```
* `param` $option
### click
Perform a click on a link or a button, given by a locator.
If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string.
For buttons, the "value" attribute, "name" attribute, and inner text are searched.
For links, the link text is searched.
For images, the "alt" attribute and inner text of any parent links are searched.
The second parameter is a context (CSS or XPath locator) to narrow the search.
Note that if the locator matches a button of type `submit`, the form will be submitted.
``` php
<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type=submit]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
```
* `param` $link
* `param` $context
### deleteHeader
Deletes the header with the passed name. Subsequent requests
will not have the deleted header in its request.
Example:
```php
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->amOnPage('some-other-page.php');
?>
```
* `param string` $name the name of the header to delete.
### dontSee
Checks that the current page doesn't contain the text specified (case insensitive).
Give a locator as the second parameter to match a specific region.
```php
<?php
$I->dontSee('Login'); // I can suppose user is already logged in
$I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1'); // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body,
so `$I->dontSee('strong')` will fail on strings like:
- `<p>I am Stronger than thou</p>`
- `<script>document.createElement('strong');</script>`
But will ignore strings like:
- `<strong>Home</strong>`
- `<div class="strong">Home</strong>`
- `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param` $text
* `param null` $selector
### dontSeeCheckboxIsChecked
Check that the specified checkbox is unchecked.
``` php
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
```
* `param` $checkbox
### dontSeeCookie
Checks that there isn't a cookie with the given name.
You can set additional cookie params like `domain`, `path` as array passed in last argument.
* `param` $cookie
* `param array` $params
### dontSeeCurrentUrlEquals
Checks that the current URL doesn't equal the given string.
Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
``` php
<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
```
* `param` $uri
### dontSeeCurrentUrlMatches
Checks that current url doesn't match the given regular expression.
``` php
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~$/users/(\d+)~');
?>
```
* `param` $uri
### dontSeeElement
Checks that the given element is invisible or not present on the page.
You can also specify expected attributes of this element.
``` php
<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
```
* `param` $selector
* `param array` $attributes
### dontSeeInCurrentUrl
Checks that the current URI doesn't contain the given string.
``` php
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
```
* `param` $uri
### dontSeeInField
Checks that an input field or textarea doesn't contain the given value.
For fuzzy locators, the field is matched by label text, CSS and XPath.
``` php
<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### dontSeeInFormFields
Checks if the array of form parameters (name => value) are not set on the form matched with
the passed selector.
``` php
<?php
$I->dontSeeInFormFields('form[name=myform]', [
'input1' => 'non-existent value',
'input2' => 'other non-existent value',
]);
?>
```
To check that an element hasn't been assigned any one of many values, an array can be passed
as the value:
``` php
<?php
$I->dontSeeInFormFields('.form-class', [
'fieldName' => [
'This value shouldn\'t be set',
'And this value shouldn\'t be set',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
``` php
<?php
$I->dontSeeInFormFields('#form-id', [
'checkbox1' => true, // fails if checked
'checkbox2' => false, // fails if unchecked
]);
?>
```
* `param` $formSelector
* `param` $params
### dontSeeInSource
Checks that the current page contains the given string in its
raw source code.
```php
<?php
$I->dontSeeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### dontSeeInTitle
Checks that the page title does not contain the given string.
* `param` $title
### dontSeeLink
Checks that the page doesn't contain a link with the given string.
If the second parameter is given, only links with a matching "href" attribute will be checked.
``` php
<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
```
* `param` $text
* `param null` $url
### dontSeeOptionIsSelected
Checks that the given option is not selected.
``` php
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### dontSeeRecord
Checks that record does not exist in database.
``` php
<?php
$I->dontSeeRecord('App\Models\Categories', ['name' => 'Testing']);
?>
```
* `param string` $model Model name
* `param array` $attributes Model attributes
* `[Part]` orm
### dontSeeResponseCodeIs
Checks that response code is equal to value provided.
```php
<?php
$I->dontSeeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param` $code
### fillField
Fills a text field or textarea with the given string.
``` php
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], 'jon@mail.com');
?>
```
* `param` $field
* `param` $value
### getApplication
Provides access the Phalcon application object.
@see \Codeception\Lib\Connector\Phalcon::getApplication
* `return` \Phalcon\Application|\Phalcon\Mvc\Micro
### grabAttributeFrom
Grabs the value of the given attribute value from the given element.
Fails if element is not found.
``` php
<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
```
* `param` $cssOrXpath
* `param` $attribute
### grabCookie
Grabs a cookie value.
You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first match.
If no parameters are provided, the full URI is returned.
``` php
<?php
$user_id = $I->grabFromCurrentUrl('~$/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
```
* `param null` $uri
### grabMultiple
Grabs either the text content, or attribute values, of nodes
matched by $cssOrXpath and returns them as an array.
```html
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
```
```php
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');
// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
```
* `param` $cssOrXpath
* `param` $attribute
* `return` string[]
### grabPageSource
Grabs current page source code.
@throws ModuleException if no page was opened.
* `return` string Current page source code.
### grabRecord
Retrieves record from database
``` php
<?php
$category = $I->grabRecord('App\Models\Categories', ['name' => 'Testing']);
?>
```
* `param string` $model Model name
* `param array` $attributes Model attributes
* `[Part]` orm
### grabServiceFromContainer
Resolves the service based on its configuration from Phalcon's DI container
Recommended to use for unit testing.
* `param string` $service Service name
* `param array` $parameters Parameters [Optional]
* `[Part]` services
### grabServiceFromDi
Alias for `grabServiceFromContainer`.
Note: Deprecated. Will be removed in Codeception 2.3.
* `param string` $service Service name
* `param array` $parameters Parameters [Optional]
* `[Part]` services
### grabTextFrom
Finds and returns the text contents of the given element.
If a fuzzy locator is used, the element is found using CSS, XPath,
and by matching the full page source by regular expression.
``` php
<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
```
* `param` $cssOrXPathOrRegex
### grabValueFrom
* `param` $field
* `return` array|mixed|null|string
### haveHttpHeader
Sets the HTTP header to the passed value - which is used on
subsequent HTTP requests through PhpBrowser.
Example:
```php
<?php
$I->setHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
?>
```
* `param string` $name the name of the request header
* `param string` $value the value to set it to for subsequent
requests
### haveInSession
Sets value to session. Use for authorization.
* `param string` $key
* `param mixed` $val
### haveRecord
Inserts record into the database.
``` php
<?php
$user_id = $I->haveRecord('App\Models\Users', ['name' => 'Phalcon']);
$I->haveRecord('App\Models\Categories', ['name' => 'Testing']');
?>
```
* `param string` $model Model name
* `param array` $attributes Model attributes
* `[Part]` orm
### haveServiceInDi
Alias for `addServiceToContainer`.
Note: Deprecated. Will be removed in Codeception 2.3.
* `param string` $name
* `param mixed` $definition
* `param boolean` $shared
* `return` mixed|null
* `[Part]` services
### moveBack
Moves back in history.
* `param int` $numberOfSteps (default value 1)
### resetCookie
Unsets cookie with the given name.
You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### see
Checks that the current page contains the given string (case insensitive).
You can specify a specific HTML element (via CSS or XPath) as the second
parameter to only search within that element.
``` php
<?php
$I->see('Logout'); // I can suppose user is logged in
$I->see('Sign Up', 'h1'); // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1'); // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body,
so `$I->see('strong')` will return true for strings like:
- `<p>I am Stronger than thou</p>`
- `<script>document.createElement('strong');</script>`
But will *not* be true for strings like:
- `<strong>Home</strong>`
- `<div class="strong">Home</strong>`
- `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param` $text
* `param null` $selector
### seeCheckboxIsChecked
Checks that the specified checkbox is checked.
``` php
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
```
* `param` $checkbox
### seeCookie
Checks that a cookie with the given name is set.
You can set additional cookie params like `domain`, `path` as array passed in last argument.
``` php
<?php
$I->seeCookie('PHPSESSID');
?>
```
* `param` $cookie
* `param array` $params
### seeCurrentRouteIs
Checks that current url matches route
``` php
<?php
$I->seeCurrentRouteIs('posts.index');
?>
```
* `param string` $routeName
### seeCurrentUrlEquals
Checks that the current URL is equal to the given string.
Unlike `seeInCurrentUrl`, this only matches the full URL.
``` php
<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
```
* `param` $uri
### seeCurrentUrlMatches
Checks that the current URL matches the given regular expression.
``` php
<?php
// to match root url
$I->seeCurrentUrlMatches('~$/users/(\d+)~');
?>
```
* `param` $uri
### seeElement
Checks that the given element exists on the page and is visible.
You can also specify expected attributes of this element.
``` php
<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);
// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
```
* `param` $selector
* `param array` $attributes
@return
### seeInCurrentUrl
Checks that current URI contains the given string.
``` php
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
```
* `param` $uri
### seeInField
Checks that the given input field or textarea contains the given value.
For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
``` php
<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### seeInFormFields
Checks if the array of form parameters (name => value) are set on the form matched with the
passed selector.
``` php
<?php
$I->seeInFormFields('form[name=myform]', [
'input1' => 'value',
'input2' => 'other value',
]);
?>
```
For multi-select elements, or to check values of multiple elements with the same name, an
array may be passed:
``` php
<?php
$I->seeInFormFields('.form-class', [
'multiselect' => [
'value1',
'value2',
],
'checkbox[]' => [
'a checked value',
'another checked value',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
``` php
<?php
$I->seeInFormFields('#form-id', [
'checkbox1' => true, // passes if checked
'checkbox2' => false, // passes if unchecked
]);
?>
```
Pair this with submitForm for quick testing magic.
``` php
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
* `param` $formSelector
* `param` $params
### seeInSession
Checks that session contains value.
If value is `null` checks that session has key.
``` php
<?php
$I->seeInSession('key');
$I->seeInSession('key', 'value');
?>
```
* `param string` $key
* `param mixed` $value
### seeInSource
Checks that the current page contains the given string in its
raw source code.
``` php
<?php
$I->seeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### seeInTitle
Checks that the page title contains the given string.
``` php
<?php
$I->seeInTitle('Blog - Post #1');
?>
```
* `param` $title
### seeLink
Checks that there's a link with the specified text.
Give a full URL as the second parameter to match links with that exact URL.
``` php
<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
```
* `param` $text
* `param null` $url
### seeNumberOfElements
Checks that there are a certain number of elements matched by the given locator on the page.
``` php
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); //between 0 and 10 elements
?>
```
* `param` $selector
* `param mixed` $expected :
- string: strict number
- array: range of numbers [0,10]
### seeOptionIsSelected
Checks that the given option is selected.
``` php
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### seePageNotFound
Asserts that current page has 404 response status code.
### seeRecord
Checks that record exists in database.
``` php
<?php
$I->seeRecord('App\Models\Categories', ['name' => 'Testing']);
?>
```
* `param string` $model Model name
* `param array` $attributes Model attributes
* `[Part]` orm
### seeResponseCodeIs
Checks that response code is equal to value provided.
```php
<?php
$I->seeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param` $code
### seeSessionHasValues
Assert that the session has a given list of values.
``` php
<?php
$I->seeSessionHasValues(['key1', 'key2']);
$I->seeSessionHasValues(['key1' => 'value1', 'key2' => 'value2']);
?>
```
* `param` array $bindings
* `return` void
### selectOption
Selects an option in a select tag or in radio button group.
``` php
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>
```
Provide an array for the second argument to select multiple options:
``` php
<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>
```
Or provide an associative array for the second argument to specifically define which selection method should be used:
``` php
<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
```
* `param` $select
* `param` $option
### sendAjaxGetRequest
If your page triggers an ajax request, you can perform it manually.
This action sends a GET ajax request with specified params.
See ->sendAjaxPostRequest for examples.
* `param` $uri
* `param` $params
### sendAjaxPostRequest
If your page triggers an ajax request, you can perform it manually.
This action sends a POST ajax request with specified params.
Additional params can be passed as array.
Example:
Imagine that by clicking checkbox you trigger ajax request which updates user settings.
We emulate that click by running this ajax request manually.
``` php
<?php
$I->sendAjaxPostRequest('/updateSettings', array('notifications' => true)); // POST
$I->sendAjaxGetRequest('/updateSettings', array('notifications' => true)); // GET
```
* `param` $uri
* `param` $params
### sendAjaxRequest
If your page triggers an ajax request, you can perform it manually.
This action sends an ajax request with specified method and params.
Example:
You need to perform an ajax request specifying the HTTP method.
``` php
<?php
$I->sendAjaxRequest('PUT', '/posts/7', array('title' => 'new title'));
```
* `param` $method
* `param` $uri
* `param` $params
### setCookie
Sets a cookie with the given name and value.
You can set additional cookie params like `domain`, `path`, `expires`, `secure` in array passed as last argument.
``` php
<?php
$I->setCookie('PHPSESSID', 'el4ukv0kqbvoirg7nkp4dncpk3');
?>
```
* `param` $name
* `param` $val
* `param array` $params
### submitForm
Submits the given form on the page, optionally with the given form
values. Pass the form field's values as an array in the second
parameter.
Although this function can be used as a short-hand version of
`fillField()`, `selectOption()`, `click()` etc. it has some important
differences:
* Only field *names* may be used, not CSS/XPath selectors nor field labels
* If a field is sent to this function that does *not* exist on the page,
it will silently be added to the HTTP request. This is helpful for testing
some types of forms, but be aware that you will *not* get an exception
like you would if you called `fillField()` or `selectOption()` with
a missing field.
Fields that are not provided will be filled by their values from the page,
or from any previous calls to `fillField()`, `selectOption()` etc.
You don't need to click the 'Submit' button afterwards.
This command itself triggers the request to form's action.
You can optionally specify which button's value to include
in the request with the last parameter (as an alternative to
explicitly setting its value in the second parameter), as
button values are not otherwise included in the request.
Examples:
``` php
<?php
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
]);
// or
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
], 'submitButtonName');
```
For example, given this sample "Sign Up" form:
``` html
<form action="/sign_up">
Login:
<input type="text" name="user[login]" /><br/>
Password:
<input type="password" name="user[password]" /><br/>
Do you agree to our terms?
<input type="checkbox" name="user[agree]" /><br/>
Select pricing plan:
<select name="plan">
<option value="1">Free</option>
<option value="2" selected="selected">Paid</option>
</select>
<input type="submit" name="submitButton" value="Submit" />
</form>
```
You could write the following to submit it:
``` php
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
],
'submitButton'
);
```
Note that "2" will be the submitted value for the "plan" field, as it is
the selected option.
You can also emulate a JavaScript submission by not specifying any
buttons in the third parameter to submitForm.
```php
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
]
);
```
This function works well when paired with `seeInFormFields()`
for quickly testing CRUD interfaces and form validation logic.
``` php
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('#my-form', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('#my-form', $form);
```
Parameter values can be set to arrays for multiple input fields
of the same name, or multi-select combo boxes. For checkboxes,
you can use either the string value or boolean `true`/`false` which will
be replaced by the checkbox's value in the DOM.
``` php
<?php
$I->submitForm('#my-form', [
'field1' => 'value',
'checkbox' => [
'value of first checkbox',
'value of second checkbox',
],
'otherCheckboxes' => [
true,
false,
false
],
'multiselect' => [
'first option value',
'second option value'
]
]);
```
Mixing string and boolean values for a checkbox's value is not supported
and may produce unexpected results.
Field names ending in `[]` must be passed without the trailing square
bracket characters, and must contain an array for its value. This allows
submitting multiple values with the same name, consider:
```php
<?php
// This will NOT work correctly
$I->submitForm('#my-form', [
'field[]' => 'value',
'field[]' => 'another value', // 'field[]' is already a defined key
]);
```
The solution is to pass an array value:
```php
<?php
// This way both values are submitted
$I->submitForm('#my-form', [
'field' => [
'value',
'another value',
]
]);
```
* `param` $selector
* `param` $params
* `param` $button
### switchToIframe
Switch to iframe or frame on the page.
Example:
``` html
<iframe name="another_frame" src="http://example.com">
```
``` php
<?php
# switch to iframe
$I->switchToIframe("another_frame");
```
* `param string` $name
### uncheckOption
Unticks a checkbox.
``` php
<?php
$I->uncheckOption('#notify');
?>
```
* `param` $option
<p> </p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.2/src/Codeception/Module/Phalcon.php">Help us to improve documentation. Edit module reference</a></div>
| {
"content_hash": "592f687e08abada484edce122d305137",
"timestamp": "",
"source": "github",
"line_count": 1488,
"max_line_length": 256,
"avg_line_length": 21.061827956989248,
"alnum_prop": 0.6669112954690491,
"repo_name": "PieterVanPittens/savvago",
"id": "a647b2f2cfc6bb776ac0aaa1ab7f39cb0b9a9104",
"size": "31352",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vendor/codeception/codeception/docs/modules/Phalcon.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "378"
},
{
"name": "CSS",
"bytes": "3812"
},
{
"name": "HTML",
"bytes": "98062"
},
{
"name": "JavaScript",
"bytes": "11298"
},
{
"name": "PHP",
"bytes": "490454"
}
],
"symlink_target": ""
} |
import { FlowRouter } from 'meteor/kadira:flow-router';
import { BlazeLayout } from 'meteor/kadira:blaze-layout';
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
//import templates
import '/imports/ui/layouts/default.js';
import '/imports/ui/components/login.js';
import '/imports/ui/components/signup.js';
import '/imports/ui/components/forgotPassword.js';
import '/imports/ui/components/resetPassword.js';
import '/imports/ui/components/dashboard.js';
/**
* Setting up password reset trigger here, because the route should automatically go to the form if a token
* was detected
*/
Session.setDefault('_resetPasswordToken', Accounts._resetPasswordToken);
Session.setDefault('_enrollAccountToken', Accounts._enrollAccountToken);
const publicRoutes = FlowRouter.group({});
publicRoutes.route('/', {
name: 'home',
triggersEnter: [function(context, redirect) {
// the default template handles redirects if a user is not found
redirect('/dashboard');
}]
});
publicRoutes.route('/signIn', {
name: 'signIn',
action() {
BlazeLayout.render("default", { authTemplate: null, pubTemplate: "loginForm" });
}
});
publicRoutes.route('/forgot-password', {
name: 'forgetPassword',
action() {
BlazeLayout.render("default", { authTemplate: null, pubTemplate: "forgetPasswordForm" });
}
});
publicRoutes.route('/reset-password/:token', {
name: 'resetPassword',
action() {
BlazeLayout.render("default", { authTemplate: null, pubTemplate: "resetpasswordForm" });
}
});
publicRoutes.route('/signup', {
name: 'register',
action() {
BlazeLayout.render("default", { authTemplate: null, pubTemplate: "signupForm" });
}
});
FlowRouter.route('/dashboard', {
name: 'dashboardHome',
action() {
BlazeLayout.render("default", { authTemplate: "welcome", pubTemplate: null });
}
});
FlowRouter.notFound = {
action() {
BlazeLayout.render("centeredLayout", { main: "t404" });
}
}
| {
"content_hash": "8120fc92f5f07622454b878a674b4b5c",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 107,
"avg_line_length": 28.25,
"alnum_prop": 0.6740412979351033,
"repo_name": "jasonnathan/user-accounts",
"id": "94061033e7d0c64e5dcdf69c0526589a929ad344",
"size": "2034",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "imports/startup/client/routes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1581"
},
{
"name": "HTML",
"bytes": "21318"
},
{
"name": "JavaScript",
"bytes": "27302"
}
],
"symlink_target": ""
} |
/**
* *************
*
* <p>This code can be embedded in arbitrary third-party projects! For maximum compatibility, use
* only Java 6 constructs.
*
* <p>*************
*/
package com.facebook.buck.jvm.java;
import com.facebook.buck.util.liteinfersupport.Nullable;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileAttribute;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class FatJarMain {
private FatJarMain() {}
/**
* Update the library search path environment variable with the given native library directory.
*/
private static void updateEnvironment(Map<String, String> env, Path libDir) {
String librarySearchPathName = getLibrarySearchPathName();
String originalLibPath = getEnvValue(librarySearchPathName);
String newlibPath =
libDir + (originalLibPath == null ? "" : File.pathSeparator + originalLibPath);
env.put(librarySearchPathName, newlibPath);
}
private static List<String> getJVMArguments() {
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
try {
return runtimeMxBean.getInputArguments();
} catch (java.lang.SecurityException e) {
// Do not have the ManagementPermission("monitor") permission
return new ArrayList<String>();
}
}
/** @return a command to start a new JVM process to execute the given main class. */
private static List<String> getCommand(Path jar, String[] args) {
List<String> cmd = new ArrayList<String>();
// Look for the Java binary given in an alternate location if given,
// otherwise use the Java binary that started us
String javaHome = System.getProperty("buck.fatjar.java.home", System.getProperty("java.home"));
cmd.add(Paths.get(javaHome).resolve("bin").resolve("java").toString());
// Pass through any VM arguments to the child process
cmd.addAll(getJVMArguments());
cmd.add("-jar");
// Lookup our current JAR context.
cmd.add(jar.toString());
Collections.addAll(cmd, args);
return cmd;
}
@SuppressWarnings("PMD.BlacklistedDefaultProcessMethod")
public static void main(String[] args) throws Exception {
Class<?> clazz = FatJarMain.class;
ClassLoader classLoader = clazz.getClassLoader();
// Load the fat jar info from it's resource.
FatJar fatJar = FatJar.load(classLoader);
ManagedTemporaryDirectory temp = new ManagedTemporaryDirectory("fatjar.");
// Create a temp dir to house the native libraries.
try {
// Unpack the real, inner JAR.
Path jar = temp.getPath().resolve("main.jar");
fatJar.unpackJarTo(classLoader, jar);
// Unpack all the native libraries, since the system loader will need to find these
// on disk.
Path nativeLibs = temp.getPath().resolve("nativelibs");
Files.createDirectory(nativeLibs);
fatJar.unpackNativeLibrariesInto(classLoader, temp.getPath());
// Update the appropriate environment variable with the location of our native libraries
// and start the real main class in a new process so that it picks it up.
ProcessBuilder builder = new ProcessBuilder();
builder.command(getCommand(jar, args));
updateEnvironment(builder.environment(), temp.getPath());
builder.inheritIO();
// Wait for the inner process to finish, and propagate it's exit code, before cleaning
// up the native libraries.
System.exit(builder.start().waitFor());
} finally {
temp.close();
}
}
/**
* @return the platform specific environment variable for setting the native library search path.
*/
private static String getLibrarySearchPathName() {
String platform = getOsPlatform();
if (platform.startsWith("Linux")) {
return "LD_LIBRARY_PATH";
} else if (platform.startsWith("Mac OS")) {
return "DYLD_LIBRARY_PATH";
} else if (isWindowsOs(platform)) {
return "PATH";
} else {
System.err.println(
"WARNING: using \"LD_LIBRARY_PATH\" for unrecognized platform " + platform);
return "LD_LIBRARY_PATH";
}
}
@Nullable
// Avoid using EnvVariablesProvider to avoid extra dependencies.
@SuppressWarnings("PMD.BlacklistedSystemGetenv")
private static String getEnvValue(String envVariableName) {
if (isWindowsOs(getOsPlatform())) {
return findMapValueIgnoreKeyCase(envVariableName, System.getenv());
} else {
return System.getenv(envVariableName);
}
}
@Nullable
private static String findMapValueIgnoreKeyCase(String key, Map<String, String> map) {
for (Map.Entry<String, String> entry : map.entrySet()) {
if (entry.getKey().equalsIgnoreCase(key)) {
return entry.getValue();
}
}
return null;
}
private static String getOsPlatform() {
return Objects.requireNonNull(System.getProperty("os.name"));
}
private static boolean isWindowsOs(String osPlatform) {
return osPlatform.startsWith("Windows");
}
/**
* A temporary directory that automatically cleans itself up when used via a try-resource block.
*/
private static class ManagedTemporaryDirectory implements AutoCloseable {
private final Path path;
private ManagedTemporaryDirectory(Path path) {
this.path = path;
}
public ManagedTemporaryDirectory(String prefix, FileAttribute<?>... attrs) throws IOException {
this(Files.createTempDirectory(prefix, attrs));
}
@Override
public void close() throws IOException {
Files.walkFileTree(
path,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
if (e != null) {
throw e;
}
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
public Path getPath() {
return path;
}
}
}
| {
"content_hash": "879fc07d8373666f5f6a037c89417104",
"timestamp": "",
"source": "github",
"line_count": 201,
"max_line_length": 99,
"avg_line_length": 32.62686567164179,
"alnum_prop": 0.680390362915523,
"repo_name": "facebook/buck",
"id": "9ba31af497db2b5a7454ebb677d1dadabf12c3d2",
"size": "7174",
"binary": false,
"copies": "5",
"ref": "refs/heads/main",
"path": "src/com/facebook/buck/jvm/java/FatJarMain.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1796"
},
{
"name": "C",
"bytes": "250514"
},
{
"name": "CSS",
"bytes": "56119"
},
{
"name": "Dockerfile",
"bytes": "2559"
},
{
"name": "HTML",
"bytes": "501"
},
{
"name": "Java",
"bytes": "33678299"
},
{
"name": "JavaScript",
"bytes": "931240"
},
{
"name": "Kotlin",
"bytes": "25953"
},
{
"name": "Lex",
"bytes": "14469"
},
{
"name": "Makefile",
"bytes": "1704"
},
{
"name": "PowerShell",
"bytes": "2154"
},
{
"name": "Python",
"bytes": "766764"
},
{
"name": "Shell",
"bytes": "39846"
},
{
"name": "Smalltalk",
"bytes": "5432"
},
{
"name": "Starlark",
"bytes": "1409831"
},
{
"name": "Thrift",
"bytes": "18470"
}
],
"symlink_target": ""
} |
define([
'underscore',
'backbone',
'geometrygraphsingleton',
],
function(_, Backbone, geometryGraph) {
var Manager = function() {
_.extend(this, Backbone.Events);
var selected = [];
this.canSelect = false;
this.selectOnly = function(id) {
if (!this.canSelect || geometryGraph.isEditing()) {
return;
}
var deselected = [];
var found = false;
for (var i in selected) {
if (selected[i] === id) {
found = true;
} else {
deselected.push(selected[i]);
}
}
if (found) {
return;
}
selected = [id];
if (deselected.length > 0) {
this.trigger('deselected', deselected, selected);
}
this.trigger('selected', [id], selected);
};
this.addToSelection = function(id) {
if (!this.canSelect || geometryGraph.isEditing()) {
return;
}
var alreadySelected = false;
for (var i in selected) {
if (selected[i] === id) {
alreadySelected = true;
}
}
if (alreadySelected) {
var index = selected.indexOf(id);
if (index !== -1) {
selected.splice(selected.indexOf(id), 1);
this.trigger('deselected', [id], selected);
}
} else {
selected.push(id);
this.trigger('selected', [id], selected);
}
};
this.deselectAll = function() {
if (selected.length > 0) {
var deselected = selected;
selected = [];
this.trigger('deselected', deselected, selected);
}
};
this.isSelected = function(id) {
return selected.indexOf(id) !== -1;
};
this.getSelected = function() {
return selected.slice(0);
};
};
return new Manager();
}); | {
"content_hash": "4f7e3be7432a31cf5ecc5e15f8a9c01a",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 59,
"avg_line_length": 23.214285714285715,
"alnum_prop": 0.47846153846153844,
"repo_name": "vtange/shapesmith.next",
"id": "09d781e7af24db525c55464eaf8a6e4878179015",
"size": "1950",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/selection.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "140547"
},
{
"name": "JavaScript",
"bytes": "1842819"
},
{
"name": "PHP",
"bytes": "28"
},
{
"name": "Shell",
"bytes": "104"
}
],
"symlink_target": ""
} |
#include <aws/connect/model/UpdateInstanceAttributeRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Connect::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
UpdateInstanceAttributeRequest::UpdateInstanceAttributeRequest() :
m_instanceIdHasBeenSet(false),
m_attributeType(InstanceAttributeType::NOT_SET),
m_attributeTypeHasBeenSet(false),
m_valueHasBeenSet(false)
{
}
Aws::String UpdateInstanceAttributeRequest::SerializePayload() const
{
JsonValue payload;
if(m_valueHasBeenSet)
{
payload.WithString("Value", m_value);
}
return payload.View().WriteReadable();
}
| {
"content_hash": "1976a2fb020b5c54040afcef9d30212e",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 68,
"avg_line_length": 19.34285714285714,
"alnum_prop": 0.7548005908419497,
"repo_name": "aws/aws-sdk-cpp",
"id": "edda8f308f1510c8fcb5d8dc78057614569da231",
"size": "796",
"binary": false,
"copies": "4",
"ref": "refs/heads/main",
"path": "aws-cpp-sdk-connect/source/model/UpdateInstanceAttributeRequest.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "309797"
},
{
"name": "C++",
"bytes": "476866144"
},
{
"name": "CMake",
"bytes": "1245180"
},
{
"name": "Dockerfile",
"bytes": "11688"
},
{
"name": "HTML",
"bytes": "8056"
},
{
"name": "Java",
"bytes": "413602"
},
{
"name": "Python",
"bytes": "79245"
},
{
"name": "Shell",
"bytes": "9246"
}
],
"symlink_target": ""
} |
// ADC.h
// Runs on LM4F120/TM4C123
// Basic ADC driver. Includes support for selecting ADC0-11
// Michael Bartling
// January 2015
#ifndef __ADC_H__
#define __ADC_H__
/**
* @brief Set up ADC on specified channel number
* @details The parameters are default as follows
* Timer0A: enabled
* Mode: 32-bit, down counting
* One-shot or periodic: periodic
* Interval value: programmable using 32-bit period
* Sample time is busPeriod*period
* sample rate: <=125,000 samples/second
*
* @param channelNum the desired ADC channel
* @return 1 if successful, -1 for device driver error
* likely indicating driver already configured.
*/
int ADC_Open(unsigned int channelNum);
/**
* @brief ADC_In gets one sample from the current ADC driver
* @details Retrieve a 10 bit scaled value from the ADC driver
* Must run ADC_Open before calling ADC_In, else returns error codes
* @return 10 bit scaled sample from configured ADC. Error Codes are
* indicated by masking with 0xFC00. 0xFC00 denotes device not initialized.
* Other error codes are reserved.
*/
unsigned short ADC_In(void);
/**
* @brief Collect a sequence of ADC values
*
* @param channelNum Channel to configure
* @param fs Sample Frequency (Hz) between 100 and 10kHz
* @param buffer Array to buffer data, does not bounds check buffer
* @param numberOfSamples number of samples to record
* must be even (multiple of two)
* @return 1 if initialization successful
*/
int ADC_Collect(unsigned int channelNum, unsigned int fs,
unsigned short buffer[], unsigned int numberOfSamples);
/**
* @brief returns 0 when ADC_collect finishes
* @return 0 if ADC_collect is complete, , else returns the remaining
* number of samples to record
*/
int ADC_Status(void);
#endif /*__ADC_H__*/ | {
"content_hash": "1a5880c82a3f79bef9d0810a5a16bfc5",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 75,
"avg_line_length": 31,
"alnum_prop": 0.7294850028296548,
"repo_name": "mbartling/RTOS_Lab2",
"id": "1d37ab962a614bcfea9fa7cf1dde2d773fcbfa6a",
"size": "1767",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ADC.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "83688"
},
{
"name": "C",
"bytes": "174852"
},
{
"name": "C++",
"bytes": "1583"
}
],
"symlink_target": ""
} |
"""Adds config flow for Mill integration."""
import logging
from mill import Mill
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import DOMAIN # pylint:disable=unused-import
_LOGGER = logging.getLogger(__name__)
DATA_SCHEMA = vol.Schema(
{vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str}
)
class MillConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Mill integration."""
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
if user_input is None:
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors={},
)
username = user_input[CONF_USERNAME].replace(" ", "")
password = user_input[CONF_PASSWORD].replace(" ", "")
mill_data_connection = Mill(
username, password, websession=async_get_clientsession(self.hass),
)
errors = {}
if not await mill_data_connection.connect():
errors["connection_error"] = "connection_error"
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors,
)
unique_id = username
await self.async_set_unique_id(unique_id)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=unique_id, data={CONF_USERNAME: username, CONF_PASSWORD: password},
)
| {
"content_hash": "d659e7ae8c3362c7f5ad87dfa873374a",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 85,
"avg_line_length": 31.01818181818182,
"alnum_prop": 0.64947245017585,
"repo_name": "titilambert/home-assistant",
"id": "08eb0f5c5361367af8208be3873eff560634019c",
"size": "1706",
"binary": false,
"copies": "5",
"ref": "refs/heads/dev",
"path": "homeassistant/components/mill/config_flow.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1488"
},
{
"name": "Python",
"bytes": "25849092"
},
{
"name": "Shell",
"bytes": "4410"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>StackSmashingDetected</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="icon" type="image/png" href="http://static1.knicket.com/play_19yd_x96_icon_data-capture-for-dhis-2.jpg" />
</head>
<body>
<!--[if lt IE 10]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<div class="canvas" id="root"></div>
</body>
</html>
| {
"content_hash": "abc44c9bccc92aadfa8699b8e636b4e6",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 178,
"avg_line_length": 36.294117647058826,
"alnum_prop": 0.6418152350081038,
"repo_name": "Eskalol/StackSmashingDetected",
"id": "bebbe8ed5ece454b14af7393134d29c28217b2dd",
"size": "617",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9204"
},
{
"name": "HTML",
"bytes": "617"
},
{
"name": "JavaScript",
"bytes": "114056"
}
],
"symlink_target": ""
} |
#include "program_registry.h"
#include "private_universe.h"
#include <cstring>
ProgramRegistry::ProgramRegistry() :
program_threads_(std::thread::hardware_concurrency()) {
id_ = 0;
}
qbId ProgramRegistry::CreateProgram(const char* program) {
qbId id = id_++;
qbProgram* p = AllocProgram(id, program);
programs_[id] = p;
if (id > 0) {
program_threads_[id] = new Task(p);
} else {
main_program_ = p;
}
return id;
}
qbResult ProgramRegistry::DetatchProgram(qbId program, const std::function<GameState*()>& game_state_fn) {
if (programs_.has(program)) {
qbProgram* to_detach = GetProgram(program);
std::unique_ptr<ProgramThread> program_thread(
new ProgramThread(to_detach));
program_thread->Run(game_state_fn);
detached_[program] = std::move(program_thread);
programs_.erase(program);
program_threads_.erase(program);
}
return QB_OK;
}
qbResult ProgramRegistry::JoinProgram(qbId program) {
qbProgram* prog = programs_[program] = detached_.find(program)->second->Release();
program_threads_[program] = new Task(prog);
detached_.erase(detached_.find(program));
return QB_OK;
}
qbProgram* ProgramRegistry::GetProgram(qbId id) {
if (!programs_.has(id)) {
return nullptr;
}
return programs_[id];
}
void ProgramRegistry::Run(GameState* state) {
for (auto& task : program_threads_) {
task.second->Ready();
}
for (auto& task : program_threads_) {
task.second->Run(state);
}
RunProgram(main_program_->id, state);
for (auto& task : program_threads_) {
task.second->Wait();
}
for (auto& task : program_threads_) {
task.second->Done();
}
}
qbResult ProgramRegistry::RunProgram(qbId program, GameState* state) {
ProgramImpl* p = (ProgramImpl*)programs_[program]->self;
p->Run(state);
return QB_OK;
}
qbProgram* ProgramRegistry::AllocProgram(qbId id, const char* name) {
qbProgram* p = (qbProgram*)calloc(1, sizeof(qbProgram));
*(qbId*)(&p->id) = id;
*(char**)(&p->name) = STRDUP(name);
p->self = new ProgramImpl(p);
return p;
}
| {
"content_hash": "17e3739bdbe5da71600fb868fba68cfd",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 106,
"avg_line_length": 23.724137931034484,
"alnum_prop": 0.6598837209302325,
"repo_name": "rohdesamuel/cubez",
"id": "41eb5476c16ef639ca0244de9b7386e8ec7de7bb",
"size": "2691",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/program_registry.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "622021"
},
{
"name": "C++",
"bytes": "904283"
},
{
"name": "GLSL",
"bytes": "41624"
},
{
"name": "HTML",
"bytes": "4742"
},
{
"name": "Makefile",
"bytes": "3075"
},
{
"name": "Objective-C",
"bytes": "416932"
},
{
"name": "Python",
"bytes": "18556"
}
],
"symlink_target": ""
} |
/**
* Module dependencies.
*/
var t = require('t');
var template = require('./template');
var View = require('view');
function LawProposal(law, idx) {
var colors = ["#7a1533", "#cf423b", "#fc7d4a"];
this.color = colors[idx % 3];
law.color = this.color;
this.law = law;
View.call(this, template, {law: law, color: this.color});
}
View(LawProposal);
module.exports = LawProposal;
| {
"content_hash": "d7558983e6e27bb51734bcfe66d3949e",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 59,
"avg_line_length": 20.736842105263158,
"alnum_prop": 0.6370558375634517,
"repo_name": "okfn-brasil/euvoto",
"id": "29e697b8cd15ca956de6ea2b311f54664dbd60ca",
"size": "394",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "lib/law-proposal/view.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "118462"
},
{
"name": "HTML",
"bytes": "60884"
},
{
"name": "JavaScript",
"bytes": "344634"
},
{
"name": "Makefile",
"bytes": "412"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Groove Basin</title>
<link rel="stylesheet" href="app.css">
<link rel="shortcut icon" href="/favicon.png">
</head>
<body>
<div id="nowplaying" class="widget" style="display: none">
<div class="playback-btns">
<button class="button" id="nowplaying-prev" tabindex="-1"><label class="icon icon-seek-prev" for="nowplaying-prev"></label></button>
<button class="button" id="nowplaying-toggle" tabindex="-1"><label id="nowplaying-toggle-icon" class="icon icon-pause" for="nowplaying-toggle-icon"></label></button>
<button class="button" id="nowplaying-stop" tabindex="-1"><label class="icon icon-stop" for="nowplaying-stop"></label></button>
<button class="button" id="nowplaying-next" tabindex="-1"><label class="icon icon-seek-next" for="nowplaying-next"></label></button>
<button class="button" id="stream-btn" tabindex="-1"><span class="icon icon-signal-diag"></span> <label id="stream-btn-label" for="stream-btn">Stream</label></button>
</div>
<div id="client-vol" style="display: none">
<span class="icon icon-volume-off"></span>
<input type="range" id="client-vol-slider" min="0.0" max="1.0" step="0.001" tabindex="-1">
<span class="icon icon-volume-on"></span>
</div>
<h1 id="track-display"></h1>
<input type="range" id="track-slider" min="0.0" max="1.0" step="0.001" tabindex="-1">
<span id="nowplaying-time-elapsed"></span>
<span id="nowplaying-time-left"></span>
<div style="clear: both;"></div>
</div>
<div id="left-window" style="display: none">
<div id="tabs">
<ul>
<li id="library-tab" class="active">Library</li>
<li id="playlists-tab">Playlists</li>
<li id="upload-tab">Import</li>
<li id="events-tab">Chat</li>
<li id="settings-tab">Settings</li>
</ul>
</div>
<div id="library-pane" class="widget">
<div id="lib-window-header" class="window-header">
<input type="text" id="lib-filter" placeholder="filter">
<select id="organize">
<option selected="selected">Artist / Album / Song</option>
</select>
</div>
<div id="library">
<ul id="library-artists">
</ul>
<p id="library-no-items">
<span class="icon icon-info"></span>
<strong id="empty-library-message">loading...</strong>
</p>
</div>
</div>
<div id="playlists-pane" class="widget" style="display: none">
<input type="text" id="new-playlist-name" placeholder="New Playlist">
<div id="playlists">
<ul id="playlists-list">
</ul>
</div>
</div>
<div id="upload-pane" class="widget" style="display: none">
<div id="upload">
<h1>Import by URL</h1>
<input id="upload-by-url" type="text" placeholder="Paste URL and press enter. Supports YouTube">
<h1>Upload Files</h1>
<div id="upload-widget">
<input type="file" id="upload-input" multiple="multiple" placeholder="Drag and drop or click to browse">
</div>
<h1>Import by Name</h1>
<textarea id="import-by-name" placeholder="Put a list of artist - title track names here, newline delimited. Enter when done. Shift+Enter for newline."></textarea>
<h1>Options</h1>
<div>
Automatically queue imported songs: <input class="button" type="button" id="auto-queue-uploads" value="On">
</div>
<div id="import-progress" style="display: none">
<h1>Ongoing Imports</h1>
<div>
<ul id="import-progress-list">
</ul>
</div>
</div>
</div>
</div>
<div id="events-pane" class="widget" style="display: none">
<div id="events-online-users">
</div>
<div id="events-list">
</div>
<div id="chat-box">
<input type="text" id="chat-box-input" placeholder="chat">
</div>
</div>
<div id="settings-pane" class="widget" style="display: none">
<div id="settings">
<div class="section">
<h1>Authentication</h1>
<div id="ensure-admin" style="display: none;">
<p>
There is currently no admin account. Press this button to create the
admin account and print the username and password to the server log:
</p>
<input class="button" type="button" id="ensure-admin-btn" value="Make Admin Account">
</div>
<div id="settings-register" style="display: none">
<input type="text" id="auth-username" placeholder="username" maxlength="64"><br>
<input type="password" id="auth-password" placeholder="password">
<input class="button" type="button" id="auth-show-password" value="Reveal"><br>
<input class="button" type="button" id="settings-auth-save" value="Save">
<input class="button" type="button" id="settings-auth-cancel" value="Cancel">
</div>
<div id="settings-show-auth">
<p>Authenticated as <span id="auth-username-display">...</span></p>
<p>Permissions:
<span class="perm" id="auth-perm-read" title="Read access to everything">read</span>
<span class="perm" id="auth-perm-add" title="Import new songs">add</span>
<span class="perm" id="auth-perm-control" title="Control playback and the queue">control</span>
<span class="perm" id="auth-perm-playlist" title="Create, update, delete playlists">playlist</span>
<span class="perm" id="auth-perm-admin" title="Delete songs, update tags, organize library">admin</span>
</p>
<input class="button" type="button" id="settings-auth-edit" value="Edit">
<input class="button" type="button" id="settings-auth-logout" value="Logout">
<input class="button" type="button" id="settings-auth-request" value="Request Validation">
</div>
<div id="settings-users">
<h1>Users</h1>
<select id="settings-users-select"></select><br>
<input class="button" type="button" id="settings-delete-user" value="Delete">
<input class="button" type="button" id="user-perm-read" value="read" title="Read access to everything">
<input class="button" type="button" id="user-perm-add" value="add" title="Import new songs">
<input class="button" type="button" id="user-perm-control" value="control" title="Control playback and the queue">
<input class="button" type="button" id="user-perm-playlist" value="playlist" title="Create, update, delete playlists">
<input class="button" type="button" id="user-perm-admin" value="admin" title="Delete songs, update tags, organize library">
</div>
<div id="settings-requests">
<h1>Requests</h1>
<div id="settings-request">
<input type="text" id="request-name"> Name<br>
<select id="request-replace"></select> Account<br>
<input class="button" type="button" id="request-approve" value="Approve">
<input class="button" type="button" id="request-deny" value="Deny">
</div>
</div>
</div>
<div class="section">
<h1>Last.fm</h1>
<div id="settings-lastfm-in">
<p>
Authenticated as
<a id="settings-lastfm-user" href="#">...</a>.
<input class="button" type="button" id="lastfm-sign-out" value="Sign out">
</p>
<p>
Scrobbling is
<input class="button" type="button" id="toggle-scrobble" value="Off">
</p>
</div>
<div id="settings-lastfm-out">
<p>
<a id="lastfm-auth-url" href="#">Authenticate with Last.fm</a>
</p>
</div>
</div>
<div class="section">
<h1>Sound</h1>
<div>
Hardware audio playback is
<input class="button" type="button" id="toggle-hardware-playback" value="On">
</div>
<div>Volume: <span id="vol-num"></span>%</div>
<div id="vol-warning" style="display: none">
Greater than 100% volume compromises audio quality.
<a target="_blank" href="https://www.youtube.com/watch?v=iuEtQqC-Sqo">Loudness Zen</a>
</div>
<div id="vol">
<span class="icon icon-volume-off"></span>
<input type="range" id="vol-slider" min="0.0" max="2.0" step="0.001">
<span class="icon icon-volume-on"></span>
</div>
<div style="clear: both;"></div>
</div>
<div class="section">
<h1>About</h1>
<ul>
<li><a id="keyboard-shortcuts-link" href="#">Keyboard Shortcuts</a></li>
<li><a id="settings-stream-url" href="#" target="_blank">Stream URL</a></li>
<li><a href="http://github.com/andrewrk/groovebasin" target="_blank">GrooveBasin on GitHub</a></li>
</ul>
</div>
</div>
</div>
</div>
<div id="queue-window" class="widget" style="display: none">
<div class="window-header">
<input class="button" type="button" id="auto-dj" value="Auto DJ" tabindex="-1">
<input class="button" type="button" id="queue-btn-repeat" value="Repeat: Off" tabindex="-1">
<span id="queue-duration-label"></span> <span id="queue-duration"></span>
</div>
<div id="queue-list">
<div id="queue-header" class="header">
<span class="track"> </span>
<span class="title">Title</span>
<span class="artist">Artist</span>
<span class="album">Album</span>
<span class="time">Time</span>
</div>
<div id="queue-items">
</div>
</div>
</div>
<div style="clear: both"></div>
<div id="main-err-msg">
<span class="icon icon-alert"></span>
<div id="main-err-msg-text">Loading...</div>
</div>
<div id="blackout" style="display: none"></div>
<div id="modal" class="widget" style="display: none" tabindex="-1">
<div id="modal-header">
<span id="modal-title">Keyboard Shortcuts</span>
<button id="modal-close" class="button"><label class="icon icon-closethick"></label></button>
</div>
<div id="modal-content"></div>
</div>
<div id="shortcuts" style="display: none" tabindex="-1">
<h1>Playback</h1>
<dl>
<dt>Space</dt>
<dd>Toggle playback</dd>
</dl>
<dl>
<dt>Left <em>and</em> Right</dt>
<dd>Skip 10 seconds in the song</dd>
</dl>
<dl>
<dt>Shift</dt>
<dd>Hold to skip by 10% instead of 10 seconds</dd>
</dl>
<dl>
<dt>< <em>or</em> Ctrl + Left <em>and</em> > <em>or</em> Ctrl + Right</dt>
<dd>Skip track</dd>
</dl>
<dl>
<dt>- <em>and</em> +</dt>
<dd>Change volume</dd>
</dl>
<dl>
<dt>s</dt>
<dd>Toggle streaming</dd>
</dl>
<h1>The Play Queue</h1>
<dl>
<dt>Up <em>and</em> Down</dt>
<dd>Select the next song</dd>
</dl>
<dl>
<dt>Alt + Up <em>and</em> Alt + Down</dt>
<dd>Move selected tracks up or down one</dd>
</dl>
<dl>
<dt>Enter</dt>
<dd>Play the selected song</dd>
</dl>
<dl>
<dt>Ctrl+A</dt>
<dd>Select all</dd>
</dl>
<dl>
<dt>H</dt>
<dd>Shuffle selection</dd>
</dl>
<dl>
<dt>d</dt>
<dd>Toggle Auto DJ</dd>
</dl>
<dl>
<dt>r</dt>
<dd>Change repeat state</dd>
</dl>
<dl>
<dt>Del</dt>
<dd>Remove selected songs from queue</dd>
</dl>
<dl>
<dt>Shift + Del</dt>
<dd>Delete selected songs from library</dd>
</dl>
<h1>Navigation</h1>
<dl>
<dt>/</dt>
<dd>Switch to Library tab and focus the Search box</dd>
</dl>
<dl>
<dt>p</dt>
<dd>Switch to Playlists tab and focus the New Playlist box</dd>
</dl>
<dl>
<dt>i</dt>
<dd>Switch to Import tab and focus the Import by URL box</dd>
</dl>
<dl>
<dt>t</dt>
<dd>Switch to Chat tab and focus the Chat box</dd>
</dl>
<dl>
<dt>e</dt>
<dd>Switch to Settings tab</dd>
</dl>
<h1>Library Search Box</h1>
<dl>
<dt>/</dt>
<dd>Focus library search</dd>
</dl>
<dl>
<dt>Esc</dt>
<dd>Clear filter. If filter is already clear, remove focus.</dd>
</dl>
<dl>
<dt>Enter</dt>
<dd>Queue all search results</dd>
</dl>
<dl>
<dt>Down</dt>
<dd>Select the first search result</dd>
</dl>
<h1>Library</h1>
<dl>
<dt>Up <em>and</em> Down</dt>
<dd>Select the next item up or down</dd>
</dl>
<dl>
<dt>Left <em>and</em> Right</dt>
<dd>Expand or collapse selected item</dd>
</dl>
<dl>
<dt>Enter</dt>
<dd>Queue selected items</dd>
</dl>
<dl>
<dt>Del</dt>
<dd>Delete selected songs from library</dd>
</dl>
<dl>
<dt>E</dt>
<dd>Edit tags for the selected songs</dd>
</dl>
<dl>
<dt>a</dt>
<dd>Add selected songs to a playlist</dd>
</dl>
<h1>Playlists</h1>
<dl>
<dt>Up <em>and</em> Down</dt>
<dd>Select the next item up or down</dd>
</dl>
<dl>
<dt>Alt + Up <em>and</em> Alt + Down</dt>
<dd>Move selected tracks up or down one</dd>
</dl>
<dl>
<dt>Left <em>and</em> Right</dt>
<dd>Expand or collapse selected playlist</dd>
</dl>
<dl>
<dt>Enter</dt>
<dd>Queue selected items</dd>
</dl>
<dl>
<dt>Del</dt>
<dd>Remove selected songs from playlist</dd>
</dl>
<dl>
<dt>Shift + Del</dt>
<dd>Delete selected songs and playlists from library</dd>
</dl>
<dl>
<dt>R</dt>
<dd>Rename selected playlist</dd>
</dl>
<h1>Miscellaneous</h1>
<dl>
<dt>?</dt>
<dd>Displays keyboard shortcuts</dd>
</dl>
<dl>
<dt>Esc</dt>
<dd>Close menu, cancel drag, clear selection</dd>
</dl>
<dl>
<dt>Alt</dt>
<dd>Hold when right clicking to get the normal browser menu</dd>
</dl>
<dl>
<dt>Shift</dt>
<dd>Hold while queuing to queue next</dd>
</dl>
<dl>
<dt>Alt</dt>
<dd>Hold while queuing to queue in random order</dd>
</dl>
<dl>
<dt>Ctrl</dt>
<dd>Hold to select multiple items</dd>
</dl>
<dl>
<dt>Shift</dt>
<dd>Hold while selecting to select all items in between</dd>
</dl>
</div>
<div id="edit-tags" style="display: none">
<div>
<span class="field">
<input type="checkbox" id="edit-tag-multi-name">
<label accesskey="i" for="edit-tag-name">T<span class="accesskey">i</span>tle:</label>
</span>
<input type="text" id="edit-tag-name">
</div>
<div>
<span class="field">
<input type="checkbox" id="edit-tag-multi-track">
<label accesskey="k" for="edit-tag-track">Trac<span class="accesskey">k</span> Number:</label>
</span>
<input type="text" id="edit-tag-track">
</div>
<div>
<span class="field">
<input type="checkbox" id="edit-tag-multi-file">
<label accesskey="f" for="edit-tag-file"><span class="accesskey">F</span>ilename:</label>
</span>
<input type="text" id="edit-tag-file">
</div>
<hr>
<div>
<span class="field">
<input type="checkbox" id="edit-tag-multi-artistName">
<label accesskey="a" for="edit-tag-artistName"><span class="accesskey">A</span>rtist:</label>
</span>
<input type="text" id="edit-tag-artistName">
</div>
<div>
<span class="field">
<input type="checkbox" id="edit-tag-multi-composerName">
<label accesskey="c" for="edit-tag-composerName"><span class="accesskey">C</span>omposer:</label>
</span>
<input type="text" id="edit-tag-composerName">
</div>
<div>
<span class="field">
<input type="checkbox" id="edit-tag-multi-performerName">
<label for="edit-tag-performerName">Performer:</label>
</span>
<input type="text" id="edit-tag-performerName">
</div>
<div>
<span class="field">
<input type="checkbox" id="edit-tag-multi-genre">
<label accesskey="g" for="edit-tag-genre"><span class="accesskey">G</span>enre:</label>
</span>
<input type="text" id="edit-tag-genre">
</div>
<hr>
<div>
<span class="field">
<input type="checkbox" id="edit-tag-multi-albumName">
<label accesskey="b" for="edit-tag-albumName">Al<span class="accesskey">b</span>um:</label>
</span>
<input type="text" id="edit-tag-albumName">
</div>
<div>
<span class="field">
<input type="checkbox" id="edit-tag-multi-albumArtistName">
<label accesskey="t" for="edit-tag-albumArtistName">Album Ar<span class="accesskey">t</span>ist:</label>
</span>
<input type="text" id="edit-tag-albumArtistName">
</div>
<div>
<span class="field">
<input type="checkbox" id="edit-tag-multi-trackCount">
<label for="edit-tag-trackCount">Track Count:</label>
</span>
<input type="text" id="edit-tag-trackCount">
</div>
<div>
<span class="field">
<input type="checkbox" id="edit-tag-multi-year">
<label accesskey="y" for="edit-tag-year"><span class="accesskey">Y</span>ear:</label>
</span>
<input type="text" id="edit-tag-year">
</div>
<div>
<span class="field">
<input type="checkbox" id="edit-tag-multi-disc">
<label accesskey="d" for="edit-tag-disc"><span class="accesskey">D</span>isc Number:</label>
</span>
<input type="text" id="edit-tag-disc">
</div>
<div>
<span class="field">
<input type="checkbox" id="edit-tag-multi-discCount">
<label for="edit-tag-discCount">Disc Count:</label>
</span>
<input type="text" id="edit-tag-discCount">
</div>
<div>
<span class="field">
<input type="checkbox" id="edit-tag-multi-compilation">
<label accesskey="m" for="edit-tag-compilation">Co<span class="accesskey">m</span>pilation:</label>
</span>
<input type="checkbox" id="edit-tag-compilation">
</div>
<hr>
<div style="float: right">
<button class="button" id="edit-tags-ok" accesskey="v">Sa<span class="accesskey">v</span>e & Close</button>
<button class="button" id="edit-tags-cancel">Cancel</button>
</div>
<button class="button" id="edit-tags-prev" type="button" accesskey="p"><span class="accesskey">P</span>revious</button>
<button class="button" id="edit-tags-next" type="button" accesskey="n"><span class="accesskey">N</span>ext</button>
<button class="button" id="edit-tags-per"><label id="edit-tags-per-label" accesskey="r" for="edit-tags-per">Pe<span class="accesskey">r</span> Track</label></button>
</div>
<ul id="context-menu" class="widget" style="display: none">
<li id="menu-queue"><a href="#">Queue</a></li>
<li id="menu-queue-next"><a href="#">Queue Next</a></li>
<li id="menu-queue-random"><a href="#">Queue in Random Order</a></li>
<li id="menu-queue-next-random"><a href="#">Queue Next in Random Order</a></li>
<li id="menu-remove"><a href="#">Remove from Playlist</a></li>
<li id="menu-add-to-playlist"><a href="#">Add to Playlist...</a></li>
<li id="menu-shuffle"><a href="#">Shuffle</a></li>
<li id="menu-delete"><a href="#">Delete from Library</a></li>
<li id="menu-delete-playlist"><a href="#">Delete Playlist</a></li>
<li id="menu-rename-playlist"><a href="#">Rename Playlist</a></li>
<li id="menu-download"><a href="#" target="_blank">Download</a></li>
<li id="menu-edit-tags"><a href="#">Edit Tags</a></li>
</ul>
<div id="add-to-playlist-dialog" style="display: none">
<div>
<input type="text" id="add-to-playlist-filter" placeholder="filter">
</div>
<ul id="add-to-playlist-list">
</ul>
<div id="add-to-playlist-new"></div>
</div>
<script src="app.js"></script>
</body>
</html>
| {
"content_hash": "2b56aec31275714aebcfca371cf57ed9",
"timestamp": "",
"source": "github",
"line_count": 566,
"max_line_length": 172,
"avg_line_length": 35.8886925795053,
"alnum_prop": 0.561807709348693,
"repo_name": "emersion/groovebasin",
"id": "e4c50e70860385d8c8a14b92ac933b1d5abb6438",
"size": "20313",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/public/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10385"
},
{
"name": "HTML",
"bytes": "20313"
},
{
"name": "JavaScript",
"bytes": "390142"
},
{
"name": "Shell",
"bytes": "179"
}
],
"symlink_target": ""
} |
<html>
<body>
<script src="phantomjs-shims.js" type="text/javascript"></script>
<script src="../target/main-test.js" type="text/javascript"></script>
</body>
</html>
| {
"content_hash": "7adbba09e8a259897e1a64f2da4fc519",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 73,
"avg_line_length": 29.666666666666668,
"alnum_prop": 0.6404494382022472,
"repo_name": "onaio/hatti",
"id": "0f279dbb237509bf2e6380ccbc0b56a8c75b911c",
"size": "178",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "phantom/unit-test.html",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Clojure",
"bytes": "272811"
},
{
"name": "HTML",
"bytes": "178"
},
{
"name": "JavaScript",
"bytes": "29505"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">
<include file="changelog-3.3.xml" relativeToChangelogFile="true" />
<include file="changelog-3.5.xml" relativeToChangelogFile="true" />
<include file="changelog-3.6.xml" relativeToChangelogFile="true" />
<include file="changelog-3.7.xml" relativeToChangelogFile="true" />
<include file="changelog-3.8.xml" relativeToChangelogFile="true" />
<include file="changelog-3.9.xml" relativeToChangelogFile="true" />
<include file="changelog-3.10.xml" relativeToChangelogFile="true" />
</databaseChangeLog>
| {
"content_hash": "731917520b29b94e0318728dfa6c5fbb",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 87,
"avg_line_length": 55.733333333333334,
"alnum_prop": 0.7260765550239234,
"repo_name": "akzeitions/HerokuTeste",
"id": "2aed50e72b867960d0027b463f9031363177765d",
"size": "836",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "schema/changelog-master.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "351"
},
{
"name": "CSS",
"bytes": "1499"
},
{
"name": "HTML",
"bytes": "1479"
},
{
"name": "Inno Setup",
"bytes": "1331"
},
{
"name": "Java",
"bytes": "2133382"
},
{
"name": "JavaScript",
"bytes": "308073"
},
{
"name": "Python",
"bytes": "1128"
},
{
"name": "Shell",
"bytes": "7075"
}
],
"symlink_target": ""
} |
from setuptools import setup
setup(name='learningml',
version='0.3',
description='This repository demonstrates how to make a project pip installable, write a Python module in C and use scikit-learn, keras and spearmint.',
url='https://github.com/weissercn/learningml',
author='Constantin Weisser',
author_email='weissercn@gmail.com',
license='MIT',
packages=['learningml'],
install_requires=[
'numpy',
'scipy',
'scikit-learn',
'keras',
],
zip_safe=False)
| {
"content_hash": "d50f0e0f21933631ac1dd149c2f1d088",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 158,
"avg_line_length": 32.705882352941174,
"alnum_prop": 0.6187050359712231,
"repo_name": "weissercn/learningml",
"id": "72bc8fa0b6e920aa6bfabbd030a60a5584c2cc6a",
"size": "556",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "902"
},
{
"name": "Python",
"bytes": "580027"
},
{
"name": "Shell",
"bytes": "191"
}
],
"symlink_target": ""
} |
title: The lab is growing
date: "May 14, 2018"
layout: post
output:
html_document:
---
Mehran Bakhtiari, Research Technician, joined the lab. Welcome Mehran!
| {
"content_hash": "188f5f5b1ec98dc01cc5865f129a344d",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 70,
"avg_line_length": 20.125,
"alnum_prop": 0.7391304347826086,
"repo_name": "kridel-lab/kridel-lab.github.io",
"id": "1d7528f5cd3e4bb4e6b6e6ac33cdf4db9349ffd8",
"size": "165",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2018-05-14-new-lab-member.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16773"
},
{
"name": "Dockerfile",
"bytes": "1101"
},
{
"name": "HTML",
"bytes": "25479"
},
{
"name": "JavaScript",
"bytes": "4356"
},
{
"name": "Ruby",
"bytes": "4343"
}
],
"symlink_target": ""
} |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Project = mongoose.model('Project'),
User = mongoose.model('User'),
_ = require('lodash');
module.exports = _.extend(
require('./projects/projects.crud.server.controller'),
require('./projects/projects.membership.server.controller'),
require('./projects/projects.positions.server.controller'),
require('./projects/projects.resources.server.controller')
); | {
"content_hash": "14a223f15329e7abbe6e3308be25404f",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 61,
"avg_line_length": 26.473684210526315,
"alnum_prop": 0.7196819085487077,
"repo_name": "hrraydov/ray-idea",
"id": "c8a5ed2ef8373196d7bd79d9b91f45125c35001b",
"size": "503",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/projects.server.controller.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "944"
},
{
"name": "JavaScript",
"bytes": "160407"
},
{
"name": "Shell",
"bytes": "693"
}
],
"symlink_target": ""
} |
select fn_db_change_column_type('vds_static','pm_password','VARCHAR','text');
| {
"content_hash": "d2912fe7077d1a5b96ce526d55d9ad95",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 77,
"avg_line_length": 78,
"alnum_prop": 0.717948717948718,
"repo_name": "raksha-rao/gluster-ovirt",
"id": "893888af9da7b979b95f8d3b3fdd4724bb900de8",
"size": "138",
"binary": false,
"copies": "5",
"ref": "refs/heads/ovirt-upstream-rebased",
"path": "backend/manager/dbscripts/upgrade/03_01_0030_change_vds_static_pm_password_to_text.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "4300"
},
{
"name": "Java",
"bytes": "15806279"
},
{
"name": "JavaScript",
"bytes": "28877"
},
{
"name": "Python",
"bytes": "1057716"
},
{
"name": "Shell",
"bytes": "78518"
}
],
"symlink_target": ""
} |
package com.impetus.client.generatedId;
import org.junit.After;
import org.junit.Before;
import com.impetus.client.cassandra.common.CassandraConstants;
public class CassandraGeneratedIdCqlTest extends CassandraGeneratedIdTest
{
@Before
public void setUp() throws Exception
{
properties.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);
super.setUp();
}
@After
public void tearDown() throws Exception
{
super.tearDown();
}
}
| {
"content_hash": "dca2fe1ac6839749d2979f3bebe4fcaa",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 91,
"avg_line_length": 21.208333333333332,
"alnum_prop": 0.7170923379174853,
"repo_name": "ravisund/Kundera",
"id": "452d3e6b8f55bb6f982d73c2ca0a394b6b835aa6",
"size": "509",
"binary": false,
"copies": "3",
"ref": "refs/heads/trunk",
"path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/CassandraGeneratedIdCqlTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "14122826"
},
{
"name": "Shell",
"bytes": "113"
}
],
"symlink_target": ""
} |
title: "GitHub Dark, Big Sur Icons, And 5 New Themes"
excerpt: "Here it is... The moment we've all been waiting for - GitHub finally has a Dark Mode! You can enable it in your settings. I know, it's not a Dracula color palette, but it's better than nothing :P"
createdAt: "2020-12-15"
updatedAt: "2021-01-30"
author:
name: Zeno Rocha
avatar: "https://github.com/zenorocha.png?size=48"
ogImage: "/static/img/blog/github-dark-big-sur-icons-and-5-new-themes-a.png"
color: "yellow"
---
Here it is... The moment we've all been waiting for - GitHub finally has a Dark Mode! You can enable it in your settings. I know, it's not a Dracula color palette, but it's better than nothing :P
[](https://github.com/settings/appearance)
## New on Dracula
This week 5 new themes have joined the Dracula clan!
- [Arduino Pro](/arduino-pro-ide): New **IDE** for more advanced developers
- [Albert](/albert): A desktop agnostic **launcher** written in C++
- [KiCad](/kicad): Cross-platform **electronics** design automation suite
- [Linear](/linear): The **issue tracking** tool you'll enjoy using
- [Standard Notes](/standard-notes): A simple and **private notes** app
[](/standard-notes)
## New on Dracula PRO
Dracula PRO received an update with new icons for **macOS Big Sur**, support for **JetBrains 2020.3**, and an **8K resolution wallpaper**. Here's a preview of the icons.
[](/pro)
[](/pro)
[](/pro)
[](/pro)
[](/pro)
[](/pro)
Happy hacking!
| {
"content_hash": "319a973f96b2912d369a4dcdce2d4d83",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 206,
"avg_line_length": 50,
"alnum_prop": 0.7213636363636363,
"repo_name": "dracula/dracula.github.io",
"id": "b4c5357cfb8720f4cdd334aace05ecd5d0a28522",
"size": "2204",
"binary": false,
"copies": "1",
"ref": "refs/heads/site",
"path": "blog/github-dark-big-sur-icons-and-5-new-themes.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "22576"
},
{
"name": "JavaScript",
"bytes": "86512"
}
],
"symlink_target": ""
} |
<!--
Inside this directive you should display the ITEMS available in the collection object.
Depending on the TYPE property of the collection, the items will be:
- books
- movies
- videogames
- music albums
This directive should display the right directive for each collection type (c.collection.type). E.g. if it is a "books" collection, the directive "items-books" must be displayed, showing the books in the appropriate format; if it is a "movies" collection, the directive "items-movies" must be displayed, showing the movies in the appropriate format. You should check the following Angular directives for this:
- ngIf - https://docs.angularjs.org/api/ng/directive/ngIf
- ngSwitch - https://docs.angularjs.org/api/ng/directive/ngSwitch
Each item must have three links/buttons:
- A link to the URL of the item.
- A link/button for building and displaying the edit template.
- A link/button for deleting the item.
When the user clicks on the item link, the function "readCollection" will be called and the client will connect to the item URL and get its representation in Collection + JSON format.
When the user clicks on the "edit" button, the function "buildEditForm" must be called to create the edit template, fill it with the item data and store it in "c.collection.editTemplate". When the user submits this form, the function "editItem" must be called.
When the user clicks on the "delete" button, the function "deleteItem" must be called.
You can change all the HTML in this page.
-->
<div class="col-lg-12" ng-show="c.collection.type != 'index'">
<div ng-show="['movies', 'movie'].indexOf(c.collection.type) != -1 ">
<items-movies></items-movies>
</div>
<div ng-show="['musicalbums', 'musicalbum'].indexOf(c.collection.type) != -1 ">
<items-musicalbums></items-musicalbums>
</div>
<div ng-show="['videogames', 'videogame'].indexOf(c.collection.type) != -1 ">
<items-videogames></items-videogames>
</div>
<div ng-show="['books', 'book'].indexOf(c.collection.type) != -1 ">
<items-books></items-books>
</div>
</div>
| {
"content_hash": "074aa42008b57710ad73494c3f8240c2",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 414,
"avg_line_length": 41.86538461538461,
"alnum_prop": 0.6945337620578779,
"repo_name": "interfacesweb15-16/s4_mercury",
"id": "4eb0155458e4bd6892c7616fe3cbaafb7b6fe93b",
"size": "2177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cliente/collection-items.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "85"
},
{
"name": "Batchfile",
"bytes": "29"
},
{
"name": "HTML",
"bytes": "14610"
},
{
"name": "JavaScript",
"bytes": "5374"
},
{
"name": "PHP",
"bytes": "37039"
}
],
"symlink_target": ""
} |
/*
* Super-Bits.com CODE CNPJ 20.019.971/0001-90
*/
package com.super_bits.config.webPaginas;
import com.super_bits.modulosSB.Persistencia.ConfigGeral.SBPersistencia;
import com.super_bits.modulosSB.SBCore.ConfigGeral.SBCore;
import com.super_bits.modulosSB.webPaginas.ConfigGeral.SBWebPaginas;
import com.super_bits.sbProjetos.Model.ConfigPersistenciaSBProject;
/**
*
* @author Salvio
*/
public abstract class SBProject {
public static void ConfiguraSBProject() {
SBCore.configurar(new Con, SBCore.ESTADO_APP.DESENVOLVIMENTO);
SBPersistencia.configuraJPA(new ConfigPersistenciaSBProject());
SBWebPaginas.configurar(new ConfigWebPaginasSBProject());
}
}
| {
"content_hash": "0cdbc4d167b5585c9a6f9f9f21431668",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 72,
"avg_line_length": 29.041666666666668,
"alnum_prop": 0.7675753228120517,
"repo_name": "salviof/SuperBits_FrameWork",
"id": "7357ba4877e8bd571dd68b307f26a6ff7693e04b",
"size": "697",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SBProjetos/webApp/src/main/java/com/super_bits/config/webPaginas/SBProject.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1086"
},
{
"name": "CSS",
"bytes": "1093328"
},
{
"name": "HTML",
"bytes": "475027"
},
{
"name": "Java",
"bytes": "1486148"
},
{
"name": "JavaScript",
"bytes": "94730"
},
{
"name": "Shell",
"bytes": "8949"
}
],
"symlink_target": ""
} |
package bdzimmer.secondary.export.controller
import java.io.{File, FileOutputStream}
import java.net.{HttpURLConnection, URL}
import scala.util.Try
import org.apache.commons.io.{FileUtils, FilenameUtils, IOUtils}
import org.apache.commons.compress.archivers.zip.ZipFile
import bdzimmer.secondary.export.model.{ProjectConfig, ProjectStructure, WorldItems, Tags}
import bdzimmer.secondary.export.model.WorldItems._
import bdzimmer.secondary.export.view.Styles
import bdzimmer.secondary.export.view.WebResource
import bdzimmer.util.{Result, Pass, Fail}
import bdzimmer.util.StringUtils._
class ExportProcess(projConf: ProjectConfig) {
val metaStatusFile = projConf.projectDir / ProjectStructure.MetaStatusFile
val refStatusFile = projConf.projectDir / ProjectStructure.RefStatusFile
val itemStatusFile = projConf.projectDir / ProjectStructure.ItemStatusFile
val wikiCache = new FilesystemCache(
projConf.projectDir / "wikicache",
".json",
ImageDownloader.getWikimediaJson)
def loadMeta(): (FileMap, FileMap) = {
val oldMetaStatus = WorldLoader.loadOrEmptyModifiedMap(metaStatusFile)
val metaStatusChanges = localMetaStatusChanges(oldMetaStatus, projConf)
val newMetaStatus = WorldLoader.mergeFileMaps(oldMetaStatus, metaStatusChanges)
(newMetaStatus, metaStatusChanges)
}
def loadRefs(world: List[WorldItem]): (FileMap, FileMap) = {
val oldRefStatus = WorldLoader.loadOrEmptyModifiedMap(refStatusFile)
val refStatusChanges = localReferencedFileStatusChanges(world, oldRefStatus, projConf)
val newRefStatus = WorldLoader.mergeFileMaps(oldRefStatus, refStatusChanges)
(newRefStatus, refStatusChanges)
}
def run(): Result[String, CollectionItem] = {
if (!projConf.localExportPathFile.exists()) {
println("creating export directory: " + projConf.localExportPath)
projConf.localExportPathFile.mkdirs()
}
val (newMetaStatus, metaStatusChanges) = loadMeta()
val loadedWorld = Timer.showTimeBrief("loading world", {WorldLoader.loadWorld(projConf, newMetaStatus)})
loadedWorld match {
case Pass(master) => {
val world = WorldItems.collectionToList(master)
val (newRefStatus, refStatusChanges) = loadRefs(world)
val (newItemStatus, itemStatusChanges) = loadItemStatus(world)
// only export the things that have changed
if (itemStatusChanges.nonEmpty || refStatusChanges.nonEmpty) {
// parse all of the tags
val stringToItem = (world.map(x => (x.id, x)) ++ world.map(x => (x.name, x))).toMap
val tagsMap = world.map(x => (x.uid, x.tags.mapValues(tag => ParseTags.parse(tag, stringToItem)))).toMap
val hiddenItems = projConf.hiddenItems.split(";\\s+").toList.flatMap(x => {
stringToItem.get(x).map(WorldItems.collectionToList)
}).flatten.distinct
val renderPages = Timer.showTimeBrief("build render pages", new RenderPages(
master,
world,
tagsMap,
wikiCache,
projConf.license,
projConf.navbars,
projConf.subarticles,
projConf.relativeLinks,
hiddenItems,
projConf.unifiedJumbotron,
projConf.search))
val renderImages = Timer.showTimeBrief("build render images", new RenderImages(
world,
tagsMap,
wikiCache,
projConf.localExportPath,
projConf.license))
val (itemsToExport, modifiedRefs) = Timer.showTime("dependency analysis", {
val modifiedIds = itemStatusChanges.keySet
// items that have been modified
val modifiedItems = world.filter(x => modifiedIds.contains(x.id))
modifiedItems.foreach(x => println("modified item: " + x.id))
// items that modified items reference
// this will keep "referenced by" lists up to date
// I don't think this is usually important; so this may be something to make optional
val modifiedItemsReferences = modifiedItems.flatMap(x => {
val refs = renderPages.references.getOrElse(x.uid, List())
refs.foreach(y => println("modified item refs: " + y.id + " <- " + x.id))
refs
})
// items that modified items are referenced by
// updates link names, flight predictions, etc.
// This is more important than above in terms of keeping things up to date.
val modifiedItemsReferencedBy = modifiedItems.flatMap(x => {
val refd = renderPages.referencedBy.getOrElse(x.uid, List())
refd.foreach(y => println("modified item refd: " + y.id + " -> " + x.id))
refd
})
// val itemsToExport = (modifiedItems ++ modifiedItemsReferences ++ modifiedItemsReferencedsBy ++ timelineItemsRefresh).distinct
val itemsToExport = (modifiedItems ++ modifiedItemsReferences ++ modifiedItemsReferencedBy).distinct
val modifiedRefs = world.collect({case x: RefItem => x }).filter(x => refStatusChanges.keySet.contains(x.filename))
(itemsToExport, modifiedRefs)
})
val (allPageOutputs, allImageOutputs) = ExportPipeline.export(
itemsToExport, modifiedRefs, renderPages, renderImages,
projConf.localExportPath, projConf.localContentPath)
saveStatus(newMetaStatus, newRefStatus, newItemStatus)
} else {
println("Nothing to do.")
}
}
case Fail(msg) => println(msg)
}
loadedWorld
}
private def localMetaStatusChanges(
oldMetaStatus: FileMap,
projConf: ProjectConfig): FileMap = {
val srcFiles = projConf.localContentPathFile.listFiles.toList.map(_.getName).filter(x => {
x.endsWith(".sec")
})
ExportPipeline.localFileUpdates(srcFiles, oldMetaStatus, projConf.localContentPath)
}
private def localReferencedFileStatusChanges(
world: List[WorldItem],
oldFileStatus: FileMap,
projConf: ProjectConfig): FileMap = {
val imageFiles = ExportPipeline.getReferencedImages(world)
ExportPipeline.localFileUpdates(imageFiles, oldFileStatus, projConf.localContentPath)
}
private def loadItemStatus(world: List[WorldItem]): (ItemMap, ItemMap) = {
val oldItemStatus = WorldLoader.loadOrEmptyItemMap(itemStatusFile)
val newItemStatus = world.map(x => (x.id, (x.srcfilename, x.hashCode))).toMap
val changes = newItemStatus.filter({case (k, v) => oldItemStatus.get(k) match {
case Some(x) => v._2 != x._2
case None => true
}})
(newItemStatus, changes)
}
private def saveStatus(
metaStatus: FileMap,
refStatus: FileMap,
itemStatus: ItemMap): Unit = {
WorldLoader.saveFileMap(metaStatusFile, metaStatus)
WorldLoader.saveFileMap(refStatusFile, refStatus)
WorldLoader.saveItemMap(itemStatusFile, itemStatus)
}
}
object ExportPipeline {
// simple export - local export everything without regard to what has changed
def exportAll(projConf: ProjectConfig): Result[String, CollectionItem] = {
FileUtils.deleteDirectory(projConf.localExportPathFile)
projConf.localExportPathFile.mkdirs()
val wikiCache = new FilesystemCache(
projConf.projectDir / "wikicache",
".json",
ImageDownloader.getWikimediaJson)
val loadedWorld = WorldLoader.loadWorld(projConf)
loadedWorld match {
case Pass(master) => {
val world = WorldItems.collectionToList(master)
// parse all of the tags
val stringToItem = (world.map(x => (x.id, x)) ++ world.map(x => (x.name, x))).toMap
val tagsMap = world.map(x => (x.uid, x.tags.mapValues(tag => ParseTags.parse(tag, stringToItem)))).toMap
val hiddenItems = projConf.hiddenItems.split(";\\s+").toList.flatMap(x => {
stringToItem.get(x).map(WorldItems.collectionToList(_))
}).flatten.distinct
val renderPages = new RenderPages(
master,
world,
tagsMap,
wikiCache,
projConf.license,
projConf.navbars,
projConf.subarticles,
projConf.relativeLinks,
hiddenItems,
projConf.unifiedJumbotron,
projConf.search)
val renderImages = new RenderImages(
world,
tagsMap,
wikiCache,
projConf.localExportPath,
projConf.license)
performRenderPages(renderPages, world, projConf.localExportPath)
performRenderImages(renderImages, world, projConf.localContentPath)
}
case Fail(msg) => println(msg)
}
loadedWorld
}
// export content from local content location to export location
// based on lists of refs to export
def export(
pagesToExport: List[WorldItem],
refsToExport: List[RefItem],
renderPages: RenderPages,
renderImages: RenderImages,
localExportPath: String,
localContentPath: String): (List[String], FileOutputsMap) = {
logList("page to export", pagesToExport.map(_.id))
// the images to export are:
// 1) the refitems in the whole collection whose referenced files were updated (refsToExport)
// 2) the imageitems whose metadata changed
val imagePagesToExport = pagesToExport.collect({case x: ImageItem => x})
logList("ref to export", refsToExport.map(_.id))
logList("image to export", imagePagesToExport.map(_.id))
// there may be overlap between the above two lists, for instance if a tileset file is modified
// and the description is also updated, so the "distinct" here should prevent duplicate work.
val imagesToExport = (refsToExport ++ imagePagesToExport).distinct
val pageOutputs = performRenderPages(renderPages, pagesToExport, localExportPath)
val imageOutputs = performRenderImages(renderImages, imagesToExport, localContentPath)
imageOutputs.foreach{case (k, v) => {
logList("image created", v.map(k + " -> " + _))
}}
println("~~~~ export complete ~~~~")
(pageOutputs, imageOutputs)
}
def performRenderPages(
renderPages: RenderPages,
pagesToExport: List[WorldItem],
localExportPath: String): List[String] = {
val startTime = System.currentTimeMillis
val pageOutputs = scala.collection.mutable.Buffer[String]()
// create master and summary pages that are always exported
// create pages that are always rendered
val (writeTime, _) = Timer.timeit(writePage(
localExportPath / RenderPages.MasterPageFile,
renderPages.masterPage()))
pageOutputs += RenderPages.MasterPageFile
println("master page created: " + RenderPages.MasterPageFile + "\t" + writeTime + " sec")
// create other pages
pagesToExport.foreach(item => {
val pageFilename = RenderPages.itemPageName(item)
val (writeTime, _ ) = Timer.timeit(writePage(
localExportPath / pageFilename,
renderPages.itemPageDispatch(item)
))
println("page created: " + pageFilename + "\t" + writeTime + " sec")
if (pageFilename.length > 0) {
pageOutputs += pageFilename
}
})
val totalTime = (System.currentTimeMillis - startTime) / 1000.0
println("total time for export pages: " + totalTime + " sec")
pageOutputs.toList
}
def performRenderImages(
renderImages: RenderImages,
imagesToExport: List[WorldItem],
localContentPath: String): FileOutputsMap = {
val startTime = System.currentTimeMillis
// TODO: move file IO here from ExportIamges
val imageOutputs = if (imagesToExport.nonEmpty) {
renderImages.exportAllImages(imagesToExport, localContentPath)
} else {
RenderImages.emptyFileOutputsMap
}
val totalTime = (System.currentTimeMillis - startTime) / 1000.0
println("total time for export images: " + totalTime + " sec")
imageOutputs
}
// generate stylesheets and download web resources into project web dir
def addStyles(projConf: ProjectConfig): Unit = {
System.setProperty("https.protocols", "TLSv1.2")
val outputDirFile = new File(projConf.localExportPath)
def download(wr: WebResource): Unit = {
val hc = wr.url.openConnection().asInstanceOf[HttpURLConnection]
hc.setRequestProperty("User-Agent", "curl/7.43.0")
FileUtils.copyInputStreamToFile(
hc.getInputStream(),
new File(outputDirFile, wr.localRelFilename))
}
def copy(wr: WebResource): Unit = {
FileUtils.copyURLToFile(wr.url, new File(outputDirFile, wr.localRelFilename))
}
// extract a zip archive
// http://stackoverflow.com/questions/9324933/what-is-a-good-java-library-to-zip-unzip-files
def extractArchive(archive: File, outputDirname: String): Unit = {
val zipFile = new ZipFile(archive)
Try {
val entries = zipFile.getEntries
val entriesIterator = Iterator.continually((entries, entries.nextElement)).takeWhile(_._1.hasMoreElements).map(_._2)
entriesIterator.foreach(entry => {
val extractedEntry = new File(outputDirname, entry.getName)
if (entry.isDirectory) {
extractedEntry.mkdirs
} else {
extractedEntry.getParentFile.mkdirs
val in = zipFile.getInputStream(entry)
val out = new FileOutputStream(extractedEntry)
IOUtils.copy(in, out)
IOUtils.closeQuietly(in)
out.close()
}
})
}
zipFile.close()
}
// create the output directories
val stylesDir = new File(outputDirFile, WebResource.StylesRelDirname)
if (stylesDir.exists) FileUtils.deleteDirectory(stylesDir)
stylesDir.mkdir()
val fontsDir = new File(outputDirFile, WebResource.FontsRelDirname)
if (fontsDir.exists) FileUtils.deleteDirectory(fontsDir)
fontsDir.mkdir()
val imagesDir = new File(outputDirFile, WebResource.ImagesRelDirname)
if (!imagesDir.exists) {
imagesDir.mkdir()
}
val treeDestDir = new File(outputDirFile, WebResource.TreeRelDirname)
if (treeDestDir.exists) FileUtils.deleteDirectory(treeDestDir)
treeDestDir.mkdir()
// generate main stylesheet in styles directory
val mainCss = Styles.styleSheet
val fileWriter = new java.io.FileWriter(
projConf.localExportPath / WebResource.MainStylesheet, false)
fileWriter.write(mainCss)
fileWriter.close()
// download webfonts
val (fontCss, fontUrls) = Fonts.convert(Styles.FontDescription)
FileUtils.writeStringToFile(
new File(outputDirFile, WebResource.FontsStylesheet), fontCss)
fontUrls.foreach(x => download(WebResource(x._1, WebResource.FontsRelDirname)))
// copy family tree files from JAR
copy(WebResource.TreeJs)
copy(WebResource.TreeCss)
// copy search files from JAR
copy(WebResource.SearchJs)
copy(WebResource.SearchCss)
// download other stylesheets and scripts used into appropriate directories
download(WebResource.BootstrapZip)
extractArchive(
new File(outputDirFile, WebResource.BootstrapZip.localRelFilename),
stylesDir.getPath)
download(WebResource.Jquery)
download(WebResource.D3)
download(WebResource.DataTablesJs)
download(WebResource.DataTablesCss)
download(WebResource.SortAsc)
download(WebResource.SortDesc)
download(WebResource.SortBoth)
}
// get all of the local image files referenced by a world
def getReferencedImages(world: List[WorldItem]): List[String] = {
// find a unique list of the files pointed to by meta items.
val uniqueFiles = world.collect({case x: RefItem => x}).map(_.filename).distinct
// some of these files are not actual local files, but links to remote data.
// so filter those out
uniqueFiles.filter(x => !x.startsWith("wikimedia:"))
}
// files is names of files relative to local content directory
def localFileUpdates(
files: List[String],
oldFileStatus: FileMap,
parentDir: String): FileMap = {
val currentStatus = files.map(x =>
(x, new File(parentDir / x).lastModified))
currentStatus.filter({case (k, v) => oldFileStatus.get(k) match {
case Some(x) => v > x._2
case None => true
}}).map(x => (x._1, ("", x._2))).toMap
}
def logList(prefix: String, list: scala.collection.Seq[String]): Unit = {
list.foreach(x => println(prefix + ": " + x))
}
private def writePage(outputFile: String, contents: String): Unit = {
val fileWriter = new java.io.FileWriter(outputFile, false)
fileWriter.write(contents)
fileWriter.close()
}
}
| {
"content_hash": "ed704d4db158773465fed9654fb6c374",
"timestamp": "",
"source": "github",
"line_count": 490,
"max_line_length": 140,
"avg_line_length": 34.16122448979592,
"alnum_prop": 0.6726805663420754,
"repo_name": "bdzimmer/secondary",
"id": "11896d73ff2a765f44c82ebf0089a27d6a85e5da",
"size": "16795",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/bdzimmer/secondary/export/controller/ExportProcess.scala",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "413"
},
{
"name": "CSS",
"bytes": "773"
},
{
"name": "JavaScript",
"bytes": "8350"
},
{
"name": "Scala",
"bytes": "253166"
},
{
"name": "Shell",
"bytes": "530"
},
{
"name": "TeX",
"bytes": "894"
}
],
"symlink_target": ""
} |
<?php
namespace Boodcode\ContactBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DefaultControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$crawler = $client->request('GET', '/hello/Fabien');
$this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
}
}
| {
"content_hash": "d3ae2f2175da96a3c6161aaad11b03b0",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 90,
"avg_line_length": 23.823529411764707,
"alnum_prop": 0.6790123456790124,
"repo_name": "boodcode/france",
"id": "869e675715db98db72ab1d0ee0c68f24c3d04d5f",
"size": "405",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Boodcode/ContactBundle/Tests/Controller/DefaultControllerTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "4312"
},
{
"name": "CSS",
"bytes": "117735"
},
{
"name": "HTML",
"bytes": "339428"
},
{
"name": "JavaScript",
"bytes": "56238"
},
{
"name": "PHP",
"bytes": "190132"
}
],
"symlink_target": ""
} |
package org.apache.flink.table.runtime.operators.multipleinput.output;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.streaming.api.operators.Output;
import org.apache.flink.streaming.api.operators.TwoInputStreamOperator;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.streamrecord.LatencyMarker;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.table.data.RowData;
import org.apache.flink.util.OutputTag;
/**
* An {@link Output} that can be used to emit copying elements and other messages for the second
* input of {@link TwoInputStreamOperator}.
*/
public class CopyingSecondInputOfTwoInputStreamOperatorOutput extends OutputBase {
private final TwoInputStreamOperator<RowData, RowData, RowData> operator;
private final TypeSerializer<RowData> serializer;
public CopyingSecondInputOfTwoInputStreamOperatorOutput(
TwoInputStreamOperator<RowData, RowData, RowData> operator,
TypeSerializer<RowData> serializer) {
super(operator);
this.operator = operator;
this.serializer = serializer;
}
@Override
public void emitWatermark(Watermark mark) {
try {
operator.processWatermark2(mark);
} catch (Exception e) {
throw new ExceptionInMultipleInputOperatorException(e);
}
}
@Override
public void emitLatencyMarker(LatencyMarker latencyMarker) {
try {
operator.processLatencyMarker2(latencyMarker);
} catch (Exception e) {
throw new ExceptionInMultipleInputOperatorException(e);
}
}
@Override
public void collect(StreamRecord<RowData> record) {
pushToOperator(record);
}
@Override
public <X> void collect(OutputTag<X> outputTag, StreamRecord<X> record) {
pushToOperator(record);
}
protected <X> void pushToOperator(StreamRecord<X> record) {
try {
// we know that the given outputTag matches our OutputTag so the record
// must be of the type that our operator expects.
@SuppressWarnings("unchecked")
StreamRecord<RowData> castRecord = (StreamRecord<RowData>) record;
StreamRecord<RowData> copy = castRecord.copy(serializer.copy(castRecord.getValue()));
operator.processElement2(copy);
} catch (Exception e) {
throw new ExceptionInMultipleInputOperatorException(e);
}
}
}
| {
"content_hash": "27959e4fede3b6faeb9eeb3e5ddaff0a",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 97,
"avg_line_length": 35.47222222222222,
"alnum_prop": 0.7028191072826938,
"repo_name": "kl0u/flink",
"id": "947b607e454d742ed698844957c7426504b23734",
"size": "3359",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/CopyingSecondInputOfTwoInputStreamOperatorOutput.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4722"
},
{
"name": "CSS",
"bytes": "58149"
},
{
"name": "Clojure",
"bytes": "93247"
},
{
"name": "Dockerfile",
"bytes": "12142"
},
{
"name": "FreeMarker",
"bytes": "28662"
},
{
"name": "HTML",
"bytes": "108850"
},
{
"name": "Java",
"bytes": "53696165"
},
{
"name": "JavaScript",
"bytes": "1829"
},
{
"name": "Makefile",
"bytes": "5134"
},
{
"name": "Python",
"bytes": "1132424"
},
{
"name": "Scala",
"bytes": "13885420"
},
{
"name": "Shell",
"bytes": "533455"
},
{
"name": "TSQL",
"bytes": "123113"
},
{
"name": "TypeScript",
"bytes": "249126"
}
],
"symlink_target": ""
} |
package org.apache.carbondata.hive;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.SettableStructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.typeinfo.CharTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.io.ArrayWritable;
class CarbonObjectInspector extends SettableStructObjectInspector {
private final TypeInfo typeInfo;
private final List<StructField> fields;
private final HashMap<String, StructFieldImpl> fieldsByName;
public CarbonObjectInspector(final StructTypeInfo rowTypeInfo) {
typeInfo = rowTypeInfo;
List<String> fieldNames = rowTypeInfo.getAllStructFieldNames();
List<TypeInfo> fieldInfos = rowTypeInfo.getAllStructFieldTypeInfos();
fields = new ArrayList<StructField>(fieldNames.size());
fieldsByName = new HashMap<String, StructFieldImpl>();
for (int i = 0; i < fieldNames.size(); ++i) {
final String name = fieldNames.get(i);
final TypeInfo fieldInfo = fieldInfos.get(i);
final StructFieldImpl field = new StructFieldImpl(name, getObjectInspector(fieldInfo), i);
fields.add(field);
fieldsByName.put(name, field);
}
}
private ObjectInspector getObjectInspector(final TypeInfo typeInfo) {
if (typeInfo.equals(TypeInfoFactory.doubleTypeInfo)) {
return PrimitiveObjectInspectorFactory.writableDoubleObjectInspector;
} else if (typeInfo.equals(TypeInfoFactory.intTypeInfo)) {
return PrimitiveObjectInspectorFactory.writableIntObjectInspector;
} else if (typeInfo.equals(TypeInfoFactory.longTypeInfo)) {
return PrimitiveObjectInspectorFactory.writableLongObjectInspector;
} else if (typeInfo.equals(TypeInfoFactory.stringTypeInfo)) {
return PrimitiveObjectInspectorFactory.writableStringObjectInspector;
} else if (typeInfo instanceof DecimalTypeInfo) {
return PrimitiveObjectInspectorFactory
.getPrimitiveWritableObjectInspector((DecimalTypeInfo) typeInfo);
} else if (typeInfo.getCategory().equals(Category.STRUCT)) {
return new CarbonObjectInspector((StructTypeInfo) typeInfo);
} else if (typeInfo.getCategory().equals(Category.LIST)) {
final TypeInfo subTypeInfo = ((ListTypeInfo) typeInfo).getListElementTypeInfo();
return new CarbonArrayInspector(getObjectInspector(subTypeInfo));
} else if (typeInfo.equals(TypeInfoFactory.shortTypeInfo)) {
return PrimitiveObjectInspectorFactory.writableShortObjectInspector;
} else if (typeInfo.equals(TypeInfoFactory.timestampTypeInfo)) {
return PrimitiveObjectInspectorFactory.writableTimestampObjectInspector;
} else if (typeInfo.equals(TypeInfoFactory.dateTypeInfo)) {
return PrimitiveObjectInspectorFactory.writableDateObjectInspector;
} else if (((CharTypeInfo) typeInfo).getPrimitiveCategory().name().equals("CHAR")) {
return PrimitiveObjectInspectorFactory.writableStringObjectInspector;
} else {
throw new UnsupportedOperationException("Unknown field type: " + typeInfo);
}
}
@Override public Category getCategory() {
return Category.STRUCT;
}
@Override public String getTypeName() {
return typeInfo.getTypeName();
}
@Override public List<? extends StructField> getAllStructFieldRefs() {
return fields;
}
@Override public Object getStructFieldData(final Object data, final StructField fieldRef) {
if (data == null) {
return null;
}
if (data instanceof ArrayWritable) {
final ArrayWritable arr = (ArrayWritable) data;
return arr.get()[((StructFieldImpl) fieldRef).getIndex()];
}
boolean isArray = !(data instanceof List);
int listSize = isArray ? ((Object[]) data).length : ((List) data).size();
int fieldID = fieldRef.getFieldID();
return fieldID >= listSize ?
null :
(isArray ? ((Object[]) data)[fieldID] : ((List) data).get(fieldID));
}
@Override public StructField getStructFieldRef(final String name) {
return fieldsByName.get(name);
}
@Override public List<Object> getStructFieldsDataAsList(final Object data) {
if (data == null) {
return null;
}
if (data instanceof ArrayWritable) {
final ArrayWritable arr = (ArrayWritable) data;
final Object[] arrWritable = arr.get();
return new ArrayList<Object>(Arrays.asList(arrWritable));
}
throw new UnsupportedOperationException("Cannot inspect " + data.getClass().getCanonicalName());
}
@Override public Object create() {
final ArrayList<Object> list = new ArrayList<Object>(fields.size());
for (int i = 0; i < fields.size(); ++i) {
list.add(null);
}
return list;
}
@Override public Object setStructFieldData(Object struct, StructField field, Object fieldValue) {
final ArrayList<Object> list = (ArrayList<Object>) struct;
list.set(((StructFieldImpl) field).getIndex(), fieldValue);
return list;
}
@Override public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final CarbonObjectInspector other = (CarbonObjectInspector) obj;
return !(this.typeInfo != other.typeInfo && (this.typeInfo == null || !this.typeInfo
.equals(other.typeInfo)));
}
@Override public int hashCode() {
int hash = 5;
hash = 29 * hash + (this.typeInfo != null ? this.typeInfo.hashCode() : 0);
return hash;
}
private static class StructFieldImpl implements StructField {
private final String name;
private final ObjectInspector inspector;
private final int index;
public StructFieldImpl(final String name, final ObjectInspector inspector, final int index) {
this.name = name;
this.inspector = inspector;
this.index = index;
}
@Override public String getFieldComment() {
return "";
}
@Override public String getFieldName() {
return name;
}
public int getIndex() {
return index;
}
@Override public ObjectInspector getFieldObjectInspector() {
return inspector;
}
@Override public int getFieldID() {
return index;
}
}
}
| {
"content_hash": "aff8e9b0c3d9b86463884f598ec8fbb3",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 100,
"avg_line_length": 36.10752688172043,
"alnum_prop": 0.7234961286480047,
"repo_name": "manishgupta88/carbondata",
"id": "6722dcfa188343b02fc2001257e417f8413f77a8",
"size": "7516",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "integration/hive/src/main/java/org/apache/carbondata/hive/CarbonObjectInspector.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1639"
},
{
"name": "C++",
"bytes": "104618"
},
{
"name": "CMake",
"bytes": "1555"
},
{
"name": "Java",
"bytes": "7163784"
},
{
"name": "Python",
"bytes": "19915"
},
{
"name": "Scala",
"bytes": "10950469"
},
{
"name": "Shell",
"bytes": "4349"
},
{
"name": "Smalltalk",
"bytes": "86"
},
{
"name": "Thrift",
"bytes": "26649"
}
],
"symlink_target": ""
} |
namespace WOX_Info
{
partial class MainWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this._tab_panel = new System.Windows.Forms.TabControl();
this._armor_panel = new System.Windows.Forms.TabPage();
this._armor_panel_stats_box = new System.Windows.Forms.GroupBox();
this._armor_panel_listview = new System.Windows.Forms.ListView();
this._armor_panel_select_label = new System.Windows.Forms.Label();
this._armor_panel_dropdown = new System.Windows.Forms.ComboBox();
this._weapon_panel = new System.Windows.Forms.TabPage();
this._weapon_panel_stats_box = new System.Windows.Forms.GroupBox();
this._weapon_panel_listview = new System.Windows.Forms.ListView();
this._weapon_panel_dropdown = new System.Windows.Forms.ComboBox();
this._weapon_panel_select_label = new System.Windows.Forms.Label();
this._accessories_panel = new System.Windows.Forms.TabPage();
this._accessories_panel_select_label = new System.Windows.Forms.Label();
this._accessories_panel_dropdown = new System.Windows.Forms.ComboBox();
this._accessories_panel_stats_box = new System.Windows.Forms.GroupBox();
this._accessories_panel_listview = new System.Windows.Forms.ListView();
this._tab_panel.SuspendLayout();
this._armor_panel.SuspendLayout();
this._armor_panel_stats_box.SuspendLayout();
this._weapon_panel.SuspendLayout();
this._weapon_panel_stats_box.SuspendLayout();
this._accessories_panel.SuspendLayout();
this._accessories_panel_stats_box.SuspendLayout();
this.SuspendLayout();
//
// _tab_panel
//
this._tab_panel.Controls.Add(this._armor_panel);
this._tab_panel.Controls.Add(this._weapon_panel);
this._tab_panel.Controls.Add(this._accessories_panel);
this._tab_panel.Dock = System.Windows.Forms.DockStyle.Fill;
this._tab_panel.Location = new System.Drawing.Point(0, 0);
this._tab_panel.Name = "_tab_panel";
this._tab_panel.SelectedIndex = 0;
this._tab_panel.Size = new System.Drawing.Size(362, 284);
this._tab_panel.TabIndex = 0;
//
// _armor_panel
//
this._armor_panel.BackColor = System.Drawing.Color.Transparent;
this._armor_panel.Controls.Add(this._armor_panel_stats_box);
this._armor_panel.Controls.Add(this._armor_panel_select_label);
this._armor_panel.Controls.Add(this._armor_panel_dropdown);
this._armor_panel.Location = new System.Drawing.Point(4, 22);
this._armor_panel.Name = "_armor_panel";
this._armor_panel.Padding = new System.Windows.Forms.Padding(3);
this._armor_panel.Size = new System.Drawing.Size(354, 258);
this._armor_panel.TabIndex = 0;
this._armor_panel.Text = "Armors";
//
// _armor_panel_stats_box
//
this._armor_panel_stats_box.Controls.Add(this._armor_panel_listview);
this._armor_panel_stats_box.Location = new System.Drawing.Point(11, 47);
this._armor_panel_stats_box.Name = "_armor_panel_stats_box";
this._armor_panel_stats_box.Size = new System.Drawing.Size(335, 203);
this._armor_panel_stats_box.TabIndex = 2;
this._armor_panel_stats_box.TabStop = false;
this._armor_panel_stats_box.Text = "Stats";
//
// _armor_panel_listview
//
this._armor_panel_listview.Location = new System.Drawing.Point(7, 20);
this._armor_panel_listview.Name = "_armor_panel_listview";
this._armor_panel_listview.Size = new System.Drawing.Size(322, 177);
this._armor_panel_listview.TabIndex = 0;
this._armor_panel_listview.UseCompatibleStateImageBehavior = false;
//
// _armor_panel_select_label
//
this._armor_panel_select_label.AutoSize = true;
this._armor_panel_select_label.Location = new System.Drawing.Point(8, 3);
this._armor_panel_select_label.Name = "_armor_panel_select_label";
this._armor_panel_select_label.Size = new System.Drawing.Size(73, 13);
this._armor_panel_select_label.TabIndex = 1;
this._armor_panel_select_label.Text = "Select Armor :";
//
// _armor_panel_dropdown
//
this._armor_panel_dropdown.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this._armor_panel_dropdown.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this._armor_panel_dropdown.FormattingEnabled = true;
this._armor_panel_dropdown.Location = new System.Drawing.Point(11, 19);
this._armor_panel_dropdown.Name = "_armor_panel_dropdown";
this._armor_panel_dropdown.Size = new System.Drawing.Size(121, 21);
this._armor_panel_dropdown.TabIndex = 0;
//
// _weapon_panel
//
this._weapon_panel.BackColor = System.Drawing.Color.Transparent;
this._weapon_panel.Controls.Add(this._weapon_panel_stats_box);
this._weapon_panel.Controls.Add(this._weapon_panel_dropdown);
this._weapon_panel.Controls.Add(this._weapon_panel_select_label);
this._weapon_panel.Location = new System.Drawing.Point(4, 22);
this._weapon_panel.Name = "_weapon_panel";
this._weapon_panel.Padding = new System.Windows.Forms.Padding(3);
this._weapon_panel.Size = new System.Drawing.Size(354, 258);
this._weapon_panel.TabIndex = 1;
this._weapon_panel.Text = "Weapons";
//
// _weapon_panel_stats_box
//
this._weapon_panel_stats_box.Controls.Add(this._weapon_panel_listview);
this._weapon_panel_stats_box.Location = new System.Drawing.Point(11, 47);
this._weapon_panel_stats_box.Name = "_weapon_panel_stats_box";
this._weapon_panel_stats_box.Size = new System.Drawing.Size(335, 203);
this._weapon_panel_stats_box.TabIndex = 2;
this._weapon_panel_stats_box.TabStop = false;
this._weapon_panel_stats_box.Text = "Stats";
//
// _weapon_panel_listview
//
this._weapon_panel_listview.Location = new System.Drawing.Point(7, 20);
this._weapon_panel_listview.Name = "_weapon_panel_listview";
this._weapon_panel_listview.Size = new System.Drawing.Size(322, 177);
this._weapon_panel_listview.TabIndex = 0;
this._weapon_panel_listview.UseCompatibleStateImageBehavior = false;
//
// _weapon_panel_dropdown
//
this._weapon_panel_dropdown.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this._weapon_panel_dropdown.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this._weapon_panel_dropdown.FormattingEnabled = true;
this._weapon_panel_dropdown.Location = new System.Drawing.Point(11, 19);
this._weapon_panel_dropdown.Name = "_weapon_panel_dropdown";
this._weapon_panel_dropdown.Size = new System.Drawing.Size(121, 21);
this._weapon_panel_dropdown.TabIndex = 1;
//
// _weapon_panel_select_label
//
this._weapon_panel_select_label.AutoSize = true;
this._weapon_panel_select_label.Location = new System.Drawing.Point(8, 3);
this._weapon_panel_select_label.Name = "_weapon_panel_select_label";
this._weapon_panel_select_label.Size = new System.Drawing.Size(87, 13);
this._weapon_panel_select_label.TabIndex = 0;
this._weapon_panel_select_label.Text = "Select Weapon :";
//
// _accessories_panel
//
this._accessories_panel.BackColor = System.Drawing.Color.Transparent;
this._accessories_panel.Controls.Add(this._accessories_panel_stats_box);
this._accessories_panel.Controls.Add(this._accessories_panel_dropdown);
this._accessories_panel.Controls.Add(this._accessories_panel_select_label);
this._accessories_panel.Location = new System.Drawing.Point(4, 22);
this._accessories_panel.Name = "_accessories_panel";
this._accessories_panel.Padding = new System.Windows.Forms.Padding(3);
this._accessories_panel.Size = new System.Drawing.Size(354, 258);
this._accessories_panel.TabIndex = 2;
this._accessories_panel.Text = "Accessories";
//
// _accessories_panel_select_label
//
this._accessories_panel_select_label.AutoSize = true;
this._accessories_panel_select_label.Location = new System.Drawing.Point(8, 3);
this._accessories_panel_select_label.Name = "_accessories_panel_select_label";
this._accessories_panel_select_label.Size = new System.Drawing.Size(92, 13);
this._accessories_panel_select_label.TabIndex = 0;
this._accessories_panel_select_label.Text = "Select Accessory:";
//
// _accessories_panel_dropdown
//
this._accessories_panel_dropdown.FormattingEnabled = true;
this._accessories_panel_dropdown.Location = new System.Drawing.Point(11, 19);
this._accessories_panel_dropdown.Name = "_accessories_panel_dropdown";
this._accessories_panel_dropdown.Size = new System.Drawing.Size(121, 21);
this._accessories_panel_dropdown.TabIndex = 1;
//
// _accessories_panel_stats_box
//
this._accessories_panel_stats_box.Controls.Add(this._accessories_panel_listview);
this._accessories_panel_stats_box.Location = new System.Drawing.Point(11, 47);
this._accessories_panel_stats_box.Name = "_accessories_panel_stats_box";
this._accessories_panel_stats_box.Size = new System.Drawing.Size(335, 203);
this._accessories_panel_stats_box.TabIndex = 2;
this._accessories_panel_stats_box.TabStop = false;
this._accessories_panel_stats_box.Text = "Stats";
//
// _accessories_panel_listview
//
this._accessories_panel_listview.Location = new System.Drawing.Point(7, 20);
this._accessories_panel_listview.Name = "_accessories_panel_listview";
this._accessories_panel_listview.Size = new System.Drawing.Size(322, 177);
this._accessories_panel_listview.TabIndex = 0;
this._accessories_panel_listview.UseCompatibleStateImageBehavior = false;
//
// MainWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(362, 284);
this.Controls.Add(this._tab_panel);
this.Name = "MainWindow";
this.Text = "World of Xeen Info!";
this._tab_panel.ResumeLayout(false);
this._armor_panel.ResumeLayout(false);
this._armor_panel.PerformLayout();
this._armor_panel_stats_box.ResumeLayout(false);
this._weapon_panel.ResumeLayout(false);
this._weapon_panel.PerformLayout();
this._weapon_panel_stats_box.ResumeLayout(false);
this._accessories_panel.ResumeLayout(false);
this._accessories_panel.PerformLayout();
this._accessories_panel_stats_box.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TabControl _tab_panel;
private System.Windows.Forms.TabPage _armor_panel;
private System.Windows.Forms.TabPage _weapon_panel;
private System.Windows.Forms.Label _armor_panel_select_label;
private System.Windows.Forms.ComboBox _armor_panel_dropdown;
private System.Windows.Forms.Label _weapon_panel_select_label;
private System.Windows.Forms.ComboBox _weapon_panel_dropdown;
private System.Windows.Forms.GroupBox _armor_panel_stats_box;
private System.Windows.Forms.ListView _armor_panel_listview;
private System.Windows.Forms.GroupBox _weapon_panel_stats_box;
private System.Windows.Forms.ListView _weapon_panel_listview;
private System.Windows.Forms.TabPage _accessories_panel;
private System.Windows.Forms.Label _accessories_panel_select_label;
private System.Windows.Forms.ComboBox _accessories_panel_dropdown;
private System.Windows.Forms.GroupBox _accessories_panel_stats_box;
private System.Windows.Forms.ListView _accessories_panel_listview;
}
}
| {
"content_hash": "35421b60ad031f5a296564e87b58dc7f",
"timestamp": "",
"source": "github",
"line_count": 258,
"max_line_length": 111,
"avg_line_length": 54.41860465116279,
"alnum_prop": 0.6111111111111112,
"repo_name": "SebGrenier/WOX_Info",
"id": "a7a8fd58ae758e0982fe4b1b6e4975684834a9b3",
"size": "14042",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WOX_Info/WOX_Info/MainWindow.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "38878"
}
],
"symlink_target": ""
} |
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")
. "$here\$sut"
Describe "New-Archive" {
# arrange
$content="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor."
$file = New-item "TestDrive:\one.txt" -Type File
Set-Content $file -value $content
It -skip "Should create a compressed file" {
# act
{ $archive = New-Archive $file -Type ZIP } | Should Not Throw
# archive should exist
Test-Path $archive | Should Be $true
}
}
| {
"content_hash": "472f1acc5265f4507e88949b5093c5db",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 543,
"avg_line_length": 45.65217391304348,
"alnum_prop": 0.7133333333333334,
"repo_name": "craibuc/Ps7z",
"id": "863fbb5ce5ff7d2799f196bc5e7eab0175b8c7a8",
"size": "1052",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Functions/New-Archive.Tests.ps1",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PowerShell",
"bytes": "16128"
}
],
"symlink_target": ""
} |
'use strict';
module.exports = {
scripts: {
test : 'jest --coverage',
flow : 'flow',
lint : 'npm run lint:js && npm run lint:css',
start : 'webpack-dev-server',
build : 'NODE_ENV=production webpack',
'lint:js' : 'eslint src',
changelog : 'conventional-changelog -p angular -i CHANGELOG.md -s -r 0',
'lint:css' : 'stylelint src/**/*.css',
postinstall : 'npm run flow-typed',
'flow-typed': 'flow-typed install',
'test:watch': 'jest --watch --coverage'
}
};
| {
"content_hash": "c721762d5a6189a247a192c513fb068e",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 78,
"avg_line_length": 31.88235294117647,
"alnum_prop": 0.551660516605166,
"repo_name": "abouthiroppy/dish",
"id": "6d70302bf25915ebff43f9860972eed9228510fd",
"size": "542",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "packages/generator-react-redux-application/npm/tasks.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "981"
},
{
"name": "HTML",
"bytes": "997"
},
{
"name": "JavaScript",
"bytes": "23264"
}
],
"symlink_target": ""
} |
#ifndef NXT6000_H
#define NXT6000_H
#include <linux/dvb/frontend.h>
struct nxt6000_config
{
/* the demodulator's i2c address */
u8 demod_address;
/* should clock inversion be used? */
u8 clock_inversion:1;
};
#if IS_ENABLED(CPTCFG_DVB_NXT6000)
extern struct dvb_frontend* nxt6000_attach(const struct nxt6000_config* config,
struct i2c_adapter* i2c);
#else
static inline struct dvb_frontend* nxt6000_attach(const struct nxt6000_config* config,
struct i2c_adapter* i2c)
{
printk(KERN_WARNING "%s: driver disabled by Kconfig\n", __func__);
return NULL;
}
#endif // CPTCFG_DVB_NXT6000
#endif // NXT6000_H
| {
"content_hash": "4f8233b5b6c8227b468dcc6c90f8bafe",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 86,
"avg_line_length": 21.724137931034484,
"alnum_prop": 0.7142857142857143,
"repo_name": "szehl/ath9k-hmac",
"id": "d573743535702d1ab2767fe25897b36312543328",
"size": "1521",
"binary": false,
"copies": "32",
"ref": "refs/heads/master",
"path": "backports-3.12.8-1/drivers/media/dvb-frontends/nxt6000.h",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "3462"
},
{
"name": "C",
"bytes": "56469383"
},
{
"name": "C++",
"bytes": "1574801"
},
{
"name": "Makefile",
"bytes": "101283"
},
{
"name": "Objective-C",
"bytes": "1434"
},
{
"name": "Python",
"bytes": "13851"
},
{
"name": "Shell",
"bytes": "12208"
}
],
"symlink_target": ""
} |
var _ = require('underscore');
var debug = require('debug')('launchpad:local:platform');
var platforms = {
win32 : './windows',
darwin : './macos',
linux : './unix',
freebsd : './unix',
sunos : './unix'
};
var platform = require(platforms[process.platform]);
var envBrowsers = process.env.LAUNCHPAD_BROWSERS;
var enabledBrowsers = envBrowsers ? envBrowsers.split(/\s*,\s*/) : Object.keys(platform);
debug('Local platform init. Enabled browsers:', enabledBrowsers.sort().join(', '));
module.exports = _.pick(platform, enabledBrowsers);
| {
"content_hash": "d6c5a6ff2172ca8fe573522a5dbac210",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 89,
"avg_line_length": 32.23529411764706,
"alnum_prop": 0.6824817518248175,
"repo_name": "flgiordano/netcash",
"id": "25ba016579f4ef603c831854e2b28d7bd9509f69",
"size": "548",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "node_modules/launchpad/lib/local/platform/index.js",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "622"
},
{
"name": "HTML",
"bytes": "33831"
},
{
"name": "JavaScript",
"bytes": "13859"
},
{
"name": "Shell",
"bytes": "2716"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Reactive.Streams;
using Reactor.Core;
using System.Threading;
using Reactor.Core.flow;
using Reactor.Core.subscriber;
using Reactor.Core.subscription;
using Reactor.Core.util;
namespace Reactor.Core.publisher
{
sealed class PublisherThen<T, U> : IFlux<U>, IMono<U>
{
readonly IPublisher<T> source;
readonly IPublisher<U> after;
internal PublisherThen(IPublisher<T> source, IPublisher<U> after)
{
this.source = source;
this.after = after;
}
public void Subscribe(ISubscriber<U> s)
{
if (s is IConditionalSubscriber<U>)
{
source.Subscribe(new ThenConditionalSubscriber((IConditionalSubscriber<U>)s, after));
}
else
{
source.Subscribe(new ThenSubscriber(s, after));
}
}
sealed class ThenSubscriber : ISubscriber<T>, ISubscription
{
readonly ISubscriber<U> actual;
readonly IPublisher<U> after;
ISubscription s;
ISubscription z;
long requested;
internal ThenSubscriber(ISubscriber<U> actual, IPublisher<U> after)
{
this.actual = actual;
this.after = after;
}
public void Cancel()
{
s.Cancel();
SubscriptionHelper.Cancel(ref z);
}
public void OnComplete()
{
after.Subscribe(new OtherSubscriber(this, actual));
}
public void OnError(Exception e)
{
actual.OnError(e);
}
public void OnNext(T t)
{
// ignored
}
public void OnSubscribe(ISubscription s)
{
if (SubscriptionHelper.Validate(ref this.s, s))
{
actual.OnSubscribe(this);
s.Request(long.MaxValue);
}
}
public void Request(long n)
{
BackpressureHelper.DeferredRequest(ref z, ref requested, n);
}
internal void AfterSubscribe(ISubscription s)
{
BackpressureHelper.DeferredSetOnce(ref z, ref requested, s);
}
sealed class OtherSubscriber : ISubscriber<U>
{
readonly ThenSubscriber parent;
readonly ISubscriber<U> actual;
internal OtherSubscriber(ThenSubscriber parent, ISubscriber<U> actual)
{
this.parent = parent;
this.actual = actual;
}
public void OnSubscribe(ISubscription s)
{
parent.AfterSubscribe(s);
}
public void OnNext(U t)
{
actual.OnNext(t);
}
public void OnError(Exception e)
{
actual.OnError(e);
}
public void OnComplete()
{
actual.OnComplete();
}
}
}
sealed class ThenConditionalSubscriber : ISubscriber<T>, ISubscription
{
readonly IConditionalSubscriber<U> actual;
readonly IPublisher<U> after;
ISubscription s;
ISubscription z;
long requested;
internal ThenConditionalSubscriber(IConditionalSubscriber<U> actual, IPublisher<U> after)
{
this.actual = actual;
this.after = after;
}
public void Cancel()
{
s.Cancel();
SubscriptionHelper.Cancel(ref z);
}
public void OnComplete()
{
after.Subscribe(new OtherSubscriber(this, actual));
}
public void OnError(Exception e)
{
actual.OnError(e);
}
public void OnNext(T t)
{
// ignored
}
public void OnSubscribe(ISubscription s)
{
if (SubscriptionHelper.Validate(ref this.s, s))
{
actual.OnSubscribe(this);
s.Request(long.MaxValue);
}
}
public void Request(long n)
{
BackpressureHelper.DeferredRequest(ref z, ref requested, n);
}
internal void AfterSubscribe(ISubscription s)
{
BackpressureHelper.DeferredSetOnce(ref z, ref requested, s);
}
sealed class OtherSubscriber : IConditionalSubscriber<U>
{
readonly ThenConditionalSubscriber parent;
readonly IConditionalSubscriber<U> actual;
internal OtherSubscriber(ThenConditionalSubscriber parent, IConditionalSubscriber<U> actual)
{
this.parent = parent;
this.actual = actual;
}
public void OnSubscribe(ISubscription s)
{
parent.AfterSubscribe(s);
}
public void OnNext(U t)
{
actual.OnNext(t);
}
public bool TryOnNext(U t)
{
return actual.TryOnNext(t);
}
public void OnError(Exception e)
{
actual.OnError(e);
}
public void OnComplete()
{
actual.OnComplete();
}
}
}
}
}
| {
"content_hash": "033f37e3723ef50806b9dd06095ca228",
"timestamp": "",
"source": "github",
"line_count": 232,
"max_line_length": 108,
"avg_line_length": 25.982758620689655,
"alnum_prop": 0.46798274717982746,
"repo_name": "reactor/reactor-core-dotnet",
"id": "519d9d72d3f0d7ecf4e809d0a9aa20a2f4388bd6",
"size": "6030",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Reactor.Core/publisher/PublisherThen.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "1519919"
}
],
"symlink_target": ""
} |
package org.jetbrains.plugins.scala.lang.completion.weighter
import com.intellij.codeInsight.completion._
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.plugins.scala.lang.completion.ScalaSmartCompletionContributor.ReferenceWithElement
import org.jetbrains.plugins.scala.lang.completion.{ScalaAfterNewCompletionUtil, ScalaCompletionUtil, ScalaSmartCompletionContributor}
import org.jetbrains.plugins.scala.lang.psi.api.expr.ScNewTemplateDefinition
import org.jetbrains.plugins.scala.lang.psi.types.ScType
import org.jetbrains.plugins.scala.lang.refactoring.util.ScalaNamesUtil
/**
* Created by Kate Ustyuzhanina on 12/2/16.
*/
object ScalaCompletionSorting {
def addScalaSorting(parameters: CompletionParameters, result: CompletionResultSet): CompletionResultSet = {
val isSmart = parameters.getCompletionType == CompletionType.SMART
val position = ScalaCompletionUtil.positionFromParameters(parameters)
val isAfterNew = ScalaAfterNewCompletionUtil.afterNewPattern.accepts(position)
var sorter = CompletionSorter.defaultSorter(parameters, result.getPrefixMatcher)
val expectedTypes: Array[ScType] = ScalaSmartCompletionContributor.extractReference(position) match {
case Some(ReferenceWithElement(reference, _)) => reference.expectedTypes()
case _ if isAfterNew =>
Option(PsiTreeUtil.getContextOfType(position, classOf[ScNewTemplateDefinition])).map(_.expectedTypes()).getOrElse(Array.empty);
case _ => Array.empty
}
if (!isSmart && isAfterNew) {
sorter = sorter.weighBefore("liftShorter", new ScalaByTypeWeigher(position))
sorter = sorter.weighAfter("scalaTypeCompletionWeigher", new ScalaByExpectedTypeWeigher(expectedTypes, position))
} else if (!isSmart) {
sorter = sorter.weighBefore("scalaContainingClassWeigher", new ScalaByTypeWeigher(position))
sorter = sorter.weighAfter("scalaKindWeigher", new ScalaByExpectedTypeWeigher(expectedTypes, position))
}
class BacktickedsPrefixMatcher(other: PrefixMatcher) extends PrefixMatcher(other.getPrefix) {
private val matcherWithoutBackticks = other.cloneWithPrefix(cleanHelper(myPrefix))
override def prefixMatches(name: String): Boolean =
if (myPrefix == "`") other.prefixMatches(name)
else matcherWithoutBackticks.prefixMatches(ScalaNamesUtil.clean(name))
override def cloneWithPrefix(prefix: String): PrefixMatcher = matcherWithoutBackticks.cloneWithPrefix(prefix)
override def isStartMatch(name: String): Boolean =
if (myPrefix == "`") other.isStartMatch(name)
else matcherWithoutBackticks.isStartMatch(ScalaNamesUtil.clean(name))
private def cleanHelper(prefix: String): String = {
if (prefix == null || prefix.isEmpty || prefix == "`") prefix
else prefix match {
case ScalaNamesUtil.isBacktickedName(s) => s
case p if p.head == '`' => p.substring(1)
case p if p.last == '`' => prefix.substring(0, prefix.length - 1)
case _ => prefix
}
}
}
result
.withRelevanceSorter(sorter)
.withPrefixMatcher(new BacktickedsPrefixMatcher(result.getPrefixMatcher))
}
} | {
"content_hash": "5fda8b1bf8f5ec550fb1cdac82547ae4",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 135,
"avg_line_length": 48.96923076923077,
"alnum_prop": 0.7499214577442664,
"repo_name": "loskutov/intellij-scala",
"id": "3617e156e913fbdc2b7d3c247efb5eb4c2ff997e",
"size": "3183",
"binary": false,
"copies": "2",
"ref": "refs/heads/idea172.x-better-implicits",
"path": "src/org/jetbrains/plugins/scala/lang/completion/weighter/ScalaCompletionSorting.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "55566"
},
{
"name": "Java",
"bytes": "1397858"
},
{
"name": "Lex",
"bytes": "35728"
},
{
"name": "Scala",
"bytes": "11387086"
},
{
"name": "Shell",
"bytes": "537"
}
],
"symlink_target": ""
} |
package net.sourceforge.stripes.validation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Documented;
/**
* <p>Annotation that marks a method in an ActionBean as a validation method. Validation methods
* are invoked after required field checks, type conversion and validations specified in
* {@literal @}Validate annotations, but before event handler methods.</p>
*
* <p>Validation methods must be public, may return any type (though any return will be ignored
* by Stripes) and may throw any exceptions. They make take either zero parameters, or a single
* parameter of type {@link ValidationErrors}. When validation methods are invoked all binding
* will have taken place and the ActionBean will have access to the
* {@link net.sourceforge.stripes.action.ActionBeanContext}, therefore methods that do not take
* ValidationErrors as a parameter may retrieve it by calling
* {@link net.sourceforge.stripes.action.ActionBeanContext#getValidationErrors()}.</p>
*
* <p>The attributes of this annotation confer significant control over when a validation method
* will be run. When a single ActionBean class has multiple validation methods the ordering
* of them can be specified using the priority attribute. Methods with lower values (i.e. nearer
* zero) are executed before those with higher values.</p>
*
* <p>The {@code on} attribute controls which events the validation method should be invoked for.
* It should be noted that the 'on' attribute is completely optional. If omitted then the
* validation method will be invoked for all events not annotated with {@literal @}DontValidate.
* The on attribute can take one of two forms. It can specify a list of events to apply the
* validation method to, for example 'on={"save", "update"}', in which case it will be invoked only
* for those events. It can alternatively specify a list of events <i>not</i> to apply the
* validation to, for example 'on="!delete"', in which case the validation will be run for all
* events except those listed.</p>
*
* <p>The {@code when} attribute controls whether or not the validation method is executed when
* one or more validation errors exist. It has no affect when there are no validation errors.
* A value of {@link ValidationState#ALWAYS} will cause the method to be invoked even if errors
* exist. This is useful when you wish to perform additional validations that do not depend
* on having a well-validated ActionBean since it allows the user to see more validation errors
* at the same time. A value of {@link ValidationState#NO_ERRORS} causes the method to be invoked
* only when there are no pre-existing validation errors. This is useful if the method relies on
* a valid ActionBean and might throw exceptions otherwise. The value
* {@link ValidationState#DEFAULT} causes Stripes to apply the system level default for this
* attribute.</p>
*
* <p>The default behaviour is such that if validation errors arise from the annotated
* validations (or type conversion), validation methods will not be called (nor will the handler
* method). This behaviour is configurable though. Please see the Stripes documentation on
* <a href="http://stripesframework.org/display/stripes/Configuration+Reference">Configuration</a>
* if you would prefer the default behaviour to be to invoke validation methods when validation errors
* have been generated by type conversion and annotation based validation.</p>
*
* @author Tim Fennell
* @since Stripes 1.3
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface ValidationMethod {
/**
* If there are multiple validation methods in an ActionBean, what is the priority of
* this one? Lower values == higher priorities and will get run before methods with
* higher values. If methods have the same priority they are executed in alphabetical
* order.
*/
int priority() default 0;
/**
* Allows the validation method to be restricted to one or more events. By default the
* validation method will execute on all events not marked with {@literal @}DontValidate.
* Can be used to specify one or more events to apply the method to (e.g. on={"save", "update"})
* or to specify one or more events <i>not</i> to apply the method to
* (e.g. on="!delete").
*/
String[] on() default {};
/**
* Controls whether or not the validation method will be executed when earlier phases of
* validation generated validation errors. Valid values are {@link ValidationState#ALWAYS},
* {@link ValidationState#NO_ERRORS} and {@link ValidationState#DEFAULT}. By specifying
* {@code ALWAYS} you can ensure that all error messages are presented to the user at once.
* By specifying {@code NO_ERRORS} you can be sure of the state of the ActionBean has been
* validated successfully prior to execution.
*/
ValidationState when() default ValidationState.DEFAULT;
}
| {
"content_hash": "a0cd9806882d30663a97482b33c8bb9c",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 102,
"avg_line_length": 58.18181818181818,
"alnum_prop": 0.750390625,
"repo_name": "bgoodin/silver-stripes",
"id": "7fec65bfb06e22cf3860330e6c6e4e415933f5d3",
"size": "5716",
"binary": false,
"copies": "5",
"ref": "refs/heads/development",
"path": "stripes/src/main/java/net/sourceforge/stripes/validation/ValidationMethod.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6578"
},
{
"name": "Groovy",
"bytes": "13842"
},
{
"name": "Java",
"bytes": "2011999"
},
{
"name": "JavaScript",
"bytes": "1435"
}
],
"symlink_target": ""
} |
package oap.util;
import oap.util.function.Functions;
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
public class Collectors {
public static final Set<Collector.Characteristics> CH_ID
= Collections.unmodifiableSet( EnumSet.of( Collector.Characteristics.IDENTITY_FINISH ) );
public static <T, K, U> Collector<T, ?, LinkedHashMap<K, U>> toLinkedHashMap( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper ) {
return java.util.stream.Collectors.toMap( keyMapper, valueMapper, throwingMerger(), LinkedHashMap::new );
}
private static <T> BinaryOperator<T> throwingMerger() {
return ( u, v ) -> {
throw new IllegalStateException( String.format( "Duplicate key %s", u ) );
};
}
public static class CollectorImpl<T, A, R> implements Collector<T, A, R> {
private final Supplier<A> supplier;
private final BiConsumer<A, T> accumulator;
private final BinaryOperator<A> combiner;
private final Function<A, R> finisher;
private final Set<Characteristics> characteristics;
public CollectorImpl( Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner,
Function<A, R> finisher, Set<Characteristics> characteristics ) {
this.supplier = supplier;
this.accumulator = accumulator;
this.combiner = combiner;
this.finisher = finisher;
this.characteristics = characteristics;
}
public CollectorImpl( Supplier<A> supplier, BiConsumer<A, T> accumulator,
BinaryOperator<A> combiner,
Set<Characteristics> characteristics ) {
this( supplier, accumulator, combiner, Functions.empty.identity(), characteristics );
}
@Override
public Supplier<A> supplier() {
return supplier;
}
@Override
public BiConsumer<A, T> accumulator() {
return accumulator;
}
@Override
public BinaryOperator<A> combiner() {
return combiner;
}
@Override
public Function<A, R> finisher() {
return finisher;
}
@Override
public Set<Characteristics> characteristics() {
return characteristics;
}
}
}
| {
"content_hash": "e80b6e05fb050599af6f7d02a436bcda",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 130,
"avg_line_length": 34.607594936708864,
"alnum_prop": 0.6115581565471836,
"repo_name": "oaplatform/oap",
"id": "7c5cccd713612d3637942502a78fff655dd190ba",
"size": "3894",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "oap-stdlib/src/main/java/oap/util/Collectors.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "17734"
},
{
"name": "Java",
"bytes": "2499156"
},
{
"name": "Shell",
"bytes": "4123"
}
],
"symlink_target": ""
} |
<a href="{{url}}">{{displayName}}</a> | {
"content_hash": "fc201d241ab708bb2e7235010beea786",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 37,
"avg_line_length": 37,
"alnum_prop": 0.5405405405405406,
"repo_name": "xSkara/core-ui",
"id": "e675ab4da3c041b35e5de4f46f3e5a9a29573fed",
"size": "37",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "demo/public/app/templates/navBarItem.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "267167"
},
{
"name": "HTML",
"bytes": "15372"
},
{
"name": "JavaScript",
"bytes": "3573084"
}
],
"symlink_target": ""
} |
package org.elasticsearch.xpack.security.authc;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.Supplier;
import org.elasticsearch.ElasticsearchSecurityException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.ContextPreservingActionListener;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.cache.Cache;
import org.elasticsearch.common.cache.CacheBuilder;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.node.Node;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportMessage;
import org.elasticsearch.xpack.core.common.IteratingActionListener;
import org.elasticsearch.xpack.core.security.authc.Authentication;
import org.elasticsearch.xpack.core.security.authc.Authentication.AuthenticationType;
import org.elasticsearch.xpack.core.security.authc.Authentication.RealmRef;
import org.elasticsearch.xpack.core.security.authc.AuthenticationFailureHandler;
import org.elasticsearch.xpack.core.security.authc.AuthenticationResult;
import org.elasticsearch.xpack.core.security.authc.AuthenticationServiceField;
import org.elasticsearch.xpack.core.security.authc.AuthenticationToken;
import org.elasticsearch.xpack.core.security.authc.Realm;
import org.elasticsearch.xpack.core.security.authz.AuthorizationEngine.EmptyAuthorizationInfo;
import org.elasticsearch.xpack.core.security.support.Exceptions;
import org.elasticsearch.xpack.core.security.user.AnonymousUser;
import org.elasticsearch.xpack.core.security.user.SystemUser;
import org.elasticsearch.xpack.core.security.user.User;
import org.elasticsearch.xpack.security.audit.AuditTrail;
import org.elasticsearch.xpack.security.audit.AuditTrailService;
import org.elasticsearch.xpack.security.audit.AuditUtil;
import org.elasticsearch.xpack.security.authc.support.RealmUserLookup;
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import static org.elasticsearch.xpack.security.support.SecurityIndexManager.isIndexDeleted;
import static org.elasticsearch.xpack.security.support.SecurityIndexManager.isMoveFromRedToNonRed;
/**
* An authentication service that delegates the authentication process to its configured {@link Realm realms}.
* This service also supports request level caching of authenticated users (i.e. once a user authenticated
* successfully, it is set on the request context to avoid subsequent redundant authentication process)
*/
public class AuthenticationService {
static final Setting<Boolean> SUCCESS_AUTH_CACHE_ENABLED =
Setting.boolSetting("xpack.security.authc.success_cache.enabled", true, Property.NodeScope);
private static final Setting<Integer> SUCCESS_AUTH_CACHE_MAX_SIZE =
Setting.intSetting("xpack.security.authc.success_cache.size", 10000, Property.NodeScope);
private static final Setting<TimeValue> SUCCESS_AUTH_CACHE_EXPIRE_AFTER_ACCESS =
Setting.timeSetting("xpack.security.authc.success_cache.expire_after_access", TimeValue.timeValueHours(1L), Property.NodeScope);
private static final Logger logger = LogManager.getLogger(AuthenticationService.class);
private final Realms realms;
private final AuditTrail auditTrail;
private final AuthenticationFailureHandler failureHandler;
private final ThreadContext threadContext;
private final String nodeName;
private final AnonymousUser anonymousUser;
private final TokenService tokenService;
private final Cache<String, Realm> lastSuccessfulAuthCache;
private final AtomicLong numInvalidation = new AtomicLong();
private final ApiKeyService apiKeyService;
private final boolean runAsEnabled;
private final boolean isAnonymousUserEnabled;
public AuthenticationService(Settings settings, Realms realms, AuditTrailService auditTrail,
AuthenticationFailureHandler failureHandler, ThreadPool threadPool,
AnonymousUser anonymousUser, TokenService tokenService, ApiKeyService apiKeyService) {
this.nodeName = Node.NODE_NAME_SETTING.get(settings);
this.realms = realms;
this.auditTrail = auditTrail;
this.failureHandler = failureHandler;
this.threadContext = threadPool.getThreadContext();
this.anonymousUser = anonymousUser;
this.runAsEnabled = AuthenticationServiceField.RUN_AS_ENABLED.get(settings);
this.isAnonymousUserEnabled = AnonymousUser.isAnonymousEnabled(settings);
this.tokenService = tokenService;
if (SUCCESS_AUTH_CACHE_ENABLED.get(settings)) {
this.lastSuccessfulAuthCache = CacheBuilder.<String, Realm>builder()
.setMaximumWeight(Integer.toUnsignedLong(SUCCESS_AUTH_CACHE_MAX_SIZE.get(settings)))
.setExpireAfterAccess(SUCCESS_AUTH_CACHE_EXPIRE_AFTER_ACCESS.get(settings))
.build();
} else {
this.lastSuccessfulAuthCache = null;
}
this.apiKeyService = apiKeyService;
}
/**
* Authenticates the user that is associated with the given request. If the user was authenticated successfully (i.e.
* a user was indeed associated with the request and the credentials were verified to be valid), the method returns
* the user and that user is then "attached" to the request's context.
*
* @param request The request to be authenticated
*/
public void authenticate(RestRequest request, ActionListener<Authentication> authenticationListener) {
createAuthenticator(request, authenticationListener).authenticateAsync();
}
/**
* Authenticates the user that is associated with the given message. If the user was authenticated successfully (i.e.
* a user was indeed associated with the request and the credentials were verified to be valid), the method returns
* the user and that user is then "attached" to the message's context. If no user was found to be attached to the given
* message, then the given fallback user will be returned instead.
*
* @param action The action of the message
* @param message The message to be authenticated
* @param fallbackUser The default user that will be assumed if no other user is attached to the message. Can be
* {@code null}, in which case there will be no fallback user and the success/failure of the
* authentication will be based on the whether there's an attached user to in the message and
* if there is, whether its credentials are valid.
*/
public void authenticate(String action, TransportMessage message, User fallbackUser, ActionListener<Authentication> listener) {
createAuthenticator(action, message, fallbackUser, listener).authenticateAsync();
}
/**
* Authenticates the user based on the contents of the token that is provided as parameter. This will not look at the values in the
* ThreadContext for Authentication.
*
* @param action The action of the message
* @param message The message that resulted in this authenticate call
* @param token The token (credentials) to be authenticated
*/
public void authenticate(String action, TransportMessage message,
AuthenticationToken token, ActionListener<Authentication> listener) {
new Authenticator(action, message, null, listener).authenticateToken(token);
}
public void expire(String principal) {
if (lastSuccessfulAuthCache != null) {
numInvalidation.incrementAndGet();
lastSuccessfulAuthCache.invalidate(principal);
}
}
public void expireAll() {
if (lastSuccessfulAuthCache != null) {
numInvalidation.incrementAndGet();
lastSuccessfulAuthCache.invalidateAll();
}
}
public void onSecurityIndexStateChange(SecurityIndexManager.State previousState, SecurityIndexManager.State currentState) {
if (lastSuccessfulAuthCache != null) {
if (isMoveFromRedToNonRed(previousState, currentState) || isIndexDeleted(previousState, currentState)) {
expireAll();
}
}
}
// pkg private method for testing
Authenticator createAuthenticator(RestRequest request, ActionListener<Authentication> listener) {
return new Authenticator(request, listener);
}
// pkg private method for testing
Authenticator createAuthenticator(String action, TransportMessage message, User fallbackUser, ActionListener<Authentication> listener) {
return new Authenticator(action, message, fallbackUser, listener);
}
// pkg private method for testing
long getNumInvalidation() {
return numInvalidation.get();
}
/**
* This class is responsible for taking a request and executing the authentication. The authentication is executed in an asynchronous
* fashion in order to avoid blocking calls on a network thread. This class also performs the auditing necessary around authentication
*/
class Authenticator {
private final AuditableRequest request;
private final User fallbackUser;
private final List<Realm> defaultOrderedRealmList;
private final ActionListener<Authentication> listener;
private RealmRef authenticatedBy = null;
private RealmRef lookedupBy = null;
private AuthenticationToken authenticationToken = null;
private AuthenticationResult authenticationResult = null;
Authenticator(RestRequest request, ActionListener<Authentication> listener) {
this(new AuditableRestRequest(auditTrail, failureHandler, threadContext, request), null, listener);
}
Authenticator(String action, TransportMessage message, User fallbackUser, ActionListener<Authentication> listener) {
this(new AuditableTransportRequest(auditTrail, failureHandler, threadContext, action, message
), fallbackUser, listener);
}
private Authenticator(AuditableRequest auditableRequest, User fallbackUser, ActionListener<Authentication> listener) {
this.request = auditableRequest;
this.fallbackUser = fallbackUser;
this.defaultOrderedRealmList = realms.asList();
this.listener = listener;
}
/**
* This method starts the authentication process. The authentication process can be broken down into distinct operations. In order,
* these operations are:
*
* <ol>
* <li>look for existing authentication {@link #lookForExistingAuthentication(Consumer)}</li>
* <li>look for a user token</li>
* <li>token extraction {@link #extractToken(Consumer)}</li>
* <li>token authentication {@link #consumeToken(AuthenticationToken)}</li>
* <li>user lookup for run as if necessary {@link #consumeUser(User, Map)} and
* {@link #lookupRunAsUser(User, String, Consumer)}</li>
* <li>write authentication into the context {@link #finishAuthentication(User)}</li>
* </ol>
*/
private void authenticateAsync() {
if (defaultOrderedRealmList.isEmpty()) {
// this happens when the license state changes between the call to authenticate and the actual invocation
// to get the realm list
listener.onResponse(null);
} else {
lookForExistingAuthentication((authentication) -> {
if (authentication != null) {
listener.onResponse(authentication);
} else {
tokenService.getAndValidateToken(threadContext, ActionListener.wrap(userToken -> {
if (userToken != null) {
writeAuthToContext(userToken.getAuthentication());
} else {
checkForApiKey();
}
}, e -> {
if (e instanceof ElasticsearchSecurityException &&
tokenService.isExpiredTokenException((ElasticsearchSecurityException) e) == false) {
// intentionally ignore the returned exception; we call this primarily
// for the auditing as we already have a purpose built exception
request.tamperedRequest();
}
listener.onFailure(e);
}));
}
});
}
}
private void checkForApiKey() {
apiKeyService.authenticateWithApiKeyIfPresent(threadContext, ActionListener.wrap(authResult -> {
if (authResult.isAuthenticated()) {
final User user = authResult.getUser();
authenticatedBy = new RealmRef(ApiKeyService.API_KEY_REALM_NAME, ApiKeyService.API_KEY_REALM_TYPE, nodeName);
writeAuthToContext(new Authentication(user, authenticatedBy, null, Version.CURRENT,
Authentication.AuthenticationType.API_KEY, authResult.getMetadata()));
} else if (authResult.getStatus() == AuthenticationResult.Status.TERMINATE) {
Exception e = (authResult.getException() != null) ? authResult.getException()
: Exceptions.authenticationError(authResult.getMessage());
listener.onFailure(e);
} else {
if (authResult.getMessage() != null) {
if (authResult.getException() != null) {
logger.warn(new ParameterizedMessage("Authentication using apikey failed - {}", authResult.getMessage()),
authResult.getException());
} else {
logger.warn("Authentication using apikey failed - {}", authResult.getMessage());
}
}
extractToken(this::consumeToken);
}
},
e -> listener.onFailure(request.exceptionProcessingRequest(e, null))));
}
/**
* Looks to see if the request contains an existing {@link Authentication} and if so, that authentication will be used. The
* consumer is called if no exception was thrown while trying to read the authentication and may be called with a {@code null}
* value
*/
private void lookForExistingAuthentication(Consumer<Authentication> authenticationConsumer) {
Runnable action;
try {
final Authentication authentication = Authentication.readFromContext(threadContext);
if (authentication != null && request instanceof AuditableRestRequest) {
action = () -> listener.onFailure(request.tamperedRequest());
} else {
action = () -> authenticationConsumer.accept(authentication);
}
} catch (Exception e) {
logger.error((Supplier<?>)
() -> new ParameterizedMessage("caught exception while trying to read authentication from request [{}]", request),
e);
action = () -> listener.onFailure(request.tamperedRequest());
}
// While we could place this call in the try block, the issue is that we catch all exceptions and could catch exceptions that
// have nothing to do with a tampered request.
action.run();
}
/**
* Attempts to extract an {@link AuthenticationToken} from the request by iterating over the {@link Realms} and calling
* {@link Realm#token(ThreadContext)}. The first non-null token that is returned will be used. The consumer is only called if
* no exception was caught during the extraction process and may be called with a {@code null} token.
*/
// pkg-private accessor testing token extraction with a consumer
void extractToken(Consumer<AuthenticationToken> consumer) {
Runnable action = () -> consumer.accept(null);
try {
if (authenticationToken != null) {
action = () -> consumer.accept(authenticationToken);
} else {
for (Realm realm : defaultOrderedRealmList) {
final AuthenticationToken token = realm.token(threadContext);
if (token != null) {
action = () -> consumer.accept(token);
break;
}
}
}
} catch (Exception e) {
logger.warn("An exception occurred while attempting to find authentication credentials", e);
action = () -> listener.onFailure(request.exceptionProcessingRequest(e, null));
}
action.run();
}
/**
* Consumes the {@link AuthenticationToken} provided by the caller. In the case of a {@code null} token, {@link #handleNullToken()}
* is called. In the case of a {@code non-null} token, the realms are iterated over in the order defined in the configuration
* while possibly also taking into consideration the last realm that authenticated this principal. When consulting multiple realms,
* the first realm that returns a non-null {@link User} is the authenticating realm and iteration is stopped. This user is then
* passed to {@link #consumeUser(User, Map)} if no exception was caught while trying to authenticate the token
*/
private void consumeToken(AuthenticationToken token) {
if (token == null) {
handleNullToken();
} else {
authenticationToken = token;
final List<Realm> realmsList = getRealmList(authenticationToken.principal());
final long startInvalidation = numInvalidation.get();
final Map<Realm, Tuple<String, Exception>> messages = new LinkedHashMap<>();
final BiConsumer<Realm, ActionListener<User>> realmAuthenticatingConsumer = (realm, userListener) -> {
if (realm.supports(authenticationToken)) {
realm.authenticate(authenticationToken, ActionListener.wrap((result) -> {
assert result != null : "Realm " + realm + " produced a null authentication result";
if (result.getStatus() == AuthenticationResult.Status.SUCCESS) {
// user was authenticated, populate the authenticated by information
authenticatedBy = new RealmRef(realm.name(), realm.type(), nodeName);
authenticationResult = result;
if (lastSuccessfulAuthCache != null && startInvalidation == numInvalidation.get()) {
lastSuccessfulAuthCache.put(authenticationToken.principal(), realm);
}
userListener.onResponse(result.getUser());
} else {
// the user was not authenticated, call this so we can audit the correct event
request.realmAuthenticationFailed(authenticationToken, realm.name());
if (result.getStatus() == AuthenticationResult.Status.TERMINATE) {
logger.info("Authentication of [{}] was terminated by realm [{}] - {}",
authenticationToken.principal(), realm.name(), result.getMessage());
Exception e = (result.getException() != null) ? result.getException()
: Exceptions.authenticationError(result.getMessage());
userListener.onFailure(e);
} else {
if (result.getMessage() != null) {
messages.put(realm, new Tuple<>(result.getMessage(), result.getException()));
}
userListener.onResponse(null);
}
}
}, (ex) -> {
logger.warn(new ParameterizedMessage(
"An error occurred while attempting to authenticate [{}] against realm [{}]",
authenticationToken.principal(), realm.name()), ex);
userListener.onFailure(ex);
}));
} else {
userListener.onResponse(null);
}
};
final IteratingActionListener<User, Realm> authenticatingListener =
new IteratingActionListener<>(ContextPreservingActionListener.wrapPreservingContext(ActionListener.wrap(
(user) -> consumeUser(user, messages),
(e) -> listener.onFailure(request.exceptionProcessingRequest(e, token))), threadContext),
realmAuthenticatingConsumer, realmsList, threadContext);
try {
authenticatingListener.run();
} catch (Exception e) {
listener.onFailure(request.exceptionProcessingRequest(e, token));
}
}
}
/**
* Possibly reorders the realm list depending on whether this principal has been recently authenticated by a specific realm
*
* @param principal The principal of the {@link AuthenticationToken} to be authenticated by a realm
* @return a list of realms ordered based on which realm should authenticate the current {@link AuthenticationToken}
*/
private List<Realm> getRealmList(String principal) {
final List<Realm> orderedRealmList = this.defaultOrderedRealmList;
if (lastSuccessfulAuthCache != null) {
final Realm lastSuccess = lastSuccessfulAuthCache.get(principal);
if (lastSuccess != null) {
final int index = orderedRealmList.indexOf(lastSuccess);
if (index > 0) {
final List<Realm> smartOrder = new ArrayList<>(orderedRealmList.size());
smartOrder.add(lastSuccess);
for (int i = 1; i < orderedRealmList.size(); i++) {
if (i != index) {
smartOrder.add(orderedRealmList.get(i));
}
}
return Collections.unmodifiableList(smartOrder);
}
}
}
return orderedRealmList;
}
/**
* Handles failed extraction of an authentication token. This can happen in a few different scenarios:
*
* <ul>
* <li>this is an initial request from a client without preemptive authentication, so we must return an authentication
* challenge</li>
* <li>this is a request made internally within a node and there is a fallback user, which is typically the
* {@link SystemUser}</li>
* <li>anonymous access is enabled and this will be considered an anonymous request</li>
* </ul>
*
* Regardless of the scenario, this method will call the listener with either failure or success.
*/
// pkg-private for tests
void handleNullToken() {
final Authentication authentication;
if (fallbackUser != null) {
RealmRef authenticatedBy = new RealmRef("__fallback", "__fallback", nodeName);
authentication = new Authentication(fallbackUser, authenticatedBy, null, Version.CURRENT, AuthenticationType.INTERNAL,
Collections.emptyMap());
} else if (isAnonymousUserEnabled) {
RealmRef authenticatedBy = new RealmRef("__anonymous", "__anonymous", nodeName);
authentication = new Authentication(anonymousUser, authenticatedBy, null, Version.CURRENT, AuthenticationType.ANONYMOUS,
Collections.emptyMap());
} else {
authentication = null;
}
Runnable action;
if (authentication != null) {
action = () -> writeAuthToContext(authentication);
} else {
action = () -> listener.onFailure(request.anonymousAccessDenied());
}
// we assign the listener call to an action to avoid calling the listener within a try block and auditing the wrong thing when
// an exception bubbles up even after successful authentication
action.run();
}
/**
* Consumes the {@link User} that resulted from attempting to authenticate a token against the {@link Realms}. When the user is
* {@code null}, authentication fails and does not proceed. When there is a user, the request is inspected to see if the run as
* functionality is in use. When run as is not in use, {@link #finishAuthentication(User)} is called, otherwise we try to lookup
* the run as user in {@link #lookupRunAsUser(User, String, Consumer)}
*/
private void consumeUser(User user, Map<Realm, Tuple<String, Exception>> messages) {
if (user == null) {
messages.forEach((realm, tuple) -> {
final String message = tuple.v1();
final String cause = tuple.v2() == null ? "" : " (Caused by " + tuple.v2() + ")";
logger.warn("Authentication to realm {} failed - {}{}", realm.name(), message, cause);
});
List<Realm> unlicensedRealms = realms.getUnlicensedRealms();
if (unlicensedRealms.isEmpty() == false) {
logger.warn("Authentication failed using realms [{}]." +
" Realms [{}] were skipped because they are not permitted on the current license",
Strings.collectionToCommaDelimitedString(defaultOrderedRealmList),
Strings.collectionToCommaDelimitedString(unlicensedRealms));
}
listener.onFailure(request.authenticationFailed(authenticationToken));
} else {
threadContext.putTransient(AuthenticationResult.THREAD_CONTEXT_KEY, authenticationResult);
if (runAsEnabled) {
final String runAsUsername = threadContext.getHeader(AuthenticationServiceField.RUN_AS_USER_HEADER);
if (runAsUsername != null && runAsUsername.isEmpty() == false) {
lookupRunAsUser(user, runAsUsername, this::finishAuthentication);
} else if (runAsUsername == null) {
finishAuthentication(user);
} else {
assert runAsUsername.isEmpty() : "the run as username may not be empty";
logger.debug("user [{}] attempted to runAs with an empty username", user.principal());
listener.onFailure(request.runAsDenied(
new Authentication(new User(runAsUsername, null, user), authenticatedBy, lookedupBy), authenticationToken));
}
} else {
finishAuthentication(user);
}
}
}
/**
* Iterates over the realms and attempts to lookup the run as user by the given username. The consumer will be called regardless of
* if the user is found or not, with a non-null user. We do not fail requests if the run as user is not found as that can leak the
* names of users that exist using a timing attack
*/
private void lookupRunAsUser(final User user, String runAsUsername, Consumer<User> userConsumer) {
final RealmUserLookup lookup = new RealmUserLookup(getRealmList(runAsUsername), threadContext);
final long startInvalidationNum = numInvalidation.get();
lookup.lookup(runAsUsername, ActionListener.wrap(tuple -> {
if (tuple == null) {
// the user does not exist, but we still create a User object, which will later be rejected by authz
userConsumer.accept(new User(runAsUsername, null, user));
} else {
User foundUser = Objects.requireNonNull(tuple.v1());
Realm realm = Objects.requireNonNull(tuple.v2());
lookedupBy = new RealmRef(realm.name(), realm.type(), nodeName);
if (lastSuccessfulAuthCache != null && startInvalidationNum == numInvalidation.get()) {
// only cache this as last success if it doesn't exist since this really isn't an auth attempt but
// this might provide a valid hint
lastSuccessfulAuthCache.computeIfAbsent(runAsUsername, s -> realm);
}
userConsumer.accept(new User(foundUser, user));
}
}, exception -> listener.onFailure(request.exceptionProcessingRequest(exception, authenticationToken))));
}
/**
* Finishes the authentication process by ensuring the returned user is enabled and that the run as user is enabled if there is
* one. If authentication is successful, this method also ensures that the authentication is written to the ThreadContext
*/
void finishAuthentication(User finalUser) {
if (finalUser.enabled() == false || finalUser.authenticatedUser().enabled() == false) {
// TODO: these should be different log messages if the runas vs auth user is disabled?
logger.debug("user [{}] is disabled. failing authentication", finalUser);
listener.onFailure(request.authenticationFailed(authenticationToken));
} else {
final Authentication finalAuth = new Authentication(finalUser, authenticatedBy, lookedupBy);
writeAuthToContext(finalAuth);
}
}
/**
* Writes the authentication to the {@link ThreadContext} and then calls the listener if
* successful
*/
void writeAuthToContext(Authentication authentication) {
request.authenticationSuccess(authentication.getAuthenticatedBy().getName(), authentication.getUser());
Runnable action = () -> listener.onResponse(authentication);
try {
authentication.writeToContext(threadContext);
} catch (Exception e) {
action = () -> listener.onFailure(request.exceptionProcessingRequest(e, authenticationToken));
}
// we assign the listener call to an action to avoid calling the listener within a try block and auditing the wrong thing
// when an exception bubbles up even after successful authentication
action.run();
}
private void authenticateToken(AuthenticationToken token) {
this.consumeToken(token);
}
}
abstract static class AuditableRequest {
final AuditTrail auditTrail;
final AuthenticationFailureHandler failureHandler;
final ThreadContext threadContext;
AuditableRequest(AuditTrail auditTrail, AuthenticationFailureHandler failureHandler, ThreadContext threadContext) {
this.auditTrail = auditTrail;
this.failureHandler = failureHandler;
this.threadContext = threadContext;
}
abstract void realmAuthenticationFailed(AuthenticationToken token, String realm);
abstract ElasticsearchSecurityException tamperedRequest();
abstract ElasticsearchSecurityException exceptionProcessingRequest(Exception e, @Nullable AuthenticationToken token);
abstract ElasticsearchSecurityException authenticationFailed(AuthenticationToken token);
abstract ElasticsearchSecurityException anonymousAccessDenied();
abstract ElasticsearchSecurityException runAsDenied(Authentication authentication, AuthenticationToken token);
abstract void authenticationSuccess(String realm, User user);
}
static class AuditableTransportRequest extends AuditableRequest {
private final String action;
private final TransportMessage message;
private final String requestId;
AuditableTransportRequest(AuditTrail auditTrail, AuthenticationFailureHandler failureHandler, ThreadContext threadContext,
String action, TransportMessage message) {
super(auditTrail, failureHandler, threadContext);
this.action = action;
this.message = message;
// There might be an existing audit-id (e.g. generated by the rest request) but there might not be (e.g. an internal action)
this.requestId = AuditUtil.getOrGenerateRequestId(threadContext);
}
@Override
void authenticationSuccess(String realm, User user) {
auditTrail.authenticationSuccess(requestId, realm, user, action, message);
}
@Override
void realmAuthenticationFailed(AuthenticationToken token, String realm) {
auditTrail.authenticationFailed(requestId, realm, token, action, message);
}
@Override
ElasticsearchSecurityException tamperedRequest() {
auditTrail.tamperedRequest(requestId, action, message);
return new ElasticsearchSecurityException("failed to verify signed authentication information");
}
@Override
ElasticsearchSecurityException exceptionProcessingRequest(Exception e, @Nullable AuthenticationToken token) {
if (token != null) {
auditTrail.authenticationFailed(requestId, token, action, message);
} else {
auditTrail.authenticationFailed(requestId, action, message);
}
return failureHandler.exceptionProcessingRequest(message, action, e, threadContext);
}
@Override
ElasticsearchSecurityException authenticationFailed(AuthenticationToken token) {
auditTrail.authenticationFailed(requestId, token, action, message);
return failureHandler.failedAuthentication(message, token, action, threadContext);
}
@Override
ElasticsearchSecurityException anonymousAccessDenied() {
auditTrail.anonymousAccessDenied(requestId, action, message);
return failureHandler.missingToken(message, action, threadContext);
}
@Override
ElasticsearchSecurityException runAsDenied(Authentication authentication, AuthenticationToken token) {
auditTrail.runAsDenied(requestId, authentication, action, message, EmptyAuthorizationInfo.INSTANCE);
return failureHandler.failedAuthentication(message, token, action, threadContext);
}
@Override
public String toString() {
return "transport request action [" + action + "]";
}
}
static class AuditableRestRequest extends AuditableRequest {
private final RestRequest request;
private final String requestId;
AuditableRestRequest(AuditTrail auditTrail, AuthenticationFailureHandler failureHandler, ThreadContext threadContext,
RestRequest request) {
super(auditTrail, failureHandler, threadContext);
this.request = request;
// There should never be an existing audit-id when processing a rest request.
this.requestId = AuditUtil.generateRequestId(threadContext);
}
@Override
void authenticationSuccess(String realm, User user) {
auditTrail.authenticationSuccess(requestId, realm, user, request);
}
@Override
void realmAuthenticationFailed(AuthenticationToken token, String realm) {
auditTrail.authenticationFailed(requestId, realm, token, request);
}
@Override
ElasticsearchSecurityException tamperedRequest() {
auditTrail.tamperedRequest(requestId, request);
return new ElasticsearchSecurityException("rest request attempted to inject a user");
}
@Override
ElasticsearchSecurityException exceptionProcessingRequest(Exception e, @Nullable AuthenticationToken token) {
if (token != null) {
auditTrail.authenticationFailed(requestId, token, request);
} else {
auditTrail.authenticationFailed(requestId, request);
}
return failureHandler.exceptionProcessingRequest(request, e, threadContext);
}
@Override
ElasticsearchSecurityException authenticationFailed(AuthenticationToken token) {
auditTrail.authenticationFailed(requestId, token, request);
return failureHandler.failedAuthentication(request, token, threadContext);
}
@Override
ElasticsearchSecurityException anonymousAccessDenied() {
auditTrail.anonymousAccessDenied(requestId, request);
return failureHandler.missingToken(request, threadContext);
}
@Override
ElasticsearchSecurityException runAsDenied(Authentication authentication, AuthenticationToken token) {
auditTrail.runAsDenied(requestId, authentication, request, EmptyAuthorizationInfo.INSTANCE);
return failureHandler.failedAuthentication(request, token, threadContext);
}
@Override
public String toString() {
return "rest request uri [" + request.uri() + "]";
}
}
public static void addSettings(List<Setting<?>> settings) {
settings.add(AuthenticationServiceField.RUN_AS_ENABLED);
settings.add(SUCCESS_AUTH_CACHE_ENABLED);
settings.add(SUCCESS_AUTH_CACHE_MAX_SIZE);
settings.add(SUCCESS_AUTH_CACHE_EXPIRE_AFTER_ACCESS);
}
}
| {
"content_hash": "d0519438680868716f711641b03db582",
"timestamp": "",
"source": "github",
"line_count": 746,
"max_line_length": 140,
"avg_line_length": 53.25335120643432,
"alnum_prop": 0.6327686460090115,
"repo_name": "coding0011/elasticsearch",
"id": "f5175b526be12edc6e7e9bf5c89603f46cafb7f6",
"size": "39968",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/AuthenticationService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "11081"
},
{
"name": "Batchfile",
"bytes": "18064"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "312193"
},
{
"name": "HTML",
"bytes": "5519"
},
{
"name": "Java",
"bytes": "41505710"
},
{
"name": "Perl",
"bytes": "7271"
},
{
"name": "Python",
"bytes": "55163"
},
{
"name": "Shell",
"bytes": "119286"
}
],
"symlink_target": ""
} |
<html lang="en">
<head>
<title>File Options - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Invoking-GDB.html#Invoking-GDB" title="Invoking GDB">
<link rel="next" href="Mode-Options.html#Mode-Options" title="Mode Options">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
Copyright (C) 1988-2013 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being ``Free Software'' and ``Free Software Needs
Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,''
and with the Back-Cover Texts as in (a) below.
(a) The FSF's Back-Cover Text is: ``You are free to copy and modify
this GNU Manual. Buying copies from GNU Press supports the FSF in
developing GNU and promoting software freedom.''
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
<link rel="stylesheet" type="text/css" href="../cs.css">
</head>
<body>
<div class="node">
<a name="File-Options"></a>
<p>
Next: <a rel="next" accesskey="n" href="Mode-Options.html#Mode-Options">Mode Options</a>,
Up: <a rel="up" accesskey="u" href="Invoking-GDB.html#Invoking-GDB">Invoking GDB</a>
<hr>
</div>
<h4 class="subsection">2.1.1 Choosing Files</h4>
<p>When <span class="sc">gdb</span> starts, it reads any arguments other than options as
specifying an executable file and core file (or process ID). This is
the same as if the arguments were specified by the ‘<samp><span class="samp">-se</span></samp>’ and
‘<samp><span class="samp">-c</span></samp>’ (or ‘<samp><span class="samp">-p</span></samp>’) options respectively. (<span class="sc">gdb</span> reads the
first argument that does not have an associated option flag as
equivalent to the ‘<samp><span class="samp">-se</span></samp>’ option followed by that argument; and the
second argument that does not have an associated option flag, if any, as
equivalent to the ‘<samp><span class="samp">-c</span></samp>’/‘<samp><span class="samp">-p</span></samp>’ option followed by that argument.)
If the second argument begins with a decimal digit, <span class="sc">gdb</span> will
first attempt to attach to it as a process, and if that fails, attempt
to open it as a corefile. If you have a corefile whose name begins with
a digit, you can prevent <span class="sc">gdb</span> from treating it as a pid by
prefixing it with <samp><span class="file">./</span></samp>, e.g. <samp><span class="file">./12345</span></samp>.
<p>If <span class="sc">gdb</span> has not been configured to included core file support,
such as for most embedded targets, then it will complain about a second
argument and ignore it.
<p>Many options have both long and short forms; both are shown in the
following list. <span class="sc">gdb</span> also recognizes the long forms if you truncate
them, so long as enough of the option is present to be unambiguous.
(If you prefer, you can flag option arguments with ‘<samp><span class="samp">--</span></samp>’ rather
than ‘<samp><span class="samp">-</span></samp>’, though we illustrate the more usual convention.)
<!-- NOTE: the @cindex entries here use double dashes ON PURPOSE. This -->
<!-- way, both those who look for -foo and -foo in the index, will find -->
<!-- it. -->
<dl>
<dt><code>-symbols </code><var>file</var><dt><code>-s </code><var>file</var><dd><a name="index-g_t_0040code_007b_002d_002dsymbols_007d-4"></a><a name="index-g_t_0040code_007b_002ds_007d-5"></a>Read symbol table from file <var>file</var>.
<br><dt><code>-exec </code><var>file</var><dt><code>-e </code><var>file</var><dd><a name="index-g_t_0040code_007b_002d_002dexec_007d-6"></a><a name="index-g_t_0040code_007b_002de_007d-7"></a>Use file <var>file</var> as the executable file to execute when appropriate,
and for examining pure data in conjunction with a core dump.
<br><dt><code>-se </code><var>file</var><dd><a name="index-g_t_0040code_007b_002d_002dse_007d-8"></a>Read symbol table from file <var>file</var> and use it as the executable
file.
<br><dt><code>-core </code><var>file</var><dt><code>-c </code><var>file</var><dd><a name="index-g_t_0040code_007b_002d_002dcore_007d-9"></a><a name="index-g_t_0040code_007b_002dc_007d-10"></a>Use file <var>file</var> as a core dump to examine.
<br><dt><code>-pid </code><var>number</var><dt><code>-p </code><var>number</var><dd><a name="index-g_t_0040code_007b_002d_002dpid_007d-11"></a><a name="index-g_t_0040code_007b_002dp_007d-12"></a>Connect to process ID <var>number</var>, as with the <code>attach</code> command.
<br><dt><code>-command </code><var>file</var><dt><code>-x </code><var>file</var><dd><a name="index-g_t_0040code_007b_002d_002dcommand_007d-13"></a><a name="index-g_t_0040code_007b_002dx_007d-14"></a>Execute commands from file <var>file</var>. The contents of this file is
evaluated exactly as the <code>source</code> command would.
See <a href="Command-Files.html#Command-Files">Command files</a>.
<br><dt><code>-eval-command </code><var>command</var><dt><code>-ex </code><var>command</var><dd><a name="index-g_t_0040code_007b_002d_002deval_002dcommand_007d-15"></a><a name="index-g_t_0040code_007b_002dex_007d-16"></a>Execute a single <span class="sc">gdb</span> command.
<p>This option may be used multiple times to call multiple commands. It may
also be interleaved with ‘<samp><span class="samp">-command</span></samp>’ as required.
<pre class="smallexample"> gdb -ex 'target sim' -ex 'load' \
-x setbreakpoints -ex 'run' a.out
</pre>
<br><dt><code>-init-command </code><var>file</var><dt><code>-ix </code><var>file</var><dd><a name="index-g_t_0040code_007b_002d_002dinit_002dcommand_007d-17"></a><a name="index-g_t_0040code_007b_002dix_007d-18"></a>Execute commands from file <var>file</var> before loading the inferior (but
after loading gdbinit files).
See <a href="Startup.html#Startup">Startup</a>.
<br><dt><code>-init-eval-command </code><var>command</var><dt><code>-iex </code><var>command</var><dd><a name="index-g_t_0040code_007b_002d_002dinit_002deval_002dcommand_007d-19"></a><a name="index-g_t_0040code_007b_002diex_007d-20"></a>Execute a single <span class="sc">gdb</span> command before loading the inferior (but
after loading gdbinit files).
See <a href="Startup.html#Startup">Startup</a>.
<br><dt><code>-directory </code><var>directory</var><dt><code>-d </code><var>directory</var><dd><a name="index-g_t_0040code_007b_002d_002ddirectory_007d-21"></a><a name="index-g_t_0040code_007b_002dd_007d-22"></a>Add <var>directory</var> to the path to search for source and script files.
<br><dt><code>-r</code><dt><code>-readnow</code><dd><a name="index-g_t_0040code_007b_002d_002dreadnow_007d-23"></a><a name="index-g_t_0040code_007b_002dr_007d-24"></a>Read each symbol file's entire symbol table immediately, rather than
the default, which is to read it incrementally as it is needed.
This makes startup slower, but makes future operations faster.
</dl>
</body></html>
| {
"content_hash": "f57157c759d53abc777315129381f0c3",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 327,
"avg_line_length": 67.08403361344538,
"alnum_prop": 0.7063760491043467,
"repo_name": "teaguejt/xinu",
"id": "d4114ffc46d260fcb30ac048f6be142f2b14cd9e",
"size": "7983",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "cross_compiler/share/doc/arm-arm-none-eabi/html/gdb/File-Options.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "6173"
},
{
"name": "C",
"bytes": "4140407"
},
{
"name": "C++",
"bytes": "8386781"
},
{
"name": "CSS",
"bytes": "4376"
},
{
"name": "Groff",
"bytes": "2490635"
},
{
"name": "HTML",
"bytes": "14436568"
},
{
"name": "Lex",
"bytes": "1439"
},
{
"name": "Logos",
"bytes": "9040"
},
{
"name": "Makefile",
"bytes": "7220"
},
{
"name": "Objective-C",
"bytes": "248283"
},
{
"name": "PHP",
"bytes": "8650"
},
{
"name": "Perl",
"bytes": "1492"
},
{
"name": "Python",
"bytes": "152128"
},
{
"name": "Shell",
"bytes": "37861"
},
{
"name": "XC",
"bytes": "8725"
},
{
"name": "XS",
"bytes": "8497"
},
{
"name": "Yacc",
"bytes": "14595"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "e67241f6bd0a1271a0d0b1a8380db598",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "4502907d070948d6d9590999dead6f239052d73b",
"size": "179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Sordariomycetes/Glomerellaceae/Colletotrichum/Colletotrichum lupini/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package exportertools_test
import (
. "github.com/aksentyev/hubble/exportertools"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
"time"
"fmt"
)
func TestCache(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Cache")
}
var _ = Describe("Cache", func() {
defer GinkgoRecover()
var cache *Cache
BeforeEach(func() {
cache = NewCache(30)
})
Describe("Cache instance", func() {
It("should return new instance", func(){
Expect(fmt.Sprintf("%T", cache)).To(Equal("*exportertools.Cache"))
Expect(cache.TTL).To(Equal(30 * time.Second))
})
It("should store and return metrics", func(){
m := &Metric{}
m.Name = "Test"
cache.Set(m)
Expect(cache.Get("Test")).To(Equal(m))
})
It("should metrics names list", func(){
m := &Metric{}
m.Name = "Test"
cache.Set(m)
Expect(cache.MetricNames()).To(Equal([]string{"Test"}))
})
})
})
| {
"content_hash": "8509e14343843580b5bbe5c1cac7bf84",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 78,
"avg_line_length": 22.851063829787233,
"alnum_prop": 0.5288640595903166,
"repo_name": "aksentyev/hubble",
"id": "c2fdfcd409cffc5cc5977cce3baf482a47f44909",
"size": "1074",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "exportertools/cache_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "30602"
},
{
"name": "Shell",
"bytes": "550"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:gravity="center_horizontal|bottom"
android:layout_height="80dp">
<ImageView
android:id="@+id/meituan_header_img"
android:adjustViewBounds="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"/>
</LinearLayout>
| {
"content_hash": "d9642532b85cbf55e853d772b5147829",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 72,
"avg_line_length": 37.23076923076923,
"alnum_prop": 0.6880165289256198,
"repo_name": "43081438/RxJavaAndRetrofitSimple",
"id": "66db9a481172dfe6c21540d3ceae9007cbd90dfa",
"size": "484",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RxJavaAndRetrofitSimple/library/src/main/res/layout/meituan_header.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "848362"
}
],
"symlink_target": ""
} |
/** @ignore */
const EventHandler = require('./EventHandler');
/**
* Emitted after a role has been updated for a guild/server.
*
* @see http://qeled.github.io/discordie/#/docs/GUILD_ROLE_UPDATE
*
* @extends {EventHandler}
*/
class GuildRoleUpdateEvent extends EventHandler {
/**
* The event-handler that is executed by Discords event dispatcher.
*
* @param {GatewaySocket} socket The Discordie gateway socket
* @return {mixed}
*/
handle(socket) {
//
}
}
module.exports = new GuildRoleUpdateEvent;
| {
"content_hash": "72eb05d8756c691491997455d5bd36e9",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 71,
"avg_line_length": 23.083333333333332,
"alnum_prop": 0.6516245487364621,
"repo_name": "Senither/AvaIre",
"id": "f374e87f269ffa1f224c7177b33d55f754a0dc42",
"size": "554",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/bot/handlers/GuildRoleUpdateEvent.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "285910"
}
],
"symlink_target": ""
} |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}
module Search.Dictionary
(
TokenMap, WordMap
, emptyWordMap, addToken, buildTokenMap, lookupWord, lookupToken
, buildWordMap
) where
import Prelude hiding (words)
import Control.Arrow (second)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Data.Text.Lazy.Encoding (decodeUtf8)
import Data.Text.Lazy (toStrict)
import Data.Tuple (swap)
import qualified Data.Vector as V
import Data.Binary
import Data.Binary.Put (putByteString)
import Data.Binary.Get (getRemainingLazyByteString)
import qualified Data.ByteString.Lazy as BL
import qualified Data.HashMap.Strict as H
import Search.Common
type WordHashMap = H.HashMap T.Text Token
data WordMap = WordMap !WordHashMap Token
deriving (Show, Eq)
data TokenMap = TokenMap !(V.Vector T.Text)
deriving (Show, Eq)
instance Binary TokenMap where
put (TokenMap v) =
V.foldM_ addBytes () v
where
addBytes _ t =
do putByteString $ encodeUtf8 t
putWord8 0
get = do bs <- getRemainingLazyByteString
let word x = let w = toStrict $ decodeUtf8 x in w `seq` w
let words [] = []
words ws = map word $ init ws
return $ TokenMap $! V.fromList $ words $ BL.split 0 bs
addToken :: WordMap -> T.Text -> (Token, Maybe WordMap)
addToken (WordMap hm ot@(Token otid)) w =
case H.lookup w hm of
Just tid -> (tid, Nothing)
Nothing -> (ot, Just $ WordMap nhm ntid)
where ntid = Token $ otid + 1
nhm = H.insert w (Token otid) hm
emptyWordMap :: WordMap
emptyWordMap = WordMap H.empty (Token 0)
lookupWord :: WordMap -> T.Text -> Maybe Token
lookupWord (WordMap hm _) w = H.lookup w hm
lookupToken :: TokenMap -> Token -> T.Text
lookupToken (TokenMap v) (Token t) = v V.! fromIntegral t
buildTokenMap :: WordMap -> TokenMap
buildTokenMap (WordMap hm (Token curId)) = TokenMap m
where m = empty V.// tokenList
empty = V.replicate (fromIntegral curId) ""
tokenList = map (swap . second (fromIntegral . unToken)) (H.toList hm)
buildWordMap :: TokenMap -> WordMap
buildWordMap (TokenMap v) =
let mapping = zip (V.toList v) $ map Token [0..]
maxToken = Token $ fromIntegral $ V.length v
in WordMap (H.fromList mapping) maxToken
| {
"content_hash": "b3a18aced409d86e75e2c3649030207f",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 80,
"avg_line_length": 30.025641025641026,
"alnum_prop": 0.6750640478223741,
"repo_name": "jdimond/diplomarbeit",
"id": "e195f4a462885b1310d20935b9a8a12c5c84fe78",
"size": "2342",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/Search/Dictionary.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "53042"
},
{
"name": "Haskell",
"bytes": "75497"
},
{
"name": "Shell",
"bytes": "2861"
}
],
"symlink_target": ""
} |
package groovy.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.nio.charset.Charset;
import java.util.Collection;
/**
* Utility class to guess the encoding of a given text file.
* <p>
* Unicode files encoded in UTF-16 (low or big endian) or UTF-8 files
* with a Byte Order Marker are correctly discovered. For UTF-8 files with no BOM, if the buffer
* is wide enough, the charset should also be discovered.
* <p>
* A byte buffer of 4KB is used to be able to guess the encoding.
* <p>
* Usage:
* <pre>
* CharsetToolkit toolkit = new CharsetToolkit(file);
*
* // guess the encoding
* Charset guessedCharset = toolkit.getCharset();
*
* // create a reader with the correct charset
* BufferedReader reader = toolkit.getReader();
*
* // read the file content
* String line;
* while ((line = br.readLine())!= null)
* {
* System.out.println(line);
* }
* </pre>
*
* @author Guillaume Laforge
*/
public class CharsetToolkit {
private final byte[] buffer;
private Charset defaultCharset;
private Charset charset;
private boolean enforce8Bit = true;
private final File file;
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
/**
* Constructor of the <code>CharsetToolkit</code> utility class.
*
* @param file of which we want to know the encoding.
*/
public CharsetToolkit(File file) throws IOException {
this.file = file;
this.defaultCharset = getDefaultSystemCharset();
this.charset = null;
InputStream input = new FileInputStream(file);
try {
byte[] bytes = new byte[4096];
int bytesRead = input.read(bytes);
if (bytesRead == -1) {
this.buffer = EMPTY_BYTE_ARRAY;
}
else if (bytesRead < 4096) {
byte[] bytesToGuess = new byte[bytesRead];
System.arraycopy(bytes, 0, bytesToGuess, 0, bytesRead);
this.buffer = bytesToGuess;
}
else {
this.buffer = bytes;
}
} finally {
try {input.close();} catch (IOException e){
// IGNORE
}
}
}
/**
* Defines the default <code>Charset</code> used in case the buffer represents
* an 8-bit <code>Charset</code>.
*
* @param defaultCharset the default <code>Charset</code> to be returned
* if an 8-bit <code>Charset</code> is encountered.
*/
public void setDefaultCharset(Charset defaultCharset) {
if (defaultCharset != null)
this.defaultCharset = defaultCharset;
else
this.defaultCharset = getDefaultSystemCharset();
}
public Charset getCharset() {
if (this.charset == null)
this.charset = guessEncoding();
return charset;
}
/**
* If US-ASCII is recognized, enforce to return the default encoding, rather than US-ASCII.
* It might be a file without any special character in the range 128-255, but that may be or become
* a file encoded with the default <code>charset</code> rather than US-ASCII.
*
* @param enforce a boolean specifying the use or not of US-ASCII.
*/
public void setEnforce8Bit(boolean enforce) {
this.enforce8Bit = enforce;
}
/**
* Gets the enforce8Bit flag, in case we do not want to ever get a US-ASCII encoding.
*
* @return a boolean representing the flag of use of US-ASCII.
*/
public boolean getEnforce8Bit() {
return this.enforce8Bit;
}
/**
* Retrieves the default Charset
*/
public Charset getDefaultCharset() {
return defaultCharset;
}
/**
* Guess the encoding of the provided buffer.
* If Byte Order Markers are encountered at the beginning of the buffer, we immediately
* return the charset implied by this BOM. Otherwise, the file would not be a human
* readable text file.
* <p>
* If there is no BOM, this method tries to discern whether the file is UTF-8 or not.
* If it is not UTF-8, we assume the encoding is the default system encoding
* (of course, it might be any 8-bit charset, but usually, an 8-bit charset is the default one).
* <p>
* It is possible to discern UTF-8 thanks to the pattern of characters with a multi-byte sequence.
* <pre>
* UCS-4 range (hex.) UTF-8 octet sequence (binary)
* 0000 0000-0000 007F 0xxxxxxx
* 0000 0080-0000 07FF 110xxxxx 10xxxxxx
* 0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx
* 0001 0000-001F FFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
* 0020 0000-03FF FFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
* 0400 0000-7FFF FFFF 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
* </pre>
* With UTF-8, 0xFE and 0xFF never appear.
*
* @return the Charset recognized.
*/
private Charset guessEncoding() {
// if the file has a Byte Order Marker, we can assume the file is in UTF-xx
// otherwise, the file would not be human readable
if (hasUTF8Bom())
return Charset.forName("UTF-8");
if (hasUTF16LEBom())
return Charset.forName("UTF-16LE");
if (hasUTF16BEBom())
return Charset.forName("UTF-16BE");
// if a byte has its most significant bit set, the file is in UTF-8 or in the default encoding
// otherwise, the file is in US-ASCII
boolean highOrderBit = false;
// if the file is in UTF-8, high order bytes must have a certain value, in order to be valid
// if it's not the case, we can assume the encoding is the default encoding of the system
boolean validU8Char = true;
// TODO the buffer is not read up to the end, but up to length - 6
int length = buffer.length;
int i = 0;
while (i < length - 6) {
byte b0 = buffer[i];
byte b1 = buffer[i + 1];
byte b2 = buffer[i + 2];
byte b3 = buffer[i + 3];
byte b4 = buffer[i + 4];
byte b5 = buffer[i + 5];
if (b0 < 0) {
// a high order bit was encountered, thus the encoding is not US-ASCII
// it may be either an 8-bit encoding or UTF-8
highOrderBit = true;
// a two-bytes sequence was encountered
if (isTwoBytesSequence(b0)) {
// there must be one continuation byte of the form 10xxxxxx,
// otherwise the following character is is not a valid UTF-8 construct
if (!isContinuationChar(b1))
validU8Char = false;
else
i++;
}
// a three-bytes sequence was encountered
else if (isThreeBytesSequence(b0)) {
// there must be two continuation bytes of the form 10xxxxxx,
// otherwise the following character is is not a valid UTF-8 construct
if (!(isContinuationChar(b1) && isContinuationChar(b2)))
validU8Char = false;
else
i += 2;
}
// a four-bytes sequence was encountered
else if (isFourBytesSequence(b0)) {
// there must be three continuation bytes of the form 10xxxxxx,
// otherwise the following character is is not a valid UTF-8 construct
if (!(isContinuationChar(b1) && isContinuationChar(b2) && isContinuationChar(b3)))
validU8Char = false;
else
i += 3;
}
// a five-bytes sequence was encountered
else if (isFiveBytesSequence(b0)) {
// there must be four continuation bytes of the form 10xxxxxx,
// otherwise the following character is is not a valid UTF-8 construct
if (!(isContinuationChar(b1)
&& isContinuationChar(b2)
&& isContinuationChar(b3)
&& isContinuationChar(b4)))
validU8Char = false;
else
i += 4;
}
// a six-bytes sequence was encountered
else if (isSixBytesSequence(b0)) {
// there must be five continuation bytes of the form 10xxxxxx,
// otherwise the following character is is not a valid UTF-8 construct
if (!(isContinuationChar(b1)
&& isContinuationChar(b2)
&& isContinuationChar(b3)
&& isContinuationChar(b4)
&& isContinuationChar(b5)))
validU8Char = false;
else
i += 5;
}
else
validU8Char = false;
}
if (!validU8Char)
break;
i++;
}
// if no byte with an high order bit set, the encoding is US-ASCII
// (it might have been UTF-7, but this encoding is usually internally used only by mail systems)
if (!highOrderBit) {
// returns the default charset rather than US-ASCII if the enforce8Bit flag is set.
if (this.enforce8Bit)
return this.defaultCharset;
else
return Charset.forName("US-ASCII");
}
// if no invalid UTF-8 were encountered, we can assume the encoding is UTF-8,
// otherwise the file would not be human readable
if (validU8Char)
return Charset.forName("UTF-8");
// finally, if it's not UTF-8 nor US-ASCII, let's assume the encoding is the default encoding
return this.defaultCharset;
}
/**
* If the byte has the form 10xxxxx, then it's a continuation byte of a multiple byte character;
*
* @param b a byte.
* @return true if it's a continuation char.
*/
private static boolean isContinuationChar(byte b) {
return -128 <= b && b <= -65;
}
/**
* If the byte has the form 110xxxx, then it's the first byte of a two-bytes sequence character.
*
* @param b a byte.
* @return true if it's the first byte of a two-bytes sequence.
*/
private static boolean isTwoBytesSequence(byte b) {
return -64 <= b && b <= -33;
}
/**
* If the byte has the form 1110xxx, then it's the first byte of a three-bytes sequence character.
*
* @param b a byte.
* @return true if it's the first byte of a three-bytes sequence.
*/
private static boolean isThreeBytesSequence(byte b) {
return -32 <= b && b <= -17;
}
/**
* If the byte has the form 11110xx, then it's the first byte of a four-bytes sequence character.
*
* @param b a byte.
* @return true if it's the first byte of a four-bytes sequence.
*/
private static boolean isFourBytesSequence(byte b) {
return -16 <= b && b <= -9;
}
/**
* If the byte has the form 11110xx, then it's the first byte of a five-bytes sequence character.
*
* @param b a byte.
* @return true if it's the first byte of a five-bytes sequence.
*/
private static boolean isFiveBytesSequence(byte b) {
return -8 <= b && b <= -5;
}
/**
* If the byte has the form 1110xxx, then it's the first byte of a six-bytes sequence character.
*
* @param b a byte.
* @return true if it's the first byte of a six-bytes sequence.
*/
private static boolean isSixBytesSequence(byte b) {
return -4 <= b && b <= -3;
}
/**
* Retrieve the default charset of the system.
*
* @return the default <code>Charset</code>.
*/
public static Charset getDefaultSystemCharset() {
return Charset.forName(System.getProperty("file.encoding"));
}
/**
* Has a Byte Order Marker for UTF-8 (Used by Microsoft's Notepad and other editors).
*
* @return true if the buffer has a BOM for UTF8.
*/
public boolean hasUTF8Bom() {
if (buffer.length >= 3)
return (buffer[0] == -17 && buffer[1] == -69 && buffer[2] == -65);
else
return false;
}
/**
* Has a Byte Order Marker for UTF-16 Low Endian
* (ucs-2le, ucs-4le, and ucs-16le).
*
* @return true if the buffer has a BOM for UTF-16 Low Endian.
*/
public boolean hasUTF16LEBom() {
if (buffer.length >= 2)
return (buffer[0] == -1 && buffer[1] == -2);
else
return false;
}
/**
* Has a Byte Order Marker for UTF-16 Big Endian
* (utf-16 and ucs-2).
*
* @return true if the buffer has a BOM for UTF-16 Big Endian.
*/
public boolean hasUTF16BEBom() {
if (buffer.length >= 2)
return (buffer[0] == -2 && buffer[1] == -1);
else
return false;
}
/**
* Gets a <code>BufferedReader</code> (indeed a <code>LineNumberReader</code>) from the <code>File</code>
* specified in the constructor of <code>CharsetToolkit</code> using the charset discovered or the default
* charset if an 8-bit <code>Charset</code> is encountered.
*
* @return a <code>BufferedReader</code>
* @throws FileNotFoundException if the file is not found.
*/
public BufferedReader getReader() throws FileNotFoundException {
LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream(file), getCharset()));
if (hasUTF8Bom() || hasUTF16LEBom() || hasUTF16BEBom()) {
try {
reader.read();
}
catch (IOException e) {
// should never happen, as a file with no content
// but with a BOM has at least one char
}
}
return reader;
}
/**
* Retrieves all the available <code>Charset</code>s on the platform,
* among which the default <code>charset</code>.
*
* @return an array of <code>Charset</code>s.
*/
public static Charset[] getAvailableCharsets() {
Collection collection = Charset.availableCharsets().values();
return (Charset[]) collection.toArray(new Charset[collection.size()]);
}
}
| {
"content_hash": "f8f7d3946fd64b08a218450a529bc296",
"timestamp": "",
"source": "github",
"line_count": 402,
"max_line_length": 119,
"avg_line_length": 36.78606965174129,
"alnum_prop": 0.5726940762780633,
"repo_name": "avafanasiev/groovy",
"id": "e1274590b65263c010f00d11f55b137059899921",
"size": "15609",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/groovy/util/CharsetToolkit.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "56807"
},
{
"name": "Batchfile",
"bytes": "23219"
},
{
"name": "CSS",
"bytes": "132839"
},
{
"name": "GAP",
"bytes": "221401"
},
{
"name": "Groovy",
"bytes": "8371935"
},
{
"name": "HTML",
"bytes": "180758"
},
{
"name": "Java",
"bytes": "12332738"
},
{
"name": "JavaScript",
"bytes": "1191"
},
{
"name": "Shell",
"bytes": "26623"
},
{
"name": "Smarty",
"bytes": "7699"
}
],
"symlink_target": ""
} |
declare module FlashMessages {
function sendAlert(message: string, options?: ConfigurationOptions): void;
function sendError(message: string, options?: ConfigurationOptions): void;
function sendSuccess(message: string, options?: ConfigurationOptions): void;
function sendInfo(message: string, options?: ConfigurationOptions): void;
function clear(): void;
function configure(options: ConfigurationOptions): void;
interface ConfigurationOptions {
autoHide?: boolean;
hideDelay?: number;
}
}
interface FlashMessagesDAO {
message: string;
style?: string;
seen?: boolean;
options?: FlashMessages.ConfigurationOptions;
}
declare var flashMessages: Mongo.Collection<FlashMessagesDAO>; | {
"content_hash": "e8dd49c32126edf2d478fd3c1753b415",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 78,
"avg_line_length": 32.40909090909091,
"alnum_prop": 0.7699859747545582,
"repo_name": "tomitrescak/meteor-boilerplate-typescript",
"id": "c42717febb2611d886e9887c75756cbd6e007ec5",
"size": "908",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "typescript/packages/flash-messages.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "522"
},
{
"name": "HTML",
"bytes": "3533"
},
{
"name": "JavaScript",
"bytes": "32396"
},
{
"name": "Shell",
"bytes": "226"
},
{
"name": "TypeScript",
"bytes": "3482"
}
],
"symlink_target": ""
} |
function getDefaultValue(type){
switch (type) {
case 'integer':
return 0;
break;
case 'array':
return '[]';
break;
case 'boolean':
return 'true';
break;
case 'string':
return '""';
break;
default:
return "{}";
}
}
function getModelExampleFromModelName(isResponse, swagger, modelName, depth){
var refDefinition = findRefDefinition(modelName, swagger);
return getModelExample(isResponse, swagger, refDefinition, depth + 1);
}
function getModelDescription(isResponse, swagger, definitions, modelName, depth){
try{
if(modelName === null || definitions[modelName] || depth >2){
return definitions;
}
modelName = modelName.replace(/#\/definitions\//,'');
if(swagger["definitions"][modelName] == null){
return definitions;
}
var model = swagger["definitions"][modelName];
var properties = model["properties"];
if(properties === null){
return definitions;
}
var propertyDescriptions = [];
var keys = Object.keys(properties);
for(var x=0; x< keys.length; x++){
var key = keys[x];
var property = properties[key];
if(isResponse || property.readOnly !== true){
propertyDescriptions.push(processPropertyDescription(isResponse,swagger, definitions, model,depth, key,property));
}
}
definitions[modelName] = propertyDescriptions
}catch(ex){
console.warn(ex);
}
return definitions;
}
function processPropertyDescription(isResponse, swagger, definitions, model, depth, name, property){
var readonlyString = property["readOnly"] == true ? ", read only" : "";
var isRequired = model["required"] !=null && model["required"].indexOf(name) > -1;
var required = isRequired ? ", required" : ", optional";
var description = property['description'] || "";
var type = property["type"];
if(property["$ref"] != null){
type= property["$ref"]
getModelDescription(isResponse, swagger, definitions, property["$ref"], depth + 1);
}
else if(property["items"] && property["items"]["$ref"]){
type= "array:" + property["items"]["$ref"]
getModelDescription(isResponse, swagger, definitions, property["items"]["$ref"], depth + 1);
}
/*
}else if(property["items"] && property["items"]["properties"]){
type= "array"
get_inline_model_description(isResponse, swagger, definitions, property["items"], name, depth + 1);
}else if (property["type"] == "object")
get_inline_model_description(isResponse, swagger, definitions, property, name, depth + 1);
*/
else if (property["items"] && property["items"]["enum"]){
description = description + " Valid Values: " + property["items"]["enum"].join(", ")
}
else if ( property["enum"]){
description = description + " Valid Values: " + property["enum"].join(", ")
}
var propertyDefinition = {
name : name,
type: type,
required: required,
readonlyString: readonlyString,
description: description
};
return propertyDefinition;
}
function getModelExample(isResponse, swagger, modelDefinition, depth){
if(depth > 3){
return "{}";
}
var definition = [];
if(!modelDefinition){
return "{}";
}
var properties = modelDefinition.properties;
for(var name in properties){
var defaultValue = '""';
if(properties[name]["$ref"]){
var refDefinition = findRefDefinition(properties[name]["$ref"], swagger);
defaultValue = getModelExample(isResponse, swagger, refDefinition, depth + 1);
}else if(properties[name]["items"] && properties[name]["items"]["$ref"]){
var refDefinition = findRefDefinition(properties[name]["items"]["$ref"], swagger);
defaultValue = "[" + getModelExample(isResponse, swagger, refDefinition, depth + 1) + "]";
}else{
defaultValue = getDefaultValue(properties[name].type);
}
if(isResponse === true || properties[name].readOnly !== true){
definition.push('"' + name + '" : ' + defaultValue );
}
}
return JSON.stringify(JSON.parse("{" + definition.join(',') + "}"), null, " ");
}
function findRefDefinition(refModelName, swagger){
if(typeof(refModelName) === "undefined"){
return {};
}
var modelName = refModelName.replace('#/definitions/','');
var properties = swagger.definitions[modelName];
return properties;
}
function convertDefinitions(definitions){
var arr = [];
if(typeof definitions === 'undefined'){
return arr;
}
for(var x=0; x < definitions.length; x++ ){
var definition = definitions[x];
//definition.name = keys[x];
arr.push(definition);
}
return arr;
}
var app = {};
app.getModelExample = function(modelName, swagger, isResponse){
var definition = findRefDefinition(modelName, swagger);
return getModelExample(isResponse, swagger, definition ,0);
};
app.getModelDescription = function(modelName, swagger, isResponse){
var descriptionHash = getModelDescription(isResponse, swagger, {}, modelName ,0);
var descriptionArray = [];
var keys = Object.keys(descriptionHash);
modelName = modelName.replace(/#\/definitions\//,'');
//make sure the parent object is first
descriptionArray.push({
name: modelName,
definitions: convertDefinitions(descriptionHash[modelName])
});
var index = keys.indexOf(modelName);
if (index > -1) {
keys.splice(index, 1);
}
for(var x=0; x < keys.length; x++ ){
var model = descriptionHash[keys[x]];
descriptionArray.push({
name: keys[x],
definitions: convertDefinitions(descriptionHash[keys[x]])
});
}
return descriptionArray;
};
app.findRefDefinition = findRefDefinition;
app.getDefaultValue = getDefaultValue;
module.exports = app;
| {
"content_hash": "ace4e79d9bbba975f026a3cb91c186a7",
"timestamp": "",
"source": "github",
"line_count": 210,
"max_line_length": 130,
"avg_line_length": 29.404761904761905,
"alnum_prop": 0.6025910931174089,
"repo_name": "KevinGlinski/openapi-model-example",
"id": "c25189348e76062f57af72c708d3706e26b1f963",
"size": "6175",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "7323"
}
],
"symlink_target": ""
} |
class Book < ActiveRecord::Base
#
end
| {
"content_hash": "a5a8f03be0712c5d170795adbc5aa997",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 31,
"avg_line_length": 13.333333333333334,
"alnum_prop": 0.7,
"repo_name": "inspire9/digestifier",
"id": "b6bba9eebfd3f7c80cc05163fbb0b845adc0567a",
"size": "40",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/internal/app/models/book.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "353"
},
{
"name": "Ruby",
"bytes": "19508"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<title>three.js canvas - panorama fisheye demo</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
background-color: rgb(200,200,200);
margin: 0px;
overflow: hidden;
}
#info {
position: absolute;
top: 0px; width: 100%;
color: #ffffff;
padding: 5px;
font-family:Monospace;
font-size:13px;
font-weight: bold;
text-align:center;
}
a {
color: #ffffff;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="info"><a href="http://github.com/mrdoob/three.js" target="_blank">three.js</a> - panorama fisheye demo. cubemap by <a href="http://www.zfight.com/" target="_blank">Jochum Skoglund</a>. (mousewheel: change fov)</div>
<script src="../build/Three.js"></script>
<script>
var camera, scene, renderer;
var texture_placeholder,
isUserInteracting = false,
onMouseDownMouseX = 0, onMouseDownMouseY = 0,
lon = 90, onMouseDownLon = 0,
lat = 0, onMouseDownLat = 0,
phi = 0, theta = 0,
target = new THREE.Vector3();
init();
function init() {
var container, mesh;
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1100 );
scene = new THREE.Scene();
scene.add( camera );
texture_placeholder = document.createElement( 'canvas' );
texture_placeholder.width = 128;
texture_placeholder.height = 128;
var context = texture_placeholder.getContext( '2d' );
context.fillStyle = 'rgb( 200, 200, 200 )';
context.fillRect( 0, 0, texture_placeholder.width, texture_placeholder.height );
var materials = [
loadTexture( 'textures/cube/skybox/px.jpg' ), // right
loadTexture( 'textures/cube/skybox/nx.jpg' ), // left
loadTexture( 'textures/cube/skybox/py.jpg' ), // top
loadTexture( 'textures/cube/skybox/ny.jpg' ), // bottom
loadTexture( 'textures/cube/skybox/pz.jpg' ), // back
loadTexture( 'textures/cube/skybox/nz.jpg' ) // front
];
mesh = new THREE.Mesh( new THREE.CubeGeometry( 300, 300, 300, 7, 7, 7, materials ), new THREE.MeshFaceMaterial() );
mesh.scale.x = - 1;
scene.add( mesh );
for ( var i = 0, l = mesh.geometry.vertices.length; i < l; i ++ ) {
var vertex = mesh.geometry.vertices[ i ];
vertex.normalize();
vertex.multiplyScalar( 550 );
}
renderer = new THREE.CanvasRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
document.addEventListener( 'mouseup', onDocumentMouseUp, false );
document.addEventListener( 'mousewheel', onDocumentMouseWheel, false );
document.addEventListener( 'DOMMouseScroll', onDocumentMouseWheel, false);
document.addEventListener( 'touchstart', onDocumentTouchStart, false );
document.addEventListener( 'touchmove', onDocumentTouchMove, false );
}
function loadTexture( path ) {
var texture = new THREE.Texture( texture_placeholder );
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: true } );
var image = new Image();
image.onload = function () {
texture.needsUpdate = true;
material.map.image = this;
render();
};
image.src = path;
return material;
}
function onDocumentMouseDown( event ) {
event.preventDefault();
isUserInteracting = true;
onPointerDownPointerX = event.clientX;
onPointerDownPointerY = event.clientY;
onPointerDownLon = lon;
onPointerDownLat = lat;
}
function onDocumentMouseMove( event ) {
if ( isUserInteracting ) {
lon = ( onPointerDownPointerX - event.clientX ) * 0.1 + onPointerDownLon;
lat = ( event.clientY - onPointerDownPointerY ) * 0.1 + onPointerDownLat;
render();
}
}
function onDocumentMouseUp( event ) {
isUserInteracting = false;
render();
}
function onDocumentMouseWheel( event ) {
// WebKit
if ( event.wheelDeltaY ) {
camera.fov -= event.wheelDeltaY * 0.05;
// Opera / Explorer 9
} else if ( event.wheelDelta ) {
camera.fov -= event.wheelDelta * 0.05;
// Firefox
} else if ( event.detail ) {
camera.fov -= event.detail * 0.05;
}
camera.updateProjectionMatrix();
render();
}
function onDocumentTouchStart( event ) {
if ( event.touches.length == 1 ) {
event.preventDefault();
onPointerDownPointerX = event.touches[ 0 ].pageX;
onPointerDownPointerY = event.touches[ 0 ].pageY;
onPointerDownLon = lon;
onPointerDownLat = lat;
}
}
function onDocumentTouchMove( event ) {
if ( event.touches.length == 1 ) {
event.preventDefault();
lon = ( onPointerDownPointerX - event.touches[0].pageX ) * 0.1 + onPointerDownLon;
lat = ( event.touches[0].pageY - onPointerDownPointerY ) * 0.1 + onPointerDownLat;
render();
}
}
function render() {
lat = Math.max( - 85, Math.min( 85, lat ) );
phi = ( 90 - lat ) * Math.PI / 180;
theta = lon * Math.PI / 180;
target.x = 500 * Math.sin( phi ) * Math.cos( theta );
target.y = 500 * Math.cos( phi );
target.z = 500 * Math.sin( phi ) * Math.sin( theta );
camera.position.x = - target.x;
camera.position.y = - target.y;
camera.position.z = - target.z;
camera.lookAt( target );
renderer.render( scene, camera );
}
</script>
</body>
</html>
| {
"content_hash": "4bd56cd34001c7dfefcde54f477e2666",
"timestamp": "",
"source": "github",
"line_count": 244,
"max_line_length": 226,
"avg_line_length": 23.5327868852459,
"alnum_prop": 0.634622082897945,
"repo_name": "bae43/three.js",
"id": "98e31021d90f9b47209365db5917d1e7842c1619",
"size": "5742",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "examples/canvas_geometry_panorama_fisheye.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
SAKSBEHANDLINGS_BIN=/srv/ws/tfk-saksbehandling/cli.js
SAKSBEHANDLINGS_OPTS=/srv/ws/tfk-saksbehandling/options.json
SAKSBEHANDLING_PATH=/srv/ws/tfk-saksbehandling/
FLOW_BIN=/srv/ws/tfk-flow/index.js
FLOW_PATH=/srv/ws/tfk-flow/
SI_BIN=/srv/ws/360import/skoleskyss.php
SI_PATH=/srv/ws/360import/
IMPORT_PATH=/srv/saksbehandling/json/
DONE_PATH=/srv/saksbehandling/json-done/
FAILED_PATH=/srv/saksbehandling/json-failed/
function delAll {
echo Deletes files in $IMPORT_PATH
rm -rf $IMPORT_PATH*
}
function fileExist {
if [ -f $1 ]; then
echo "File $1 exists."
else
echo "File $1 does not exist."
exit 1
fi
}
function errorMessage {
echo -e "*** Error in $1 ! ***"
exit 1
}
function giveMeError {
if [ -z "$2" ]; then
errorMessage $1
exit 1
else
filename=$(basename $2)
echo -e "Moving: $2 to $FAILED_PATH$filename"
mv $2 $FAILED_PATH$filename
delAll
errorMessage $1
fi
}
function saksbehandling {
echo -e "\n*** RUNNING SAKSBEHANDLING ***"
cd $SAKSBEHANDLING_PATH
echo Command: node $SAKSBEHANDLINGS_BIN $SAKSBEHANDLINGS_OPTS
node $SAKSBEHANDLINGS_BIN $SAKSBEHANDLINGS_OPTS
if [ $? -ne 0 ]; then
giveMeError saksbehandling
fi
}
function flow {
echo -e "\n*** RUNNING FLOW ***"
cd $FLOW_PATH
echo Command: node $FLOW_BIN $1
node $FLOW_BIN $1
if [ $? -ne 0 ]; then
giveMeError flow $1
fi
}
function siimport {
echo -e "\n*** RUNNING 360IMPORT ***"
cd $SI_PATH
echo Command: php $SI_BIN $1
php $SI_BIN $1
if [ $? -ne 0 ]; then
giveMeError siimport $1
fi
}
saksbehandling
for f in $IMPORT_PATH*.json; do
echo "Processing $f file..";
fileExist $f
flow $f
siimport $f
filename=$(basename $f)
mv $f $DONE_PATH$filename
delAll
done
| {
"content_hash": "39dc2e086852283eecc40676f2813175",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 63,
"avg_line_length": 20.529411764705884,
"alnum_prop": 0.6716332378223495,
"repo_name": "telemark/tfk-run-skoleskyss",
"id": "e0c75d9d773b846d52aae403522a34d66e0f66a7",
"size": "1758",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "run_skoleskyss.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "1758"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_24) on Wed Apr 17 10:23:35 UTC 2013 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.encog.ml.hmm.distributions Class Hierarchy (Encog Core 3.2.0-SNAPSHOT API)
</TITLE>
<META NAME="date" CONTENT="2013-04-17">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title = "org.encog.ml.hmm.distributions Class Hierarchy (Encog Core 3.2.0-SNAPSHOT API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/encog/ml/hmm/alog/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../../org/encog/ml/hmm/train/bw/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/encog/ml/hmm/distributions/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if (window == top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
Hierarchy For Package org.encog.ml.hmm.distributions
</H2>
</CENTER>
<DL>
<DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../overview-tree.html">All Packages</A></DL>
<HR>
<H2>
Class Hierarchy
</H2>
<UL>
<LI TYPE="circle">java.lang.<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><B>Object</B></A><UL>
<LI TYPE="circle">org.encog.ml.hmm.distributions.<A HREF="../../../../../org/encog/ml/hmm/distributions/ContinousDistribution.html" title="class in org.encog.ml.hmm.distributions"><B>ContinousDistribution</B></A> (implements org.encog.ml.hmm.distributions.<A HREF="../../../../../org/encog/ml/hmm/distributions/StateDistribution.html" title="interface in org.encog.ml.hmm.distributions">StateDistribution</A>)
<LI TYPE="circle">org.encog.ml.hmm.distributions.<A HREF="../../../../../org/encog/ml/hmm/distributions/DiscreteDistribution.html" title="class in org.encog.ml.hmm.distributions"><B>DiscreteDistribution</B></A> (implements org.encog.ml.hmm.distributions.<A HREF="../../../../../org/encog/ml/hmm/distributions/StateDistribution.html" title="interface in org.encog.ml.hmm.distributions">StateDistribution</A>)
</UL>
</UL>
<H2>
Interface Hierarchy
</H2>
<UL>
<LI TYPE="circle">java.lang.<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Cloneable.html?is-external=true" title="class or interface in java.lang"><B>Cloneable</B></A><UL>
<LI TYPE="circle">org.encog.ml.hmm.distributions.<A HREF="../../../../../org/encog/ml/hmm/distributions/StateDistribution.html" title="interface in org.encog.ml.hmm.distributions"><B>StateDistribution</B></A> (also extends java.io.<A HREF="http://java.sun.com/javase/6/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</A>)
</UL>
<LI TYPE="circle">java.io.<A HREF="http://java.sun.com/javase/6/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io"><B>Serializable</B></A><UL>
<LI TYPE="circle">org.encog.ml.hmm.distributions.<A HREF="../../../../../org/encog/ml/hmm/distributions/StateDistribution.html" title="interface in org.encog.ml.hmm.distributions"><B>StateDistribution</B></A> (also extends java.lang.<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Cloneable.html?is-external=true" title="class or interface in java.lang">Cloneable</A>)
</UL>
</UL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/encog/ml/hmm/alog/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../../org/encog/ml/hmm/train/bw/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/encog/ml/hmm/distributions/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if (window == top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2013. All Rights Reserved.
</BODY>
</HTML>
| {
"content_hash": "38fd237e3e5d7a4932818f07e3b96122",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 425,
"avg_line_length": 60.40119760479042,
"alnum_prop": 0.5276097947853673,
"repo_name": "ladygagapowerbot/bachelor-thesis-implementation",
"id": "eb8f966a0d688106b68d2f51fef63bd1bbf30a0a",
"size": "10087",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/Encog/apidocs/org/encog/ml/hmm/distributions/package-tree.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
import pytest
from .config import *
@pytest.fixture
def app():
main.app.config["TESTING"] = True
main.app.config["SQLALCHEMY_DATABASE_URI"] = TEST_DATABASE_URI
main.db.create_all()
return main.app
@pytest.fixture
def test_client(app):
return app.test_client()
def test_hello(test_client):
assert isinstance(test_client, FlaskClient)
def test_keyboard(test_client):
response = test_client.get("/keyboard")
check_response(response)
keyboard = json.loads(response.data)
assert keyboard["type"] == "buttons"
assert keyboard["buttons"] == ["홈버튼 1", "홈버튼 2", "홈버튼 3"]
def test_fail_message(test_client):
data = dict(
user_key="test_id"
)
json_data = json.dumps(data)
response = test_client.post("/message", data=json_data, content_type="application/json")
assert response.status_code == 400
message = json.loads(response.data)
assert message["message"]["text"] == "오류가 발생하였습니다."
def test_message(test_client):
data = dict(
user_key="test_id",
type="text",
content="홈버튼 1"
)
json_data = json.dumps(data)
response = test_client.post("/message", data=json_data, content_type="application/json")
check_response(response)
message = json.loads(response.data)
assert message["message"]["text"] == "기본 메시지"
assert message["keyboard"]["type"] == "buttons"
assert message["keyboard"]["buttons"] == ["홈버튼 1", "홈버튼 2", "홈버튼 3"]
def test_add_friend(test_client):
data = dict(
user_key="test_id"
)
json_data = json.dumps(data)
response = test_client.post("/friend", data=json_data, content_type="application/json")
check_success_response(response)
def test_block_firend(test_client):
user_key = "test_id"
response = test_client.delete("/friend/{}".format(user_key))
check_success_response(response)
def test_exit_chatroom(test_client):
user_key = "test_id"
response = test_client.delete("/chat_room/{}".format(user_key))
check_success_response(response)
def test_remove_keyboard(test_client):
msg = message.BaseMessage()
msg.remove_keyboard()
assert "keyboard" not in msg.get_message()
def test_add_photo(test_client):
msg = message.BaseMessage()
url = "https://www.python.org/static/img/python-logo.png"
msg.add_photo(url, 320, 240)
assert "photo" in msg.get_message()["message"]
assert url == msg.get_message()["message"]["photo"]["url"]
assert 320 == msg.get_message()["message"]["photo"]["width"]
assert 240 == msg.get_message()["message"]["photo"]["height"]
def test_add_message_button(test_client):
msg = message.BaseMessage()
url = "https://www.ruby-lang.org/ko/"
msg.add_message_button(url, "루비")
assert "message_button" in msg.get_message()["message"]
assert url == msg.get_message()["message"]["message_button"]["url"]
assert "루비" == msg.get_message()["message"]["message_button"]["label"]
def test_update_message(teset_client):
msg = message.BaseMessage()
msg.update_message("파이썬")
assert "파이썬" == msg.get_message()["message"]["text"]
def test_update_message(test_client):
msg = message.BaseMessage()
msg.update_keyboard(["파이썬", "루비", "아희"])
assert ["파이썬", "루비", "아희"] == msg.get_message()["keyboard"]["buttons"]
def check_success_response(response):
check_response(response)
message = json.loads(response.data)
assert message["message"] == "SUCCESS"
assert message["comment"] == "정상 응답"
def check_response(response):
assert response.status_code == 200
assert response.content_type == "application/json"
assert isinstance(response.data, bytes)
assert isinstance(json.loads(response.data), dict)
| {
"content_hash": "39385a8c95297978a95a97268793130d",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 92,
"avg_line_length": 29.385826771653544,
"alnum_prop": 0.6543408360128617,
"repo_name": "JungWinter/yellowid-flask",
"id": "1a8683fdb1d1d0da7e6efa1309788057c6bec6c6",
"size": "3860",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test_routing.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "20052"
}
],
"symlink_target": ""
} |
namespace Bearded.Photones {
class GameStatistics {
public int NrGameObjects;
}
}
| {
"content_hash": "645703359e8a6a30533d062d19a41a3b",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 33,
"avg_line_length": 16.666666666666668,
"alnum_prop": 0.65,
"repo_name": "Mattias1/photones",
"id": "3f8e8fbe7c8e7ca27d5fa6a208533290bd5886d2",
"size": "102",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Bearded/GameStatistics.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "52410"
},
{
"name": "CSS",
"bytes": "10550"
},
{
"name": "F#",
"bytes": "16577"
},
{
"name": "GLSL",
"bytes": "759"
},
{
"name": "JavaScript",
"bytes": "2125"
}
],
"symlink_target": ""
} |
package eventstore.j
import java.util
import scala.concurrent.Future
import eventstore.EventData
import eventstore.core.ScalaCompat.JavaConverters._
class EsTransactionImpl(transaction: eventstore.akka.EsTransaction) extends EsTransaction {
def getId: Long = transaction.transactionId
def write(events: util.Collection[EventData]): Future[Unit] = transaction.write(events.asScala.toList)
def commit(): Future[Unit] = transaction.commit()
} | {
"content_hash": "7f5ba2bf7c61b150316e9abc4f0803e7",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 104,
"avg_line_length": 37.25,
"alnum_prop": 0.8120805369127517,
"repo_name": "EventStore/EventStore.JVM",
"id": "c2a15ed6cd69582b3664cb17067526fae885b0e5",
"size": "447",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/src/main/scala/eventstore/j/EsTransactionImpl.scala",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "29794"
},
{
"name": "Scala",
"bytes": "683287"
}
],
"symlink_target": ""
} |
package org.apache.flink.table.types;
import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.util.Preconditions;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import static org.apache.flink.table.types.logical.utils.LogicalTypeUtils.toInternalConversionClass;
/**
* A data type that contains field data types (i.e. row and structured type).
*
* @see DataTypes for a list of supported data types
*/
@PublicEvolving
public final class FieldsDataType extends DataType {
private final List<DataType> fieldDataTypes;
public FieldsDataType(
LogicalType logicalType,
@Nullable Class<?> conversionClass,
List<DataType> fieldDataTypes) {
super(logicalType, conversionClass);
Preconditions.checkNotNull(fieldDataTypes, "Field data types must not be null.");
this.fieldDataTypes =
fieldDataTypes.stream().map(this::updateInnerDataType).collect(Collectors.toList());
}
public FieldsDataType(LogicalType logicalType, List<DataType> fieldDataTypes) {
this(logicalType, null, fieldDataTypes);
}
@Override
public DataType notNull() {
return new FieldsDataType(logicalType.copy(false), conversionClass, fieldDataTypes);
}
@Override
public DataType nullable() {
return new FieldsDataType(logicalType.copy(true), conversionClass, fieldDataTypes);
}
@Override
public DataType bridgedTo(Class<?> newConversionClass) {
return new FieldsDataType(
logicalType,
Preconditions.checkNotNull(
newConversionClass, "New conversion class must not be null."),
fieldDataTypes);
}
@Override
public List<DataType> getChildren() {
return fieldDataTypes;
}
@Override
public <R> R accept(DataTypeVisitor<R> visitor) {
return visitor.visit(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
FieldsDataType that = (FieldsDataType) o;
return fieldDataTypes.equals(that.fieldDataTypes);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), fieldDataTypes);
}
// --------------------------------------------------------------------------------------------
private DataType updateInnerDataType(DataType innerDataType) {
if (conversionClass == RowData.class) {
return innerDataType.bridgedTo(
toInternalConversionClass(innerDataType.getLogicalType()));
}
return innerDataType;
}
}
| {
"content_hash": "20ebdbd3499c40f9586ec002c5382dd5",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 100,
"avg_line_length": 30.019801980198018,
"alnum_prop": 0.6388522427440633,
"repo_name": "tony810430/flink",
"id": "26a41092263a32852bce4e8504cea79a68bbda64",
"size": "3837",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/FieldsDataType.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "20596"
},
{
"name": "Batchfile",
"bytes": "1863"
},
{
"name": "C",
"bytes": "847"
},
{
"name": "Clojure",
"bytes": "84752"
},
{
"name": "Cython",
"bytes": "130661"
},
{
"name": "Dockerfile",
"bytes": "5563"
},
{
"name": "FreeMarker",
"bytes": "92068"
},
{
"name": "GAP",
"bytes": "139514"
},
{
"name": "HTML",
"bytes": "154937"
},
{
"name": "HiveQL",
"bytes": "119074"
},
{
"name": "Java",
"bytes": "92143788"
},
{
"name": "JavaScript",
"bytes": "7038"
},
{
"name": "Less",
"bytes": "68979"
},
{
"name": "Makefile",
"bytes": "5134"
},
{
"name": "Python",
"bytes": "2567118"
},
{
"name": "Scala",
"bytes": "10731670"
},
{
"name": "Shell",
"bytes": "528828"
},
{
"name": "TypeScript",
"bytes": "311274"
},
{
"name": "q",
"bytes": "9630"
}
],
"symlink_target": ""
} |
package AGVS.Data;
import java.util.List;
public class PosicaoInicioTurno {
private String nome;
private Tag tag;
private AGV agv;
private List<FuncaoPos> fps;
public List<FuncaoPos> getFps() {
return fps;
}
public void setFps(List<FuncaoPos> fps) {
this.fps = fps;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Tag getTag() {
return tag;
}
public void setTag(Tag tag) {
this.tag = tag;
}
public PosicaoInicioTurno(String nome, Tag tag, AGV agv, List<FuncaoPos> fps) {
super();
this.nome = nome;
this.tag = tag;
this.agv = agv;
this.fps = fps;
}
public AGV getAgv() {
return agv;
}
public void setAgv(AGV agv) {
this.agv = agv;
}
}
| {
"content_hash": "f64c31376a6ef67f01b88d379a9360d1",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 80,
"avg_line_length": 15.72549019607843,
"alnum_prop": 0.614713216957606,
"repo_name": "cabralsilva/Supervisorio",
"id": "08f5f7f206091bd8d17210700859bb89b76b4fdf",
"size": "802",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Supervisorio/src/AGVS/Data/PosicaoInicioTurno.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3487728"
},
{
"name": "HTML",
"bytes": "413392"
},
{
"name": "Java",
"bytes": "772220"
},
{
"name": "JavaScript",
"bytes": "931467"
},
{
"name": "PHP",
"bytes": "74"
}
],
"symlink_target": ""
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . '/libraries/REST_Controller.php';
class Gifting extends REST_Controller {
public function __construct() {
parent::__construct();
$this->load->model('gifting_model');
$this->load->model('notifications_model');
$this->load->library('session');
$this->_all_request_parameters = array_merge($this->input->get()? : array(), $this->args());
}
public function index_get() {
try {
if (!isset($this->_all_request_parameters["id"])) {
$this->get_giftings();
}
$giftingId = $this->_all_request_parameters["id"];
$gifting = $this->gifting_model->get_gifting($giftingId);
$this->response($gifting, 200);
} catch (Exception $e) {
$error_response = array();
$error_response['error'] = '[Error] ' . $e->getMessage();
$error_response['code'] = 404;
$this->response($error_response, 404);
}
}
public function get_giftings() {
try {
if (is_numeric($this->session->userdata("user_id"))) {
$user_id = $this->session->userdata("user_id");
}
$giftings = $this->gifting_model->get_giftings($user_id);
$this->response($giftings, 200);
} catch (Exception $e) {
$error_response = array();
$error_response['error'] = '[Error] ' . $e->getMessage();
$error_response['code'] = 404;
$this->response($error_response, 404);
}
}
public function send_get() {
$this->send_post();
}
public function send_post() {
try {
if (is_numeric($this->session->userdata("user_id"))) {
$this->_all_request_parameters["sender_fb_id"] = $this->session->userdata("user_id");
}
$gifting_id = $this->gifting_model->set_gifting_send($this->_all_request_parameters);
$fields["user_id"] = $this->_all_request_parameters["receiver_fb_id"];
$fields["message"] = "Hi! You have received a new gift! <a href='/dashboard/receive-gift/" . $gifting_id . "'>Click here</a> to check it out.";
$this->notifications_model->create_notification($fields);
$this->response($gifting_id, 200);
} catch (Exception $e) {
$error_response = array();
$error_response['error'] = '[Error] ' . $e->getMessage();
$error_response['code'] = 404;
$this->response($error_response, 404);
}
}
public function accept_get() {
$this->accept_post();
}
public function accept_post() {
try {
if (is_numeric($this->session->userdata("user_id"))) {
// $this->_all_request_parameters["receiver_fb_id"] = $this->session->userdata("receiver_fb_id");
}
$result = $this->gifting_model->set_gifting_accept($this->_all_request_parameters);
$fields["user_id"] = $this->_all_request_parameters["sender_fb_id"];
$fields["message"] = "Hi! Your gift was accepted! <a href='/dashboard/view-gift/" . $this->_all_request_parameters['gifting_id'] . "'>Click here</a> to check it out.";
$this->notifications_model->create_notification($fields);
$this->response($result, 200);
} catch (Exception $e) {
$error_response = array();
$error_response['error'] = '[Error] ' . $e->getMessage();
$error_response['code'] = 404;
$this->response($error_response, 404);
}
}
} | {
"content_hash": "e515576780c8f81b869d230b7bce42e6",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 170,
"avg_line_length": 31.989795918367346,
"alnum_prop": 0.6287081339712919,
"repo_name": "stiucsib86/happiness-app",
"id": "1b16f9601f9e76b249d095c8cc3982ab44433520",
"size": "3135",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/controllers/gifting.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "604703"
},
{
"name": "PHP",
"bytes": "1284016"
},
{
"name": "Perl",
"bytes": "6113"
}
],
"symlink_target": ""
} |
import { test as it, expect } from './pageTest';
async function giveItAChanceToResolve(page) {
for (let i = 0; i < 5; i++)
await page.evaluate(() => new Promise(f => requestAnimationFrame(() => requestAnimationFrame(f))));
}
it('should wait for visible', async ({ page }) => {
await page.setContent(`<div style='display:none'>content</div>`);
const div = await page.$('div');
let done = false;
const promise = div.waitForElementState('visible').then(() => done = true);
await giveItAChanceToResolve(page);
expect(done).toBe(false);
await div.evaluate(div => div.style.display = 'block');
await promise;
});
it('should wait for already visible', async ({ page }) => {
await page.setContent(`<div>content</div>`);
const div = await page.$('div');
await div.waitForElementState('visible');
});
it('should timeout waiting for visible', async ({ page }) => {
await page.setContent(`<div style='display:none'>content</div>`);
const div = await page.$('div');
const error = await div.waitForElementState('visible', { timeout: 1000 }).catch(e => e);
expect(error.message).toContain('Timeout 1000ms exceeded');
});
it('should throw waiting for visible when detached', async ({ page }) => {
await page.setContent(`<div style='display:none'>content</div>`);
const div = await page.$('div');
const promise = div.waitForElementState('visible').catch(e => e);
await div.evaluate(div => div.remove());
const error = await promise;
expect(error.message).toContain('Element is not attached to the DOM');
});
it('should wait for hidden', async ({ page }) => {
await page.setContent(`<div>content</div>`);
const div = await page.$('div');
let done = false;
const promise = div.waitForElementState('hidden').then(() => done = true);
await giveItAChanceToResolve(page);
expect(done).toBe(false);
await div.evaluate(div => div.style.display = 'none');
await promise;
});
it('should wait for already hidden', async ({ page }) => {
await page.setContent(`<div></div>`);
const div = await page.$('div');
await div.waitForElementState('hidden');
});
it('should wait for hidden when detached', async ({ page }) => {
await page.setContent(`<div>content</div>`);
const div = await page.$('div');
let done = false;
const promise = div.waitForElementState('hidden').then(() => done = true);
await giveItAChanceToResolve(page);
expect(done).toBe(false);
await div.evaluate(div => div.remove());
await promise;
});
it('should throw waiting for enabled when detached', async ({ page }) => {
await page.setContent(`<button disabled>Target</button>`);
const button = await page.$('button');
const promise = button.waitForElementState('enabled').catch(e => e);
await button.evaluate(button => button.remove());
const error = await promise;
expect(error.message).toContain('Element is not attached to the DOM');
});
it('should wait for aria enabled button', async ({ page }) => {
await page.setContent('<button aria-disabled=true><span>Target</span></button>');
const span = await page.$('text=Target');
let done = false;
const promise = span.waitForElementState('enabled').then(() => done = true);
await giveItAChanceToResolve(page);
expect(done).toBe(false);
await span.evaluate(span => span.parentElement.setAttribute('aria-disabled', 'false'));
await promise;
});
it('should wait for button with an aria-disabled parent', async ({ page }) => {
await page.setContent('<div role="group" aria-disabled=true><button><span>Target</span></button></div>');
const span = await page.$('text=Target');
let done = false;
const promise = span.waitForElementState('enabled').then(() => done = true);
await giveItAChanceToResolve(page);
expect(done).toBe(false);
await span.evaluate(span => span.parentElement.parentElement.setAttribute('aria-disabled', 'false'));
await promise;
});
it('should wait for stable position', async ({ page, server, browserName, platform }) => {
it.fixme(browserName === 'firefox' && platform === 'linux');
await page.goto(server.PREFIX + '/input/button.html');
const button = await page.$('button');
await page.$eval('button', button => {
button.style.transition = 'margin 10000ms linear 0s';
button.style.marginLeft = '20000px';
});
let done = false;
const promise = button.waitForElementState('stable').then(() => done = true);
await giveItAChanceToResolve(page);
expect(done).toBe(false);
await button.evaluate(button => button.style.transition = '');
await promise;
});
it('should wait for editable input', async ({ page, server }) => {
await page.setContent('<input readonly>');
const input = await page.$('input');
let done = false;
const promise = input.waitForElementState('editable').then(() => done = true);
await giveItAChanceToResolve(page);
expect(done).toBe(false);
await input.evaluate(input => input.readOnly = false);
await promise;
});
| {
"content_hash": "38dc589817a26b78b32e367420ef0407",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 107,
"avg_line_length": 38.5,
"alnum_prop": 0.6751217532467533,
"repo_name": "microsoft/playwright",
"id": "1dc17b409b05b7c00769a734faf086b8ff18c3b3",
"size": "5598",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "tests/page/elementhandle-wait-for-element-state.spec.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "291"
},
{
"name": "C",
"bytes": "7890"
},
{
"name": "C#",
"bytes": "2296"
},
{
"name": "C++",
"bytes": "116810"
},
{
"name": "CMake",
"bytes": "2704"
},
{
"name": "CSS",
"bytes": "103622"
},
{
"name": "HTML",
"bytes": "339177"
},
{
"name": "Java",
"bytes": "16271"
},
{
"name": "JavaScript",
"bytes": "75700"
},
{
"name": "Makefile",
"bytes": "377"
},
{
"name": "Objective-C",
"bytes": "63418"
},
{
"name": "PowerShell",
"bytes": "4150"
},
{
"name": "Python",
"bytes": "2965"
},
{
"name": "Shell",
"bytes": "43661"
},
{
"name": "Svelte",
"bytes": "3358"
},
{
"name": "TypeScript",
"bytes": "5956124"
},
{
"name": "Vue",
"bytes": "6225"
}
],
"symlink_target": ""
} |
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace metrics
{
struct LastReportedMetrics
{
std::unique_ptr<AttributesHashMap> attributes_map;
opentelemetry::common::SystemTimestamp collection_ts;
};
class TemporalMetricStorage
{
public:
TemporalMetricStorage(InstrumentDescriptor instrument_descriptor,
const AggregationConfig *aggregation_config);
bool buildMetrics(CollectorHandle *collector,
nostd::span<std::shared_ptr<CollectorHandle>> collectors,
opentelemetry::common::SystemTimestamp sdk_start_ts,
opentelemetry::common::SystemTimestamp collection_ts,
std::shared_ptr<AttributesHashMap> delta_metrics,
nostd::function_ref<bool(MetricData)> callback) noexcept;
private:
InstrumentDescriptor instrument_descriptor_;
// unreported metrics stash for all the collectors
std::unordered_map<CollectorHandle *, std::list<std::shared_ptr<AttributesHashMap>>>
unreported_metrics_;
// last reported metrics stash for all the collectors.
std::unordered_map<CollectorHandle *, LastReportedMetrics> last_reported_metrics_;
// Lock while building metrics
mutable opentelemetry::common::SpinLockMutex lock_;
const AggregationConfig *aggregation_config_;
};
} // namespace metrics
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE
| {
"content_hash": "5a9d9a052f1b34aae9d88e3856e60a15",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 86,
"avg_line_length": 33.78048780487805,
"alnum_prop": 0.7249097472924187,
"repo_name": "open-telemetry/opentelemetry-cpp",
"id": "439ca3cd4df32c2a881f9140fb09a844480c0aa7",
"size": "1739",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/include/opentelemetry/sdk/metrics/state/temporal_metric_storage.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "26333"
},
{
"name": "C",
"bytes": "53444"
},
{
"name": "C++",
"bytes": "2433332"
},
{
"name": "CMake",
"bytes": "121041"
},
{
"name": "Dockerfile",
"bytes": "8258"
},
{
"name": "Jinja",
"bytes": "2860"
},
{
"name": "PowerShell",
"bytes": "9791"
},
{
"name": "Python",
"bytes": "191"
},
{
"name": "Shell",
"bytes": "45013"
},
{
"name": "Starlark",
"bytes": "83119"
}
],
"symlink_target": ""
} |
<!doctype html>
<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]-->
<!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]-->
<head>
<meta charset="utf-8">
<title>Latest Posts – www.DanLevy.net</title>
<meta name="description" content="Dan Levy's Website & Blog Musings">
<meta name="keywords" content="programming, languages, javascript, angularjs, devops, docker, security">
<!-- Twitter Cards -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="/images/abstract-1.jpg">
<meta name="twitter:title" content="Latest Posts">
<meta name="twitter:description" content="Dan Levy's Website & Blog Musings">
<meta name="twitter:creator" content="@justsml">
<script>window.twttr = (function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
t = window.twttr || {};
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
t._e = [];
t.ready = function(f) {
t._e.push(f);
};
return t;
}(document, "script", "twitter-wjs"));
</script>
<!-- Open Graph -->
<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="Latest Posts">
<meta property="og:description" content="Dan Levy's Website & Blog Musings">
<meta property="og:url" content="/index.html">
<meta property="og:site_name" content="www.DanLevy.net">
<meta name="google-site-verification" content="aQmDDAD2Nia138WekOPnb9tQ_J9AcRUDLbij5PxCmes">
<meta name="msvalidate.01" content="1A9E3CE623BA981E829FE1023285585D">
<link rel="canonical" href="/">
<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="www.DanLevy.net Feed">
<!-- http://t.co/dKP3o1e -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- For all browsers -->
<link rel="stylesheet" href="/assets/css/main.css">
<link rel="stylesheet" href="/assets/css/custom.css">
<!-- Webfonts -->
<link async defer href="//fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic" rel="stylesheet" type="text/css">
<meta http-equiv="cleartype" content="on">
<!-- Load Modernizr -->
<script src="/assets/js/vendor/modernizr-2.6.2.custom.min.js"></script>
<script async defer src="/assets/js/hacks.js"></script>
<!-- <link async defer rel="stylesheet" href="/assets/css/prism.css">
<script async defer src="/assets/js/vendor/prism.js"></script>
-->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.7/styles/default.min.css" />
<script defer async="async" src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.7/highlight.min.js"></script>
<!-- Icons -->
<!-- 16x16 -->
<link rel="shortcut icon" href="/favicon.ico">
<!-- 32x32 -->
<link rel="shortcut icon" href="/favicon.png">
<!-- 57x57 (precomposed) for iPhone 3GS, pre-2011 iPod Touch and older Android devices -->
<link rel="apple-touch-icon-precomposed" href="/images/apple-touch-icon-precomposed.png">
<!-- 72x72 (precomposed) for 1st generation iPad, iPad 2 and iPad mini -->
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="/images/apple-touch-icon-72x72-precomposed.png">
<!-- 114x114 (precomposed) for iPhone 4, 4S, 5 and post-2011 iPod Touch -->
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="/images/apple-touch-icon-114x114-precomposed.png">
<!-- 144x144 (precomposed) for iPad 3rd and 4th generation -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/images/apple-touch-icon-144x144-precomposed.png">
<!--
<style type="text/css">body { background-repeat: repeat-x; background-image:url(/images/abstract-3.jpg);}</style>
-->
<!-- Syntax Highlighting -->
<!-- <script async defer type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/prism/0.0.1/prism.min.js'></script>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/prism/0.0.1/prism.min.css' />
--><!-- https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.7/highlight.min.js
-->
<style type='text/css'>
#toc, .toc, .mw-warning {
background-color: #F9F9F9;
border: 1px solid #AAAAAA;
font-size: 95%;
padding: 5px;
}
#toc h2, .toc h2 {
border: medium none;
display: inline;
font-size: 100%;
font-weight: bold;
padding: 0;
}
#toc #toctitle, .toc #toctitle, #toc .toctitle, .toc .toctitle {
text-align: center;
}
#toc ul, .toc ul {
list-style-image: none;
list-style-type: none;
margin-left: 0;
margin-bottom: 0;
padding-left: 0;
text-align: left;
}
#toc ul ul, .toc ul ul {
margin: 0 0 0 2em;
}
#toc .toctoggle, .toc .toctoggle {
font-size: 94%;
}
#toc ul li {
list-style-type: none;
padding-left: 0;
}
#toc-container {
margin-bottom: 10px;
}
</style>
</head>
<body id="post-index" class="feature">
<!--[if lt IE 9]><div class="upgrade"><strong><a href="http://whatbrowser.org/">Your browser is quite old!</strong> Why not upgrade to a different browser to better enjoy this site?</a></div><![endif]-->
<nav id="dl-menu" class="dl-menuwrapper" role="navigation">
<button class="dl-trigger">Open Menu</button>
<ul class="dl-menu">
<li><a href="/">Home</a></li>
<li><a href="/tags">Tags</a></li>
<li>
<a href="#">About Dan</a>
<ul class="dl-submenu">
<li>
<img src="/images/avatar.jpg" alt="Dan Levy photo" class="author-photo">
<div class="clearfix"></div>
<h3 style="float: left; display: inline; margin-left: 12px;">Dan Levy</h3>
<p style="float: right; display: inline;">Devout Programmer</p>
<div class="clearfix"></div>
</li>
<li><a href="/cv/resume-dan-levy-2015-07.pdf" target='_blank'><span class="btn btn-inverse">Resume</span></a></li>
<li>
<a href="mailto:Dan@DanLevy.net"><i class="fa fa-fw fa-envelope"></i> Email</a>
</li>
<li>
<a target="_blank" href="http://github.com/justsml"><i class="fa fa-fw fa-github"></i> GitHub</a>
</li>
<li>
<a target="_blank" href="http://twitter.com/justsml"><i class="fa fa-fw fa-twitter"></i> Twitter</a>
</li>
<li>
<a target="_blank" href="http://facebook.com/justsml"><i class="fa fa-fw fa-facebook"></i> Facebook</a>
</li>
<li>
<a target="_blank" href="https://google.com/+justsml"><i class="fa fa-fw fa-google-plus"></i> Google+</a>
</li>
<li>
<a target="_blank" href="http://linkedin.com/in/realdanlevy"><i class="fa fa-fw fa-linkedin"></i> LinkedIn</a>
</li>
</ul><!-- /.dl-submenu -->
</li>
<li>
<a href="#">Articles</a>
<ul class="dl-submenu article-list">
<li class="entry-title">
<a href="/2015/09/22/concatenation-anti-patterns/" title="Beautiful Models (and Data)">
<div>Beautiful Models (and Data)</div>
<em>2015-09-22</em>
</a>
</li>
<li class="entry-title">
<a href="/2015/09/22/beautiful-engineering-models-and-data/" title="Beautiful Models (and Data)">
<div>Beautiful Models (and Data)</div>
<em>2015-09-22</em>
</a>
</li>
<li class="entry-title">
<a href="/2015/08/05/angularjs-v2-impending-schism/" title="AngularJS v2.0 and the Impending Schism">
<div>AngularJS v2.0 and the Impending Schism</div>
<em>2015-08-05</em>
</a>
</li>
<li class="entry-title">
<a href="/2015/06/12/polyglot-redux/" title="Polyglot Redux">
<div>Polyglot Redux</div>
<em>2015-06-12</em>
</a>
</li>
<li class="entry-title">
<a href="/2015/06/10/docker-great-though-boot2docker-sucks/" title="Docker rocks. Boot2docker just sucks.">
<div>Docker rocks. Boot2docker just sucks.</div>
<em>2015-06-10</em>
</a>
</li>
<li style="text-align: center;"><a href="/posts/"><strong>[ All Articles ]</strong></a></li>
</ul>
</li>
<li><a href="/cv/resume-dan-levy-2015-07.pdf" >Download Resume</a></li>
<li><a href="http://github.com/justsml" target="_blank">GitHub</a></li>
</ul><!-- /.dl-menu -->
</nav><!-- /.dl-menuwrapper -->
<div class="entry-header">
<div class="image-credit">Image source: <a href="">dargadgetz</a></div><!-- /.image-credit -->
<div class="entry-image">
<img src="/images/abstract-1.jpg" alt="Latest Posts">
</div><!-- /.entry-image -->
<div class="header-title">
<div class="header-title-wrap">
<h1>www.DanLevy.net</h1>
<h2>Latest Posts</h2>
</div><!-- /.header-title-wrap -->
</div><!-- /.header-title -->
</div><!-- /.entry-header -->
<div id="main" role="main">
<article class="hentry">
<header>
<div class="entry-image-index">
<a href="/2015/09/22/concatenation-anti-patterns/" title="Beautiful Models (and Data)"><img src="/images/abstract-5.jpg" alt="Beautiful Models (and Data)"></a>
</div><!-- /.entry-image -->
<div class="entry-meta">
<span class="entry-date date published updated"><time datetime="2015-09-22T00:00:00-06:00"><a href="/2015/09/22/concatenation-anti-patterns/">September 22, 2015</a></time></span><span class="author vcard"><span class="fn"><a href="/about/" title="About Dan Levy">Dan Levy</a></span></span>
<span class="entry-reading-time">
<i class="fa fa-clock-o"></i>
Reading time ~18 minutes
</span><!-- /.entry-reading-time -->
</div><!-- /.entry-meta -->
<h1 class="entry-title"><a href="/2015/09/22/concatenation-anti-patterns/" rel="bookmark" title="Beautiful Models (and Data)" itemprop="url">Beautiful Models (and Data)</a></h1>
</header>
<div class="entry-content">
<a name="L.em.Work-in-progress..updated.Nov..2015...em."></a>
<h4><em>Work-in-progress (updated Nov. 2015)</em></h4>
<a name="Array-.or.Set-based.Coding.Style"></a>
<h1>Array- or Set-based Coding Style</h1>
<a name="An.Anti-Pattern."></a>
<h2>An Anti-Pattern?</h2>
<blockquote><p>Note: This is not Yet-Another-Article warning noobs about RAM usage when appending strings</p></blockquote>
<p>This is an exploration of advantages gained when you <strong>code everything as an array.</strong> (Using Jedi concepts from SmallTalk)</p>
<p>Here’s some guiding principles:</p>
<ol>
<li>All input is array-like. Even if an array of 1.</li>
<li>Functions should generally accept AND return arrays.</li>
<li>99 out of 100 devs code suffers from what I call <code>acute schema surplusage</code> syndrome -based models.</li>
<li><p>Yes, beware <code>fat ASS models</code> - with all the predictable trappings: fragile <code>instance state</code> - so many levers and knobs to mess with, DB transactions, sql locks, async/mutexing (that always works first time), using idiomatic <code>property getter/setters</code>, and your <code>public/private/final/etc</code> usage is solid, right?</p></li>
<li><p>So let me take a common problem and <em>shoehorn</em> <del>add</del> some of my set-based heretical musings.</p></li>
<li> Why is a Product price always a single data point? Why on earth would I make price(s) an Array?</li>
<li> Let’s add this functionality:
<ol type="a">
<li><strong>New requirements:</strong> <code>retailPrice</code>, <code>priceSavings</code></li>
</ol>
</li>
<li>These changes hopefully look no worse than my sorry attempt:</li>
</ol>
<pre><code class="java">package net.danlevy.testpool.why.java.has.so.many.dots;
public class Product {
public String Name;
public float Price;
public float retailPrice;
public float priceSavings;
public Product(String name, float price) {
Name = name;
Price = price;
this.retailPrice = price;
this.priceSavings = 0.0f;
}
public Product(String name, float price,
float retailPrice,
float priceSavings) {
this.name = name;
this.price = price;
this.retailPrice = retailPrice;
this.priceSavings = priceSavings;
}
public float getPriceSavings() {
return this.retailPrice - this.price;
}
}
</code></pre>
<p> (I’m not replacing the valid pattern of tracking historical prices in tables)
1. I’m not sure about you, but price of just about anything is in flux - just given time.
1.
I <strong>experience</strong> price as constantly fluctuating data point.</p>
<ol>
<li> For example, even values which seem like singular variables - say a <code>Product</code> class includes <code>var listPrice = 125</code> - change it to <code>var prices = [50, 100, 125]</code>.</li>
<li> Bear with me. That is not likely the final re-factor on that…</li>
</ol>
<pre><code class="js">function Product({name='widget', prices=[]}) {
}
</code></pre>
<blockquote><p>Foreshadowing: We’re going to go through a concept familiar to LISP, SmallTalk, et al. devs.
It’s known by many names, however I prefer <strong>Array-based programming.</strong></p></blockquote>
<a name="The.issue.we.ll.examine.is.deceptively.simple..amp..subtle:..strong.Naming..strong."></a>
<h2>The issue we’ll examine is deceptively simple & subtle: <strong>Naming</strong></h2>
<blockquote><p>I want to avoid the super-fancy-tech-lingo for this article; and hopefully I can illustrate the issue in a more useful fashion.</p>
<p>While covered in exhausting detail before, the subject matter often gets too technical for the novice programmer to draw any practical understanding. You probably don’t need to read this if the following makes sense: <code>No-Sql denormalization strategy</code>, or <code>Boyce Codd Normal Forms</code></p>
<p>Recommended reading includes:</p>
<ol>
<li>Book: Code Complete</li>
<li><a href="http://phlonx.com/resources/nf3/">http://phlonx.com/resources/nf3/</a></li>
<li><a href="https://en.wikipedia.org/wiki/Database_normalization">https://en.wikipedia.org/wiki/Database_normalization</a></li>
</ol>
</blockquote>
<a name="The.Problem.-.by.Example"></a>
<h2>The Problem - by Example</h2>
<p>Have you ever designed a <code>data model</code> (in code, Sql, or excel worksheets)?
Does the following look familiar?</p>
<pre><code>*** anti-pattern - don't copy-paste ***
* User
- id
- avatarUrl
- email
- passwordHash
* Agent
- id
- primaryPhoto
- agentName
- agentEmail
- agentPhoneMain
- agentEmailPrimary
- agentPhonePrimary
- agentAddressLine1
- agentCompanyName
- agentCompanyAddress
- *userEmail* - 'Pointer' to User table ^^^
</code></pre>
<p>If this is familiar to you, I’ll bet you:</p>
<ol>
<li>Feel any change to your app will necessitate hours of arduous debugging.</li>
<li>Fear ANY Changing Requirements
<img src="https://res.cloudinary.com/ddd/image/upload/bldg-collapse__wsZKhIc_kafcha.gif" alt="schema refactor" /></li>
</ol>
<a name="The.Cost.of.Bad..Naming..Habits"></a>
<h2>The Cost of Bad (Naming) Habits</h2>
<p>Let’s examine some of the subtle issues (probably familiar):</p>
<hr />
<p>Why is naming a field <code>agentEmailPrimary</code> the worst?</p>
<p>For starters, you are <strong>not</strong> creating an entirely new object unto the universe. Over-specificity has some traps:</p>
<ol>
<li>‘Locked’ into highly specific name, means <code>agentEmailPrimary</code> probably make your views and related code <strong>0% reusable</strong>, and featuring annoyingly recurring bugs like:
<ul>
<li>Data not syncing between tables (not obvious if <code>user.email</code> needs to propagate to <code>agent.agentEmail</code> or vice-versa - nevermind complexity of manually implementing where & how to enforce this ‘logic’ …)</li>
<li>Validation rules/logic are likely duplicated & inconsitent.</li>
<li>Increasingly, your project will resemble a shaky Jenga tower.</li>
<li>Fragility piles up with every single new file, as an extremely high attention to detail is required for even trivial changes</li>
</ul>
</li>
</ol>
<p>I know, you probably feel something like…</p>
<p><img src="https://res.cloudinary.com/ddd/image/upload/panda-rampage__tumblr_nq7srwTXqr1stn6klo1_500_gm2som.gif" alt="fuck this" /></p>
<a name="A.Solution"></a>
<h2>A Solution</h2>
<pre><code>// Dan's Recommended Schema Consolidation:
User
- id
- role: ['agent', 'lead', 'admin']
- name
- phone
- address
- email
- passwordHash
- company
- name
- address
</code></pre>
<p>I removed the <code>Agent</code> table, as it didn’t contain fields which were uniquely related to Agents.</p>
<p>All changes were made with these general ideas in mind:</p>
<ol>
<li>Eliminate unessesary tables. If you have a few dozen tables, this step is mandatory.</li>
<li> Try merge related tables. <strong>Important if you are coming from a SQL background to No-SQL</strong></li>
<li> Delete redundant data collection (e.g. remove <code>ActivityLogs</code> table if replaced by Google Analytics)</li>
<li>Try keeping <strong>all field names</strong> to a <strong>single word/noun/pro-noun</strong>.</li>
<li> There is <strong>no such thing</strong> as <code>Agent.agentEmail</code> or <code>Agent.agentPhonePrimary</code>. Period.</li>
<li> By using Highly Specific Names, you cast-in-stone a specific level of <code>code-reusability</code> and <code>durability</code>, well, specifically <strong>ZERO %</strong>.</li>
<li> Don’t think you are doing yourself any favors with crap like this <code>User.profileSummaryEmail</code> (where ‘profile’ could include contact details for a personal ads site) . This is probably a good point to create a new table, say <code>Profiles</code> which includes <code>Profiles.email</code>.</li>
</ol>
<a name="L.em.Work-in-progress..updated.Nov..2015...em."></a>
<h3><em>Work-in-progress (updated Nov. 2015)</em></h3>
<!-- ![schema refactor][schema_refactor] -->
</div><!-- /.entry-content -->
</article><!-- /.hentry -->
<article class="hentry">
<header>
<div class="entry-image-index">
<a href="/2015/09/22/beautiful-engineering-models-and-data/" title="Beautiful Models (and Data)"><img src="/images/abstract-5.jpg" alt="Beautiful Models (and Data)"></a>
</div><!-- /.entry-image -->
<div class="entry-meta">
<span class="entry-date date published updated"><time datetime="2015-09-22T00:00:00-06:00"><a href="/2015/09/22/beautiful-engineering-models-and-data/">September 22, 2015</a></time></span><span class="author vcard"><span class="fn"><a href="/about/" title="About Dan Levy">Dan Levy</a></span></span>
<span class="entry-reading-time">
<i class="fa fa-clock-o"></i>
Reading time ~10 minutes
</span><!-- /.entry-reading-time -->
</div><!-- /.entry-meta -->
<h1 class="entry-title"><a href="/2015/09/22/beautiful-engineering-models-and-data/" rel="bookmark" title="Beautiful Models (and Data)" itemprop="url">Beautiful Models (and Data)</a></h1>
</header>
<div class="entry-content">
<a name="L.em.Work-in-progress..updated.Sep..2015...em."></a>
<h4><em>Work-in-progress (updated Sep. 2015)</em></h4>
<a name="The.issue.we.ll.examine.is.deceptively.simple..amp..subtle:..strong.Naming..strong."></a>
<h2>The issue we’ll examine is deceptively simple & subtle: <strong>Naming</strong></h2>
<blockquote><p>I want to avoid the super-fancy-tech-lingo for this article; and hopefully I can illustrate the issue in a more useful fashion.</p>
<p>While covered in exhausting detail before, the subject matter often gets too technical for the novice programmer to draw any practical understanding. You probably don’t need to read this if the following makes sense: <code>No-Sql denormalization strategy</code>, or <code>Boyce Codd Normal Forms</code></p>
<p>Recommended reading includes:</p>
<ol>
<li>Book: Code Complete</li>
<li><a href="http://phlonx.com/resources/nf3/">http://phlonx.com/resources/nf3/</a></li>
<li><a href="https://en.wikipedia.org/wiki/Database_normalization">https://en.wikipedia.org/wiki/Database_normalization</a></li>
</ol>
</blockquote>
<a name="The.Problem.-.by.Example"></a>
<h2>The Problem - by Example</h2>
<p>Have you ever designed a <code>data model</code> (in code, Sql, or excel worksheets)?
Does the following look familiar?</p>
<pre><code>*** anti-pattern - don't copy-paste ***
* User
- id
- avatarUrl
- email
- passwordHash
* Agent
- id
- primaryPhoto
- agentName
- agentEmail
- agentPhoneMain
- agentEmailPrimary
- agentPhonePrimary
- agentAddressLine1
- agentCompanyName
- agentCompanyAddress
- *userEmail* - 'Pointer' to User table ^^^
</code></pre>
<p>If this is familiar to you, I’ll bet you:</p>
<ol>
<li>Feel any change to your app will necessitate hours of arduous debugging.</li>
<li>Fear ANY Changing Requirements
<img src="https://res.cloudinary.com/ddd/image/upload/bldg-collapse__wsZKhIc_kafcha.gif" alt="schema refactor" /></li>
</ol>
<a name="The.Cost.of.Bad..Naming..Habits"></a>
<h2>The Cost of Bad (Naming) Habits</h2>
<p>Let’s examine some of the subtle issues (probably familiar):</p>
<hr />
<p>Why is naming a field <code>agentEmailPrimary</code> the worst?</p>
<p>For starters, you are <strong>not</strong> creating an entirely new object unto the universe. Over-specificity has some traps:</p>
<ol>
<li>‘Locked’ into highly specific name, means <code>agentEmailPrimary</code> probably make your views and related code <strong>0% reusable</strong>, and featuring annoyingly recurring bugs like:
<ul>
<li>Data not syncing between tables (not obvious if <code>user.email</code> needs to propagate to <code>agent.agentEmail</code> or vice-versa - nevermind complexity of manually implementing where & how to enforce this ‘logic’ …)</li>
<li>Validation rules/logic are likely duplicated & inconsitent.</li>
<li>Increasingly, your project will resemble a shaky Jenga tower.</li>
<li>Fragility piles up with every single new file, as an extremely high attention to detail is required for even trivial changes</li>
</ul>
</li>
</ol>
<p>I know, you probably feel something like…</p>
<p><img src="https://res.cloudinary.com/ddd/image/upload/panda-rampage__tumblr_nq7srwTXqr1stn6klo1_500_gm2som.gif" alt="fuck this" /></p>
<a name="A.Solution"></a>
<h2>A Solution</h2>
<pre><code>// Dan's Recommended Schema Consolidation:
User
- id
- role: ['agent', 'lead', 'admin']
- name
- phone
- address
- email
- passwordHash
- company
- name
- address
</code></pre>
<p>I removed the <code>Agent</code> table, as it didn’t contain fields which were uniquely related to Agents.</p>
<p>All changes were made with these general ideas in mind:</p>
<ol>
<li>Eliminate unessesary tables. If you have a few dozen tables, this step is mandatory.</li>
<li> Try merge related tables. <strong>Important if you are coming from a SQL background to No-SQL</strong></li>
<li> Delete redundant data collection (e.g. remove <code>ActivityLogs</code> table if replaced by Google Analytics)</li>
<li>Try keeping <strong>all field names</strong> to a <strong>single word/noun/pro-noun</strong>.</li>
<li> There is <strong>no such thing</strong> as <code>Agent.agentEmail</code> or <code>Agent.agentPhonePrimary</code>. Period.</li>
<li> By using Highly Specific Names, you cast-in-stone a specific level of <code>code-reusability</code> and <code>durability</code>, well, specifically <strong>ZERO %</strong>.</li>
<li> Don’t think you are doing yourself any favors with crap like this <code>User.profileSummaryEmail</code> (where ‘profile’ could include contact details for a personal ads site) . This is probably a good point to create a new table, say <code>Profiles</code> which includes <code>Profiles.email</code>.</li>
</ol>
<a name="L.em.Work-in-progress..updated.Sep..2015...em."></a>
<h3><em>Work-in-progress (updated Sep. 2015)</em></h3>
<!-- ![schema refactor][schema_refactor] -->
</div><!-- /.entry-content -->
</article><!-- /.hentry -->
<article class="hentry">
<header>
<div class="entry-image-index">
<a href="/2015/08/05/angularjs-v2-impending-schism/" title="AngularJS v2.0 and the Impending Schism"><img src="/images/abstract-11.jpg" alt="AngularJS v2.0 and the Impending Schism"></a>
</div><!-- /.entry-image -->
<div class="entry-meta">
<span class="entry-date date published updated"><time datetime="2015-08-05T00:00:00-06:00"><a href="/2015/08/05/angularjs-v2-impending-schism/">August 05, 2015</a></time></span><span class="author vcard"><span class="fn"><a href="/about/" title="About Dan Levy">Dan Levy</a></span></span>
<span class="entry-reading-time">
<i class="fa fa-clock-o"></i>
Reading time ~3 minutes
</span><!-- /.entry-reading-time -->
</div><!-- /.entry-meta -->
<h1 class="entry-title"><a href="/2015/08/05/angularjs-v2-impending-schism/" rel="bookmark" title="AngularJS v2.0 and the Impending Schism" itemprop="url">AngularJS v2.0 and the Impending Schism</a></h1>
</header>
<div class="entry-content">
<p>I think we are witnessing the Python 2->3 ‘Conversion’ all over again.
AngularJS v2.0 introduces too many changes. <strong>Not least of which is TypeScript</strong>, which is a big ask amidst the finalization of JS’s latest version: ES6.</p>
<blockquote><p>Let me say clearly: I love TypeScript. I seccretly wish the TC-39 meetings had produced it… They didn’t.
However, They came up with another (totally different), also-awesome spec…</p></blockquote>
<p>While TypeScript compiles to JavaScript, it doesn’t mean you blindly copy & paste ‘compiled’ TypeScript. It effectively becomes required learning, as to understand annotated AngularJS 2.0 TypeScript.</p>
<p>Now, newbies must climb ‘Mount TypeScript’ before they can even start assembling an Angular app (with some level of understanding).</p>
<p>I have a feeling how this might go…</p>
<div class="anigif end">
<img alt='endless loop' src="https://res.cloudinary.com/ddd/image/upload/timeout-expired.gif" />
</div>
<p>Oh well, I’ll add it to the Newbie training list: somewhere between <code>Basic Shell Usage</code> and <code>Gulp or Grunt? Godsend+Misery!</code></p>
<blockquote><p>Anyway, I hope this works out…</p></blockquote>
<div class="anigif top end">
<img alt='everything is going to be ok' src="http://res.cloudinary.com/ddd/image/upload/v1442175801/system-maint-anon.gif" />
</div>
</div><!-- /.entry-content -->
</article><!-- /.hentry -->
<article class="hentry">
<header>
<div class="entry-image-index">
<a href="/2015/06/12/polyglot-redux/" title="Polyglot Redux"><img src="/images/abstract-11.jpg" alt="Polyglot Redux"></a>
</div><!-- /.entry-image -->
<div class="entry-meta">
<span class="entry-date date published updated"><time datetime="2015-06-12T03:21:12-06:00"><a href="/2015/06/12/polyglot-redux/">June 12, 2015</a></time></span><span class="author vcard"><span class="fn"><a href="/about/" title="About Dan Levy">Dan Levy</a></span></span>
<span class="entry-reading-time">
<i class="fa fa-clock-o"></i>
Reading time ~23 minutes
</span><!-- /.entry-reading-time -->
</div><!-- /.entry-meta -->
<h1 class="entry-title"><a href="/2015/06/12/polyglot-redux/" rel="bookmark" title="Polyglot Redux" itemprop="url">Polyglot Redux</a></h1>
</header>
<div class="entry-content">
<a name="Programming.Languages.Notes"></a>
<h1>Programming Languages Notes</h1>
<a name="L.em.Work-in-progress..updated.Sept..25th.2015...em."></a>
<h3><em>Work-in-progress (updated Sept. 25th 2015)</em></h3>
<a name="I.m.sure.my.Miscellaneous.Observations.have.been.made.before..but.here.is.my.list.of.most.interesting.languages:"></a>
<h3>I’m sure my Miscellaneous Observations have been made before, but here is my list of most interesting languages:</h3>
<a name="JavaScript"></a>
<h2>JavaScript</h2>
<p>My One True Love, supremely versatile & ubiquitous - the all-around, amazingly-powerful champ!
It’s the #1 Most Active/Popular Language on GitHub.com for <em>years</em> running.</p>
<p>I hate to admit it, but for years I foolishly had nothing but scorn and derision for what is now, <strong>my favorite language</strong>.</p>
<p><strong>ES6</strong> has only increased my <del>addiction</del> love. While pure ES5 will always hold a special place in my heart, each time I use some <strong>ES6</strong>, I feel that radioactive spider-bite…</p>
<p>There were 4 factors which pushed me into the <strong>ES6 Camp</strong>:</p>
<ol>
<li>It’s fun. Seriously. There are tangible gains in beauty, clarity & productivity.</li>
<li>Subjective claims, you say? Let me show you a bit of ES6:</li>
<li><code>let expired = users.filter(u => Date.now() > u.trialDate)</code></li>
<li>Now you don’t have to pretend you know how to use <code>Object.create</code> or <code>Object.defineProperty</code></li>
<li>See examples below</li>
<li>As of July 2015, ES6 is an officially finalized standard now!</li>
<li>Support is Effectively 100%*! … Ok, BabelJS is needed to patch your code so it’s ES5 compatible. Historically JS transpilers have been frowned upon. However, as of late (2014-15) things have changed as BabelJS has become a key enabler/driver of language advancement. Tons of companies including Microsoft & Facebook use it on some of the largest sites around.</li>
<li><a href="https://nodejs.org/en/blog/release/v4.0.0/">Latest versions of Node</a> include the same V8 JS engine as Chrome v45, it’s v4.5</li>
</ol>
<a name="Examples"></a>
<h3>Examples</h3>
<blockquote><p>I’m going to show you what finally made me <em>start</em> drinking that ES6-flavoured KoolAid.</p></blockquote>
<p>In my recent experience, ES6 helps you write code faster. To the point.
Because code is more succinct, appreciably less brain power is needed to sift through and understand your old code (or that of a teammates).</p>
<p>I have regularly seen KLOC savings roughly of 20-50%. That’s like Kate Moss trim!</p>
<p><img src="/images/screenshots/Diff-ES6-vs-ES5-Head-to-Head.png" alt="EcmaScript 5 vs ES 2016 - Demo: Classes, Destructuring, Sexiness" /></p>
<pre><code class="js">// /services/users.js
class Users {
constructor(data) {
this.users = data || [];
}
expired() {
return this.users
.filter(u => Date.now() > u.trialDate)
}
}
</code></pre>
<ul>
<li>No more tedious code to ‘extract’ and ‘check’ fields passed to a function. Cut to example <code>add()</code>:</li>
</ul>
<pre><code class="js">// /services/users.js
class Users {
constructor(data) { this.users = data || []; }
add({name, email, password}) {
// Store pwd hash, We only need to define 1 explicit `var/let` - the other vars are 'defined' with the `{fields}` wizardry above ^^^
let hash = getSha256(password);
return http.post('/users', {
'name': name,
'email': email,
'passwordHash': hash
}).then(usr => this.users.push(usr)); // append user upon service response
}
}
</code></pre>
<p><noscript><pre>// services/user.js
function Users(data) {
// ensure we're a real thing
if (!(this instanceof Users)) { return new Users(data); }
this.users = data || [];
}</p>
<p>Users.prototype.add = function(opts) {
// Validate input, We need to extract the 3 fields from opts
if ( !opts || typeof(opts) !== 'object' ) {
return Promise.reject('add() requires Opts parameter');
}
// Unpack data, assuming keys are there
var name = opts.name,
email = opts.email,
pass = opts.password;
var hash = getSha256(pass);</p>
<pre><code>return http.post(&#39;/users&#39;, {
&#39;name&#39;: name,
&#39;email&#39;: email,
&#39;passwordHash&#39;: hash})
.then(function(usr) {
return this.users.push(usr);
});
</code></pre>
<p> }
}</pre></noscript><script src="https://gist.github.com/justsml/aaddc9852c1624d61cf3.js"> </script></p>
<p> </p>
<a name="Jumping.on.ES6.can.feel.like.going.from:"></a>
<h3>Jumping on ES6 can feel like going from:</h3>
<div class="anigif top">
<img alt='huh' title="Huh?" src="http://res.cloudinary.com/ddd/image/upload/v1441143891/wtf__tumblr_inline_n7ygqh6Y0C1svcdm1_igeqey.gif" />
</div>
<h3>To</h3>
<div class="anigif">
<img alt='wtf' title="WTF?!?!" src="http://res.cloudinary.com/ddd/image/upload/v1443133148/cat-wtf-trap.gif" />
</div>
<h3>To</h3>
<div class="anigif end">
<img alt='#winning' title='#winning' src="http://res.cloudinary.com/ddd/image/upload/v1443133141/full-throttle.gif" />
</div>
<p>Just keep sifting through the new stuff. Check out string templates, auto <code>this</code> binding, more-sane inheritance…</p>
<a name="Node.JS"></a>
<h4><a href="http://nodejs.org/">Node.JS</a></h4>
<a name="Rust"></a>
<h2>Rust</h2>
<a name="Official.Site"></a>
<h4><a href="http://www.rust-lang.org/">Official Site</a></h4>
<ul>
<li><p><strong>Pros</strong></p>
<ul>
<li>Imagine if there was a language as fast as C and as powerful as Python/C++, yet without the complexity/pitfalls that usually trap even the most skilled devs.</li>
<li>In fact I’d guess Rust is roughly as complex as the ES6 spec.</li>
<li>It includes a ton of extras:
<ol>
<li>Essentially Rust transpiles from semi-dynamic syntax into <strong>pure C code</strong>!</li>
<li>Including <strong><strong>all the best practices</strong></strong> in C you would probably screw up on, I <del>eventually</del> always do.</li>
<li>Automatically you get:</li>
<li>Auto Memory management (no need for a slow garbage collector!)</li>
<li>Perfectly scoped Object ownership/locking (mutexting & context switching minimized)</li>
<li>Object lifetimes (automatically implemented*, and auto coded like you knew every edge case)</li>
<li>Prevent virtually all run time errors (seriously, your code-paths become explicit: you just can’t overlook a code-path)</li>
</ol>
</li>
<li>Oh yeah, it throws in true language extensibility with a sensible ‘macro’ feature.
<ul>
<li>Need Comprehensions? <a href="https://gist.github.com/hanny24/5749688">Scala style? Done</a>, and <a href="https://gist.github.com/JeffBelgum/5e762761cd63c796e803">Like Python? Done</a>.</li>
<li>Too good to be true? Nah, It gets better:</li>
<li>Bleeding edge indicators (github.com stats) reveal Rust is highly competitive or even beating Go (Google’s hot-newish language)
<ul>
<li>About 4K More Stars than Go (currently around 12,200)</li>
<li>More total Contributors ( 2x! - 1,071 vs. Go’s 479 )</li>
<li>More forks ( 3X! - 2,343 vs. 765 )</li>
<li>Number of Open Issues, Loses by a hair ( 2,000 vs 1,730 from Go )</li>
<li>Pull Requests (Rust 70+ vs. Go’s 1)</li>
</ul>
</li>
<li>I had to triple check the numbers too.</li>
</ul>
</li>
<li>Other libraries are very stable due to the constructs & rules of rust.</li>
<li>Threading model usable by mere mortals</li>
</ul>
</li>
<li><p><strong>Cons</strong></p>
<ul>
<li>Decent <strong>web frameworks</strong> are relatively new, untested, and usually undocumented (though they are <strong>getting</strong> very impressive - as of March 2015).</li>
<li>Lots of early pre-1.0 breaking changes</li>
</ul>
</li>
</ul>
<a name="Python"></a>
<h2>Python</h2>
<ul>
<li><strong>Pros</strong>
<ul>
<li>Overwhelmingly complete assortment of algorithms are already implemented in Python ( see: scilearnkit, numpy, matplotlib, pil/pillow, etc. )</li>
<li>Very Fun to write! Comprehensions and Decomposition are great features and make other languages seem just bloated!</li>
</ul>
</li>
</ul>
<pre><code class="python"># dummy code: defines a color + pixel-coord -
def pixel(x, y, r, g, b): return dict(x=x, y=y, r=r, g=g, b=b)
# Create a new pixel object and apply to set of vars
x, y, r, g, b = pixel(10, 20, 255, 255, 255)
# Now we can call pixel
</code></pre>
<ul>
<li><p>Tuples and arbitrary sets are so easy</p></li>
<li><p><strong>Cons</strong></p>
<ul>
<li>Annoyingly, Python 2.x and 3.x are incompatible. The Great Schism continues, so many years later.</li>
</ul>
</li>
</ul>
<a name="Haskell"></a>
<h2>Haskell</h2>
<ul>
<li><strong>Pros</strong>
<ul>
<li>Very rewarding when you finally memorize enough syntax to whip up comprehensions-based expressive patterns</li>
<li>You will learn mind-bending code patterns - often somewhat applicable to other languages.</li>
</ul>
</li>
<li><strong>Cons</strong>
<ul>
<li>Syntax & Patterns can be hard to get used to.</li>
</ul>
</li>
</ul>
<div class="anigif end">
<img alt='endless loop' src="http://res.cloudinary.com/ddd/image/upload/v1441143881/endless-loop.gif" />
</div>
<a name="SmallTalk-80"></a>
<h2>SmallTalk-80</h2>
<ul>
<li><strong>Pros</strong>
<ul>
<li>Incredibly simple compilers (original especially)</li>
<li>Great resources: <a href="http://peter.michaux.ca/articles/smalltalk-mvc-translated-to-javascript">Smalltalk MVC Translated to JavaScript</a></li>
</ul>
</li>
<li><strong>Cons</strong>
<ul>
<li>You will likely never use this language for anything. Zero projects. However it will have more of an impact on your coding style, faster than other functional languages… This should be in the pros list)</li>
</ul>
</li>
</ul>
<a name="L.em.Work-in-progress..updated.Sept..25th.2015...em."></a>
<h3><em>Work-in-progress (updated Sept. 25th 2015)</em></h3>
</div><!-- /.entry-content -->
</article><!-- /.hentry -->
<article class="hentry">
<header>
<div class="entry-image-index">
<a href="/2015/06/10/docker-great-though-boot2docker-sucks/" title="Docker rocks. Boot2docker just sucks."><img src="/images/abstract-10.jpg" alt="Docker rocks. Boot2docker just sucks."></a>
</div><!-- /.entry-image -->
<div class="entry-meta">
<span class="entry-date date published updated"><time datetime="2015-06-10T23:00:12-06:00"><a href="/2015/06/10/docker-great-though-boot2docker-sucks/">June 10, 2015</a></time></span><span class="author vcard"><span class="fn"><a href="/about/" title="About Dan Levy">Dan Levy</a></span></span>
<span class="entry-reading-time">
<i class="fa fa-clock-o"></i>
Reading time ~5 minutes
</span><!-- /.entry-reading-time -->
</div><!-- /.entry-meta -->
<h1 class="entry-title"><a href="/2015/06/10/docker-great-though-boot2docker-sucks/" rel="bookmark" title="Docker rocks. Boot2docker just sucks." itemprop="url">Docker rocks. Boot2docker just sucks.</a></h1>
</header>
<div class="entry-content">
<a name="Overview"></a>
<h1>Overview</h1>
<a name="To.everyone.on.OSX.or.Windows:.Don.t.let.Boot2docker.leave.you.with.the.impression.that.Docker.sucks..It.s.really.just.your.antique.OS."></a>
<h4>To everyone on OSX or Windows: Don’t let Boot2docker leave you with the impression that Docker sucks! It’s really just your antique OS.</h4>
<ol>
<li>Docker is amazing, period.</li>
<li>However it’s rough-around-the-edges, hackey utility, boot2docker - for OS X, Windows and old Linux Kernels - leaves a <strong>lot</strong> to be desired.</li>
</ol>
<a name="Issues"></a>
<h1>Issues</h1>
<blockquote><p>Boot2docker causes 99/100 headaches compared with using a native docker install locally.
I should concede that it wraps several other complicated/flakey technologies:
VirtualBox, x-platform Folder Sharing, and also the docker cli command runs in a network-client mode so,</p>
<a name="file.copying..builds.etc.take.a.long.time..vs..running.a.native.docker.server."></a>
<h1>file copying, builds etc take a long time vs. running a native docker server.</h1>
<p>Docker can currently only run natively on a Linux Kernel 3.4+ - and the current boot2docker vm actually runs v4.
Bottom Line: Install the Latest Debian (w/ xfce or MATE) on your Mac/Windows box,
… c'mon those games aren’t helping your code…</p></blockquote>
<a name="Boot2docker.Key.Commands"></a>
<h1>Boot2docker Key Commands</h1>
<a name="When.you.get.error:..FATA.0000.."></a>
<h2>When you get error: ‘FATA[0000]’</h2>
<ul>
<li>Full error message:
<ul>
<li>FATA[0000] Get <a href="http:///var/run/docker.sock/v1.18/info:">http:///var/run/docker.sock/v1.18/info:</a> dial unix /var/run/docker.sock: no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS?</li>
</ul>
</li>
<li>Solution: You need some info from boot2docker
<ul>
<li>Run this to get the 3 needed shell environment variables:</li>
</ul>
</li>
</ul>
<pre><code class="sh">boot2docker shellinit
# Copy & paste the exports into the current shell, & retry $(docker info)
</code></pre>
<a name="Get.Docker.Server.IP.Address"></a>
<h2>Get Docker Server IP Address</h2>
<pre><code class="sh">boot2docker ip
</code></pre>
<blockquote><p>Now your app on port 3000 is available at something like: <a href="http://$">http://$</a>(boot2docker ip):3000/</p></blockquote>
<a name="Boot2Docker.Quick.Start.for.OS.X"></a>
<h1>Boot2Docker Quick Start for OS X</h1>
<ol>
<li>In a terminal on your <code>brew</code> able Mac:</li>
</ol>
<pre><code class="sh">brew install boot2docker
boot2docker init
boot2docker up
</code></pre>
</div><!-- /.entry-content -->
</article><!-- /.hentry -->
<div class="pagination">
Previous
<ul class="inline-list">
<li>
<span class="current-page">1</span>
</li>
<li>
<a href="/page2">2</a>
</li>
<li>
<a href="/page3">3</a>
</li>
</ul>
<a href="/page2" class="btn">Next</a>
</div><!-- /.pagination -->
</div><!-- /#main -->
<div class="footer-wrapper">
<footer role="contentinfo">
<span class="faded">© 2015 Dan Levy. Powered by <a href="http://jekyllrb.com" rel="nofollow">Jekyll</a> using the <a href="http://mademistakes.com/hpstr/" rel="notfollow">HPSTR Theme</a>.</span>
<script>
try {
setTimeout(function() {
hljs.initHighlightingOnLoad();
}, hljs ? 10 : 5000);
} catch(ex) {
// err, highlightjs failed to async load
}
</script>
</footer>
</div><!-- /.footer-wrapper -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/assets/js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script src="/assets/js/scripts.min.js"></script>
<!-- Asynchronous Google Analytics snippet -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-59708923-1', 'auto');
ga('require', 'linkid', 'linkid.js');
ga('send', 'pageview');
</script>
</body>
</html> | {
"content_hash": "cc49606f3b58de8c5700e1972d8ab46f",
"timestamp": "",
"source": "github",
"line_count": 1183,
"max_line_length": 385,
"avg_line_length": 37.043956043956044,
"alnum_prop": 0.6729114848367296,
"repo_name": "justsml/justsml.github.io",
"id": "ff84f51d57192ee81d2c132d7a2aff3cb4dff22f",
"size": "43823",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/public/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "66639"
},
{
"name": "HTML",
"bytes": "386052"
},
{
"name": "JavaScript",
"bytes": "133208"
},
{
"name": "Makefile",
"bytes": "255"
},
{
"name": "Ruby",
"bytes": "15835"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE426_Untrusted_Search_Path__char_system_32.c
Label Definition File: CWE426_Untrusted_Search_Path.label.xml
Template File: sources-sink-32.tmpl.c
*/
/*
* @description
* CWE: 426 Untrusted Search Path
* BadSource: Don't specify the full path in the OS command
* GoodSource: Specify the full path in the OS command
* Sink: system
* BadSink : Execute the system function
* Flow Variant: 32 Data flow using two pointers to the same value within the same function
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define BAD_OS_COMMAND "cmd.exe /c dir"
/* REVIEWERS NOTE:
* This hard-coded path is probably incorrect for Windows systems, as it will
* function improperly on 9x/NT/2K, possibly on XP+ systems upgraded from 2K,
* and could introduce code execution vulnerabilities on Windows systems that
* have a system drive on an alternate drive letter (e.g., d:\windows)
*/
#define GOOD_OS_COMMAND "c:\\windows\\system32\\cmd.exe /c dir"
#else /* NOT _WIN32 */
#define BAD_OS_COMMAND "ls -la"
#define GOOD_OS_COMMAND "/usr/bin/ls -la"
#endif /* end NOT _WIN32 */
#ifdef _WIN32
#define SYSTEM system
#else /* NOT _WIN32 */
#define SYSTEM system
#endif
#ifndef OMITBAD
void CWE426_Untrusted_Search_Path__char_system_32_bad()
{
char * data;
char * *dataPtr1 = &data;
char * *dataPtr2 = &data;
char dataBuffer[100] = "";
data = dataBuffer;
{
char * data = *dataPtr1;
/* FLAW: the full path is not specified */
strcpy(data, BAD_OS_COMMAND);
*dataPtr1 = data;
}
{
char * data = *dataPtr2;
/* POTENTIAL FLAW: Executing the system() function without specifying the full path to the executable
* can allow an attacker to run their own program */
if (SYSTEM(data) <= 0)
{
printLine("command execution failed!");
exit(1);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
char * data;
char * *dataPtr1 = &data;
char * *dataPtr2 = &data;
char dataBuffer[100] = "";
data = dataBuffer;
{
char * data = *dataPtr1;
/* FIX: full path is specified */
strcpy(data, GOOD_OS_COMMAND);
*dataPtr1 = data;
}
{
char * data = *dataPtr2;
/* POTENTIAL FLAW: Executing the system() function without specifying the full path to the executable
* can allow an attacker to run their own program */
if (SYSTEM(data) <= 0)
{
printLine("command execution failed!");
exit(1);
}
}
}
void CWE426_Untrusted_Search_Path__char_system_32_good()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE426_Untrusted_Search_Path__char_system_32_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE426_Untrusted_Search_Path__char_system_32_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "a3b10721809599a4799be6659252d8ee",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 109,
"avg_line_length": 28.48062015503876,
"alnum_prop": 0.62084921066957,
"repo_name": "maurer/tiamat",
"id": "91a39dab18243e9c67fc82154f351d8e9d0dd2b6",
"size": "3674",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE426_Untrusted_Search_Path/CWE426_Untrusted_Search_Path__char_system_32.c",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "25ea6917440858119c447f53638eda18",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "e6cb484433f11e08af5d62b349347b2d635a41dd",
"size": "190",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Venturiaceae/Coleroa/Coleroa chaetomium/ Syn. Mollisia rubi/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#ifndef __FILE_COLLECTOR__
#define __FILE_COLLECTOR__
#include <vector>
#include <string>
using namespace std;
namespace cossb {
namespace file {
class collector {
public:
typedef struct _path {
string absolute;
string relative;
string filename;
string ext;
} filepath;
collector(const char* path, const char* ext);
virtual ~collector();
/*
@brief update files in the path
@return number of files
*/
int update();
/*
@return file container
*/
vector<filepath>& getList() { return _file_container; }
/*
@brief return true if exist
*/
bool exist(const char* filename);
/*
@brief remove elements
*/
void remove(const char* filename);
/*
@brief number of collected files
*/
int size() { return (int)_file_container.size(); }
/*
@brief return path
*/
filepath getPath(const char* filename) {
filepath tmp;
for (auto& file : _file_container) {
if (file.filename == filename) {
tmp = file;
break;
}
}
return tmp;
}
void ordering();
private:
void _update(const char* path, const char* ext);
private:
string _path;
string _ext;
vector<filepath> _file_container;
//order
vector<pair<int, int>> _order_index; //stem, index
};
}
}
#endif
| {
"content_hash": "95f8f666f365292690c7a8ead7c5547e",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 58,
"avg_line_length": 15.406976744186046,
"alnum_prop": 0.6015094339622642,
"repo_name": "nsynapse/cossb",
"id": "e6b0a6deaef5ea7557f33a331b70bec19447e6c2",
"size": "1325",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/file/collector.hpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "720"
},
{
"name": "C++",
"bytes": "1036526"
},
{
"name": "CMake",
"bytes": "1745"
},
{
"name": "CSS",
"bytes": "240097"
},
{
"name": "HTML",
"bytes": "165114"
},
{
"name": "JavaScript",
"bytes": "363365"
},
{
"name": "Makefile",
"bytes": "82433"
},
{
"name": "Python",
"bytes": "3274"
},
{
"name": "Shell",
"bytes": "1409"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<meta content='IE=edge,chrome=1' http-equiv='X-UA-Compatible'>
<meta content='width=device-width, initial-scale=1.0' name='viewport'>
<!-- Favicon -->
<link href='favicon.ico' rel='shortcut icon' type='image/x-icon'>
<!-- Typekit -->
<script src="https://use.typekit.net/ddg5xff.js"></script>
<script>try{Typekit.load({ async: true });}catch(e){}</script>
<!-- Use title if it's in the page YAML frontmatter -->
<title>Dan Denney</title>
<link href='/assets/javascripts/vendor/chartist/dist/chartist.min.css' rel='stylesheet'>
<link href="../../../assets/stylesheets/application.css" rel="stylesheet" />
</head>
<body class='posts posts_2012 posts_2012_09 posts_2012_09_22'>
<h1>Archive for
Sep 22 2012
</h1>
<ul>
<li><a href="/posts/conferences/circles-conf-2012">Circles Conf 2012</a> <span>Sep 22</span></li>
<li><a href="/posts/conferences/rebuild-conference-2012">re:build Conference 2012</a> <span>Sep 22</span></li>
</ul>
<footer>
<p class='dib'>
Dan Denney
</p>
<nav class='dib'>
<a class="mls" href="/posts">Posts</a>
<a class="mls" href="/blips">Blips</a>
<a class="mls" href="/tinkerings">Tinkerings</a>
<a class="mls" href="/">Home</a>
</nav>
</footer>
<script src="../../../assets/javascripts/vendor.js"></script>
<!-- = javascript_include_tag 'application' -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-3589831-2', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
| {
"content_hash": "a3af9f8790ce8886d6c6eef2a65f6877",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 114,
"avg_line_length": 33.339622641509436,
"alnum_prop": 0.6632710809281268,
"repo_name": "dandenney/dandenney.com",
"id": "bf5f29a133a453f6bbe9ee2deb14ba574618da7c",
"size": "1767",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build/posts/2012/09/22.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "85858"
},
{
"name": "CoffeeScript",
"bytes": "18793"
},
{
"name": "HTML",
"bytes": "682538"
},
{
"name": "JavaScript",
"bytes": "26"
},
{
"name": "Ruby",
"bytes": "10295"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Destiny STL Generator</title>
<!-- Bootstrap core CSS -->
<link href="static/css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap theme -->
<link href="static/css/bootstrap-theme.min.css" rel="stylesheet">
<!-- Select2 styles -->
<link rel="stylesheet" href="static/css/select2/select2.css">
<link rel="stylesheet" href="static/css/select2/select2-bootstrap.css">
<!-- Custom styles for this template -->
<link href="static/css/theme.css" rel="stylesheet">
<!-- jquery script -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body role="document">
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Destiny STL Generator</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="/">Home</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</div>
</div>
</nav>
<div class="container theme-showcase" role="main">
<div class="jumbotron">
<div class="container">
<h1>Welcome!</h1>
<p>This website can be used to generate stl files for thousands of in game items found in Destiny.
The files are created with the same source geometry used to render your character on the official
Destiny mobile app and Bungie website.</p>
</div>
</div>
<br>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h2>Destiny 1</h2>
<form class="input-group input-group-lg select2-bootstrap-append" action="download">
<select name="item" class="form-control select2-allow-clear">
<option></option>
{% for key in gear_d1 %}
<option>{{ gear_d1[key]["name"] }}</option>
{% endfor %}
</select>
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Generate</button>
</span>
</form>
</div>
</div>
<br>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h2>Destiny 2</h2>
<form class="input-group input-group-lg select2-bootstrap-append" action="download">
<select name="item" class="form-control select2-allow-clear">
<option></option>
{% for key in gear_d2 %}
<option>{{ gear_d2[key]["name"] }}</option>
{% endfor %}
</select>
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Generate</button>
</span>
</form>
</div>
</div>
<br>
<div class="row">
<div class="col-md-5 col-md-offset-1">
<h2>Usage</h2>
<ol>
<li>Select an item and click generate.</li>
<li>Download the generated stl file or zip file containing all the parts.</li>
<li>Import the .stl file into your favorite CAD program or a 3D printing clean up utility such as <a href="https://netfabb.azurewebsites.net/">NetFabb Cloud</a>.</li>
</ol>
</div>
<div class="col-md-5">
<h2>Notes</h2>
<ol>
<li>This is a beta version and not all items have been tested.</li>
<li>It is recommended to clean up any models using a tool such as <a href="https://tools3d.azurewebsites.net/">Microsoft 3D Repair</a> before they can be 3D printed.</li>
</ol>
</div>
</div>
<br>
<br>
<br>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<center>
<label class="control-label">If you find this tool useful please consider supporting the project and donating.</label>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="BVNUNKBVBVAHS">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
</center>
</div>
</div>
<br>
<div id="footer"></div>
<script>
$("#footer").load("static/html/footer.html");
</script>
</div>
</div>
<script src="static/js/select2.js"></script>
<script>
var placeholder = "Select an item";
$( ".select2, .select2-multiple" ).select2( { placeholder: placeholder } );
$( ".select2-allow-clear" ).select2( { allowClear: true, placeholder: placeholder } );
</script>
<script src="static/js/bootstrap.min.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-58101529-1', 'auto');
ga('send', 'pageview');
</script>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
</body> | {
"content_hash": "8e8818d53601a2f6dc9a00cf81ada06d",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 303,
"avg_line_length": 52.60526315789474,
"alnum_prop": 0.4687343671835918,
"repo_name": "bepo13/destiny-stl-generator-web",
"id": "65d1e2eb9e8eba10d5504f8b909c3f143fd93481",
"size": "7996",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templates/old/welcome.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "46"
},
{
"name": "CSS",
"bytes": "110727"
},
{
"name": "HTML",
"bytes": "31301"
},
{
"name": "JavaScript",
"bytes": "761816"
},
{
"name": "Procfile",
"bytes": "35"
},
{
"name": "Python",
"bytes": "29404"
},
{
"name": "Shell",
"bytes": "1490"
}
],
"symlink_target": ""
} |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "base/at_exit.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/strings/string_piece.h"
#include "base/strings/stringprintf.h"
#include "base/threading/thread.h"
#include "tools/android/forwarder2/common.h"
#include "tools/android/forwarder2/daemon.h"
#include "tools/android/forwarder2/device_controller.h"
#include "tools/android/forwarder2/pipe_notifier.h"
namespace forwarder2 {
namespace {
// Leaky global instance, accessed from the signal handler.
forwarder2::PipeNotifier* g_notifier = NULL;
const int kBufSize = 256;
const char kDaemonIdentifier[] = "chrome_device_forwarder_daemon";
const char kKillServerCommand[] = "kill-server";
const char kStartCommand[] = "start";
void KillHandler(int /* unused */) {
CHECK(g_notifier);
if (!g_notifier->Notify())
exit(1);
}
// Lets the daemon fetch the exit notifier file descriptor.
int GetExitNotifierFD() {
DCHECK(g_notifier);
return g_notifier->receiver_fd();
}
class ServerDelegate : public Daemon::ServerDelegate {
public:
// Daemon::ServerDelegate:
virtual void Init() OVERRIDE {
DCHECK(!g_notifier);
g_notifier = new forwarder2::PipeNotifier();
signal(SIGTERM, KillHandler);
signal(SIGINT, KillHandler);
controller_thread_.reset(new base::Thread("controller_thread"));
controller_thread_->Start();
}
virtual void OnClientConnected(scoped_ptr<Socket> client_socket) OVERRIDE {
char buf[kBufSize];
const int bytes_read = client_socket->Read(buf, sizeof(buf));
if (bytes_read <= 0) {
if (client_socket->DidReceiveEvent())
return;
PError("Read()");
return;
}
const std::string adb_socket_path(buf, bytes_read);
if (adb_socket_path == adb_socket_path_) {
client_socket->WriteString("OK");
return;
}
if (!adb_socket_path_.empty()) {
client_socket->WriteString(
base::StringPrintf(
"ERROR: Device controller already running (adb_socket_path=%s)",
adb_socket_path_.c_str()));
return;
}
adb_socket_path_ = adb_socket_path;
controller_thread_->message_loop()->PostTask(
FROM_HERE,
base::Bind(&ServerDelegate::StartController, adb_socket_path,
GetExitNotifierFD(), base::Passed(&client_socket)));
}
virtual void OnServerExited() OVERRIDE {}
private:
static void StartController(const std::string& adb_socket_path,
int exit_notifier_fd,
scoped_ptr<Socket> client_socket) {
forwarder2::DeviceController controller(exit_notifier_fd);
if (!controller.Init(adb_socket_path)) {
client_socket->WriteString(
base::StringPrintf("ERROR: Could not initialize device controller "
"with ADB socket path: %s",
adb_socket_path.c_str()));
return;
}
client_socket->WriteString("OK");
client_socket->Close();
// Note that the following call is blocking which explains why the device
// controller has to live on a separate thread (so that the daemon command
// server is not blocked).
controller.Start();
}
base::AtExitManager at_exit_manager_; // Used by base::Thread.
scoped_ptr<base::Thread> controller_thread_;
std::string adb_socket_path_;
};
class ClientDelegate : public Daemon::ClientDelegate {
public:
ClientDelegate(const std::string& adb_socket)
: adb_socket_(adb_socket),
has_failed_(false) {
}
bool has_failed() const { return has_failed_; }
// Daemon::ClientDelegate:
virtual void OnDaemonReady(Socket* daemon_socket) OVERRIDE {
// Send the adb socket path to the daemon.
CHECK(daemon_socket->Write(adb_socket_.c_str(),
adb_socket_.length()));
char buf[kBufSize];
const int bytes_read = daemon_socket->Read(
buf, sizeof(buf) - 1 /* leave space for null terminator */);
CHECK_GT(bytes_read, 0);
DCHECK(bytes_read < sizeof(buf));
buf[bytes_read] = 0;
base::StringPiece msg(buf, bytes_read);
if (msg.starts_with("ERROR")) {
LOG(ERROR) << msg;
has_failed_ = true;
return;
}
}
private:
const std::string adb_socket_;
bool has_failed_;
};
int RunDeviceForwarder(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr,
"Usage: %s kill-server|<adb_socket>\n"
" <adb_socket> is the abstract Unix Domain Socket path "
"where Adb is configured to forward from.\n", argv[0]);
return 1;
}
CommandLine::Init(argc, argv); // Needed by logging.
const char* const command =
!strcmp(argv[1], kKillServerCommand) ? kKillServerCommand : kStartCommand;
ClientDelegate client_delegate(argv[1]);
ServerDelegate daemon_delegate;
const char kLogFilePath[] = ""; // Log to logcat.
Daemon daemon(kLogFilePath, kDaemonIdentifier, &client_delegate,
&daemon_delegate, &GetExitNotifierFD);
if (command == kKillServerCommand)
return !daemon.Kill();
DCHECK(command == kStartCommand);
if (!daemon.SpawnIfNeeded())
return 1;
return client_delegate.has_failed();
}
} // namespace
} // namespace forwarder2
int main(int argc, char** argv) {
return forwarder2::RunDeviceForwarder(argc, argv);
}
| {
"content_hash": "5377f1d7e0669a3966a123ae1a409eb4",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 80,
"avg_line_length": 31.127777777777776,
"alnum_prop": 0.6537569159378904,
"repo_name": "jing-bao/pa-chromium",
"id": "f822d285a1080905a6d0c4f5a841af46aeffb866",
"size": "5603",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "tools/android/forwarder2/device_forwarder_main.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
// TabSelectorCtl.h : Declaration of the CTabSelectorCtrl OLE control class.
#include <afxcmn.h>
#include "CategoriesCombo.h"
#include "QueriesCombo.h"
#include "GroupsCombo.h"
#define IDC_TAB 100
#define IDC_CATEGORIES 101
#define IDC_QUERIES 102
#define IDC_GROUPS 103
/////////////////////////////////////////////////////////////////////////////
// CTabSelectorCtrl : See TabSelectorCtl.cpp for implementation.
class CTabSelectorCtrl : public COleControl
{
DECLARE_DYNCREATE(CTabSelectorCtrl)
// Constructor
public:
CTabSelectorCtrl();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CTabSelectorCtrl)
public:
virtual void OnDraw(CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid);
virtual void DoPropExchange(CPropExchange* pPX);
virtual void OnResetState();
//}}AFX_VIRTUAL
// Implementation
protected:
~CTabSelectorCtrl();
DECLARE_OLECREATE_EX(CTabSelectorCtrl) // Class factory and guid
DECLARE_OLETYPELIB(CTabSelectorCtrl) // GetTypeInfo
DECLARE_PROPPAGEIDS(CTabSelectorCtrl) // Property page IDs
DECLARE_OLECTLTYPE(CTabSelectorCtrl) // Type name and misc status
// Message maps
//{{AFX_MSG(CTabSelectorCtrl)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnSelchangeTab(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnCategoryChanged(LPCSTR catList);
afx_msg void OnGroupChanged(LPCSTR catList);
afx_msg void OnQueryChanged(LPCSTR queriesList);
afx_msg void OnGroupCreated(LPCSTR name);
afx_msg void OnGroupRemoved(short amount);
afx_msg void OnGroupInsSel(void);
afx_msg void OnGroupDelSel(void);
DECLARE_EVENTSINK_MAP()
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
// Dispatch maps
//{{AFX_DISPATCH(CTabSelectorCtrl)
afx_msg LPDISPATCH GetDataSource();
afx_msg void SetDataSource(LPDISPATCH newValue);
afx_msg BSTR GetOutputVariable();
afx_msg void SetOutputVariable(LPCTSTR lpszNewValue);
afx_msg BSTR GetSelectionVariable();
afx_msg void SetSelectionVariable(LPCTSTR lpszNewValue);
afx_msg BSTR GetSelectedCategories();
afx_msg void SetSelectedCategories(LPCTSTR lpszNewValue);
afx_msg BSTR AccessFromName(LPCTSTR name);
afx_msg void Update();
afx_msg BSTR AccessFromCategory(LPCTSTR category);
afx_msg BSTR AccessFromQuery(LPCTSTR query);
afx_msg void Unselect();
//}}AFX_DISPATCH
DECLARE_DISPATCH_MAP()
afx_msg void AboutBox();
// Event maps
//{{AFX_EVENT(CTabSelectorCtrl)
void FireModeChanged(short modeID)
{FireEvent(eventidModeChanged,EVENT_PARAM(VTS_I2), modeID);}
void FireCategoryChanged(LPCTSTR catList)
{FireEvent(eventidCategoryChanged,EVENT_PARAM(VTS_BSTR), catList);}
void FireQueryChanged(LPCTSTR name)
{FireEvent(eventidQueryChanged,EVENT_PARAM(VTS_BSTR), name);}
void FireGroupChanged(LPCTSTR varName)
{FireEvent(eventidGroupChanged,EVENT_PARAM(VTS_BSTR), varName);}
//}}AFX_EVENT
DECLARE_EVENT_MAP()
// Dispatch and event IDs
public:
enum {
//{{AFX_DISP_ID(CTabSelectorCtrl)
dispidDataSource = 1L,
dispidOutputVariable = 2L,
dispidSelectionVariable = 3L,
dispidSelectedCategories = 4L,
dispidAccessFromName = 5L,
dispidUpdate = 6L,
dispidAccessFromCategory = 7L,
dispidAccessFromQuery = 8L,
dispidUnselect = 9L,
eventidModeChanged = 1L,
eventidCategoryChanged = 2L,
eventidQueryChanged = 3L,
eventidGroupChanged = 4L,
//}}AFX_DISP_ID
};
private:
BOOL m_EnableCategories;
CString m_SelectedCategories;
CFont infoFont;
CString m_Projects;
CString m_SelectionVar;
LPDISPATCH m_DataSource;
CTabCtrl m_Tab;
CGroupsCombo m_Groups;
CQueriesCombo m_Queries;
CCategoriesCombo m_Categories;
};
| {
"content_hash": "bbae52da4b6986048fec904bdb0b0b61",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 78,
"avg_line_length": 30.272727272727273,
"alnum_prop": 0.7493857493857494,
"repo_name": "kit-transue/software-emancipation-discover",
"id": "a37cb24899649f9ade91a18c8e8c2d78e2f8e54f",
"size": "5687",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "newntui/activex/tabselector/include/tabselectorctl.h",
"mode": "33261",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "178658"
},
{
"name": "C",
"bytes": "2730024"
},
{
"name": "C#",
"bytes": "308"
},
{
"name": "C++",
"bytes": "23349265"
},
{
"name": "CSS",
"bytes": "1861130"
},
{
"name": "Crystal",
"bytes": "105"
},
{
"name": "Emacs Lisp",
"bytes": "50226"
},
{
"name": "GLSL",
"bytes": "2698016"
},
{
"name": "Gnuplot",
"bytes": "1219"
},
{
"name": "Groff",
"bytes": "10934"
},
{
"name": "HTML",
"bytes": "10534201"
},
{
"name": "Java",
"bytes": "272548"
},
{
"name": "Lex",
"bytes": "269984"
},
{
"name": "Makefile",
"bytes": "487619"
},
{
"name": "Objective-C",
"bytes": "10093"
},
{
"name": "Perl",
"bytes": "719227"
},
{
"name": "Perl6",
"bytes": "15568"
},
{
"name": "PostScript",
"bytes": "25588"
},
{
"name": "Ruby",
"bytes": "77891"
},
{
"name": "Scilab",
"bytes": "11247"
},
{
"name": "Shell",
"bytes": "320920"
},
{
"name": "Smalltalk",
"bytes": "83"
},
{
"name": "SuperCollider",
"bytes": "23447"
},
{
"name": "Tcl",
"bytes": "1047438"
},
{
"name": "XSLT",
"bytes": "5277"
},
{
"name": "Yacc",
"bytes": "514644"
}
],
"symlink_target": ""
} |
<ion-view title="Display" ng-init="init()">
<ion-nav-buttons side="right">
<button class="button button-icon icon ion-camera" ng-click="upload()"></button>
</ion-nav-buttons>
<ion-content>
<div class="list list-inset">
<button class="button button-block button-positive" ng-click="logout()">
Facebook Logout
</button>
</div>
<div class="row" ng-repeat="image in images | orderBy:'-created_at'" ng-if="$index % 4 === 0">
<div class="col col-25" ng-if="$index < images.length">
<img ng-src="data:image/jpeg;base64,{{images[$index].image}}" width="100%" />
</div>
<div class="col col-25" ng-if="$index + 1 < images.length">
<img ng-src="data:image/jpeg;base64,{{images[$index + 1].image}}" width="100%" />
</div>
<div class="col col-25" ng-if="$index + 2 < images.length">
<img ng-src="data:image/jpeg;base64,{{images[$index + 2].image}}" width="100%" />
</div>
<div class="col col-25" ng-if="$index + 3 < images.length">
<img ng-src="data:image/jpeg;base64,{{images[$index + 3].image}}" width="100%" />
</div>
</div>
</ion-content>
</ion-view> | {
"content_hash": "4d05a4220bc127cb37fb225baa9729bc",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 102,
"avg_line_length": 49.65384615384615,
"alnum_prop": 0.5274980635166537,
"repo_name": "jpavlo/TicOneMagazine",
"id": "7192fc89eff8e739502f40093e03685ed370d39b",
"size": "1291",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "platforms/android/assets/www/templates/display.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "14302"
},
{
"name": "C",
"bytes": "11103350"
},
{
"name": "C#",
"bytes": "4624338"
},
{
"name": "C++",
"bytes": "995221"
},
{
"name": "CSS",
"bytes": "1561575"
},
{
"name": "HTML",
"bytes": "35962"
},
{
"name": "Java",
"bytes": "745750"
},
{
"name": "JavaScript",
"bytes": "9131469"
},
{
"name": "Objective-C",
"bytes": "706488"
},
{
"name": "PowerShell",
"bytes": "1435"
},
{
"name": "QML",
"bytes": "6499"
},
{
"name": "Ruby",
"bytes": "884"
},
{
"name": "Shell",
"bytes": "5944"
}
],
"symlink_target": ""
} |
#include "resource/resource_stdneb.h"
#include "resource/reslable.h"
#include "system/byteorder.h"
#include "audioresloader.h"
namespace Resources
{
__ImplementClass(Resources::AudioResLoader,'AULD',Resources::ResourceLoader);
//------------------------------------------------------------------------
AudioResLoader::AudioResLoader()
{
}
//------------------------------------------------------------------------
AudioResLoader::~AudioResLoader()
{
}
//------------------------------------------------------------------------
bool
AudioResLoader::LoadResource(Resource* res )
{
if ( !res )
return false;
if ( res->GetRtti() != &AudioRes::RTTI )
{
return false;
}
GPtr<Resource> pRes = res;
GPtr<AudioRes> pAudioRes = pRes.downcast<AudioRes>();
n_assert(pAudioRes);
if (!LoadAudioRes(pAudioRes))
{
return false;
}
return true;
}
//------------------------------------------------------------------------------
bool AudioResLoader::LoadAudioRes(GPtr<AudioRes>& pAudioRes)
{
if ( !mStream.isvalid())
{
return false;
}
n_assert(mStream->IsOpen());
const int tplSize = mStream->GetSize();
if ( tplSize == 0 )
{
return false;
}
pAudioRes->Setup(tplSize);
mStream->Read(pAudioRes->GetPtr(), tplSize );
return true;
}
}
| {
"content_hash": "e237f9857d7ad2e1a373ff019b5e4156",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 81,
"avg_line_length": 19.78787878787879,
"alnum_prop": 0.5061255742725881,
"repo_name": "stonejiang/genesis-3d",
"id": "248a7a80f622da688fde8340918af017c20dc4f4",
"size": "2569",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Engine/addons/resource/audioresloader.cc",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package com.skynav.ttv.model.imsc;
import java.net.URI;
import java.util.Map;
import com.skynav.ttv.model.Profile.Specification;
import com.skynav.ttv.model.Profile.Usage;
import com.skynav.ttv.model.smpte.ST20522010TTML1;
import com.skynav.ttv.model.ttml.TTML1;
import static com.skynav.ttv.model.imsc.IMSC10.Constants.NAMESPACE_IMSC_EXTENSION;
public class IMSC10TextProfileSpecification extends Specification {
private static final Object[][] featureMapEntries = new Object[][] {
{ "#animation", Usage.REQUIRED },
{ "#backgroundColor", Usage.REQUIRED },
{ "#backgroundColor-block", Usage.REQUIRED },
{ "#backgroundColor-inline", Usage.REQUIRED },
{ "#backgroundColor-region", Usage.REQUIRED },
{ "#bidi", Usage.REQUIRED },
{ "#cellResolution", Usage.REQUIRED },
{ "#clockMode", Usage.OPTIONAL },
{ "#clockMode-gps", Usage.OPTIONAL },
{ "#clockMode-local", Usage.OPTIONAL },
{ "#clockMode-utc", Usage.OPTIONAL },
{ "#color", Usage.REQUIRED },
{ "#content", Usage.REQUIRED },
{ "#core", Usage.REQUIRED },
{ "#direction", Usage.REQUIRED },
{ "#display", Usage.REQUIRED },
{ "#display-block", Usage.REQUIRED },
{ "#display-inline", Usage.REQUIRED },
{ "#display-region", Usage.REQUIRED },
{ "#displayAlign", Usage.REQUIRED },
{ "#dropMode", Usage.OPTIONAL },
{ "#dropMode-dropNTSC", Usage.OPTIONAL },
{ "#dropMode-dropPAL", Usage.OPTIONAL },
{ "#dropMode-nonDrop", Usage.OPTIONAL },
{ "#extent", Usage.REQUIRED },
{ "#extent-region", Usage.REQUIRED },
{ "#extent-root", Usage.REQUIRED },
{ "#fontFamily", Usage.REQUIRED },
{ "#fontFamily-generic", Usage.REQUIRED },
{ "#fontFamily-non-generic", Usage.REQUIRED },
{ "#fontSize", Usage.REQUIRED },
{ "#fontSize-anamorphic", Usage.REQUIRED },
{ "#fontSize-isomorphic", Usage.REQUIRED },
{ "#fontStyle", Usage.REQUIRED },
{ "#fontStyle-italic", Usage.REQUIRED },
{ "#fontStyle-oblique", Usage.REQUIRED },
{ "#fontWeight", Usage.REQUIRED },
{ "#fontWeight-bold", Usage.REQUIRED },
{ "#frameRate", Usage.REQUIRED },
{ "#frameRateMultiplier", Usage.REQUIRED },
{ "#layout", Usage.REQUIRED },
{ "#length", Usage.REQUIRED },
{ "#length-cell", Usage.REQUIRED },
{ "#length-em", Usage.REQUIRED },
{ "#length-integer", Usage.REQUIRED },
{ "#length-negative", Usage.REQUIRED },
{ "#length-percentage", Usage.REQUIRED },
{ "#length-pixel", Usage.REQUIRED },
{ "#length-positive", Usage.REQUIRED },
{ "#length-real", Usage.REQUIRED },
{ "#lineBreak-uax14", Usage.OPTIONAL },
{ "#lineHeight", Usage.REQUIRED },
{ "#markerMode", Usage.OPTIONAL },
{ "#markerMode-continuous", Usage.OPTIONAL },
{ "#markerMode-discontinuous", Usage.OPTIONAL },
{ "#metadata", Usage.REQUIRED },
{ "#nested-div", Usage.REQUIRED },
{ "#nested-span", Usage.REQUIRED },
{ "#opacity", Usage.REQUIRED },
{ "#origin", Usage.REQUIRED },
{ "#overflow", Usage.REQUIRED },
{ "#overflow-visible", Usage.REQUIRED },
{ "#padding", Usage.REQUIRED },
{ "#padding-1", Usage.REQUIRED },
{ "#padding-2", Usage.REQUIRED },
{ "#padding-3", Usage.REQUIRED },
{ "#padding-4", Usage.REQUIRED },
{ "#pixelAspectRatio", Usage.OPTIONAL },
{ "#presentation", Usage.REQUIRED },
{ "#profile", Usage.REQUIRED },
{ "#showBackground", Usage.REQUIRED },
{ "#structure", Usage.REQUIRED },
{ "#styling", Usage.REQUIRED },
{ "#styling-chained", Usage.REQUIRED },
{ "#styling-inheritance-content", Usage.REQUIRED },
{ "#styling-inheritance-region", Usage.REQUIRED },
{ "#styling-inline", Usage.REQUIRED },
{ "#styling-nested", Usage.REQUIRED },
{ "#styling-referential", Usage.REQUIRED },
{ "#subFrameRate", Usage.OPTIONAL },
{ "#textAlign", Usage.REQUIRED },
{ "#textAlign-absolute", Usage.REQUIRED },
{ "#textAlign-relative", Usage.REQUIRED },
{ "#textDecoration", Usage.REQUIRED },
{ "#textDecoration-over", Usage.REQUIRED },
{ "#textDecoration-through", Usage.REQUIRED },
{ "#textDecoration-under", Usage.REQUIRED },
{ "#textOutline", Usage.REQUIRED },
{ "#textOutline-blurred", Usage.REQUIRED },
{ "#textOutline-unblurred", Usage.REQUIRED },
{ "#tickRate", Usage.REQUIRED },
{ "#time-clock", Usage.REQUIRED },
{ "#time-clock-with-frames", Usage.REQUIRED },
{ "#time-offset", Usage.REQUIRED },
{ "#time-offset-with-frames", Usage.REQUIRED },
{ "#time-offset-with-ticks", Usage.REQUIRED },
{ "#timeBase-clock", Usage.OPTIONAL },
{ "#timeBase-media", Usage.REQUIRED },
{ "#timeBase-smpte", Usage.OPTIONAL },
{ "#timeContainer", Usage.REQUIRED },
{ "#timing", Usage.REQUIRED },
{ "#transformation", Usage.REQUIRED },
{ "#unicodeBidi", Usage.REQUIRED },
{ "#visibility", Usage.REQUIRED },
{ "#visibility-block", Usage.REQUIRED },
{ "#visibility-inline", Usage.REQUIRED },
{ "#visibility-region", Usage.REQUIRED },
{ "#wrapOption", Usage.REQUIRED },
{ "#writingMode", Usage.REQUIRED },
{ "#writingMode-horizontal", Usage.REQUIRED },
{ "#writingMode-horizontal-lr", Usage.REQUIRED },
{ "#writingMode-horizontal-rl", Usage.REQUIRED },
{ "#writingMode-vertical", Usage.REQUIRED },
{ "#zIndex", Usage.REQUIRED },
};
private static final Object[][] smpteExtensionMapEntries = new Object[][] {
{ "#image", Usage.OPTIONAL },
};
private static final Object[][] imsc10ExtensionMapEntries = new Object[][] {
{ "#altText", Usage.REQUIRED },
{ "#aspectRatio", Usage.REQUIRED },
{ "#forcedDisplay", Usage.REQUIRED },
{ "#linePadding", Usage.REQUIRED },
{ "#multiRowAlign", Usage.REQUIRED },
{ "#progressivelyDecodable", Usage.REQUIRED },
};
public IMSC10TextProfileSpecification(URI profileUri) {
super(profileUri, null, featuresMap(TTML1.Constants.NAMESPACE_TT_FEATURE, featureMapEntries), makeExtensionsMap());
}
private static Map<URI,Usage> makeExtensionsMap() {
Map<URI,Usage> fm = new java.util.HashMap<URI,Usage>();
fm.putAll(featuresMap(ST20522010TTML1.Constants.NAMESPACE_2010_EXTENSION, smpteExtensionMapEntries));
fm.putAll(featuresMap(NAMESPACE_IMSC_EXTENSION, imsc10ExtensionMapEntries));
return fm;
}
}
| {
"content_hash": "01efc226cf6a65a923c2d3c7509cb7a8",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 123,
"avg_line_length": 43.27215189873418,
"alnum_prop": 0.5885622348983472,
"repo_name": "skynav/ttt",
"id": "665a3cfac026b26377d9abf3acea4ddd6911dfdd",
"size": "8191",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ttt-ttv/src/main/java/com/skynav/ttv/model/imsc/IMSC10TextProfileSpecification.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "22996"
},
{
"name": "HTML",
"bytes": "4728"
},
{
"name": "Java",
"bytes": "4407277"
},
{
"name": "JavaScript",
"bytes": "9251"
},
{
"name": "Shell",
"bytes": "2813"
},
{
"name": "XSLT",
"bytes": "5232"
}
],
"symlink_target": ""
} |
const Stack = require('../index');
const config = {
region: '', // aws region
secretAccessKey: '', // aws secretAccessKey
accessKeyId: '', // aws accessKeyId
name: '', // aws tag for instance name
env: '', // aws tag for enviroment
};
const stack = new Stack(config);
stack.status((err, res) => {
if (err) throw err;
console.log(res);
});
stack.getSQS('url.of.sqs.queue', (err, res) => {
if (err) throw err;
console.log(res);
});
| {
"content_hash": "008dd328350c96b75807669af58f5e92",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 48,
"avg_line_length": 21.523809523809526,
"alnum_prop": 0.6106194690265486,
"repo_name": "danm/stack-status",
"id": "7feb0bb6336da323c4897ae7fb49bb9a77b3c66a",
"size": "452",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "example/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "23339"
}
],
"symlink_target": ""
} |
import EmberObject from 'ember-object';
import { A } from 'ember-array/utils';
import get from 'ember-metal/get';
export default function groupBy(content, groupPath) {
let groups = A();
if (!groupPath) { return content; }
if (content && content.length) {
content.forEach((item) => {
let label = get(item, groupPath);
if (label) {
let group = groups.findBy('groupName', label);
if (group == null) {
group = EmberObject.create({
groupName: label,
options: A()
});
groups.pushObject(group);
}
get(group, 'options').pushObject(item);
} else {
groups.pushObject(item);
}
});
}
return groups;
}
| {
"content_hash": "e24276f6c3c228a43cc6a6bca84ae760",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 54,
"avg_line_length": 21.085714285714285,
"alnum_prop": 0.5528455284552846,
"repo_name": "Fabriquartz/ember-railio-form-components",
"id": "a33d59eb2ef319588405ebf2aa9f654ff184c77e",
"size": "738",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "addon/utils/group-by.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1936"
},
{
"name": "HTML",
"bytes": "12641"
},
{
"name": "JavaScript",
"bytes": "170079"
}
],
"symlink_target": ""
} |
<?php
namespace HtCountryModule\Factory\Validator;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use HtCountryModule\Validator\CountryValidator;
class CountryValidatorFactory implements FactoryInterface
{
/**
* @param ServiceLocatorInterface $validators
*
* @return CountryValidator
*/
public function createService(ServiceLocatorInterface $validators)
{
return new CountryValidator($validators->getServiceLocator()->get('Phine\Country\Loader\Loader'));
}
}
| {
"content_hash": "ed9cbc3aca152d8d7c18442eac7de8a0",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 106,
"avg_line_length": 28.894736842105264,
"alnum_prop": 0.7650273224043715,
"repo_name": "hrevert/HtCountryModule",
"id": "b1f998f3b752ce00c53955330d1272b4c5d04cc1",
"size": "549",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Factory/Validator/CountryValidatorFactory.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "11023"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Documentation</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="../">
<link rel="icon" href="images/favicon.ico"/>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/base.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@400;600;700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@400;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/template.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0/css/all.min.css" integrity="sha256-ybRkN9dBjhcS2qrW1z+hfCxq+1aBdwyQM5wlQoQVt/0=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.23.0/themes/prism-okaidia.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.23.0/plugins/line-numbers/prism-line-numbers.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.23.0/plugins/line-highlight/prism-line-highlight.css">
<script src="https://cdn.jsdelivr.net/npm/fuse.js@3.4.6"></script>
<script src="https://cdn.jsdelivr.net/npm/css-vars-ponyfill@2"></script>
<script src="js/search.js"></script>
<script defer src="js/searchIndex.js"></script>
</head>
<body id="top">
<header class="phpdocumentor-header phpdocumentor-section">
<h1 class="phpdocumentor-title"><a href="" class="phpdocumentor-title__link">Documentation</a></h1>
<input class="phpdocumentor-header__menu-button" type="checkbox" id="menu-button" name="menu-button" />
<label class="phpdocumentor-header__menu-icon" for="menu-button">
<i class="fas fa-bars"></i>
</label>
<section data-search-form class="phpdocumentor-search">
<label>
<span class="visually-hidden">Search for</span>
<svg class="phpdocumentor-search__icon" width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="7.5" cy="7.5" r="6.5" stroke="currentColor" stroke-width="2"/>
<line x1="12.4892" y1="12.2727" x2="19.1559" y2="18.9393" stroke="currentColor" stroke-width="3"/>
</svg>
<input type="search" class="phpdocumentor-field phpdocumentor-search__field" placeholder="Loading .." disabled />
</label>
</section>
<nav class="phpdocumentor-topnav">
<ul class="phpdocumentor-topnav__menu">
</ul>
</nav>
</header>
<main class="phpdocumentor">
<div class="phpdocumentor-section">
<input class="phpdocumentor-sidebar__menu-button" type="checkbox" id="sidebar-button" name="sidebar-button" />
<label class="phpdocumentor-sidebar__menu-icon" for="sidebar-button">
Menu
</label>
<aside class="phpdocumentor-column -four phpdocumentor-sidebar">
<section class="phpdocumentor-sidebar__category">
<h2 class="phpdocumentor-sidebar__category-header">Namespaces</h2>
<h4 class="phpdocumentor-sidebar__root-namespace">
<a href="namespaces/easypost.html" class="">EasyPost</a>
</h4>
<ul class="phpdocumentor-list">
<li>
<a href="namespaces/easypost-beta.html" class="">Beta</a>
</li>
</ul>
</section>
<section class="phpdocumentor-sidebar__category">
<h2 class="phpdocumentor-sidebar__category-header">Packages</h2>
<h4 class="phpdocumentor-sidebar__root-namespace">
<a href="packages/Application.html" class="">Application</a>
</h4>
<h4 class="phpdocumentor-sidebar__root-namespace">
<a href="packages/EasyPost.html" class="">EasyPost</a>
</h4>
<ul class="phpdocumentor-list">
<li>
<a href="packages/EasyPost-Beta.html" class="">Beta</a>
</li>
</ul>
</section>
<section class="phpdocumentor-sidebar__category">
<h2 class="phpdocumentor-sidebar__category-header">Reports</h2>
<h3 class="phpdocumentor-sidebar__root-package"><a href="reports/deprecated.html">Deprecated</a></h3>
<h3 class="phpdocumentor-sidebar__root-package"><a href="reports/errors.html">Errors</a></h3>
<h3 class="phpdocumentor-sidebar__root-package"><a href="reports/markers.html">Markers</a></h3>
</section>
<section class="phpdocumentor-sidebar__category">
<h2 class="phpdocumentor-sidebar__category-header">Indices</h2>
<h3 class="phpdocumentor-sidebar__root-package"><a href="indices/files.html">Files</a></h3>
</section>
</aside>
<div class="phpdocumentor-column -eight phpdocumentor-content">
<ul class="phpdocumentor-breadcrumbs">
</ul>
<article class="phpdocumentor-element -file">
<h2 class="phpdocumentor-content__title">Billing.php</h2>
<section class="phpdocumentor-description"></section>
<h3 id="interfaces_class_traits">
Interfaces, Classes, Traits and Enums
<a href="#interfaces_class_traits" class="headerlink"><i class="fas fa-link"></i></a>
</h3>
<dl class="phpdocumentor-table-of-contents">
<dt class="phpdocumentor-table-of-contents__entry -class"><a href="classes/EasyPost-Billing.html"><abbr title="\EasyPost\Billing">Billing</abbr></a></dt>
<dd></dd>
</dl>
</article>
<section data-search-results class="phpdocumentor-search-results phpdocumentor-search-results--hidden">
<section class="phpdocumentor-search-results__dialog">
<header class="phpdocumentor-search-results__header">
<h2 class="phpdocumentor-search-results__title">Search results</h2>
<button class="phpdocumentor-search-results__close"><i class="fas fa-times"></i></button>
</header>
<section class="phpdocumentor-search-results__body">
<ul class="phpdocumentor-search-results__entries"></ul>
</section>
</section>
</section>
</div>
</div>
<a href="files/easypost-billing.html#top" class="phpdocumentor-back-to-top"><i class="fas fa-chevron-circle-up"></i></a>
</main>
<script>
cssVars({});
</script>
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.23.0/prism.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.23.0/plugins/autoloader/prism-autoloader.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.23.0/plugins/line-numbers/prism-line-numbers.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.23.0/plugins/line-highlight/prism-line-highlight.min.js"></script>
</body>
</html>
| {
"content_hash": "101d93681dbb8beed0c4ed075df3d4e5",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 203,
"avg_line_length": 44.24223602484472,
"alnum_prop": 0.6254387196406008,
"repo_name": "EasyPost/easypost-php",
"id": "81c878f083b8b9cd9da43602745c17392213d090",
"size": "7123",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/files/easypost-billing.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "1259"
},
{
"name": "PHP",
"bytes": "197091"
}
],
"symlink_target": ""
} |
package config
import (
"os"
"github.com/BurntSushi/toml"
"github.com/njpatel/loggo"
"utils"
)
//go:generate bash bake_default_config.sh
const defaultTomlConfig = `
# This is where top level info is stored for the counter manager we
# could also use a boltDB in the DataDir but this would make it harder
# to sync over replicas since not all replicas will hold the all the
# counters.
info_dir = "~/.skizze"
# This is where the data is stored either as json or .count (pure bytes)
data_dir = "~/.skizze/data"
# The host interface for the server
host = "localhost"
# The port number for the server
port = 3596
# Treshold for saving a sketch to disk
save_threshold_seconds = 1
`
var logger = loggo.GetLogger("config")
// Config stores all configuration parameters for Go
type Config struct {
InfoDir string `toml:"info_dir"`
DataDir string `toml:"data_dir"`
Host string `toml:"host"`
Port int `toml:"port"`
SaveThresholdSeconds uint `toml:"save_threshold_seconds"`
}
var config *Config
// InfoDir initialized from config file
var InfoDir string
// DataDir initialized from config file
var DataDir string
// Host initialized from config file
var Host string
// Port initialized from config file
var Port int
// SaveThresholdSeconds initialized from config file
var SaveThresholdSeconds uint
// MaxKeySize for BoltDB keys in bytes
const MaxKeySize int = 32768
func parseConfigTOML() *Config {
cfg := &Config{}
if _, err := toml.Decode(defaultTomlConfig, &cfg); err != nil {
utils.PanicOnError(err)
}
configPath := os.Getenv("SKIZZE_CONFIG")
if configPath != "" {
_, err := os.Open(configPath)
if err != nil {
logger.Warningf("Unable to find config file, using defaults")
return cfg
}
if _, err := toml.DecodeFile(configPath, &cfg); err != nil {
logger.Warningf("Error parsing config file, using defaults")
}
}
// make paths absolute
infodir, err := utils.FullPath(cfg.InfoDir)
if err != nil {panic(err)}
datadir, err := utils.FullPath(cfg.DataDir)
if err != nil {panic(err)}
cfg.InfoDir = infodir
cfg.DataDir = datadir
return cfg
}
// GetConfig returns a singleton Configuration
func GetConfig() *Config {
if config == nil {
config = parseConfigTOML()
InfoDir = config.InfoDir
DataDir = config.DataDir
Host = config.Host
Port = config.Port
SaveThresholdSeconds = config.SaveThresholdSeconds
if err := os.MkdirAll(InfoDir, os.ModePerm); err != nil {
panic(err)
}
if err := os.MkdirAll(DataDir, os.ModePerm); err != nil {
panic(err)
}
}
return config
}
// init initializes a singleton Configuration
func init() {
GetConfig()
}
// Reset ...
func Reset() {
GetConfig()
}
| {
"content_hash": "7b1c3054c441de182dd6af9008af1064",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 72,
"avg_line_length": 24.156521739130437,
"alnum_prop": 0.6807055435565155,
"repo_name": "seiflotfy/counts",
"id": "48769015f6d420fa5f2221b4ad4cf93e6d51f738",
"size": "2778",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/config/config.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "84291"
},
{
"name": "Makefile",
"bytes": "880"
},
{
"name": "Protocol Buffer",
"bytes": "4116"
},
{
"name": "Shell",
"bytes": "143"
}
],
"symlink_target": ""
} |
<!--
Unsafe sample
input : get the field userData from the variable $_GET via an object, which store it in a array
Flushes content of $sanitized if the filter number_float_filter is not applied
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
class Input{
private $input;
public function getInput(){
return $this->input[1];
}
public function __construct(){
$this->input = array();
$this->input[0]= 'safe' ;
$this->input[1]= $_GET['UserData'] ;
$this->input[2]= 'safe' ;
}
}
$temp = new Input();
$tainted = $temp->getInput();
if (filter_var($sanitized, FILTER_VALIDATE_FLOAT))
$tainted = $sanitized ;
else
$tainted = "" ;
//flaw
echo $tainted ;
?>
</style>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html> | {
"content_hash": "fddba3e7d008a3ff0f0d9878c426e61f",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 95,
"avg_line_length": 22.12987012987013,
"alnum_prop": 0.721830985915493,
"repo_name": "stivalet/PHP-Vulnerability-test-suite",
"id": "a4bd5c686d9291d98a6f3888aa6ceb29a4b98d5e",
"size": "1704",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "XSS/CWE_79/unsafe/CWE_79__object-Array__func_FILTER-VALIDATION-number_float_filter__Unsafe_use_untrusted_data-style.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "64184004"
}
],
"symlink_target": ""
} |
using System;
using Nimbus.DependencyResolution;
using Nimbus.Interceptors.Inbound;
using Nimbus.UnitTests.DispatcherTests.Handlers;
using Nimbus.UnitTests.DispatcherTests.MessageContracts;
using NSubstitute;
using NUnit.Framework;
namespace Nimbus.UnitTests.DispatcherTests
{
public class WhenHandlerThrowsAnExceptionInRequestMessageDispatcher
: MessageDispatcherTestBase
{
[Test]
public void TheExceptionIsBubbledThroughTheInterceptors()
{
var interceptor = Substitute.For<IInboundInterceptor>();
var dispatcher = GetRequestMessageDispatcher<ExceptingRequest, ExceptingResponse, ExceptingRequestHandler>(interceptor);
var brokeredMessage = BrokeredMessageFactory.Create(new ExceptingRequest()).Result;
dispatcher.Dispatch(brokeredMessage).Wait();
interceptor
.Received()
.OnRequestHandlerError(Arg.Any<ExceptingRequest>(), brokeredMessage, Arg.Any<Exception>());
}
}
} | {
"content_hash": "cbb65bc5dd89b814d1e6e816d10828e7",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 132,
"avg_line_length": 36.357142857142854,
"alnum_prop": 0.7269155206286837,
"repo_name": "rebase42/Anubus",
"id": "83ddb10029a14f665d0ae3de03eea35fb8306385",
"size": "1020",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/Tests/Nimbus.UnitTests/DispatcherTests/WhenHandlerThrowsAnExceptionInRequestMessageDispatcher.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "106"
},
{
"name": "C#",
"bytes": "824936"
},
{
"name": "CSS",
"bytes": "685"
},
{
"name": "HTML",
"bytes": "5125"
},
{
"name": "JavaScript",
"bytes": "19477"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<page
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"
>
<body>
<referenceBlock
name="product.info.type.giftcard"
remove="true"
/>
<referenceBlock
name="product.info.addtocart.additional"
remove="true"
/>
</body>
</page>
| {
"content_hash": "b70a10fd417ecf2443d4816f1f57d883",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 96,
"avg_line_length": 25.764705882352942,
"alnum_prop": 0.589041095890411,
"repo_name": "SnowdogApps/magento2-alpaca-theme",
"id": "cada7926e16bb17e2f8a0f54bd3bdf51dc0f1fdd",
"size": "438",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Magento_GiftCard/layout/catalog_product_view_type_giftcard.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1928585"
},
{
"name": "Handlebars",
"bytes": "223862"
},
{
"name": "JavaScript",
"bytes": "918919"
},
{
"name": "PHP",
"bytes": "172"
},
{
"name": "SCSS",
"bytes": "993052"
}
],
"symlink_target": ""
} |
"""Exception types that can be raised by Gnuplot.py."""
class Error(Exception):
"""All our exceptions are derived from this one."""
pass
class OptionError(Error):
"""Raised for unrecognized option(s)"""
pass
class DataError(Error):
"""Raised for data in the wrong format"""
pass
| {
"content_hash": "6a353aae5d824d5fcade124df1fe05db",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 55,
"avg_line_length": 17.27777777777778,
"alnum_prop": 0.6591639871382636,
"repo_name": "pombredanne/ompc",
"id": "0a4e27f2f312c23032ba09cf9f2f31160f7c8835",
"size": "546",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ompclib/gplot/Errors.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "250"
},
{
"name": "Python",
"bytes": "498364"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="x-ua-compatible" content="IE=edge"/>
<title>Test results - Class com.ddchen.test1.Test1Test</title>
<link href="../css/base-style.css" rel="stylesheet" type="text/css"/>
<link href="../css/style.css" rel="stylesheet" type="text/css"/>
<script src="../js/report.js" type="text/javascript"></script>
</head>
<body>
<div id="content">
<h1>Class com.ddchen.test1.Test1Test</h1>
<div class="breadcrumbs">
<a href="../index.html">all</a> >
<a href="../packages/com.ddchen.test1.html">com.ddchen.test1</a> > Test1Test</div>
<div id="summary">
<table>
<tr>
<td>
<div class="summaryGroup">
<table>
<tr>
<td>
<div class="infoBox" id="tests">
<div class="counter">1</div>
<p>tests</p>
</div>
</td>
<td>
<div class="infoBox" id="failures">
<div class="counter">1</div>
<p>failures</p>
</div>
</td>
<td>
<div class="infoBox" id="ignored">
<div class="counter">0</div>
<p>ignored</p>
</div>
</td>
<td>
<div class="infoBox" id="duration">
<div class="counter">0.003s</div>
<p>duration</p>
</div>
</td>
</tr>
</table>
</div>
</td>
<td>
<div class="infoBox failures" id="successRate">
<div class="percent">0%</div>
<p>successful</p>
</div>
</td>
</tr>
</table>
</div>
<div id="tabs">
<ul class="tabLinks">
<li>
<a href="#tab0">Failed tests</a>
</li>
<li>
<a href="#tab1">Tests</a>
</li>
<li>
<a href="#tab2">Standard output</a>
</li>
</ul>
<div id="tab0" class="tab">
<h2>Failed tests</h2>
<div class="test">
<a name="testSomeLibraryMethod"></a>
<h3 class="failures">testSomeLibraryMethod</h3>
<span class="code">
<pre>java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertTrue(Assert.java:52)
at com.ddchen.test1.Test1Test.testSomeLibraryMethod(Test1Test.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:109)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:377)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</pre>
</span>
</div>
</div>
<div id="tab1" class="tab">
<h2>Tests</h2>
<table>
<thead>
<tr>
<th>Test</th>
<th>Duration</th>
<th>Result</th>
</tr>
</thead>
<tr>
<td class="failures">testSomeLibraryMethod</td>
<td>0.003s</td>
<td class="failures">failed</td>
</tr>
</table>
</div>
<div id="tab2" class="tab">
<h2>Standard output</h2>
<span class="code">
<pre>this is test1
this is test2!
</pre>
</span>
</div>
</div>
<div id="footer">
<p>
<div>
<label class="hidden" id="label-for-line-wrapping-toggle" for="line-wrapping-toggle">Wrap lines
<input id="line-wrapping-toggle" type="checkbox" autocomplete="off"/>
</label>
</div>Generated by
<a href="http://www.gradle.org">Gradle 3.2.1</a> at Dec 28, 2016 2:33:16 PM</p>
</div>
</div>
</body>
</html>
| {
"content_hash": "42e212bcca2c8a11f6a5539dd8654495",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 121,
"avg_line_length": 36.720238095238095,
"alnum_prop": 0.7735451450802399,
"repo_name": "ddki/my_study_project",
"id": "f309fafeebb1700433c8648f5a188f891c2027da",
"size": "6169",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/android/tools/gradle/test_gradle_dep/gradle_dep_loca_demo/build/reports/tests/test/classes/com.ddchen.test1.Test1Test.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AspectJ",
"bytes": "3520"
},
{
"name": "Batchfile",
"bytes": "10160"
},
{
"name": "C",
"bytes": "43156"
},
{
"name": "C++",
"bytes": "16295"
},
{
"name": "CSS",
"bytes": "54735"
},
{
"name": "Dockerfile",
"bytes": "538"
},
{
"name": "Elixir",
"bytes": "7538"
},
{
"name": "GAP",
"bytes": "133251"
},
{
"name": "Go",
"bytes": "23393"
},
{
"name": "HTML",
"bytes": "183017"
},
{
"name": "Haskell",
"bytes": "18024"
},
{
"name": "Java",
"bytes": "3890824"
},
{
"name": "JavaScript",
"bytes": "1150724"
},
{
"name": "Lex",
"bytes": "22606"
},
{
"name": "Makefile",
"bytes": "1772"
},
{
"name": "Objective-C",
"bytes": "9224"
},
{
"name": "PHP",
"bytes": "31"
},
{
"name": "Python",
"bytes": "2968992"
},
{
"name": "Ragel",
"bytes": "16770"
},
{
"name": "Ruby",
"bytes": "95237"
},
{
"name": "Scala",
"bytes": "23930"
},
{
"name": "Shell",
"bytes": "47348"
},
{
"name": "Smali",
"bytes": "71959175"
},
{
"name": "Swift",
"bytes": "211292"
},
{
"name": "XSLT",
"bytes": "104965"
}
],
"symlink_target": ""
} |
const http = require('http');
const chalk = require('chalk');
const log = console.log.bind(console);
const {
ROLLBAR_SERVER_TOKEN,
ROLLBAR_ENVIRONMENT,
BUILD_TAG,
USER,
GIT_COMMIT
} = process.env;
module.exports = function rollbar(data) {
notify(data).catch(() => {
process.exit(1);
});
};
function notify({
token = ROLLBAR_SERVER_TOKEN,
env = ROLLBAR_ENVIRONMENT,
tag = BUILD_TAG,
user = USER,
comment = GIT_COMMIT
}) {
const data = {
access_token: token,
environment: env,
revision: tag,
local_username: user,
comment
};
return Promise.resolve(data).then(makeRequest);
}
function handler(res) {
return new Promise((resolve, reject) => {
let body = '';
log(chalk.cyan('Rollbar response status'), res.statusCode);
res.on('data', (data) => body += data);
res.on('end', () => {
log(chalk.cyan('Rollbar response'), body);
if (res.statusCode !== 200) {
return reject(res);
}
return resolve(body);
});
});
}
function makeRequest(body) {
return new Promise((resolve, reject) => {
const request = http.request({
host: 'api.rollbar.com',
path: '/api/1/deploy/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': JSON.stringify(body).length
}
},
(res) => resolve(handler(res)));
request.on('error', (error) => {
log(chalk.red('Something bad happened'), error);
reject(error);
});
request.write(JSON.stringify(body));
request.end();
});
}
| {
"content_hash": "efe3f4155df8a7d879e236a6a1ab99ad",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 63,
"avg_line_length": 19.6875,
"alnum_prop": 0.5892063492063492,
"repo_name": "pismo/almighty",
"id": "6741e13342425b20e81c24cf89d64310ad069be8",
"size": "1575",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tasks/rollbar.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "9053"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.jeesuite.admin.dao.mapper.UserEntityMapper" >
<resultMap id="BaseResultMap" type="com.jeesuite.admin.dao.entity.UserEntity" >
<!--
WARNING - @mbg.generated
-->
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="mobile" property="mobile" jdbcType="CHAR" />
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="type" property="type" jdbcType="CHAR" />
<result column="enabled" property="enabled" jdbcType="BIT" />
<result column="group_id" property="groupId" jdbcType="INTEGER" />
<result column="created_at" property="createdAt" jdbcType="TIMESTAMP" />
<result column="updated_at" property="updatedAt" jdbcType="TIMESTAMP" />
</resultMap>
</mapper> | {
"content_hash": "427568865cd32eee4ac8b93d6b936f87",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 108,
"avg_line_length": 55.10526315789474,
"alnum_prop": 0.6829035339063992,
"repo_name": "vakinge/jeesuite-config",
"id": "39b9f35fedd8b7c8d62de3e7b9824c4a6a5a9ebc",
"size": "1047",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jeesuite-config-server/src/main/resources/mapper/UserEntityMapper.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "25103"
},
{
"name": "HTML",
"bytes": "59273"
},
{
"name": "Java",
"bytes": "162584"
},
{
"name": "JavaScript",
"bytes": "66863"
},
{
"name": "TSQL",
"bytes": "10126"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Reflection;
using Marten.Linq;
using Marten.Services.Includes;
using Remotion.Linq;
namespace Marten.Schema
{
public interface IQueryableDocument
{
IWhereFragment FilterDocuments(QueryModel model, IWhereFragment query);
IWhereFragment DefaultWhereFragment();
IncludeJoin<TOther> JoinToInclude<TOther>(JoinType joinType, IQueryableDocument other, MemberInfo[] members, Action<TOther> callback);
IField FieldFor(IEnumerable<MemberInfo> members);
string[] SelectFields();
PropertySearching PropertySearching { get; }
TableName Table { get; }
DuplicatedField[] DuplicatedFields { get; }
DeleteStyle DeleteStyle { get; }
Type DocumentType { get; }
}
} | {
"content_hash": "5634642f7fbb15698da40827572ae083",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 142,
"avg_line_length": 25.28125,
"alnum_prop": 0.7107540173053152,
"repo_name": "jamesfarrer/marten",
"id": "649fb56a495f1ad39a3821e8ac997484d687319d",
"size": "809",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Marten/Schema/IQueryableDocument.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2119669"
},
{
"name": "CSS",
"bytes": "50263"
},
{
"name": "HTML",
"bytes": "8646"
},
{
"name": "JavaScript",
"bytes": "449113"
},
{
"name": "PLpgSQL",
"bytes": "3714"
},
{
"name": "Ruby",
"bytes": "5097"
},
{
"name": "SQLPL",
"bytes": "193"
}
],
"symlink_target": ""
} |
from cgum.utility import *
from cgum.program import Program
import codecs
import json
import tempfile
from subprocess import Popen
class Mappings(object):
@staticmethod
def from_json(jsn):
before_to_after = dict()
after_to_before = dict()
for m in jsn:
src = int(m['src'])
dest = int(m['dest'])
before_to_after[src] = dest
after_to_before[dest] = src
return Mappings(before_to_after, after_to_before)
def __init__(self, before_to_after, after_to_before):
self.before_to_after = before_to_after
self.after_to_before = after_to_before
# Given the number of a node in P, returns the number of the matching node
# in P', or None if no such match exists.
def after(self, num):
return self.before_to_after.get(num, None)
# Given the number of a node in P', returns the number of the matching node
# in P, or None if no such match exists.
def before(self, num):
return self.after_to_before.get(num, None)
class Action(object):
@staticmethod
def from_json_with_mappings(jsn, mapping):
return ({
'insert': Insert,
'update': Update,
'move': Move,
'delete': Delete
})[jsn['action']].from_json_with_mappings(jsn, mapping)
# Gives the ID of the node in the original tree that was deleted.
class Delete(Action):
@staticmethod
def from_json_with_mappings(jsn, mapping):
return Delete(jsn['tree'])
def __init__(self, node_id):
self.__deleted_id = node_id
self.__deleted = None
def annotate(self, before, after):
self.__deleted = before.find(self.__deleted_id)
# Returns the deleted node from the before AST
def deleted(self):
return self.__deleted
def __str__(self):
return "DEL(%d)" % self.__deleted_id
# Position parameter is NOT to be trusted
class Move(Action):
@staticmethod
def from_json_with_mappings(jsn, mapping):
from_id = jsn['tree']
to_id = mapping.after(from_id)
return Move(from_id, to_id, jsn['parent'], jsn['at'])
def __init__(self, from_id, to_id, parent_id, position):
self.__from_id = from_id
self.__to_id = to_id
self.__parent_id = parent_id
self.__position = position
self.__from = None
self.__to = None
# Annotates this action by recording the from and to nodes
def annotate(self, before, after):
self.__from = before.find(self.__from_id)
self.__to = after.find(self.__to_id)
# Returns the node in the before AST
def moved_from(self):
if self.__from is None:
raise Exception("moved_from: action hasn't been annotated")
return self.__from
# Returns the node in the after AST
def moved_to(self):
if self.__to is None:
raise Exception("moved_to: action hasn't been annotated")
return self.__to
# Returns the ID of the node that was moved in the before AST
def moved_from_id(self):
return self.__to_id
def moved_to_id(self):
return self.__from_id
# Returns the original (incorrect) GumTree description
def __str__(self):
return "MOV(%d, %d, %d)" % \
(self.__from_id, self.__parent_id, self.__position)
# Doesn't handle insert root?
class Insert(Action):
@staticmethod
def from_json_with_mappings(jsn, mapping):
return Insert(jsn['tree'], jsn['parent'], jsn['at'])
def __init__(self, inserted_id, parent_id, position):
self.__inserted_id = inserted_id
self.__parent_id = parent_id
self.__position = position
self.__inserted = None
self.__parent = None
# Annotates this action by caching the inserted and parent nodes
def annotate(self, before, after):
self.__inserted = after.find(self.__inserted_id)
self.__parent = after.find(self.__parent_id)
# Returns the node which was inserted into the AST
def inserted(self):
return self.__inserted
# Returns the parent of the node that was inserted into the AST
def parent(self):
return self.__parent
# Returns the ID of the node that was inserted into the AST
def inserted_id(self):
return self.__child_id
def parent_id(self):
return self.__parent_id
# Returns the position that the node was inserted into its parents subtree,
# according to GumTree output; flawed.
def position(self):
return self.__position
def __str__(self):
return "INS(%d, %d, %d)" % \
(self.__inserted_id, self.__parent_id, self.__position)
class Update(Action):
@staticmethod
def from_json_with_mappings(jsn, mapping):
after_id = mapping.after(jsn['tree'])
return Update(jsn['tree'], after_id, jsn['label'])
def __init__(self, before_id, after_id, label):
self.__before_id = before_id
self.__after_id = after_id
self.__label = label
self.__before = None
self.__after = None
# Annotates this action by caching the before and after forms of the node
def annotate(self, before, after):
self.__before = before.find(self.__before_id)
self.__after = after.find(self.__after_id)
# Returns the node that was the subject of this Update operation, in P
def before(self):
return self.__before
# Returns the node that was the subject of this Update operation, in P'
def after(self):
return self.__after
# Returns the ID of the node in P
def before_id(self):
return self.__before_id
# Returns the ID of the node in P'
def after_id(self):
return self.__after_id
# Returns the updated label for this node
def label(self):
return self.__label
# Returns a string description of the operation, in its original GumTree
# encoding
def __str__(self):
return "UPD(%d, %s)" % (self.__before_id, self.__label)
class AnnotatedDiff(object):
@staticmethod
def from_source_files(fn_from, fn_to):
tmp_f = tempfile.NamedTemporaryFile()
AnnotatedDiff.parse_to_json_file(fn_from, fn_to, tmp_f)
before = Program.from_source_file(fn_from)
after = Program.from_source_file(fn_to)
return AnnotatedDiff.from_file(tmp_f.name,\
before,\
after)
@staticmethod
def parse_to_json_file(fn_from, fn_to, jsn_fn):
assert Popen(("gumtree jsondiff \"%s\" \"%s\"" % (fn_from, fn_to)), \
shell=True, stdin=FNULL, stdout=jsn_fn).wait() == 0
@staticmethod
def from_file(fn, before, after):
with codecs.open(fn, 'r', 'utf-8') as f:
return AnnotatedDiff.from_json(json.load(f), before, after)
@staticmethod
def from_json(jsn, before, after):
mappings = Mappings.from_json(jsn['matches'])
actions = \
[Action.from_json_with_mappings(a, mappings) for a in jsn['actions']]
return AnnotatedDiff(actions, mappings, before, after)
def __init__(self, actions, mappings, before, after):
self.__actions = actions
self.__mappings = mappings
self.__before = before
self.__after = after
self.__insertions = []
self.__deletions = []
self.__updates = []
self.__moves = []
# Annotate and group the actions
for action in self.__actions:
action.annotate(before, after)
({
Insert: self.__insertions,
Delete: self.__deletions,
Update: self.__updates,
Move: self.__moves
})[action.__class__].append(action)
def before(self):
return self.__before
def after(self):
return self.__after
def actions(self):
return self.__actions
def insertions(self):
return self.__insertions
def deletions(self):
return self.__deletions
def moves(self):
return self.__moves
def updates(self):
return self.__updates
def mappings(self):
return self.__mappings
# checks whether a given node in P' was moved to that location
def was_moved_to(self, to):
return any([to == move.moved_to() in self.moves()])
# checks whether a given node in P was moved to another location
def was_moved_from(self, frm):
return any([frm == move.moved_from() in self.moves()])
# Given a node in P, return the matching node in P', or None if no such
# match exists.
def was_is(self, node):
assert not node is None, "was_is: provided node must not be null"
was_num = node.number()
is_num = self.__mappings.after(was_num)
if is_num is None:
return None
else:
return self.__after.find(is_num)
# Given a node in P', return the matching node in P, or None if no such
# match exists.
def is_was(self, node):
assert not node is None, "is_was: provided node must not be null"
is_num = node.number()
was_num = self.__mappings.before(is_num)
if was_num is None:
return None
else:
return self.__before.find(was_num)
def __str__(self):
return '\n'.join(map(str, self.__actions))
| {
"content_hash": "4b520ed7758377cbbd6eccefe784bd7b",
"timestamp": "",
"source": "github",
"line_count": 288,
"max_line_length": 81,
"avg_line_length": 32.763888888888886,
"alnum_prop": 0.5922000847816872,
"repo_name": "ChrisTimperley/PythonCGum",
"id": "2fe555bf3f8a8e05534d9f0d5bda5368d0a72daa",
"size": "9451",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cgum/diff.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "580845"
},
{
"name": "Python",
"bytes": "49990"
}
],
"symlink_target": ""
} |
namespace fgui {
export class TranslationHelper {
public static strings: { [index: string]: { [index: string]: string } };
constructor() {
}
public static loadFromXML(source: string): void {
let strings = {};
TranslationHelper.strings = strings;
var xml: any = Laya.Utils.parseXMLFromString(source);
var resNode: any = findChildNode(xml, "resources");
var nodes: any[] = resNode.childNodes;
var length1: number = nodes.length;
for (var i1: number = 0; i1 < length1; i1++) {
var cxml: any = nodes[i1];
if (cxml.nodeName == "string") {
var key: string = cxml.getAttribute("name");
var text: string = cxml.textContent;
var i: number = key.indexOf("-");
if (i == -1)
continue;
var key2: string = key.substr(0, i);
var key3: string = key.substr(i + 1);
var col: Object = strings[key2];
if (!col) {
col = {};
strings[key2] = col;
}
col[key3] = text;
}
}
}
public static translateComponent(item: PackageItem): void {
if (TranslationHelper.strings == null)
return;
var compStrings: { [index: string]: string } = TranslationHelper.strings[item.owner.id + item.id];
if (compStrings == null)
return;
var elementId: string, value: string;
var buffer: ByteBuffer = item.rawData;
var nextPos: number;
var itemCount: number;
var i: number, j: number, k: number;
var dataLen: number;
var curPos: number;
var valueCnt: number;
var page: string;
buffer.seek(0, 2);
var childCount: number = buffer.getInt16();
for (i = 0; i < childCount; i++) {
dataLen = buffer.getInt16();
curPos = buffer.pos;
buffer.seek(curPos, 0);
var baseType: number = buffer.readByte();
var type: number = baseType;
buffer.skip(4);
elementId = buffer.readS();
if (type == ObjectType.Component) {
if (buffer.seek(curPos, 6))
type = buffer.readByte();
}
buffer.seek(curPos, 1);
if ((value = compStrings[elementId + "-tips"]) != null)
buffer.writeS(value);
buffer.seek(curPos, 2);
var gearCnt: number = buffer.getInt16();
for (j = 0; j < gearCnt; j++) {
nextPos = buffer.getInt16();
nextPos += buffer.pos;
if (buffer.readByte() == 6) //gearText
{
buffer.skip(2);//controller
valueCnt = buffer.getInt16();
for (k = 0; k < valueCnt; k++) {
page = buffer.readS();
if (page != null) {
if ((value = compStrings[elementId + "-texts_" + k]) != null)
buffer.writeS(value);
else
buffer.skip(2);
}
}
if (buffer.readBool() && (value = compStrings[elementId + "-texts_def"]) != null)
buffer.writeS(value);
}
buffer.pos = nextPos;
}
if (baseType == ObjectType.Component && buffer.version >= 2) {
buffer.seek(curPos, 4);
buffer.skip(2); //pageController
buffer.skip(4 * buffer.getUint16());
var cpCount: number = buffer.getUint16();
for (var k: number = 0; k < cpCount; k++) {
var target: string = buffer.readS();
var propertyId: number = buffer.getUint16();
if (propertyId == 0 && (value = compStrings[elementId + "-cp-" + target]) != null)
buffer.writeS(value);
else
buffer.skip(2);
}
}
switch (type) {
case ObjectType.Text:
case ObjectType.RichText:
case ObjectType.InputText:
{
if ((value = compStrings[elementId]) != null) {
buffer.seek(curPos, 6);
buffer.writeS(value);
}
if ((value = compStrings[elementId + "-prompt"]) != null) {
buffer.seek(curPos, 4);
buffer.writeS(value);
}
break;
}
case ObjectType.List:
case ObjectType.Tree:
{
buffer.seek(curPos, 8);
buffer.skip(2);
itemCount = buffer.getUint16();
for (j = 0; j < itemCount; j++) {
nextPos = buffer.getUint16();
nextPos += buffer.pos;
buffer.skip(2); //url
if (type == ObjectType.Tree)
buffer.skip(2);
//title
if ((value = compStrings[elementId + "-" + j]) != null)
buffer.writeS(value);
else
buffer.skip(2);
//selected title
if ((value = compStrings[elementId + "-" + j + "-0"]) != null)
buffer.writeS(value);
else
buffer.skip(2);
if (buffer.version >= 2) {
buffer.skip(6);
buffer.skip(buffer.getUint16() * 4);//controllers
var cpCount: number = buffer.getUint16();
for (var k: number = 0; k < cpCount; k++) {
var target: string = buffer.readS();
var propertyId: number = buffer.getUint16();
if (propertyId == 0 && (value = compStrings[elementId + "-" + j + "-" + target]) != null)
buffer.writeS(value);
else
buffer.skip(2);
}
}
buffer.pos = nextPos;
}
break;
}
case ObjectType.Label:
{
if (buffer.seek(curPos, 6) && buffer.readByte() == type) {
if ((value = compStrings[elementId]) != null)
buffer.writeS(value);
else
buffer.skip(2);
buffer.skip(2);
if (buffer.readBool())
buffer.skip(4);
buffer.skip(4);
if (buffer.readBool() && (value = compStrings[elementId + "-prompt"]) != null)
buffer.writeS(value);
}
break;
}
case ObjectType.Button:
{
if (buffer.seek(curPos, 6) && buffer.readByte() == type) {
if ((value = compStrings[elementId]) != null)
buffer.writeS(value);
else
buffer.skip(2);
if ((value = compStrings[elementId + "-0"]) != null)
buffer.writeS(value);
}
break;
}
case ObjectType.ComboBox:
{
if (buffer.seek(curPos, 6) && buffer.readByte() == type) {
itemCount = buffer.getInt16();
for (j = 0; j < itemCount; j++) {
nextPos = buffer.getInt16();
nextPos += buffer.pos;
if ((value = compStrings[elementId + "-" + j]) != null)
buffer.writeS(value);
buffer.pos = nextPos;
}
if ((value = compStrings[elementId]) != null)
buffer.writeS(value);
}
break;
}
}
buffer.pos = curPos + dataLen;
}
}
}
function findChildNode(xml: any, name: string): Object {
var col: any[] = xml.childNodes;
var length1: number = col.length;
if (length1 > 0) {
for (var i1: number = 0; i1 < length1; i1++) {
var cxml: any = col[i1];
if (cxml.nodeName == name) {
return cxml;
}
}
}
return null;
}
} | {
"content_hash": "5f000dfb2000c227795f45bda36c15a9",
"timestamp": "",
"source": "github",
"line_count": 259,
"max_line_length": 129,
"avg_line_length": 41.20849420849421,
"alnum_prop": 0.3396420875105406,
"repo_name": "fairygui/FairyGUI-layabox",
"id": "aca10a2883170862db7674b739d7ff4b3f0d8232",
"size": "10673",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/src/fairygui/TranslationHelper.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "691113"
},
{
"name": "TypeScript",
"bytes": "763947"
}
],
"symlink_target": ""
} |
using JetBrains.ReSharper.Psi.ExtensionsAPI.Tree;
namespace JetBrains.ReSharper.Plugins.Unity.Shaders.ShaderLab.Psi.Parsing
{
public partial class ShaderLabTokenType
{
public static readonly NodeTypeSet KEYWORDS;
static ShaderLabTokenType()
{
KEYWORDS = new NodeTypeSet(
SHADER_KEYWORD,
PROPERTIES_KEYWORD,
CATEGORY_KEYWORD,
SUB_SHADER_KEYWORD,
FALLBACK_KEYWORD,
CUSTOM_EDITOR_KEYWORD,
DEPENDENCY_KEYWORD,
COLOR_KEYWORD,
FLOAT_KEYWORD,
INT_KEYWORD,
RANGE_KEYWORD,
VECTOR_KEYWORD,
ANY_KEYWORD,
CUBE_KEYWORD,
CUBE_ARRAY_KEYWORD,
RECT_KEYWORD,
TEXTURE_2D_KEYWORD,
TEXTURE_2D_ARRAY_KEYWORD,
TEXTURE_3D_KEYWORD,
TAGS_KEYWORD,
PASS_KEYWORD,
USEPASS_KEYWORD,
GRABPASS_KEYWORD,
CULL_KEYWORD,
ZCLIP_KEYWORD,
ZTEST_KEYWORD,
ZWRITE_KEYWORD,
CONSERVATIVE_KEYWORD,
OFFSET_KEYWORD,
BLEND_KEYWORD,
BLEND_OP_KEYWORD,
ALPHA_TO_MASK_KEYWORD,
COLOR_MASK_KEYWORD,
STENCIL_KEYWORD,
NAME_KEYWORD,
LOD_KEYWORD,
BIND_CHANNELS_KEYWORD,
BACK_KEYWORD,
FRONT_KEYWORD,
LIGHTING_KEYWORD,
MATERIAL_KEYWORD,
SEPARATE_SPECULAR_KEYWORD,
COLOR_MATERIAL_KEYWORD,
FOG_KEYWORD,
ALPHA_TEST_KEYWORD,
SET_TEXTURE_KEYWORD,
DIFFUSE_KEYWORD,
AMBIENT_KEYWORD,
SPECULAR_KEYWORD,
SHININESS_KEYWORD,
COMBINE_KEYWORD,
CONSTANT_COLOR_KEYWORD,
MATRIX_KEYWORD,
LIGHTMAP_MODE_KEYWORD,
TEX_GEN_KEYWORD,
PREVIOUS_KEYWORD,
PRIMARY_KEYWORD,
TEXTURE_KEYWORD,
CONSTANT_KEYWORD,
DOUBLE_KEYWORD,
QUAD_KEYWORD,
LERP_KEYWORD,
ONE_KEYWORD,
ALPHA_KEYWORD,
DOT3_KEYWORD,
DOT3RGBA_KEYWORD,
SPHERE_MAP_KEYWORD,
EYE_LINEAR_KEYWORD,
CUBE_REFLECT_KEYWORD,
CUBE_NORMAL_KEYWORD,
OBJECT_LINEAR_KEYWORD,
BIND_KEYWORD,
AMBIENT_AND_DIFFUSE_KEYWORD,
EMISSION_KEYWORD,
MODE_KEYWORD,
DENSITY_KEYWORD,
GLOBAL_KEYWORD,
LINEAR_KEYWORD,
EXP_KEYWORD,
EXP2_KEYWORD,
REF_KEYWORD,
READ_MASK_KEYWORD,
WRITE_MASK_KEYWORD,
PASS_FRONT_KEYWORD,
PASS_BACK_KEYWORD,
COMP_KEYWORD,
COMP_FRONT_KEYWORD,
COMP_BACK_KEYWORD,
FAIL_KEYWORD,
FAIL_FRONT_KEYWORD,
FAIL_BACK_KEYWORD,
ZFAIL_KEYWORD,
ZFAIL_FRONT_KEYWORD,
ZFAIL_BACK_KEYWORD,
GREATER_KEYWORD,
GEQUAL_KEYWORD,
LESS_KEYWORD,
LEQUAL_KEYWORD,
EQUAL_KEYWORD,
NOT_EQUAL_KEYWORD,
ALWAYS_KEYWORD,
NEVER_KEYWORD,
KEEP_KEYWORD,
ZERO_KEYWORD,
REPLACE_KEYWORD,
INCR_SAT_KEYWORD,
DECR_SAT_KEYWORD,
INVERT_KEYWORD,
INCR_WRAP_KEYWORD,
DECR_WRAP_KEYWORD,
TRUE_KEYWORD,
FALSE_KEYWORD,
ON_KEYWORD,
OFF_KEYWORD
);
}
}
} | {
"content_hash": "446a201648583f6b176ae9a31341fc18",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 73,
"avg_line_length": 28.38095238095238,
"alnum_prop": 0.43744007670182167,
"repo_name": "JetBrains/resharper-unity",
"id": "9af18e13de1358f95d191a6f10add029935ae9fa",
"size": "4174",
"binary": false,
"copies": "1",
"ref": "refs/heads/net223",
"path": "resharper/resharper-unity/src/Unity.Shaders/ShaderLab/Psi/Parsing/ShaderLabTokenType.NodeSets.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "4469066"
},
{
"name": "GLSL",
"bytes": "15101"
},
{
"name": "Kotlin",
"bytes": "708533"
},
{
"name": "Lex",
"bytes": "36667"
},
{
"name": "PowerShell",
"bytes": "1044"
},
{
"name": "ShaderLab",
"bytes": "89447"
},
{
"name": "Shell",
"bytes": "163"
}
],
"symlink_target": ""
} |
num_load_balancers=2
for i in $(seq $num_load_balancers)
do
neutron lbaas-pool-delete lbaas-migrate-pool-http-$i
neutron lbaas-listener-delete lbaas-migrate-http-$i
neutron lbaas-loadbalancer-delete lbaas-migrate-$i
done
# delete health monitors
hm_list=$(neutron lbaas-healthmonitor-list -f value | awk '{ print $1 }')
for hm in $hm_list
do
neutron lbaas-healthmonitor-delete $hm
done
heat stack-delete lbaas
| {
"content_hash": "e82706c4495b0c5719ec3f66f44b5044",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 73,
"avg_line_length": 25.235294117647058,
"alnum_prop": 0.7435897435897436,
"repo_name": "SUSE-Cloud/automation",
"id": "c303fa4a7786f1f1d5f23de537f3df4ddaa8f46c",
"size": "440",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "scripts/heat/load-balancer-delete.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "3703"
},
{
"name": "Emacs Lisp",
"bytes": "135"
},
{
"name": "Groovy",
"bytes": "9471"
},
{
"name": "Jinja",
"bytes": "47616"
},
{
"name": "Makefile",
"bytes": "3438"
},
{
"name": "Perl",
"bytes": "35913"
},
{
"name": "Python",
"bytes": "435834"
},
{
"name": "Ruby",
"bytes": "29921"
},
{
"name": "Shell",
"bytes": "628238"
}
],
"symlink_target": ""
} |
cask "tempo" do
arch arm: "release-arm64", intel: "release"
version "6.0.0"
sha256 arm: "67260ec4260e30da28abc20d847282f08e09d8bce00730594c598caf3a63bdb7",
intel: "acfe86aedce23077a34de27717f38920bf4eafb740841088ab31b685fec4e3af"
url "https://download.yourtempo.co/#{arch}/Tempo-#{version}.dmg"
name "Tempo"
desc "Email client that delivers all email in batches"
homepage "https://www.yourtempo.co/"
auto_updates true
app "Tempo.app"
zap trash: [
"~/Library/Application Support/Tempo",
"~/Library/Logs/Tempo",
"~/Library/Preferences/com.founders.mial.plist",
"~/Library/Saved Application State/com.founders.mial.savedState",
]
caveats do
discontinued
end
end
| {
"content_hash": "ff2f7a5a4720c49566b826772eb9044d",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 83,
"avg_line_length": 26.74074074074074,
"alnum_prop": 0.7174515235457064,
"repo_name": "JosephViolago/homebrew-cask",
"id": "2cd71b9dc6d06e2f4a926bc63349dd5b8f38a0ac",
"size": "722",
"binary": false,
"copies": "16",
"ref": "refs/heads/master",
"path": "Casks/tempo.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "3630"
},
{
"name": "Ruby",
"bytes": "3111150"
},
{
"name": "Shell",
"bytes": "32035"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../includes/main.css" type="text/css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
<title>Apache CloudStack | The Power Behind Your Cloud</title>
</head>
<body>
<div id="insidetopbg">
<div id="inside_wrapper">
<div class="uppermenu_panel">
<div class="uppermenu_box"></div>
</div>
<div id="main_master">
<div id="inside_header">
<div class="header_top">
<a class="cloud_logo" href="http://cloudstack.org"></a>
<div class="mainemenu_panel"></div>
</div>
</div>
<div id="main_content">
<div class="inside_apileftpanel">
<div class="inside_contentpanel" style="width:930px;">
<div class="api_titlebox">
<div class="api_titlebox_left">
<span>
Apache CloudStack v4.6.0 Root Admin API Reference
</span>
<p></p>
<h1>deleteVpnCustomerGateway</h1>
<p>Delete site to site vpn customer gateway</p>
</div>
<div class="api_titlebox_right">
<a class="api_backbutton" href="../TOC_Root_Admin.html"></a>
</div>
</div>
<div class="api_tablepanel">
<h2>Request parameters</h2>
<table class="apitable">
<tr class="hed">
<td style="width:200px;"><strong>Parameter Name</strong></td><td style="width:500px;">Description</td><td style="width:180px;">Required</td>
</tr>
<tr>
<td style="width:200px;"><strong>id</strong></td><td style="width:500px;"><strong>id of customer gateway</strong></td><td style="width:180px;"><strong>true</strong></td>
</tr>
</table>
</div>
<div class="api_tablepanel">
<h2>Response Tags</h2>
<table class="apitable">
<tr class="hed">
<td style="width:200px;"><strong>Response Name</strong></td><td style="width:500px;">Description</td>
</tr>
<tr>
<td style="width:200px;"><strong>displaytext</strong></td><td style="width:500px;">any text associated with the success or failure</td>
</tr>
<tr>
<td style="width:200px;"><strong>success</strong></td><td style="width:500px;">true if operation is executed successfully</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="comments_thread">
<script type="text/javascript" src="https://comments.apache.org/show_comments.lua?site=test" async="true"></script>
<noscript>
<iframe width="930" height="500" src="https://comments.apache.org/iframe.lua?site=test&page=4.2.0/rootadmin"></iframe>
</noscript>
</div>
<div id="footer_mainmaster">
<p>Copyright © 2015 The Apache Software Foundation, Licensed under the
<a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0.</a>
<br>
Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo and the Apache feather logo are trademarks of The Apache Software Foundation.</p>
</div>
</div>
</div>
</div>
</body>
</html>
| {
"content_hash": "0a70eceb86237e867bf87c8e426f75f6",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 186,
"avg_line_length": 34.78823529411765,
"alnum_prop": 0.6885356780520798,
"repo_name": "terbolous/cloudstack-www",
"id": "4ef22081e27123f23534e027eb7598ab56e97af7",
"size": "2957",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "content/api/apidocs-4.6/root_admin/deleteVpnCustomerGateway.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "303768"
},
{
"name": "HTML",
"bytes": "123165841"
},
{
"name": "Python",
"bytes": "2684"
},
{
"name": "Ruby",
"bytes": "1967"
},
{
"name": "Shell",
"bytes": "861"
}
],
"symlink_target": ""
} |
This cookbook is a representation of a foundation cookbook set up with Conjur.
The Chef flow looks like this:
1. Foundation cookbook is used to build an initial image
2. Conjur identity is side-loaded at node initial
3. Application cookbook runs on top, can access secrets via Conjur
This foundation is distributed as a Docker image.
Note: `files/conjur-demo.pem` is meant to only validate inside instances
launched via demo-factory.
| {
"content_hash": "f2a24e13da7d96617d533f08bec5af07",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 78,
"avg_line_length": 36.5,
"alnum_prop": 0.7990867579908676,
"repo_name": "conjurdemos/chefconf15-base",
"id": "e6fa04d1846a247a6987c11037844253223139df",
"size": "452",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "121"
},
{
"name": "Ruby",
"bytes": "3268"
},
{
"name": "Shell",
"bytes": "825"
}
],
"symlink_target": ""
} |
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.IO
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests
<UseExportProvider>
Public NotInheritable Class OutputFormatTests
<Fact>
Public Async Function TestLineModeOutput() As Task
Dim stringWriter = New StringWriter()
Dim jsonWriter = New LineModeLsifJsonWriter(stringWriter)
Await TestLsifOutput.GenerateForWorkspaceAsync(
TestWorkspace.CreateWorkspace(
<Workspace>
<Project Language="C#" Name="TestProject" FilePath="Z:\TestProject.csproj">
<Document Name="A.cs" FilePath="Z:\A.cs"/>
</Project>
</Workspace>), jsonWriter)
AssertEx.EqualOrDiff(
"{""hoverProvider"":true,""declarationProvider"":false,""definitionProvider"":true,""referencesProvider"":true,""typeDefinitionProvider"":false,""documentSymbolProvider"":false,""foldingRangeProvider"":true,""diagnosticProvider"":false,""id"":1,""type"":""vertex"",""label"":""capabilities""}
{""kind"":""csharp"",""resource"":""file:///Z:/TestProject.csproj"",""name"":""TestProject"",""id"":2,""type"":""vertex"",""label"":""project""}
{""kind"":""begin"",""scope"":""project"",""data"":2,""id"":3,""type"":""vertex"",""label"":""$event""}
{""uri"":""file:///Z:/A.cs"",""languageId"":""csharp"",""id"":4,""type"":""vertex"",""label"":""document""}
{""kind"":""begin"",""scope"":""document"",""data"":4,""id"":5,""type"":""vertex"",""label"":""$event""}
{""outV"":4,""inVs"":[],""id"":6,""type"":""edge"",""label"":""contains""}
{""result"":[],""id"":7,""type"":""vertex"",""label"":""foldingRangeResult""}
{""outV"":4,""inVs"":[7],""id"":8,""type"":""edge"",""label"":""textDocument/foldingRange""}
{""kind"":""end"",""scope"":""document"",""data"":4,""id"":9,""type"":""vertex"",""label"":""$event""}
{""outV"":2,""inVs"":[4],""id"":10,""type"":""edge"",""label"":""contains""}
{""kind"":""end"",""scope"":""project"",""data"":2,""id"":11,""type"":""vertex"",""label"":""$event""}
", stringWriter.ToString())
End Function
<Fact>
Public Async Function TestJsonModeOutput() As Task
Dim stringWriter = New StringWriter()
Using jsonWriter = New JsonModeLsifJsonWriter(stringWriter)
Await TestLsifOutput.GenerateForWorkspaceAsync(
TestWorkspace.CreateWorkspace(
<Workspace>
<Project Language="C#" Name="TestProject" FilePath="Z:\TestProject.csproj">
<Document Name="A.cs" FilePath="Z:\A.cs"/>
</Project>
</Workspace>), jsonWriter)
End Using
AssertEx.EqualOrDiff(
"[
{
""hoverProvider"": true,
""declarationProvider"": false,
""definitionProvider"": true,
""referencesProvider"": true,
""typeDefinitionProvider"": false,
""documentSymbolProvider"": false,
""foldingRangeProvider"": true,
""diagnosticProvider"": false,
""id"": 1,
""type"": ""vertex"",
""label"": ""capabilities""
},
{
""kind"": ""csharp"",
""resource"": ""file:///Z:/TestProject.csproj"",
""name"": ""TestProject"",
""id"": 2,
""type"": ""vertex"",
""label"": ""project""
},
{
""kind"": ""begin"",
""scope"": ""project"",
""data"": 2,
""id"": 3,
""type"": ""vertex"",
""label"": ""$event""
},
{
""uri"": ""file:///Z:/A.cs"",
""languageId"": ""csharp"",
""id"": 4,
""type"": ""vertex"",
""label"": ""document""
},
{
""kind"": ""begin"",
""scope"": ""document"",
""data"": 4,
""id"": 5,
""type"": ""vertex"",
""label"": ""$event""
},
{
""outV"": 4,
""inVs"": [],
""id"": 6,
""type"": ""edge"",
""label"": ""contains""
},
{
""result"": [],
""id"": 7,
""type"": ""vertex"",
""label"": ""foldingRangeResult""
},
{
""outV"": 4,
""inVs"": [
7
],
""id"": 8,
""type"": ""edge"",
""label"": ""textDocument/foldingRange""
},
{
""kind"": ""end"",
""scope"": ""document"",
""data"": 4,
""id"": 9,
""type"": ""vertex"",
""label"": ""$event""
},
{
""outV"": 2,
""inVs"": [
4
],
""id"": 10,
""type"": ""edge"",
""label"": ""contains""
},
{
""kind"": ""end"",
""scope"": ""project"",
""data"": 2,
""id"": 11,
""type"": ""vertex"",
""label"": ""$event""
}
]", stringWriter.ToString())
End Function
End Class
End Namespace
| {
"content_hash": "e649c1d2ccd9df00a8f50d10b2c2ced0",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 292,
"avg_line_length": 33.13815789473684,
"alnum_prop": 0.5292833035537026,
"repo_name": "bartdesmet/roslyn",
"id": "b168b9758581890e24711322fdc3442568b9271d",
"size": "5039",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Features/Lsif/GeneratorTest/OutputFormatTests.vb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "257760"
},
{
"name": "Batchfile",
"bytes": "8186"
},
{
"name": "C#",
"bytes": "174646794"
},
{
"name": "C++",
"bytes": "5602"
},
{
"name": "CMake",
"bytes": "12939"
},
{
"name": "Dockerfile",
"bytes": "441"
},
{
"name": "F#",
"bytes": "549"
},
{
"name": "PowerShell",
"bytes": "284945"
},
{
"name": "Shell",
"bytes": "133800"
},
{
"name": "Vim Snippet",
"bytes": "6353"
},
{
"name": "Visual Basic .NET",
"bytes": "73846000"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.