text stringlengths 2 1.04M | meta dict |
|---|---|
'''Test percolator.py.'''
from test.support import requires
requires('gui')
import unittest
from tkinter import Text, Tk, END
from idlelib.percolator import Percolator, Delegator
class MyFilter(Delegator):
def __init__(self):
Delegator.__init__(self, None)
def insert(self, *args):
self.insert_called_with = args
self.delegate.insert(*args)
def delete(self, *args):
self.delete_called_with = args
self.delegate.delete(*args)
def uppercase_insert(self, index, chars, tags=None):
chars = chars.upper()
self.delegate.insert(index, chars)
def lowercase_insert(self, index, chars, tags=None):
chars = chars.lower()
self.delegate.insert(index, chars)
def dont_insert(self, index, chars, tags=None):
pass
class PercolatorTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.root = Tk()
cls.text = Text(cls.root)
@classmethod
def tearDownClass(cls):
del cls.text
cls.root.destroy()
del cls.root
def setUp(self):
self.percolator = Percolator(self.text)
self.filter_one = MyFilter()
self.filter_two = MyFilter()
self.percolator.insertfilter(self.filter_one)
self.percolator.insertfilter(self.filter_two)
def tearDown(self):
self.percolator.close()
self.text.delete('1.0', END)
def test_insertfilter(self):
self.assertIsNotNone(self.filter_one.delegate)
self.assertEqual(self.percolator.top, self.filter_two)
self.assertEqual(self.filter_two.delegate, self.filter_one)
self.assertEqual(self.filter_one.delegate, self.percolator.bottom)
def test_removefilter(self):
filter_three = MyFilter()
self.percolator.removefilter(self.filter_two)
self.assertEqual(self.percolator.top, self.filter_one)
self.assertIsNone(self.filter_two.delegate)
filter_three = MyFilter()
self.percolator.insertfilter(self.filter_two)
self.percolator.insertfilter(filter_three)
self.percolator.removefilter(self.filter_one)
self.assertEqual(self.percolator.top, filter_three)
self.assertEqual(filter_three.delegate, self.filter_two)
self.assertEqual(self.filter_two.delegate, self.percolator.bottom)
self.assertIsNone(self.filter_one.delegate)
def test_insert(self):
self.text.insert('insert', 'foo')
self.assertEqual(self.text.get('1.0', END), 'foo\n')
self.assertTupleEqual(self.filter_one.insert_called_with,
('insert', 'foo', None))
def test_modify_insert(self):
self.filter_one.insert = self.filter_one.uppercase_insert
self.text.insert('insert', 'bAr')
self.assertEqual(self.text.get('1.0', END), 'BAR\n')
def test_modify_chain_insert(self):
filter_three = MyFilter()
self.percolator.insertfilter(filter_three)
self.filter_two.insert = self.filter_two.uppercase_insert
self.filter_one.insert = self.filter_one.lowercase_insert
self.text.insert('insert', 'BaR')
self.assertEqual(self.text.get('1.0', END), 'bar\n')
def test_dont_insert(self):
self.filter_one.insert = self.filter_one.dont_insert
self.text.insert('insert', 'foo bar')
self.assertEqual(self.text.get('1.0', END), '\n')
self.filter_one.insert = self.filter_one.dont_insert
self.text.insert('insert', 'foo bar')
self.assertEqual(self.text.get('1.0', END), '\n')
def test_without_filter(self):
self.text.insert('insert', 'hello')
self.assertEqual(self.text.get('1.0', 'end'), 'hello\n')
def test_delete(self):
self.text.insert('insert', 'foo')
self.text.delete('1.0', '1.2')
self.assertEqual(self.text.get('1.0', END), 'o\n')
self.assertTupleEqual(self.filter_one.delete_called_with,
('1.0', '1.2'))
if __name__ == '__main__':
unittest.main(verbosity=2)
| {
"content_hash": "18644620a382a9c90a96e09ebf83e0dc",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 74,
"avg_line_length": 34.38135593220339,
"alnum_prop": 0.634458959822529,
"repo_name": "Microsoft/PTVS",
"id": "573b9a1e8e69e3905122b905c4f30ee3958b17d7",
"size": "4057",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "Python/Product/Miniconda/Miniconda3-x64/Lib/idlelib/idle_test/test_percolator.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "109"
},
{
"name": "Batchfile",
"bytes": "10898"
},
{
"name": "C",
"bytes": "23236"
},
{
"name": "C#",
"bytes": "12235396"
},
{
"name": "C++",
"bytes": "212001"
},
{
"name": "CSS",
"bytes": "7025"
},
{
"name": "HTML",
"bytes": "34251"
},
{
"name": "JavaScript",
"bytes": "87257"
},
{
"name": "PowerShell",
"bytes": "44322"
},
{
"name": "Python",
"bytes": "847130"
},
{
"name": "Rich Text Format",
"bytes": "260880"
},
{
"name": "Smarty",
"bytes": "8156"
},
{
"name": "Tcl",
"bytes": "24968"
}
],
"symlink_target": ""
} |
package org.xdi.oxauth.clientinfo.ws.rs;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;
import org.xdi.model.GluuAttribute;
import org.xdi.oxauth.model.clientinfo.ClientInfoErrorResponseType;
import org.xdi.oxauth.model.clientinfo.ClientInfoParamsValidator;
import org.xdi.oxauth.model.common.AuthorizationGrant;
import org.xdi.oxauth.model.common.AuthorizationGrantList;
import org.xdi.oxauth.model.common.Scope;
import org.xdi.oxauth.model.error.ErrorResponseFactory;
import org.xdi.oxauth.model.registration.Client;
import org.xdi.oxauth.service.AttributeService;
import org.xdi.oxauth.service.ScopeService;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import java.util.Set;
/**
* Provides interface for Client Info REST web services
*
* @author Javier Rojas Blum
* @version 0.9 March 27, 2015
*/
@Name("requestClientInfoRestWebService")
public class ClientInfoRestWebServiceImpl implements ClientInfoRestWebService {
@Logger
private Log log;
@In
private ErrorResponseFactory errorResponseFactory;
@In
private AuthorizationGrantList authorizationGrantList;
@In
private ScopeService scopeService;
@In
private AttributeService attributeService;
@Override
public Response requestUserInfoGet(String accessToken, String authorization, SecurityContext securityContext) {
return requestClientInfo(accessToken, authorization, securityContext);
}
@Override
public Response requestUserInfoPost(String accessToken, String authorization, SecurityContext securityContext) {
return requestClientInfo(accessToken, authorization, securityContext);
}
public Response requestClientInfo(String accessToken, String authorization, SecurityContext securityContext) {
if (authorization != null && !authorization.isEmpty() && authorization.startsWith("Bearer ")) {
accessToken = authorization.substring(7);
}
log.debug("Attempting to request Client Info, Access token = {0}, Is Secure = {1}",
accessToken, securityContext.isSecure());
Response.ResponseBuilder builder = Response.ok();
if (!ClientInfoParamsValidator.validateParams(accessToken)) {
builder = Response.status(400);
builder.entity(errorResponseFactory.getErrorAsJson(ClientInfoErrorResponseType.INVALID_REQUEST));
} else {
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
if (authorizationGrant == null) {
builder = Response.status(400);
builder.entity(errorResponseFactory.getErrorAsJson(ClientInfoErrorResponseType.INVALID_TOKEN));
} else {
CacheControl cacheControl = new CacheControl();
cacheControl.setPrivate(true);
cacheControl.setNoTransform(false);
cacheControl.setNoStore(true);
builder.cacheControl(cacheControl);
builder.header("Pragma", "no-cache");
builder.entity(getJSonResponse(authorizationGrant.getClient(),
authorizationGrant.getScopes()));
}
}
return builder.build();
}
/**
* Builds a JSon String with the response parameters.
*/
public String getJSonResponse(Client client, Set<String> scopes) {
// FileConfiguration ldapConfiguration = ConfigurationFactory.getLdapConfiguration();
JSONObject jsonObj = new JSONObject();
try {
for (String scopeName : scopes) {
Scope scope = scopeService.getScopeByDisplayName(scopeName);
if (scope.getOxAuthClaims() != null) {
for (String claimDn : scope.getOxAuthClaims()) {
GluuAttribute attribute = attributeService.getAttributeByDn(claimDn);
String attributeName = attribute.getName();
Object attributeValue = client.getAttribute(attribute.getName());
jsonObj.put(attributeName, attributeValue);
}
}
}
} catch (JSONException e) {
log.error(e.getMessage(), e);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return jsonObj.toString();
}
} | {
"content_hash": "4eeb092723c930592e7afca2b3611f7e",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 123,
"avg_line_length": 38.583333333333336,
"alnum_prop": 0.6827213822894168,
"repo_name": "nixu-corp/oxAuth",
"id": "cb490833e3ddbc0d210b4b08afbf3e706af665ca",
"size": "4774",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Server/src/main/java/org/xdi/oxauth/clientinfo/ws/rs/ClientInfoRestWebServiceImpl.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "49"
},
{
"name": "C",
"bytes": "102966"
},
{
"name": "CSS",
"bytes": "43980"
},
{
"name": "HTML",
"bytes": "156734"
},
{
"name": "Java",
"bytes": "4559838"
},
{
"name": "JavaScript",
"bytes": "9618"
},
{
"name": "PHP",
"bytes": "19271"
},
{
"name": "Python",
"bytes": "267184"
},
{
"name": "XSLT",
"bytes": "35486"
}
],
"symlink_target": ""
} |
<?php
/**
* DO NOT EDIT THIS FILE!
*
* This file was automatically generated from external sources.
*
* Any manual change here will be lost the next time the SDK
* is updated. You've been warned!
*/
namespace DTS\eBaySDK\FindingAPI\Types;
/**
*
*/
class DecimalType extends \DTS\eBaySDK\Types\DecimalType
{
/**
* @var array Properties belonging to objects of this class.
*/
private static $propertyTypes = [
];
/**
* @param array $values Optional properties and values to assign to the object.
*/
public function __construct(array $values = [])
{
list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);
parent::__construct($parentValues);
if (!array_key_exists(__CLASS__, self::$properties)) {
self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
}
if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
self::$xmlNamespaces[__CLASS__] = 'xmlns="http://davidtsadler.com"';
}
$this->setValues(__CLASS__, $childValues);
}
}
| {
"content_hash": "30bb5ad40cec206b985c3083be332a53",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 116,
"avg_line_length": 26.86046511627907,
"alnum_prop": 0.6164502164502165,
"repo_name": "davidtsadler/ebay-api-sdk-php",
"id": "8847828a95f94c699278f54a770408fa30c02dc8",
"size": "1155",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/expected/FindingAPI/DecimalType.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "13087"
},
{
"name": "Makefile",
"bytes": "15524"
},
{
"name": "PHP",
"bytes": "127573"
},
{
"name": "XSLT",
"bytes": "37005"
}
],
"symlink_target": ""
} |
require 'fci/version.rb'
require 'freshdesk_api'
require 'crowdin-api'
require 'nokogiri'
require 'zip'
# require 'byebug'
# Add requires for other files you add to your project here, so
# you just need to require this one file in your bin file
require 'fci/helpers.rb'
require 'fci/init.rb'
require 'fci/import.rb'
require 'fci/download.rb'
require 'fci/export.rb'
| {
"content_hash": "637870a4a3d6eb1df13cb89c18e81093",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 63,
"avg_line_length": 23.0625,
"alnum_prop": 0.7506775067750677,
"repo_name": "mamantoha/fci",
"id": "b5f07dd803deeb6a230645b3e4569798f23f72eb",
"size": "369",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/fci.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Gherkin",
"bytes": "260"
},
{
"name": "Ruby",
"bytes": "30715"
}
],
"symlink_target": ""
} |
if (Test-Path dist) {
Remove-Item dist -Recurse -Force
}
if (Test-Path build) {
Remove-Item build -Recurse -Force
}
if (Test-Path .tmp) {
Remove-Item .tmp -Recurse -Force
}
& gulp js:build
Copy-Item -Path src/tsconfig-build.json -Destination .tmp/tsconfig-build.json
Copy-Item -Path src/tsconfig-es5.json -Destination .tmp/tsconfig-es5.json
# Variables
$NGC="node_modules/.bin/ngc.cmd"
$ROLLUP="node_modules/.bin/rollup.cmd"
# Run Angular Compiler
& "$NGC" -p .tmp/tsconfig-build.json
# Rollup angular-datepickr.js
& "$ROLLUP" build/angular-datepickr.js -o dist/angular-datepickr.js
# Run Angular Compiler to ES5
& "$NGC" -p .tmp/tsconfig-es5.json
# Rollup angular-datepickr.js
& "$ROLLUP" build/angular-datepickr.js -o dist/angular-datepickr.es5.js
# Copy non-js files from build
Copy-Item -Exclude *.js -Recurse -Path build/* -Destination dist
# Copy library package.json
Copy-Item -Path src/package.json -Destination dist/package.json
Copy-Item -Path README.md -Destination dist/README.md | {
"content_hash": "2d450319db32d1e701fa4571e7aa2b09",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 77,
"avg_line_length": 25.76923076923077,
"alnum_prop": 0.7402985074626866,
"repo_name": "JiriBalcar/angular2-datepicker",
"id": "b0477e42795a4c7372b1780434eb2842be236b2f",
"size": "1056",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build.ps1",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3914"
},
{
"name": "HTML",
"bytes": "2246"
},
{
"name": "TypeScript",
"bytes": "16030"
}
],
"symlink_target": ""
} |
//
// SupportingWebApiClient.h
// BRFCore
//
// Created by Matt on 15/09/15.
// Copyright (c) 2015 Blue Rocket, Inc. Distributable under the terms of the Apache License, Version 2.0.
//
#import "WebApiClient.h"
NS_ASSUME_NONNULL_BEGIN
/**
API for a WebApiClient with extended attributes, geared for implementation support.
*/
@protocol SupportingWebApiClient <WebApiClient>
/**
Get a registered route by its name.
The WebApiClient API does not specify how routes are registered.
@param name The name of the route to get.
@param error An error if the route is not registered. Pass @c nil if you don't need the error.
The localized message @c web.api.missingRoute will be returned.
@return The route associated with @c name, or @c nil if not registered.
*/
- (nullable id<WebApiRoute>)routeForName:(NSString *)name error:(NSError * __nullable __autoreleasing *)error;
/**
Get a @c URL instance for a route.
@param route The route.
@param pathVariables An optional path variables object. All path variables will be resolved against this object.
@param parameters An optional parameters object to encode as the query component of the request URL.
@param error An error if the route has no associated path. Pass @c nil if you don't need the error.
The localized message @c web.api.missingRoutePath will be returned.
@return The URL instance.
*/
- (NSURL *)URLForRoute:(id<WebApiRoute>)route
pathVariables:(nullable id)pathVariables
parameters:(nullable id)parameters
error:(NSError * __autoreleasing *)error;
@end
NS_ASSUME_NONNULL_END
| {
"content_hash": "d3833fb213ef76941ab414f8018bcd4f",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 113,
"avg_line_length": 33.5531914893617,
"alnum_prop": 0.7469879518072289,
"repo_name": "Blue-Rocket/WebApiClient",
"id": "693f5142e4ae9d44b259dbf942f2e61d05946858",
"size": "1577",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WebApiClient/Code/WebApiClient/SupportingWebApiClient.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "4137"
},
{
"name": "Objective-C",
"bytes": "249783"
},
{
"name": "Ruby",
"bytes": "3698"
}
],
"symlink_target": ""
} |
/**
* The HasAndBelongsToMany Field class
*
* @constructor
*
* @author Jelle De Loecker <jelle@develry.be>
* @since 0.2.0
* @version 1.1.0
*/
var HABTM = Function.inherits('Alchemy.Field', function HasAndBelongsToMany(schema, name, options) {
HasAndBelongsToMany.super.call(this, schema, name, options);
// @todo: set index stuff
});
/**
* Cast the given value to this field's type
*
* @author Jelle De Loecker <jelle@develry.be>
* @since 0.2.0
* @version 1.1.0
*
* @param {Mixed} value
*
* @return {ObjectId}
*/
HABTM.setMethod(function cast(value, to_datasource) {
var result,
temp,
ds = this.datasource,
i;
value = Array.cast(value);
result = [];
for (i = 0; i < value.length; i++) {
if (to_datasource && ds) {
if (ds.supports('objectid')) {
temp = alchemy.castObjectId(value[i]);
} else {
temp = String(value[i]);
}
} else {
temp = alchemy.castObjectId(value[i]);
}
if (temp) {
result.push(temp);
}
}
return result;
}); | {
"content_hash": "73503cea4f1c515d31c9605e92b61e7b",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 100,
"avg_line_length": 18.69090909090909,
"alnum_prop": 0.6040856031128404,
"repo_name": "skerit/alchemy",
"id": "106a7cbff59a2123fc5e7d9e78361f73201c9ec3",
"size": "1028",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/app/helper_field/habtm_field.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1818"
},
{
"name": "HTML",
"bytes": "6234"
},
{
"name": "JavaScript",
"bytes": "858316"
}
],
"symlink_target": ""
} |
import ko = require('knockout')
import { Pin } from '../../model/pin'
import { Sequence } from '../../model/sequence'
import { Model, AppState, Observer, ErrorDescriptor } from '../../frame'
import { Constants } from '../../config'
class ViewSequence {
public isEditing: KnockoutObservable<boolean>
public sequence: Sequence
constructor(newSequence: Sequence) {
this.isEditing = ko.observable(false)
this.sequence = newSequence
}
}
class ViewModel {
router: any
isEditing: KnockoutObservable<boolean>
appState: AppState
pinModel: Model<Pin>
sequenceModel: Model<Sequence>
index: number
pin: KnockoutObservable<Pin>
viewSequences: KnockoutObservableArray<ViewSequence>
pinObserver: Observer<Pin>
sequenceObserver: Observer<Sequence>
constructor(params) {
let viewState = params.viewState
let appState = params.appState
this.isEditing = ko.observable(false)
this.router = appState.router
this.pinModel = appState.getModel(Constants.model.pin)
this.sequenceModel = appState.getModel(Constants.model.sequence)
this.index = viewState.index
this.pin = ko.observable(undefined)
this.viewSequences = ko.observableArray([])
let globThis = this
this.sequenceObserver = {
objectAdded: (seq: Sequence) => { globThis.addSequence(seq) },
objectModified: (seq: Sequence) => { globThis.modifySequence(seq) },
objectRemoved: (seq: Sequence) => { globThis.removeSequence(seq) }
}
this.sequenceModel.addObserver(this.sequenceObserver)
this.pinObserver = {
objectAdded: (pin: Pin) => {},
objectModified: (pin: Pin) => { globThis.modifyPin(pin) },
objectRemoved: (pin: Pin) => { globThis.pinDeleted(pin) }
}
this.pinModel.addObserver(this.pinObserver)
this.pinModel.findOne(viewState.route.vals.pinId).then((pin: Pin) => {
this.pin(pin)
})
this.sequenceModel.findAll({
relation: [{
type: Constants.model.pin,
id: viewState.route.vals.pinId
}],
attributes: []
}).then((sequences: Sequence[]) => {
this.viewSequences(sequences.map((seq: Sequence, i: number) => {
return new ViewSequence(seq)
}))
})
}
public modifyPin = (pin: Pin) => {
if (this.pin() && this.pin().id == pin.id) {
this.pin().update(pin)
} else {
console.log("wrong pin")
}
}
public addSequence = (sequence: Sequence) => {
this.viewSequences.push(new ViewSequence(sequence))
}
public modifySequence = (sequence: Sequence) => {
var oldVSeq = ko.utils.arrayFirst(this.viewSequences(), (testVSeq: ViewSequence) => {
return testVSeq.sequence.id == sequence.id
})
if (oldVSeq == undefined) {
throw "Updated sequence not found!"
} else {
oldVSeq.sequence.update(sequence)
}
}
public removeSequence = (sequence: Sequence) => {
let viewSeqDel = ko.utils.arrayFirst(this.viewSequences(), (viewSeq: ViewSequence) => {
return viewSeq.sequence.id == sequence.id
})
this.viewSequences.remove(viewSeqDel)
}
public pinDeleted = (pin: Pin) => {
if (pin.id == this.pin().id) {
this.pushClose(pin)
}
}
public pushEditPin = (params) => {
if (this.isEditing()) {
let globThis = this
this.pinModel.update(this.pin()).then( () => {
globThis.isEditing(!this.isEditing)
},(error) => {
if (error.code == 401) {
globThis.router.transitionTo('login', {
backRoute: globThis.router.state.path
})
} else {
console.log("Error!", error)
}
})
} else {
this.isEditing(true)
}
}
public pushEditSequence = (viewSequence: ViewSequence) => {
if (viewSequence.isEditing()) {
let globThis = this
this.sequenceModel.update(viewSequence.sequence).then( () => {
viewSequence.isEditing(!viewSequence.isEditing)
},(error) => {
if (error.code == 401) {
globThis.router.transitionTo('login', {
backRoute: globThis.router.state.path
})
} else {
console.log("Error!", error)
}
})
} else {
viewSequence.isEditing(true)
}
}
public pushClose = (params) => {
// get the route bevor the current route
let last_route = this.router.state.routes[this.index]
this.router.transitionTo(last_route.name)
}
public pushRemove = (viewSequence: ViewSequence) => {
this.sequenceModel.remove(viewSequence.sequence).then((removedSeq: Sequence) => {
this.viewSequences.remove(new ViewSequence(removedSeq))
})
}
public pushAdd = (params) => {
this.router.transitionTo('add-sequence', { pinId: this.pin().id })
}
public dispose = () => {
this.pinModel.removeObserver(this.pinObserver)
this.sequenceModel.removeObserver(this.sequenceObserver)
}
}
export = ViewModel | {
"content_hash": "7d4793720a3873183e8772959778c106",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 92,
"avg_line_length": 26.61849710982659,
"alnum_prop": 0.6731813246471227,
"repo_name": "weichweich/Pi-Timeswitch",
"id": "1a799d3dae303122578f272abfd7037d31c382fa",
"size": "4659",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Client/src/components/sequences-fragment/sequences-fragment.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "808"
},
{
"name": "CSS",
"bytes": "3696"
},
{
"name": "HTML",
"bytes": "10861"
},
{
"name": "JavaScript",
"bytes": "2877"
},
{
"name": "Makefile",
"bytes": "2356"
},
{
"name": "Python",
"bytes": "69018"
},
{
"name": "Shell",
"bytes": "613"
},
{
"name": "TypeScript",
"bytes": "42694"
}
],
"symlink_target": ""
} |
require 'pathname'
Puppet::Type.newtype(:dsc_xexchpopsettings) do
require Pathname.new(__FILE__).dirname + '../../' + 'puppet/type/base_dsc'
require Pathname.new(__FILE__).dirname + '../../puppet_x/puppetlabs/dsc_type_helpers'
@doc = %q{
The DSC xExchPopSettings resource type.
Automatically generated from
'xExchange/DSCResources/MSFT_xExchPopSettings/MSFT_xExchPopSettings.schema.mof'
To learn more about PowerShell Desired State Configuration, please
visit https://technet.microsoft.com/en-us/library/dn249912.aspx.
For more information about built-in DSC Resources, please visit
https://technet.microsoft.com/en-us/library/dn249921.aspx.
For more information about xDsc Resources, please visit
https://github.com/PowerShell/DscResources.
}
validate do
fail('dsc_server is a required attribute') if self[:dsc_server].nil?
end
def dscmeta_resource_friendly_name; 'xExchPopSettings' end
def dscmeta_resource_name; 'MSFT_xExchPopSettings' end
def dscmeta_module_name; 'xExchange' end
def dscmeta_module_version; '1.16.0.0' end
newparam(:name, :namevar => true ) do
end
ensurable do
newvalue(:exists?) { provider.exists? }
newvalue(:present) { provider.create }
defaultto { :present }
end
# Name: PsDscRunAsCredential
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_psdscrunascredential) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "PsDscRunAsCredential"
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("Credential", value)
end
end
# Name: Server
# Type: string
# IsMandatory: True
# Values: None
newparam(:dsc_server) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "Server"
isrequired
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: Credential
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_credential) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "Credential"
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("Credential", value)
end
end
# Name: AllowServiceRestart
# Type: boolean
# IsMandatory: False
# Values: None
newparam(:dsc_allowservicerestart) do
def mof_type; 'boolean' end
def mof_is_embedded?; false end
desc "AllowServiceRestart"
validate do |value|
end
newvalues(true, false)
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_boolean(value.to_s)
end
end
# Name: DomainController
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_domaincontroller) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "DomainController"
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: LoginType
# Type: string
# IsMandatory: False
# Values: ["PlainTextLogin", "PlainTextAuthentication", "SecureLogin"]
newparam(:dsc_logintype) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "LoginType - Valid values are PlainTextLogin, PlainTextAuthentication, SecureLogin."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
unless ['PlainTextLogin', 'plaintextlogin', 'PlainTextAuthentication', 'plaintextauthentication', 'SecureLogin', 'securelogin'].include?(value)
fail("Invalid value '#{value}'. Valid values are PlainTextLogin, PlainTextAuthentication, SecureLogin")
end
end
end
# Name: ExternalConnectionSettings
# Type: string[]
# IsMandatory: False
# Values: None
newparam(:dsc_externalconnectionsettings, :array_matching => :all) do
def mof_type; 'string[]' end
def mof_is_embedded?; false end
desc "ExternalConnectionSettings"
validate do |value|
unless value.kind_of?(Array) || value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string or an array of strings")
end
end
munge do |value|
Array(value)
end
end
# Name: X509CertificateName
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_x509certificatename) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "X509CertificateName"
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
def builddepends
pending_relations = super()
PuppetX::Dsc::TypeHelpers.ensure_reboot_relationship(self, pending_relations)
end
end
Puppet::Type.type(:dsc_xexchpopsettings).provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do
confine :true => (Gem::Version.new(Facter.value(:powershell_version)) >= Gem::Version.new('5.0.10586.117'))
defaultfor :operatingsystem => :windows
mk_resource_methods
end
| {
"content_hash": "b888c8bbfde031a9cbdd3e89fa7e68ae",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 149,
"avg_line_length": 30.25136612021858,
"alnum_prop": 0.65625,
"repo_name": "Iristyle/puppetlabs-dsc",
"id": "18cf2f77e6f0f23cb9e57b29977dc6a822f085bb",
"size": "5536",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/puppet/type/dsc_xexchpopsettings.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "11740"
},
{
"name": "HTML",
"bytes": "18505"
},
{
"name": "NSIS",
"bytes": "1454"
},
{
"name": "PowerShell",
"bytes": "5676269"
},
{
"name": "Puppet",
"bytes": "522"
},
{
"name": "Ruby",
"bytes": "3143467"
},
{
"name": "Shell",
"bytes": "3616"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
import re
class Migration(migrations.Migration):
dependencies = [
('livelayermanager', '0009_auto_20170602_1459'),
]
operations = [
migrations.AlterField(
model_name='sqlviewlayer',
name='name',
field=models.SlugField(help_text='The name of live layer', max_length=60, unique=True, validators=[django.core.validators.RegexValidator(re.compile('^[a-z_][a-z0-9_]+$'), 'Slug can only start with lowercase letters or underscore, and contain lowercase letters, numbers and underscore', 'invalid')]),
),
]
| {
"content_hash": "fd05949bc2edf45e27e0fe63a81c2868",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 311,
"avg_line_length": 34.6,
"alnum_prop": 0.6734104046242775,
"repo_name": "rockychen-dpaw/borgcollector",
"id": "9b790ac6cd18f8edcbf931cbddce23b37ec13c15",
"size": "764",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "livelayermanager/migrations/0010_auto_20170602_1609.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "9821"
},
{
"name": "JavaScript",
"bytes": "55"
},
{
"name": "Python",
"bytes": "720469"
},
{
"name": "TSQL",
"bytes": "9939"
}
],
"symlink_target": ""
} |
package mll.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.json.simple.JSONObject;
import mll.beans.Invite;
import mll.beans.UserDetails;
import mll.utility.SessionFactoryUtil;
public class RegistrationDAO
{
@SuppressWarnings("unchecked")
public JSONObject registerUser(UserDetails userdetails) throws Exception
{
Session session = null;
Transaction tx = null;
JSONObject responseObject = new JSONObject();
try
{
if(null != userdetails && null != userdetails.getToken() && null != userdetails.getToken().getToken() && null != userdetails.getToken().getInviteType() && null != userdetails.getUsers())
{
// Initialize the session and transaction
session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
tx = session.beginTransaction();
Invite invite = new Invite();
invite.setToken(userdetails.getToken());
InviteDAO inviteDao = new InviteDAO();
invite = inviteDao.validateInvite(invite);
if(invite.getIsValid())
{ invite.getToken().setIsUsed(true);
session.update(invite.getToken());
Integer userId = (Integer)session.save(userdetails.getUsers());
if(null != userId)
{
responseObject.put("isRegistered", true);
responseObject.put("userId", userId);
responseObject.put("type", userdetails.getType());
if(userdetails.getType().equalsIgnoreCase("user"))
{
userdetails.getAruser().setId(userId);
session.save(userdetails.getAruser());
responseObject.put("browse", true);
responseObject.put("upload", false);
}
else if(userdetails.getType().equalsIgnoreCase("musician"))
{
userdetails.getMusician().setId(userId);
userdetails.getMusician().setAdded_by(invite.getToken().getUserId());
session.save(userdetails.getMusician());
responseObject.put("browse", false);
responseObject.put("upload", true);
responseObject.put("type", userdetails.getType());
}
}
else
{
responseObject.put("isRegistered", false);
responseObject.put("errorMessage", "Not able to save user details.");
}
}
else
{
responseObject.put("isRegistered", false);
responseObject.put("errorMessage", "Token is already used.");
}
tx.commit();
}
}
catch(Exception e)
{
if( null != tx)
{
tx.rollback();
}
e.printStackTrace();
responseObject.put("isRegistered", false);
responseObject.put("errorMessage", "Error while saving data.");
}
return responseObject;
}
public Boolean checkAlreadyExists(String username) {
// TODO Auto-generated method stub
Transaction tx = null;
Session session =null;
Boolean result = false;
if (username != null){
try{
session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
tx = session.beginTransaction();
String hql = "FROM User WHERE userName = :username";
Query query = session.createQuery(hql);
query.setParameter("username", username);
List results = query.list();
if (results.size()>0){
result = true;
}else
result = false;
tx.commit();
return result;
}
catch(Exception e){
if( null != tx)
{
tx.rollback();
}
e.printStackTrace();
return result;
}
} else
return result;
}
}
| {
"content_hash": "34d7fa0b1fa73c3f78b0dc14e10fbb61",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 189,
"avg_line_length": 26.119402985074625,
"alnum_prop": 0.6425714285714286,
"repo_name": "akhil0/MLL",
"id": "77cee7c1bef2f76852e42a0c1539d61ac5c87660",
"size": "3500",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/mll/dao/RegistrationDAO.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13461"
},
{
"name": "HTML",
"bytes": "181664"
},
{
"name": "Java",
"bytes": "267714"
},
{
"name": "JavaScript",
"bytes": "274735"
}
],
"symlink_target": ""
} |
package com.orientechnologies.orient.test.domain.business;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Id;
import com.orientechnologies.orient.core.annotation.OAfterDeserialization;
import com.orientechnologies.orient.core.annotation.OBeforeSerialization;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
public class Account {
@Id
private Object rid;
private int id;
private String name;
private String surname;
private Date birthDate;
private float salary;
private List<Address> addresses = new ArrayList<Address>();
private byte[] thumbnail;
private transient byte[] photo;
private transient boolean initialized = false;
public Account() {
}
public Account(int iId, String iName, String iSurname) {
this.id = iId;
this.name = iName;
this.surname = iSurname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public List<Address> getAddresses() {
return addresses;
}
public void setAddresses(List<Address> addresses) {
this.addresses = addresses;
}
public int getId() {
return id;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public boolean isInitialized() {
return initialized;
}
public Object getRid() {
return rid;
}
public byte[] getThumbnail() {
return thumbnail;
}
public void setThumbnail(byte[] iThumbnail) {
this.thumbnail = iThumbnail;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
@OAfterDeserialization
public void fromStream(final ODocument iDocument) {
initialized = true;
if (iDocument.containsField("externalPhoto")) {
// READ THE PHOTO FROM AN EXTERNAL RECORD AS PURE BINARY
ORecordBytes extRecord = iDocument.field("externalPhoto");
photo = extRecord.toStream();
}
}
@OBeforeSerialization
public void toStream(final ODocument iDocument) {
if (thumbnail != null) {
// WRITE THE PHOTO IN AN EXTERNAL RECORD AS PURE BINARY
ORecordBytes externalPhoto = new ORecordBytes(thumbnail);
iDocument.field("externalPhoto", externalPhoto);
}
}
}
| {
"content_hash": "f85487e03b73743adeeeb1e9abebaa3e",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 74,
"avg_line_length": 21.862903225806452,
"alnum_prop": 0.6864625599409812,
"repo_name": "redox/OrientDB",
"id": "7a77ce89c1ddb67f9495e10db93456e5b89afbae",
"size": "3364",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/src/test/java/com/orientechnologies/orient/test/domain/business/Account.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "6591639"
},
{
"name": "JavaScript",
"bytes": "462216"
},
{
"name": "PHP",
"bytes": "9168"
},
{
"name": "Shell",
"bytes": "16948"
}
],
"symlink_target": ""
} |
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**
Autoloading and Reloading Constants (Classic Mode)
==================================================
This guide documents how constant autoloading and reloading works in `classic` mode.
After reading this guide, you will know:
* Key aspects of Ruby constants
* What the `autoload_paths` are and how eager loading works in production
* How constant autoloading works
* What `require_dependency` is
* How constant reloading works
* Solutions to common autoloading gotchas
--------------------------------------------------------------------------------
Introduction
------------
INFO. This guide documents autoloading in `classic` mode, which is the traditional one. If you'd like to read about `zeitwerk` mode instead, the new one in Rails 6, please check [Autoloading and Reloading Constants (Zeitwerk Mode)](autoloading_and_reloading_constants.html).
Ruby on Rails allows applications to be written as if their code was preloaded.
In a normal Ruby program classes need to load their dependencies:
```ruby
require "application_controller"
require "post"
class PostsController < ApplicationController
def index
@posts = Post.all
end
end
```
Our Rubyist instinct quickly sees some redundancy in there: If classes were
defined in files matching their name, couldn't their loading be automated
somehow? We could save scanning the file for dependencies, which is brittle.
Moreover, `Kernel#require` loads files once, but development is much more smooth
if code gets refreshed when it changes without restarting the server. It would
be nice to be able to use `Kernel#load` in development, and `Kernel#require` in
production.
Indeed, those features are provided by Ruby on Rails, where we just write
```ruby
class PostsController < ApplicationController
def index
@posts = Post.all
end
end
```
This guide documents how that works.
Constants Refresher
-------------------
While constants are trivial in most programming languages, they are a rich
topic in Ruby.
It is beyond the scope of this guide to document Ruby constants, but we are
nevertheless going to highlight a few key topics. Truly grasping the following
sections is instrumental to understanding constant autoloading and reloading.
### Nesting
Class and module definitions can be nested to create namespaces:
```ruby
module XML
class SAXParser
# (1)
end
end
```
The *nesting* at any given place is the collection of enclosing nested class and
module objects outwards. The nesting at any given place can be inspected with
`Module.nesting`. For example, in the previous example, the nesting at
(1) is
```ruby
[XML::SAXParser, XML]
```
It is important to understand that the nesting is composed of class and module
*objects*, it has nothing to do with the constants used to access them, and is
also unrelated to their names.
For instance, while this definition is similar to the previous one:
```ruby
class XML::SAXParser
# (2)
end
```
the nesting in (2) is different:
```ruby
[XML::SAXParser]
```
`XML` does not belong to it.
We can see in this example that the name of a class or module that belongs to a
certain nesting does not necessarily correlate with the namespaces at the spot.
Even more, they are totally independent, take for instance
```ruby
module X
module Y
end
end
module A
module B
end
end
module X::Y
module A::B
# (3)
end
end
```
The nesting in (3) consists of two module objects:
```ruby
[A::B, X::Y]
```
So, it not only doesn't end in `A`, which does not even belong to the nesting,
but it also contains `X::Y`, which is independent from `A::B`.
The nesting is an internal stack maintained by the interpreter, and it gets
modified according to these rules:
* The class object following a `class` keyword gets pushed when its body is
executed, and popped after it.
* The module object following a `module` keyword gets pushed when its body is
executed, and popped after it.
* A singleton class opened with `class << object` gets pushed, and popped later.
* When `instance_eval` is called using a string argument,
the singleton class of the receiver is pushed to the nesting of the eval'ed
code. When `class_eval` or `module_eval` is called using a string argument,
the receiver is pushed to the nesting of the eval'ed code.
* The nesting at the top-level of code interpreted by `Kernel#load` is empty
unless the `load` call receives a true value as second argument, in which case
a newly created anonymous module is pushed by Ruby.
It is interesting to observe that blocks do not modify the stack. In particular
the blocks that may be passed to `Class.new` and `Module.new` do not get the
class or module being defined pushed to their nesting. That's one of the
differences between defining classes and modules in one way or another.
### Class and Module Definitions are Constant Assignments
Let's suppose the following snippet creates a class (rather than reopening it):
```ruby
class C
end
```
Ruby creates a constant `C` in `Object` and stores in that constant a class
object. The name of the class instance is "C", a string, named after the
constant.
That is,
```ruby
class Project < ApplicationRecord
end
```
performs a constant assignment equivalent to
```ruby
Project = Class.new(ApplicationRecord)
```
including setting the name of the class as a side-effect:
```ruby
Project.name # => "Project"
```
Constant assignment has a special rule to make that happen: if the object
being assigned is an anonymous class or module, Ruby sets the object's name to
the name of the constant.
INFO. From then on, what happens to the constant and the instance does not
matter. For example, the constant could be deleted, the class object could be
assigned to a different constant, be stored in no constant anymore, etc. Once
the name is set, it doesn't change.
Similarly, module creation using the `module` keyword as in
```ruby
module Admin
end
```
performs a constant assignment equivalent to
```ruby
Admin = Module.new
```
including setting the name as a side-effect:
```ruby
Admin.name # => "Admin"
```
WARNING. The execution context of a block passed to `Class.new` or `Module.new`
is not entirely equivalent to the one of the body of the definitions using the
`class` and `module` keywords. But both idioms result in the same constant
assignment.
Thus, an informal expression like "the `String` class" technically means the
class object stored in the constant called "String". That constant, in turn,
belongs to the class object stored in the constant called "Object".
`String` is an ordinary constant, and everything related to them such as
resolution algorithms applies to it.
Likewise, in the controller
```ruby
class PostsController < ApplicationController
def index
@posts = Post.all
end
end
```
`Post` is not syntax for a class. Rather, `Post` is a regular Ruby constant. If
all is good, the constant is evaluated to an object that responds to `all`.
That is why we talk about *constant* autoloading, Rails has the ability to
load constants on the fly.
### Constants are Stored in Modules
Constants belong to modules in a very literal sense. Classes and modules have
a constant table; think of it as a hash table.
Let's analyze an example to really understand what that means. While common
abuses of language like "the `String` class" are convenient, the exposition is
going to be precise here for didactic purposes.
Let's consider the following module definition:
```ruby
module Colors
RED = '0xff0000'
end
```
First, when the `module` keyword is processed, the interpreter creates a new
entry in the constant table of the class object stored in the `Object` constant.
Said entry associates the name "Colors" to a newly created module object.
Furthermore, the interpreter sets the name of the new module object to be the
string "Colors".
Later, when the body of the module definition is interpreted, a new entry is
created in the constant table of the module object stored in the `Colors`
constant. That entry maps the name "RED" to the string "0xff0000".
In particular, `Colors::RED` is totally unrelated to any other `RED` constant
that may live in any other class or module object. If there were any, they
would have separate entries in their respective constant tables.
Pay special attention in the previous paragraphs to the distinction between
class and module objects, constant names, and value objects associated to them
in constant tables.
### Resolution Algorithms
#### Resolution Algorithm for Relative Constants
At any given place in the code, let's define *cref* to be the first element of
the nesting if it is not empty, or `Object` otherwise.
Without getting too much into the details, the resolution algorithm for relative
constant references goes like this:
1. If the nesting is not empty the constant is looked up in its elements and in
order. The ancestors of those elements are ignored.
2. If not found, then the algorithm walks up the ancestor chain of the cref.
3. If not found and the cref is a module, the constant is looked up in `Object`.
4. If not found, `const_missing` is invoked on the cref. The default
implementation of `const_missing` raises `NameError`, but it can be overridden.
Rails autoloading **does not emulate this algorithm**, but its starting point is
the name of the constant to be autoloaded, and the cref. See more in [Relative
References](#autoloading-algorithms-relative-references).
#### Resolution Algorithm for Qualified Constants
Qualified constants look like this:
```ruby
Billing::Invoice
```
`Billing::Invoice` is composed of two constants: `Billing` is relative and is
resolved using the algorithm of the previous section.
INFO. Leading colons would make the first segment absolute rather than
relative: `::Billing::Invoice`. That would force `Billing` to be looked up
only as a top-level constant.
`Invoice` on the other hand is qualified by `Billing` and we are going to see
its resolution next. Let's define *parent* to be that qualifying class or module
object, that is, `Billing` in the example above. The algorithm for qualified
constants goes like this:
1. The constant is looked up in the parent and its ancestors. In Ruby >= 2.5,
`Object` is skipped if present among the ancestors. `Kernel` and `BasicObject`
are still checked though.
2. If the lookup fails, `const_missing` is invoked in the parent. The default
implementation of `const_missing` raises `NameError`, but it can be overridden.
INFO. In Ruby < 2.5 `String::Hash` evaluates to `Hash` and the interpreter
issues a warning: "toplevel constant Hash referenced by String::Hash". Starting
with 2.5, `String::Hash` raises `NameError` because `Object` is skipped.
As you see, this algorithm is simpler than the one for relative constants. In
particular, the nesting plays no role here, and modules are not special-cased,
if neither they nor their ancestors have the constants, `Object` is **not**
checked.
Rails autoloading **does not emulate this algorithm**, but its starting point is
the name of the constant to be autoloaded, and the parent. See more in
[Qualified References](#autoloading-algorithms-qualified-references).
Vocabulary
----------
### Parent Namespaces
Given a string with a constant path we define its *parent namespace* to be the
string that results from removing its rightmost segment.
For example, the parent namespace of the string "A::B::C" is the string "A::B",
the parent namespace of "A::B" is "A", and the parent namespace of "A" is "".
The interpretation of a parent namespace when thinking about classes and modules
is tricky though. Let's consider a module M named "A::B":
* The parent namespace, "A", may not reflect nesting at a given spot.
* The constant `A` may no longer exist, some code could have removed it from
`Object`.
* If `A` exists, the class or module that was originally in `A` may not be there
anymore. For example, if after a constant removal there was another constant
assignment there would generally be a different object in there.
* In such case, it could even happen that the reassigned `A` held a new class or
module called also "A"!
* In the previous scenarios M would no longer be reachable through `A::B` but
the module object itself could still be alive somewhere and its name would
still be "A::B".
The idea of a parent namespace is at the core of the autoloading algorithms
and helps explain and understand their motivation intuitively, but as you see
that metaphor leaks easily. Given an edge case to reason about, take always into
account that by "parent namespace" the guide means exactly that specific string
derivation.
### Loading Mechanism
Rails autoloads files with `Kernel#load` when `config.cache_classes` is false,
the default in development mode, and with `Kernel#require` otherwise, the
default in production mode.
`Kernel#load` allows Rails to execute files more than once if [constant
reloading](#constant-reloading) is enabled.
This guide uses the word "load" freely to mean a given file is interpreted, but
the actual mechanism can be `Kernel#load` or `Kernel#require` depending on that
flag.
Autoloading Availability
------------------------
Rails is always able to autoload provided its environment is in place. For
example the `runner` command autoloads:
```bash
$ bin/rails runner 'p User.column_names'
["id", "email", "created_at", "updated_at"]
```
The console autoloads, the test suite autoloads, and of course the application
autoloads.
By default, Rails eager loads the application files when it boots in production
mode, so most of the autoloading going on in development does not happen. But
autoloading may still be triggered during eager loading.
For example, given
```ruby
class BeachHouse < House
end
```
if `House` is still unknown when `app/models/beach_house.rb` is being eager
loaded, Rails autoloads it.
autoload_paths and eager_load_paths
-----------------------------------
As you probably know, when `require` gets a relative file name:
```ruby
require "erb"
```
Ruby looks for the file in the directories listed in `$LOAD_PATH`. That is, Ruby
iterates over all its directories and for each one of them checks whether they
have a file called "erb.rb", or "erb.so", or "erb.o", or "erb.dll". If it finds
any of them, the interpreter loads it and ends the search. Otherwise, it tries
again in the next directory of the list. If the list gets exhausted, `LoadError`
is raised.
We are going to cover how constant autoloading works in more detail later, but
the idea is that when a constant like `Post` is hit and missing, if there's a
`post.rb` file for example in `app/models` Rails is going to find it, evaluate
it, and have `Post` defined as a side-effect.
All right, Rails has a collection of directories similar to `$LOAD_PATH` in which
to look up `post.rb`. That collection is called `autoload_paths` and by
default it contains:
* All subdirectories of `app` in the application and engines present at boot
time. For example, `app/controllers`. They do not need to be the default
ones, any custom directories like `app/workers` belong automatically to
`autoload_paths`.
* Any existing second level directories called `app/*/concerns` in the
application and engines.
* The directory `test/mailers/previews`.
`eager_load_paths` is initially the `app` paths above
How files are autoloaded depends on `eager_load` and `cache_classes` config settings which typically vary in development, production, and test modes:
* In **development**, you want quicker startup with incremental loading of application code. So `eager_load` should be set to `false`, and Rails will autoload files as needed (see [Autoloading Algorithms](#autoloading-algorithms) below) -- and then reload them when they change (see [Constant Reloading](#constant-reloading) below).
* In **production**, however, you want consistency and thread-safety and can live with a longer boot time. So `eager_load` is set to `true`, and then during boot (before the app is ready to receive requests) Rails loads all files in the `eager_load_paths` and then turns off auto loading (NB: autoloading may be needed during eager loading). Not autoloading after boot is a `good thing`, as autoloading can cause the app to have thread-safety problems.
* In **test**, for speed of execution (of individual tests) `eager_load` is `false`, so Rails follows development behaviour.
What is described above are the defaults with a newly generated Rails app.
There are multiple ways this can be configured differently (see [Configuring
Rails Applications](configuring.html#rails-general-configuration)). In the past, before
Rails 5, developers might configure `autoload_paths` to add in extra locations
(e.g. `lib` which used to be an autoload path list years ago, but no longer
is). However this is now discouraged for most purposes, as it is likely to
lead to production-only errors. It is possible to add new locations to both
`config.eager_load_paths` and `config.autoload_paths` but use at your own risk.
See also [Autoloading in the Test Environment](#autoloading-in-the-test-environment).
The value of `autoload_paths` can be inspected. In a just-generated application
it is (edited):
```bash
$ bin/rails runner 'puts ActiveSupport::Dependencies.autoload_paths'
.../app/assets
.../app/channels
.../app/controllers
.../app/controllers/concerns
.../app/helpers
.../app/jobs
.../app/mailers
.../app/models
.../app/models/concerns
.../activestorage/app/assets
.../activestorage/app/controllers
.../activestorage/app/javascript
.../activestorage/app/jobs
.../activestorage/app/models
.../actioncable/app/assets
.../actionview/app/assets
.../test/mailers/previews
```
INFO. `autoload_paths` is computed and cached during the initialization process.
The application needs to be restarted to reflect any changes in the directory
structure.
Autoloading Algorithms
----------------------
### Relative References
A relative constant reference may appear in several places, for example, in
```ruby
class PostsController < ApplicationController
def index
@posts = Post.all
end
end
```
all three constant references are relative.
#### Constants after the `class` and `module` Keywords
Ruby performs a lookup for the constant that follows a `class` or `module`
keyword because it needs to know if the class or module is going to be created
or reopened.
If the constant is not defined at that point it is not considered to be a
missing constant, autoloading is **not** triggered.
So, in the previous example, if `PostsController` is not defined when the file
is interpreted Rails autoloading is not going to be triggered, Ruby will just
define the controller.
#### Top-Level Constants
On the contrary, if `ApplicationController` is unknown, the constant is
considered missing and an autoload is going to be attempted by Rails.
In order to load `ApplicationController`, Rails iterates over `autoload_paths`.
First it checks if `app/assets/application_controller.rb` exists. If it does not,
which is normally the case, it continues and finds
`app/controllers/application_controller.rb`.
If the file defines the constant `ApplicationController` all is fine, otherwise
`LoadError` is raised:
```
unable to autoload constant ApplicationController, expected
<full path to application_controller.rb> to define it (LoadError)
```
INFO. Rails does not require the value of autoloaded constants to be a class or
module object. For example, if the file `app/models/max_clients.rb` defines
`MAX_CLIENTS = 100` autoloading `MAX_CLIENTS` works just fine.
#### Namespaces
Autoloading `ApplicationController` looks directly under the directories of
`autoload_paths` because the nesting in that spot is empty. The situation of
`Post` is different, the nesting in that line is `[PostsController]` and support
for namespaces comes into play.
The basic idea is that given
```ruby
module Admin
class BaseController < ApplicationController
@@all_roles = Role.all
end
end
```
to autoload `Role` we are going to check if it is defined in the current or
parent namespaces, one at a time. So, conceptually we want to try to autoload
any of
```
Admin::BaseController::Role
Admin::Role
Role
```
in that order. That's the idea. To do so, Rails looks in `autoload_paths`
respectively for file names like these:
```
admin/base_controller/role.rb
admin/role.rb
role.rb
```
modulus some additional directory lookups we are going to cover soon.
INFO. `'Constant::Name'.underscore` gives the relative path without extension of
the file name where `Constant::Name` is expected to be defined.
Let's see how Rails autoloads the `Post` constant in the `PostsController`
above assuming the application has a `Post` model defined in
`app/models/post.rb`.
First it checks for `posts_controller/post.rb` in `autoload_paths`:
```
app/assets/posts_controller/post.rb
app/controllers/posts_controller/post.rb
app/helpers/posts_controller/post.rb
...
test/mailers/previews/posts_controller/post.rb
```
Since the lookup is exhausted without success, a similar search for a directory
is performed, we are going to see why in the [next section](#automatic-modules):
```
app/assets/posts_controller/post
app/controllers/posts_controller/post
app/helpers/posts_controller/post
...
test/mailers/previews/posts_controller/post
```
If all those attempts fail, then Rails starts the lookup again in the parent
namespace. In this case only the top-level remains:
```
app/assets/post.rb
app/controllers/post.rb
app/helpers/post.rb
app/mailers/post.rb
app/models/post.rb
```
A matching file is found in `app/models/post.rb`. The lookup stops there and the
file is loaded. If the file actually defines `Post` all is fine, otherwise
`LoadError` is raised.
### Qualified References
When a qualified constant is missing Rails does not look for it in the parent
namespaces. But there is a caveat: when a constant is missing, Rails is
unable to tell if the trigger was a relative reference or a qualified one.
For example, consider
```ruby
module Admin
User
end
```
and
```ruby
Admin::User
```
If `User` is missing, in either case all Rails knows is that a constant called
"User" was missing in a module called "Admin".
If there is a top-level `User` Ruby would resolve it in the former example, but
wouldn't in the latter. In general, Rails does not emulate the Ruby constant
resolution algorithms, but in this case it tries using the following heuristic:
> If none of the parent namespaces of the class or module has the missing
> constant then Rails assumes the reference is relative. Otherwise qualified.
For example, if this code triggers autoloading
```ruby
Admin::User
```
and the `User` constant is already present in `Object`, it is not possible that
the situation is
```ruby
module Admin
User
end
```
because otherwise Ruby would have resolved `User` and no autoloading would have
been triggered in the first place. Thus, Rails assumes a qualified reference and
considers the file `admin/user.rb` and directory `admin/user` to be the only
valid options.
In practice, this works quite well as long as the nesting matches all parent
namespaces respectively and the constants that make the rule apply are known at
that time.
However, autoloading happens on demand. If by chance the top-level `User` was
not yet loaded, then Rails assumes a relative reference by contract.
Naming conflicts of this kind are rare in practice, but if one occurs,
`require_dependency` provides a solution by ensuring that the constant needed
to trigger the heuristic is defined in the conflicting place.
### Automatic Modules
When a module acts as a namespace, Rails does not require the application to
define a file for it, a directory matching the namespace is enough.
Suppose an application has a back office whose controllers are stored in
`app/controllers/admin`. If the `Admin` module is not yet loaded when
`Admin::UsersController` is hit, Rails needs first to autoload the constant
`Admin`.
If `autoload_paths` has a file called `admin.rb` Rails is going to load that
one, but if there's no such file and a directory called `admin` is found, Rails
creates an empty module and assigns it to the `Admin` constant on the fly.
### Generic Procedure
Relative references are reported to be missing in the cref where they were hit,
and qualified references are reported to be missing in their parent (see
[Resolution Algorithm for Relative
Constants](#resolution-algorithm-for-relative-constants) at the beginning of
this guide for the definition of *cref*, and [Resolution Algorithm for Qualified
Constants](#resolution-algorithm-for-qualified-constants) for the definition of
*parent*).
The procedure to autoload constant `C` in an arbitrary situation is as follows:
```
if the class or module in which C is missing is Object
let ns = ''
else
let M = the class or module in which C is missing
if M is anonymous
let ns = ''
else
let ns = M.name
end
end
loop do
# Look for a regular file.
for dir in autoload_paths
if the file "#{dir}/#{ns.underscore}/c.rb" exists
load/require "#{dir}/#{ns.underscore}/c.rb"
if C is now defined
return
else
raise LoadError
end
end
end
# Look for an automatic module.
for dir in autoload_paths
if the directory "#{dir}/#{ns.underscore}/c" exists
if ns is an empty string
let C = Module.new in Object and return
else
let C = Module.new in ns.constantize and return
end
end
end
if ns is empty
# We reached the top-level without finding the constant.
raise NameError
else
if C exists in any of the parent namespaces
# Qualified constants heuristic.
raise NameError
else
# Try again in the parent namespace.
let ns = the parent namespace of ns and retry
end
end
end
```
require_dependency
------------------
Constant autoloading is triggered on demand and therefore code that uses a
certain constant may have it already defined or may trigger an autoload. That
depends on the execution path and it may vary between runs.
There are times, however, in which you want to make sure a certain constant is
known when the execution reaches some code. `require_dependency` provides a way
to load a file using the current [loading mechanism](#loading-mechanism), and
keeping track of constants defined in that file as if they were autoloaded to
have them reloaded as needed.
`require_dependency` is rarely needed, but see a couple of use cases in
[Autoloading and STI](#autoloading-and-sti) and [When Constants aren't
Triggered](#when-constants-aren-t-missed).
WARNING. Unlike autoloading, `require_dependency` does not expect the file to
define any particular constant. Exploiting this behavior would be a bad practice
though, file and constant paths should match.
Constant Reloading
------------------
When `config.cache_classes` is false Rails is able to reload autoloaded
constants.
For example, if you're in a console session and edit some file behind the
scenes, the code can be reloaded with the `reload!` command:
```irb
irb> reload!
```
When the application runs, code is reloaded when something relevant to this
logic changes. In order to do that, Rails monitors a number of things:
* `config/routes.rb`.
* Locales.
* Ruby files under `autoload_paths`.
* `db/schema.rb` and `db/structure.sql`.
If anything in there changes, there is a middleware that detects it and reloads
the code.
Autoloading keeps track of autoloaded constants. Reloading is implemented by
removing them all from their respective classes and modules using
`Module#remove_const`. That way, when the code goes on, those constants are
going to be unknown again, and files reloaded on demand.
INFO. This is an all-or-nothing operation, Rails does not attempt to reload only
what changed since dependencies between classes makes that really tricky.
Instead, everything is wiped.
Common Gotchas
--------------
### Nesting and Qualified Constants
Let's consider
```ruby
module Admin
class UsersController < ApplicationController
def index
@users = User.all
end
end
end
```
and
```ruby
class Admin::UsersController < ApplicationController
def index
@users = User.all
end
end
```
To resolve `User` Ruby checks `Admin` in the former case, but it does not in
the latter because it does not belong to the nesting (see [Nesting](#nesting)
and [Resolution Algorithms](#resolution-algorithms)).
Unfortunately Rails autoloading does not know the nesting in the spot where the
constant was missing and so it is not able to act as Ruby would. In particular,
`Admin::User` will get autoloaded in either case.
Albeit qualified constants with `class` and `module` keywords may technically
work with autoloading in some cases, it is preferable to use relative constants
instead:
```ruby
module Admin
class UsersController < ApplicationController
def index
@users = User.all
end
end
end
```
### Defining vs Reopening Namespaces
Let's consider:
```ruby
# app/models/blog.rb
module Blog
def self.table_name_prefix
"blog_"
end
end
```
```ruby
# app/models/blog/post.rb
module Blog
class Post < ApplicationRecord
end
end
```
The table name for `Blog::Post` should be `blog_posts` due to the existence of
the method `Blog.table_name_prefix`. However, if `app/models/blog/post.rb` is
executed before `app/models/blog.rb` is, Active Record is not aware of the
existence of such method, and assumes the table is `posts`.
To resolve a situation like this, it helps thinking clearly about which file
_defines_ the `Blog` module (`app/models/blog.rb`), and which one _reopens_ it
(`app/models/blog/post.rb`). Then, you ensure that the definition is executed
first using `require_dependency`:
```ruby
# app/models/blog/post.rb
require_dependency "blog"
module Blog
class Post < ApplicationRecord
end
end
```
### Autoloading and STI
Single Table Inheritance (STI) is a feature of Active Record that enables
storing a hierarchy of models in one single table. The API of such models is
aware of the hierarchy and encapsulates some common needs. For example, given
these classes:
```ruby
# app/models/polygon.rb
class Polygon < ApplicationRecord
end
```
```ruby
# app/models/triangle.rb
class Triangle < Polygon
end
```
```ruby
# app/models/rectangle.rb
class Rectangle < Polygon
end
```
`Triangle.create` creates a row that represents a triangle, and
`Rectangle.create` creates a row that represents a rectangle. If `id` is the
ID of an existing record, `Polygon.find(id)` returns an object of the correct
type.
Methods that operate on collections are also aware of the hierarchy. For
example, `Polygon.all` returns all the records of the table, because all
rectangles and triangles are polygons. Active Record takes care of returning
instances of their corresponding class in the result set.
Types are autoloaded as needed. For example, if `Polygon.first` is a rectangle
and `Rectangle` has not yet been loaded, Active Record autoloads it and the
record is correctly instantiated.
All good, but if instead of performing queries based on the root class we need
to work on some subclass, things get interesting.
While working with `Polygon` you do not need to be aware of all its descendants,
because anything in the table is by definition a polygon, but when working with
subclasses Active Record needs to be able to enumerate the types it is looking
for. Let's see an example.
`Rectangle.all` only loads rectangles by adding a type constraint to the query:
```sql
SELECT "polygons".* FROM "polygons"
WHERE "polygons"."type" IN ("Rectangle")
```
Let's introduce now a subclass of `Rectangle`:
```ruby
# app/models/square.rb
class Square < Rectangle
end
```
`Rectangle.all` should now return rectangles **and** squares:
```sql
SELECT "polygons".* FROM "polygons"
WHERE "polygons"."type" IN ("Rectangle", "Square")
```
But there's a caveat here: How does Active Record know that the class `Square`
exists at all?
Even if the file `app/models/square.rb` exists and defines the `Square` class,
if no code yet used that class, `Rectangle.all` issues the query
```sql
SELECT "polygons".* FROM "polygons"
WHERE "polygons"."type" IN ("Rectangle")
```
That is not a bug, the query includes all *known* descendants of `Rectangle`.
A way to ensure this works correctly regardless of the order of execution is to
manually load the direct subclasses at the bottom of the file that defines each
intermediate class:
```ruby
# app/models/rectangle.rb
class Rectangle < Polygon
end
require_dependency 'square'
```
This needs to happen for every intermediate (non-root and non-leaf) class. The
root class does not scope the query by type, and therefore does not necessarily
have to know all its descendants.
### Autoloading and `require`
Files defining constants to be autoloaded should never be `require`d:
```ruby
require "user" # DO NOT DO THIS
class UsersController < ApplicationController
# ...
end
```
There are two possible gotchas here in development mode:
1. If `User` is autoloaded before reaching the `require`, `app/models/user.rb`
runs again because `load` does not update `$LOADED_FEATURES`.
2. If the `require` runs first Rails does not mark `User` as an autoloaded
constant and changes to `app/models/user.rb` aren't reloaded.
Just follow the flow and use constant autoloading always, never mix
autoloading and `require`. As a last resort, if some file absolutely needs to
load a certain file use `require_dependency` to play nice with constant
autoloading. This option is rarely needed in practice, though.
Of course, using `require` in autoloaded files to load ordinary 3rd party
libraries is fine, and Rails is able to distinguish their constants, they are
not marked as autoloaded.
### Autoloading and Initializers
Consider this assignment in `config/initializers/set_auth_service.rb`:
```ruby
AUTH_SERVICE = if Rails.env.production?
RealAuthService
else
MockedAuthService
end
```
The purpose of this setup would be that the application uses the class that
corresponds to the environment via `AUTH_SERVICE`. In development mode
`MockedAuthService` gets autoloaded when the initializer runs. Let's suppose
we do some requests, change its implementation, and hit the application again.
To our surprise the changes are not reflected. Why?
As [we saw earlier](#constant-reloading), Rails removes autoloaded constants,
but `AUTH_SERVICE` stores the original class object. Stale, non-reachable
using the original constant, but perfectly functional.
The following code summarizes the situation:
```ruby
class C
def quack
'quack!'
end
end
X = C
Object.instance_eval { remove_const(:C) }
X.new.quack # => quack!
X.name # => C
C # => uninitialized constant C (NameError)
```
Because of that, it is not a good idea to autoload constants on application
initialization.
In the case above we could implement a dynamic access point:
```ruby
# app/models/auth_service.rb
class AuthService
if Rails.env.production?
def self.instance
RealAuthService
end
else
def self.instance
MockedAuthService
end
end
end
```
and have the application use `AuthService.instance` instead. `AuthService`
would be loaded on demand and be autoload-friendly.
### `require_dependency` and Initializers
As we saw before, `require_dependency` loads files in an autoloading-friendly
way. Normally, though, such a call does not make sense in an initializer.
One could think about doing some [`require_dependency`](#require-dependency)
calls in an initializer to make sure certain constants are loaded upfront, for
example as an attempt to address the [gotcha with STIs](#autoloading-and-sti).
Problem is, in development mode [autoloaded constants are wiped](#constant-reloading)
if there is any relevant change in the file system. If that happens then
we are in the very same situation the initializer wanted to avoid!
Calls to `require_dependency` have to be strategically written in autoloaded
spots.
### When Constants aren't Missed
#### Relative References
Let's consider a flight simulator. The application has a default flight model
```ruby
# app/models/flight_model.rb
class FlightModel
end
```
that can be overridden by each airplane, for instance
```ruby
# app/models/bell_x1/flight_model.rb
module BellX1
class FlightModel < FlightModel
end
end
```
```ruby
# app/models/bell_x1/aircraft.rb
module BellX1
class Aircraft
def initialize
@flight_model = FlightModel.new
end
end
end
```
The initializer wants to create a `BellX1::FlightModel` and nesting has
`BellX1`, that looks good. But if the default flight model is loaded and the
one for the Bell-X1 is not, the interpreter is able to resolve the top-level
`FlightModel` and autoloading is thus not triggered for `BellX1::FlightModel`.
That code depends on the execution path.
These kind of ambiguities can often be resolved using qualified constants:
```ruby
module BellX1
class Plane
def flight_model
@flight_model ||= BellX1::FlightModel.new
end
end
end
```
Also, `require_dependency` is a solution:
```ruby
require_dependency 'bell_x1/flight_model'
module BellX1
class Plane
def flight_model
@flight_model ||= FlightModel.new
end
end
end
```
#### Qualified References
WARNING. This gotcha is only possible in Ruby < 2.5.
Given
```ruby
# app/models/hotel.rb
class Hotel
end
```
```ruby
# app/models/image.rb
class Image
end
```
```ruby
# app/models/hotel/image.rb
class Hotel
class Image < Image
end
end
```
the expression `Hotel::Image` is ambiguous because it depends on the execution
path.
As [we saw before](#resolution-algorithm-for-qualified-constants), Ruby looks
up the constant in `Hotel` and its ancestors. If `app/models/image.rb` has
been loaded but `app/models/hotel/image.rb` hasn't, Ruby does not find `Image`
in `Hotel`, but it does in `Object`:
```bash
$ bin/rails runner 'Image; p Hotel::Image' 2>/dev/null
Image # NOT Hotel::Image!
```
The code evaluating `Hotel::Image` needs to make sure
`app/models/hotel/image.rb` has been loaded, possibly with
`require_dependency`.
In these cases the interpreter issues a warning though:
```
warning: toplevel constant Image referenced by Hotel::Image
```
This surprising constant resolution can be observed with any qualifying class:
```irb
irb(main):001:0> String::Array
(irb):1: warning: toplevel constant Array referenced by String::Array
=> Array
```
WARNING. To find this gotcha the qualifying namespace has to be a class,
`Object` is not an ancestor of modules.
### Autoloading within Singleton Classes
Let's suppose we have these class definitions:
```ruby
# app/models/hotel/services.rb
module Hotel
class Services
end
end
```
```ruby
# app/models/hotel/geo_location.rb
module Hotel
class GeoLocation
class << self
Services
end
end
end
```
If `Hotel::Services` is known by the time `app/models/hotel/geo_location.rb`
is being loaded, `Services` is resolved by Ruby because `Hotel` belongs to the
nesting when the singleton class of `Hotel::GeoLocation` is opened.
But if `Hotel::Services` is not known, Rails is not able to autoload it, the
application raises `NameError`.
The reason is that autoloading is triggered for the singleton class, which is
anonymous, and as [we saw before](#generic-procedure), Rails only checks the
top-level namespace in that edge case.
An easy solution to this caveat is to qualify the constant:
```ruby
module Hotel
class GeoLocation
class << self
Hotel::Services
end
end
end
```
### Autoloading in `BasicObject`
Direct descendants of `BasicObject` do not have `Object` among their ancestors
and cannot resolve top-level constants:
```ruby
class C < BasicObject
String # NameError: uninitialized constant C::String
end
```
When autoloading is involved that plot has a twist. Let's consider:
```ruby
class C < BasicObject
def user
User # WRONG
end
end
```
Since Rails checks the top-level namespace `User` gets autoloaded just fine the
first time the `user` method is invoked. You only get the exception if the
`User` constant is known at that point, in particular in a *second* call to
`user`:
```ruby
c = C.new
c.user # surprisingly fine, User
c.user # NameError: uninitialized constant C::User
```
because it detects that a parent namespace already has the constant (see [Qualified
References](#autoloading-algorithms-qualified-references)).
As with pure Ruby, within the body of a direct descendant of `BasicObject` use
always absolute constant paths:
```ruby
class C < BasicObject
::String # RIGHT
def user
::User # RIGHT
end
end
```
### Autoloading in the Test Environment
When configuring the `test` environment for autoloading you might consider multiple factors.
For example it might be worth running your tests with an identical setup to production (`config.eager_load = true`, `config.cache_classes = true`) in order to catch any problems before they hit production (this is compensation for the lack of dev-prod parity). However this will slow down the boot time for individual tests on a dev machine (and is not immediately compatible with spring see below). So one possibility is to do this on a
[CI](https://en.wikipedia.org/wiki/Continuous_integration) machine only (which should run without spring).
On a development machine you can then have your tests running with whatever is fastest (ideally `config.eager_load = false`).
With the [Spring](https://github.com/rails/spring) pre-loader (included with new Rails apps), you ideally keep `config.eager_load = false` as per development. Sometimes you may end up with a hybrid configuration (`config.eager_load = true`, `config.cache_classes = true` AND `config.enable_dependency_loading = true`), see [spring issue](https://github.com/rails/spring/issues/519#issuecomment-348324369). However it might be simpler to keep the same configuration as development, and work out whatever it is that is causing autoloading to fail (perhaps by the results of your CI test results).
Occasionally you may need to explicitly eager_load by using `Rails
.application.eager_load!` in the setup of your tests -- this might occur if your [tests involve multithreading](https://stackoverflow.com/questions/25796409/in-rails-how-can-i-eager-load-all-code-before-a-specific-rspec-test).
## Troubleshooting
### Tracing Autoloads
Active Support is able to report constants as they are autoloaded. To enable these traces in a Rails application, put the following two lines in some initializer:
```ruby
ActiveSupport::Dependencies.logger = Rails.logger
ActiveSupport::Dependencies.verbose = true
```
### Where is a Given Autoload Triggered?
If constant `Foo` is being autoloaded, and you'd like to know where is that autoload coming from, just throw
```ruby
puts caller
```
at the top of `foo.rb` and inspect the printed stack trace.
### Which Constants Have Been Autoloaded?
At any given time,
```ruby
ActiveSupport::Dependencies.autoloaded_constants
```
has the collection of constants that have been autoloaded so far.
| {
"content_hash": "2e64abcf0d234d66ff48a5f9c2ac1088",
"timestamp": "",
"source": "github",
"line_count": 1408,
"max_line_length": 594,
"avg_line_length": 30.787642045454547,
"alnum_prop": 0.7551731297146417,
"repo_name": "EmmaB/rails-1",
"id": "98b262f3cc74c8948f6820390503091791b5db6b",
"size": "43349",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "guides/source/autoloading_and_reloading_constants_classic_mode.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34354"
},
{
"name": "CoffeeScript",
"bytes": "40518"
},
{
"name": "HTML",
"bytes": "202985"
},
{
"name": "JavaScript",
"bytes": "98658"
},
{
"name": "Ruby",
"bytes": "11087847"
},
{
"name": "Yacc",
"bytes": "968"
}
],
"symlink_target": ""
} |
/* common style */
button.customview-button{
background-color:transparent;
background-position:left top;
background-repeat:no-repeat;
background-size:30px 30px;
border:none;
box-sizing:border-box;
cursor:pointer;
font-size:13px;
height:auto;
margin:0px 3px;
min-height:30px;
min-width:30px;
outline:none;
padding:0px;
vertical-align:top;
width:auto;
}
button.calendar-button{
background-image:url('https://tis2010.jp/library/kintone/images/calendar.png');
padding-left:30px;
}
button.close-button{
background-image:url('https://tis2010.jp/library/kintone/images/close.png');
padding-left:30px;
}
button.compass-button{
background-image:url('https://tis2010.jp/library/kintone/images/compass.png');
padding-left:30px;
}
button.download-button{
background-image:url('https://tis2010.jp/library/kintone/images/download.png');
padding-left:30px;
}
button.edit-button{
background-image:url('https://tis2010.jp/library/kintone/images/edit.png');
padding-left:30px;
}
button.next-button{
background-image:url('https://tis2010.jp/library/kintone/images/next.png');
padding-left:30px;
}
button.pdf-button{
background-image:url('https://tis2010.jp/library/kintone/images/pdf.png');
padding-left:30px;
}
button.prev-button{
background-image:url('https://tis2010.jp/library/kintone/images/prev.png');
padding-left:30px;
}
button.search-button{
background-image:url('https://tis2010.jp/library/kintone/images/search.png');
padding-left:30px;
}
button.time-button{
background-image:url('https://tis2010.jp/library/kintone/images/time.png');
padding-left:30px;
}
div.customview-container{
box-sizing:border-box;
font-size:13px;
width:100%;
}
p.customview-p{
box-sizing:border-box;
line-height:30px;
margin:0px;
padding:0px 3px;
vertical-align:top;
}
span.customview-span{
box-sizing:border-box;
display:inline-block;
line-height:30px;
margin:0px;
padding:0px 3px;
vertical-align:top;
}
table.customview-table{
border:none;
border-collapse:collapse;
border-spacing:0;
box-sizing:border-box;
margin:0px;
min-width:100%;
padding:0px;
}
table.customview-table thead th,
table.customview-table tfoot th{
background-color:#EFEFEF;
border:1px solid #C9C9C9;
font-weight:normal;
height:auto;
line-height:30px;
margin:0px;
padding:0px 3px;
text-align:center;
}
table.customview-table tbody td{
border:1px solid #C9C9C9;
height:auto;
line-height:30px;
margin:0px;
padding:0px;
}
table.customview-table tbody tr:nth-of-type(odd){
background-color:#FFFFFF;
}
table.customview-table tbody tr:nth-of-type(even){
background-color:#FAF9F9;
}
table.customview-table input[type=text],
table.customview-table label,
table.customview-table select,
table.customview-table textarea{
background-color:transparent;
border:none;
box-sizing:border-box;
font-size:13px;
line-height:30px;
margin:0px;
min-height:30px;
outline:none;
padding:0px 3px;
vertical-align:top;
width:100%;
}
table.customview-table input[type=text],
table.customview-table select{
height:30px;
min-width:100px;
}
table.customview-table input[type=text]:focus,
table.customview-table select:focus,
table.customview-table textarea:focus{
background-color:#F7ECE1;
box-shadow:0px 0px 2px 2px #7BDFF2 inset;
}
.left{
text-align:left;
}
.right{
text-align:right;
}
.center{
text-align:center;
}
| {
"content_hash": "4354cf27cf56dfc29f1a8b2d4a83c779",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 80,
"avg_line_length": 22.594594594594593,
"alnum_prop": 0.7485047846889952,
"repo_name": "TIS2010/jslibs",
"id": "5180eef58183c4e04938f13af7404de0db408da5",
"size": "3344",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kintone/plugins/orders/sophy/timetable_cs@sophy/css/desktop/common.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5869614"
},
{
"name": "HTML",
"bytes": "470025"
},
{
"name": "JavaScript",
"bytes": "3511533"
},
{
"name": "Shell",
"bytes": "42512"
}
],
"symlink_target": ""
} |
package com.ghgande.j2mod.modbus.facade;
import com.ghgande.j2mod.modbus.Modbus;
import com.ghgande.j2mod.modbus.io.AbstractModbusTransport;
import com.ghgande.j2mod.modbus.net.SerialConnection;
import com.ghgande.j2mod.modbus.util.SerialParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Modbus/Serial Master facade.
*
* @author Dieter Wimberger
* @author John Charlton
* @author Steve O'Hara (4energy)
* @version 2.0 (March 2016)
*/
public class ModbusSerialMaster extends AbstractModbusMaster {
private static final Logger logger = LoggerFactory.getLogger(ModbusSerialMaster.class);
private SerialConnection connection;
/**
* Constructs a new master facade instance for communication
* with a given slave.
*
* @param param SerialParameters specifies the serial port parameters to use
* to communicate with the slave device network.
*/
public ModbusSerialMaster(SerialParameters param) {
this(param, Modbus.DEFAULT_TIMEOUT);
}
/**
* Constructs a new master facade instance for communication
* with a given slave.
*
* @param param SerialParameters specifies the serial port parameters to use
* to communicate with the slave device network.
* @param timeout Receive timeout in milliseconds
*/
public ModbusSerialMaster(SerialParameters param, int timeout) {
try {
connection = new SerialConnection(param);
connection.setTimeout(timeout);
this.timeout = timeout;
}
catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* Connects this <tt>ModbusSerialMaster</tt> with the slave.
*
* @throws Exception if the connection cannot be established.
*/
public synchronized void connect() throws Exception {
if (connection != null && !connection.isOpen()) {
connection.open();
transaction = connection.getModbusTransport().createTransaction();
setTransaction(transaction);
}
}
/**
* Disconnects this <tt>ModbusSerialMaster</tt> from the slave.
*/
public synchronized void disconnect() {
if (connection != null && connection.isOpen()) {
connection.close();
transaction = null;
setTransaction(null);
}
}
@Override
public void setTimeout(int timeout) {
super.setTimeout(timeout);
if (connection != null) {
connection.setTimeout(timeout);
}
}
@Override
public AbstractModbusTransport getTransport() {
return connection == null ? null : connection.getModbusTransport();
}
} | {
"content_hash": "a5c512960a2715d519fa0721db19fdbf",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 91,
"avg_line_length": 30.666666666666668,
"alnum_prop": 0.6489130434782608,
"repo_name": "j123b567/j2mod",
"id": "5e2b86b3223f9f4508e13961f4926e7d75df4137",
"size": "3375",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "src/main/java/com/ghgande/j2mod/modbus/facade/ModbusSerialMaster.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Arduino",
"bytes": "41628"
},
{
"name": "Java",
"bytes": "833283"
}
],
"symlink_target": ""
} |
package com.greensopinion.finance.services.encryption;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.logging.Logger;
import javax.inject.Inject;
import com.greensopinion.finance.services.domain.Categories;
import com.greensopinion.finance.services.domain.CategoriesService;
import com.greensopinion.finance.services.domain.Transactions;
import com.greensopinion.finance.services.domain.TransactionsService;
class MasterPasswordChangeSupport implements EncryptorListener {
private final CategoriesService categoriesService;
private final TransactionsService transactionsService;
private Transactions transactions;
private Categories categories;
private final Logger logger;
@Inject
MasterPasswordChangeSupport(TransactionsService transactionsService, CategoriesService categoriesService,
Logger logger) {
this.transactionsService = checkNotNull(transactionsService);
this.categoriesService = checkNotNull(categoriesService);
this.logger = checkNotNull(logger);
}
@Override
public void aboutToChangeEncryptor() {
transactions = transactionsService.retrieve();
categories = categoriesService.retrieve();
}
@Override
public void encryptorChanged() {
checkNotNull(transactions);
checkNotNull(categories);
transactionsService.update(transactions);
transactions = null;
categoriesService.update(categories);
categories = null;
logger.info("encrypted data with new master password");
}
}
| {
"content_hash": "b9c3d9710345a958f761ecc65e2ebf77",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 106,
"avg_line_length": 31.21276595744681,
"alnum_prop": 0.8234492160872529,
"repo_name": "greensopinion/greenbeans",
"id": "2c2399a325bfa3b25619e2651ce3b69747c9664d",
"size": "2229",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "services/src/main/java/com/greensopinion/finance/services/encryption/MasterPasswordChangeSupport.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3732"
},
{
"name": "HTML",
"bytes": "40915"
},
{
"name": "Java",
"bytes": "382130"
},
{
"name": "JavaScript",
"bytes": "148330"
}
],
"symlink_target": ""
} |
import Component from '../editors/editor-xp';
export default Component;
| {
"content_hash": "26b6ce182093702c8576c1c636be4d6e",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 45,
"avg_line_length": 25.333333333333332,
"alnum_prop": 0.7368421052631579,
"repo_name": "randowize/e-app",
"id": "7a3aa5a01f6787da71429101ffc79a682f1759fd",
"size": "76",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ui/components/content/index.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1031"
},
{
"name": "HTML",
"bytes": "3212"
},
{
"name": "JavaScript",
"bytes": "27974"
},
{
"name": "TypeScript",
"bytes": "261867"
}
],
"symlink_target": ""
} |
namespace content {
#if defined(OS_WIN)
namespace {
// The write must be performed on the UI thread because the clipboard object
// from the IO thread cannot create windows so it cannot be the "owner" of the
// clipboard's contents. // See http://crbug.com/5823.
void WriteObjectsOnUIThread(ui::Clipboard::ObjectMap* objects) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
static ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
clipboard->WriteObjects(ui::Clipboard::BUFFER_STANDARD, *objects);
}
} // namespace
#endif
ClipboardMessageFilter::ClipboardMessageFilter() {}
void ClipboardMessageFilter::OverrideThreadForMessage(
const IPC::Message& message, BrowserThread::ID* thread) {
// Clipboard writes should always occur on the UI thread due the restrictions
// of various platform APIs. In general, the clipboard is not thread-safe, so
// all clipboard calls should be serviced from the UI thread.
//
// Windows needs clipboard reads to be serviced from the IO thread because
// these are sync IPCs which can result in deadlocks with NPAPI plugins if
// serviced from the UI thread. Note that Windows clipboard calls ARE
// thread-safe so it is ok for reads and writes to be serviced from different
// threads.
#if !defined(OS_WIN)
if (IPC_MESSAGE_CLASS(message) == ClipboardMsgStart)
*thread = BrowserThread::UI;
#endif
#if defined(OS_WIN)
if (message.type() == ClipboardHostMsg_ReadImage::ID)
*thread = BrowserThread::FILE;
#endif
}
bool ClipboardMessageFilter::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(ClipboardMessageFilter, message, *message_was_ok)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_WriteObjectsAsync, OnWriteObjectsAsync)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_WriteObjectsSync, OnWriteObjectsSync)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_GetSequenceNumber, OnGetSequenceNumber)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_IsFormatAvailable, OnIsFormatAvailable)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_Clear, OnClear)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadAvailableTypes,
OnReadAvailableTypes)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadText, OnReadText)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadAsciiText, OnReadAsciiText)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadHTML, OnReadHTML)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadRTF, OnReadRTF)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ClipboardHostMsg_ReadImage, OnReadImage)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadCustomData, OnReadCustomData)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadData, OnReadData)
#if defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_FindPboardWriteStringAsync,
OnFindPboardWriteString)
#endif
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
ClipboardMessageFilter::~ClipboardMessageFilter() {
}
void ClipboardMessageFilter::OnWriteObjectsSync(
ui::Clipboard::ObjectMap objects,
base::SharedMemoryHandle bitmap_handle) {
DCHECK(base::SharedMemory::IsHandleValid(bitmap_handle))
<< "Bad bitmap handle";
// Splice the shared memory handle into the clipboard data.
ui::Clipboard::ReplaceSharedMemHandle(&objects, bitmap_handle, peer_handle());
#if defined(OS_WIN)
// We cannot write directly from the IO thread, and cannot service the IPC
// on the UI thread. We'll copy the relevant data and get a handle to any
// shared memory so it doesn't go away when we resume the renderer, and post
// a task to perform the write on the UI thread.
ui::Clipboard::ObjectMap* long_living_objects = new ui::Clipboard::ObjectMap;
long_living_objects->swap(objects);
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&WriteObjectsOnUIThread, base::Owned(long_living_objects)));
#else
GetClipboard()->WriteObjects(ui::Clipboard::BUFFER_STANDARD, objects);
#endif
}
void ClipboardMessageFilter::OnWriteObjectsAsync(
const ui::Clipboard::ObjectMap& objects) {
#if defined(OS_WIN)
// We cannot write directly from the IO thread, and cannot service the IPC
// on the UI thread. We'll copy the relevant data and post a task to preform
// the write on the UI thread.
ui::Clipboard::ObjectMap* long_living_objects =
new ui::Clipboard::ObjectMap(objects);
// This async message doesn't support shared-memory based bitmaps; they must
// be removed otherwise we might dereference a rubbish pointer.
long_living_objects->erase(ui::Clipboard::CBF_SMBITMAP);
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&WriteObjectsOnUIThread, base::Owned(long_living_objects)));
#else
GetClipboard()->WriteObjects(ui::Clipboard::BUFFER_STANDARD, objects);
#endif
}
void ClipboardMessageFilter::OnGetSequenceNumber(
ui::Clipboard::Buffer buffer, uint64* sequence_number) {
*sequence_number = GetClipboard()->GetSequenceNumber(buffer);
}
void ClipboardMessageFilter::OnReadAvailableTypes(
ui::Clipboard::Buffer buffer, std::vector<string16>* types,
bool* contains_filenames) {
GetClipboard()->ReadAvailableTypes(buffer, types, contains_filenames);
}
void ClipboardMessageFilter::OnIsFormatAvailable(
const ui::Clipboard::FormatType& format, ui::Clipboard::Buffer buffer,
bool* result) {
*result = GetClipboard()->IsFormatAvailable(format, buffer);
}
void ClipboardMessageFilter::OnClear(ui::Clipboard::Buffer buffer) {
GetClipboard()->Clear(buffer);
}
void ClipboardMessageFilter::OnReadText(
ui::Clipboard::Buffer buffer, string16* result) {
GetClipboard()->ReadText(buffer, result);
}
void ClipboardMessageFilter::OnReadAsciiText(
ui::Clipboard::Buffer buffer, std::string* result) {
GetClipboard()->ReadAsciiText(buffer, result);
}
void ClipboardMessageFilter::OnReadHTML(
ui::Clipboard::Buffer buffer, string16* markup, GURL* url,
uint32* fragment_start, uint32* fragment_end) {
std::string src_url_str;
GetClipboard()->ReadHTML(buffer, markup, &src_url_str, fragment_start,
fragment_end);
*url = GURL(src_url_str);
}
void ClipboardMessageFilter::OnReadRTF(
ui::Clipboard::Buffer buffer, std::string* result) {
GetClipboard()->ReadRTF(buffer, result);
}
void ClipboardMessageFilter::OnReadImage(
ui::Clipboard::Buffer buffer, IPC::Message* reply_msg) {
SkBitmap bitmap = GetClipboard()->ReadImage(buffer);
#if defined(USE_X11)
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(
&ClipboardMessageFilter::OnReadImageReply, this, bitmap, reply_msg));
#else
OnReadImageReply(bitmap, reply_msg);
#endif
}
void ClipboardMessageFilter::OnReadImageReply(
const SkBitmap& bitmap, IPC::Message* reply_msg) {
base::SharedMemoryHandle image_handle = base::SharedMemory::NULLHandle();
uint32 image_size = 0;
std::string reply_data;
if (!bitmap.isNull()) {
std::vector<unsigned char> png_data;
SkAutoLockPixels lock(bitmap);
if (gfx::PNGCodec::EncodeWithCompressionLevel(
static_cast<const unsigned char*>(bitmap.getPixels()),
gfx::PNGCodec::FORMAT_BGRA,
gfx::Size(bitmap.width(), bitmap.height()),
bitmap.rowBytes(),
false,
std::vector<gfx::PNGCodec::Comment>(),
Z_BEST_SPEED,
&png_data)) {
base::SharedMemory buffer;
if (buffer.CreateAndMapAnonymous(png_data.size())) {
memcpy(buffer.memory(), vector_as_array(&png_data), png_data.size());
if (buffer.GiveToProcess(peer_handle(), &image_handle)) {
image_size = png_data.size();
}
}
}
}
ClipboardHostMsg_ReadImage::WriteReplyParams(reply_msg, image_handle,
image_size);
Send(reply_msg);
}
void ClipboardMessageFilter::OnReadCustomData(
ui::Clipboard::Buffer buffer, const string16& type, string16* result) {
GetClipboard()->ReadCustomData(buffer, type, result);
}
void ClipboardMessageFilter::OnReadData(const ui::Clipboard::FormatType& format,
std::string* data) {
GetClipboard()->ReadData(format, data);
}
// static
ui::Clipboard* ClipboardMessageFilter::GetClipboard() {
// We have a static instance of the clipboard service for use by all message
// filters. This instance lives for the life of the browser processes.
static ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
return clipboard;
}
} // namespace content
| {
"content_hash": "340ed74848f5865c9bfed60ee8390174",
"timestamp": "",
"source": "github",
"line_count": 228,
"max_line_length": 80,
"avg_line_length": 37.85526315789474,
"alnum_prop": 0.7174139728884255,
"repo_name": "windyuuy/opera",
"id": "6935aba4f66ecbbecbf2494a84098796e79e4d93",
"size": "9267",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "chromium/src/content/browser/renderer_host/clipboard_message_filter.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "25707"
},
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Assembly",
"bytes": "51642"
},
{
"name": "Batchfile",
"bytes": "35942"
},
{
"name": "C",
"bytes": "4303018"
},
{
"name": "C#",
"bytes": "35203"
},
{
"name": "C++",
"bytes": "207333360"
},
{
"name": "CMake",
"bytes": "25089"
},
{
"name": "CSS",
"bytes": "681256"
},
{
"name": "Dart",
"bytes": "24294"
},
{
"name": "Emacs Lisp",
"bytes": "25534"
},
{
"name": "Groff",
"bytes": "5283"
},
{
"name": "HTML",
"bytes": "10400943"
},
{
"name": "IDL",
"bytes": "836"
},
{
"name": "Java",
"bytes": "2821184"
},
{
"name": "JavaScript",
"bytes": "14563996"
},
{
"name": "Lua",
"bytes": "13749"
},
{
"name": "Makefile",
"bytes": "55521"
},
{
"name": "Objective-C",
"bytes": "1211523"
},
{
"name": "Objective-C++",
"bytes": "6221908"
},
{
"name": "PHP",
"bytes": "61320"
},
{
"name": "Perl",
"bytes": "82949"
},
{
"name": "Protocol Buffer",
"bytes": "280464"
},
{
"name": "Python",
"bytes": "12627773"
},
{
"name": "Rebol",
"bytes": "262"
},
{
"name": "Ruby",
"bytes": "937"
},
{
"name": "Scheme",
"bytes": "10604"
},
{
"name": "Shell",
"bytes": "894814"
},
{
"name": "VimL",
"bytes": "4953"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "14650"
}
],
"symlink_target": ""
} |
export default function ensureExist(module, moduleName) {
if (!module) {
throw new Error(`'${moduleName}' is a required dependency for '${this.constructor.name}'`);
}
return module;
}
| {
"content_hash": "c6a887311055bbb9947ea27e3c3b6e7c",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 95,
"avg_line_length": 32.333333333333336,
"alnum_prop": 0.6907216494845361,
"repo_name": "ele828/ringcentral-js-integration-commons",
"id": "fbb81ce7a305c00b5e8371118479b34a7f5e0573",
"size": "194",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/lib/ensureExist.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2305"
},
{
"name": "JavaScript",
"bytes": "1179672"
},
{
"name": "PowerShell",
"bytes": "173"
},
{
"name": "Shell",
"bytes": "1144"
}
],
"symlink_target": ""
} |
class AppListModelUpdater;
class ChromeSearchResult;
class Profile;
namespace app_list {
namespace test {
FORWARD_DECLARE_TEST(MixerTest, Publish);
}
class ChipRanker;
class SearchControllerImpl;
class SearchProvider;
class SearchResultRanker;
enum class RankingItemType;
// Mixer collects results from providers, sorts them and publishes them to the
// SearchResults UI model. The targeted results have 6 slots to hold the
// result.
class Mixer {
public:
Mixer(AppListModelUpdater* model_updater,
SearchControllerImpl* search_controller);
Mixer(const Mixer&) = delete;
Mixer& operator=(const Mixer&) = delete;
~Mixer();
// Adds a new mixer group. A "soft" maximum of |max_results| results will be
// chosen from this group (if 0, will allow unlimited results from this
// group). If there aren't enough results from all groups, more than
// |max_results| may be chosen from this group. Returns the group's group_id.
size_t AddGroup(size_t max_results);
// Associates a provider with a mixer group.
void AddProviderToGroup(size_t group_id, SearchProvider* provider);
// Collects the results, sorts and publishes them.
void MixAndPublish(size_t num_max_results, const std::u16string& query);
// Sets a SearchResultRanker to re-rank non-app search results before they are
// published.
void SetNonAppSearchResultRanker(std::unique_ptr<SearchResultRanker> ranker);
void InitializeRankers(Profile* profile);
SearchResultRanker* search_result_ranker() {
if (!search_result_ranker_)
return nullptr;
return search_result_ranker_.get();
}
// Sets a ChipRanker to re-rank chip results before they are published.
void SetChipRanker(std::unique_ptr<ChipRanker> ranker);
// Handle a training signal.
void Train(const LaunchData& launch_data);
// Used for sorting and mixing results.
struct SortData {
SortData();
SortData(ChromeSearchResult* result, double score);
bool operator<(const SortData& other) const;
raw_ptr<ChromeSearchResult> result; // Not owned.
double score;
};
typedef std::vector<Mixer::SortData> SortedResults;
private:
FRIEND_TEST_ALL_PREFIXES(test::MixerTest, Publish);
class Group;
typedef std::vector<std::unique_ptr<Group>> Groups;
void FetchResults(const std::u16string& query);
const raw_ptr<AppListModelUpdater> model_updater_; // Not owned.
const raw_ptr<SearchControllerImpl> search_controller_; // Not owned.
Groups groups_;
// Adaptive models used for re-ranking search results.
std::unique_ptr<SearchResultRanker> search_result_ranker_;
std::unique_ptr<ChipRanker> chip_ranker_;
};
} // namespace app_list
#endif // CHROME_BROWSER_UI_APP_LIST_SEARCH_MIXER_H_
| {
"content_hash": "3b878cdf012bbc92d36af8c0616a4149",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 80,
"avg_line_length": 29.695652173913043,
"alnum_prop": 0.7342606149341142,
"repo_name": "ric2b/Vivaldi-browser",
"id": "3c718d92501c4e503e2d21f9e4118012b4fe693a",
"size": "3212",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "chromium/chrome/browser/ui/app_list/search/mixer.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
import tensorflow as tf
with tf.name_scope('policy') as scope:
# tf Graph Input
features = 4
objects = 8
layers = 3
x = tf.placeholder(tf.float32, [None, 8, 8, features], name='input')
y = tf.placeholder(tf.float32, [None, 8, 8, 1], name='expected')
# Set model weights
#first pass filters
Fa = tf.Variable(tf.random_normal([1,8,features,objects]))
Fb = tf.Variable(tf.random_normal([8,1,features,objects]))
b = tf.Variable(tf.random_normal([objects,8,8]))
# Construct model
La = tf.transpose(tf.nn.conv2d(x, Fa, [1,1,1,1], 'VALID'),[0,3,1,2])
Lb = tf.transpose(tf.nn.conv2d(x, Fb, [1,1,1,1], 'VALID'),[0,3,1,2])
L = tf.transpose(tf.tanh(tf.matmul(La, Lb) + b), [0,2,3,1])
for i in range(layers):
Fa = tf.Variable(tf.random_normal([1,8,objects,objects]))
Fb = tf.Variable(tf.random_normal([8,1,objects,objects]))
b = tf.Variable(tf.random_normal([objects,8,8]))
La = tf.transpose(tf.nn.conv2d(L, Fa, [1,1,1,1], 'VALID'),[0,3,1,2])
Lb = tf.transpose(tf.nn.conv2d(L, Fb, [1,1,1,1], 'VALID'),[0,3,1,2])
L = tf.transpose(tf.tanh(tf.matmul(La, Lb) + b), [0,2,3,1])
#Consolidation filters
F = tf.Variable(tf.random_normal([1,1,objects,1]))
b = tf.Variable(tf.random_normal([8,8,1]))
# the output of the model
pred = tf.nn.sigmoid(tf.nn.conv2d(L, F, [1,1,1,1], 'VALID') + b, name='output')
cost = tf.pow(tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
labels = tf.reshape(y, [-1, 64]),
logits = tf.log(tf.reshape(pred, [-1, 64])),
)), 2, name='cost')
learning_rate = tf.placeholder(tf.float32, [], name='learning_rate')
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost, name='train')
tf.variables_initializer(tf.global_variables(), name = 'init')
definition = tf.Session().graph_def
directory = '../../data/policy'
saver = tf.train.Saver(tf.global_variables(), name='saver')
saver_def = saver.as_saver_def()
# The name of the tensor you must feed with a filename when saving/restoring.
print(saver_def.filename_tensor_name)
# The name of the target operation you must run when restoring.
print(saver_def.restore_op_name)
# The name of the target operation you must run when saving.
print(saver_def.save_tensor_name)
tf.train.write_graph(definition, directory, 'policy-{}x{}.pb'.format(objects, layers), as_text=False)
exit()
# Initializing the variables
init = tf.global_variables_initializer()
import random
training_epochs = 20
display_step = 1
lr = 0.01
with tf.Session() as sess:
sess.run(init)
batch_size = 100
# Training cycle
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = 1000
# Loop over all batches
batch_xs = []
batch_ys = []
for _ in range(batch_size):
itmi = [[[0 for ___ in range(4)] for __ in range(8)] for _ in range(8)]
itmj = [[[0] for __ in range(8)] for _ in range(8)]
batch_xs.append(itmi)
batch_ys.append(itmj)
for i in range(total_batch):
ix = i * batch_size
for k in range(batch_size):
for Y in range(8):
for X in range(8):
itmj[Y][X][0] = random.choice([0.0,1.0])
for j in range(4):
itmi[Y][X][j] = random.choice([0.0, 1.0])
batch_xs.append(itmi)
batch_ys.append(itmj)
# Run optimization op (backprop) and cost op (to get loss value)
_, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,
y: batch_ys,
learning_rate: lr})
# Compute average loss
del batch_xs[:]
del batch_ys[:]
avg_cost += c
#print("cost=",c," avg=",avg_cost/(i+1))
if (i % 100 == 0):
print(100.0 * i/float(total_batch), '%')
# Display logs per epoch step
if (epoch+1) % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost/total_batch))
saver.save(sess, 'policy_net', global_step=epoch)
lr = lr * 0.97
print("Optimization Finished!") | {
"content_hash": "bb61f38e013a549471c95015e0040f6c",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 101,
"avg_line_length": 35.59349593495935,
"alnum_prop": 0.5600730927364094,
"repo_name": "Tenebryo/coin",
"id": "6a10ed6975deea4245c15d71f79e160fcfcbd483",
"size": "4378",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ml/policy/src/model.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "18015"
},
{
"name": "Rust",
"bytes": "409527"
},
{
"name": "Shell",
"bytes": "154"
}
],
"symlink_target": ""
} |
package funnel
| {
"content_hash": "317d6825f9de8869333bbf3320d49fbf",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 14,
"avg_line_length": 15,
"alnum_prop": 0.8666666666666667,
"repo_name": "Gawainli/funnel",
"id": "ff56589d715f4a21353802b10f10ff39b3bcd67f",
"size": "15",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "main.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "13616"
}
],
"symlink_target": ""
} |
import { Vector,
Matrix,
Line,
Plane,
LinkedListNode,
LinkedList,
CircularLinkedList,
Vertex,
Polygon,
LineSegment,
PRECISION,
mht,
makeLookAt,
makeOrtho,
makePerspective,
makeFrustum } from "sylvester-es6";
// Vector
const vector1 = new Vector([1, 2]);
const vector2 = new Vector(vector1);
const vectorI = Vector.i;
const vectorJ = Vector.j;
const vectorK = Vector.k;
const vectorZero = Vector.Zero(1);
const vectorE = vector2.e(1);
const vectorDimensions = vector2.dimensions();
const vectorModulus = vector2.modulus();
const vectorEql1 = vector2.eql(vector1);
const vectorEql2 = vector2.eql([1, 2]);
const vectorDup = vector2.dup();
const vectorMap = vector2.map((x, i) => x * i);
const vectorEach = vector2.map((x, i) => x + i);
const vectorToUnitVector = vector2.toUnitVector();
const vectorAngleFrom = vector2.angleFrom(vector1);
const vectorIsParallelTo = vector2.isParallelTo(vector1);
const vectorIsAntiparallelTo = vector2.isAntiparallelTo(vector1);
const vectorIsPerpendicularTo = vector2.isPerpendicularTo(vector1);
const vectorAdd1 = vector2.add(vector1);
const vectorAdd2 = vector2.add([1, 2]);
const vectorSubtract1 = vector2.subtract(vector1);
const vectorSubtract2 = vector2.subtract([1, 2]);
const vectorMultiply = vector2.multiply(2);
const vectorX = vector2.x(3);
const vectorDot1 = vector2.dot(vector1);
const vectorDot2 = vector2.dot(vector2);
const vectorCross1 = vector2.cross(vector1);
const vectorCross2 = vector2.cross(vector2);
const vectorMax = vector2.max();
const vectorIndexOf = vector2.indexOf(4);
const vectorToDiagonalMatrix = vector2.toDiagonalMatrix();
const vectorRound = vector2.round();
const vectorSnapTo = vector2.snapTo(5);
const vectorDistanceFrom1 = vector2.distanceFrom(vector1);
const vectorDistanceFrom2 = vector2.distanceFrom(new Line([1, 0], [0, 1]));
const vectorDistanceFrom3 = vector2.distanceFrom(new Plane([1, 0], [0, 1]));
const vectorLiesOn = vector2.liesOn(new Line([1, 0], [0, 1]));
const vectorLiesIn = vector2.liesIn(new Plane([1, 0], [0, 1]));
const vectorRotate1 = vector2.rotate(1, vector1);
const vectorRotate2 = vector2.rotate(1, new Line([1, 0], [0, 1]));
const vectorRotate3 = vector2.rotate(new Matrix([[1, 0], [0, 1]]), new Line([1, 0], [0, 1]));
const vectorReflectionIn1 = vector2.reflectionIn(vector1);
const vectorReflectionIn2 = vector2.reflectionIn(new Line([1, 0], [0, 1]));
const vectorReflectionIn3 = vector2.reflectionIn(new Plane([1, 0], [0, 1]));
const vectorTo3D = vector2.to3D();
const vectorInspect = vector2.inspect();
const vectorSetElements1 = vector2.setElements(vector1);
const vectorSetElements2 = vector2.setElements(vector2);
// Vertex
const vertex1 = new Vertex([1, 2]);
const vertex2 = new Vertex(vertex1);
const vertexI = Vertex.i;
const vertexJ = Vertex.j;
const vertexK = Vertex.k;
const vertexConvert1 = Vertex.convert([[1, 2], [2, 3]]);
const vertexConvert2 = Vertex.convert([vector1, vector2]);
const vertexZero = Vertex.Zero(1);
const vertexE = vertex2.e(1);
const vertexDimensions = vertex2.dimensions();
const vertexModulus = vertex2.modulus();
const vertexEql1 = vertex2.eql(vertex1);
const vertexEql2 = vertex2.eql([1, 2]);
const vertexDup = vertex2.dup();
const vertexMap = vertex2.map((x, i) => x * i);
const vertexEach = vertex2.map((x, i) => x + i);
const vertexToUnitvertex = vertex2.toUnitVector();
const vertexAngleFrom = vertex2.angleFrom(vertex1);
const vertexIsParallelTo = vertex2.isParallelTo(vertex1);
const vertexIsAntiparallelTo = vertex2.isAntiparallelTo(vertex1);
const vertexIsPerpendicularTo = vertex2.isPerpendicularTo(vertex1);
const vertexAdd1 = vertex2.add(vertex1);
const vertexAdd2 = vertex2.add([1, 2]);
const vertexSubtract1 = vertex2.subtract(vertex1);
const vertexSubtract2 = vertex2.subtract([1, 2]);
const vertexMultiply = vertex2.multiply(2);
const vertexX = vertex2.x(3);
const vertexDot1 = vertex2.dot(vertex1);
const vertexDot2 = vertex2.dot(vertex2);
const vertexCross1 = vertex2.cross(vertex1);
const vertexCross2 = vertex2.cross(vertex2);
const vertexMax = vertex2.max();
const vertexIndexOf = vertex2.indexOf(4);
const vertexToDiagonalMatrix = vertex2.toDiagonalMatrix();
const vertexRound = vertex2.round();
const vertexSnapTo = vertex2.snapTo(5);
const vertexDistanceFrom1 = vertex2.distanceFrom(vertex1);
const vertexDistanceFrom2 = vertex2.distanceFrom(new Line([1, 0], [0, 1]));
const vertexDistanceFrom3 = vertex2.distanceFrom(new Plane([1, 0], [0, 1]));
const vertexLiesOn = vertex2.liesOn(new Line([1, 0], [0, 1]));
const vertexLiesIn = vertex2.liesIn(new Plane([1, 0], [0, 1]));
const vertexRotate1 = vertex2.rotate(1, vertex1);
const vertexRotate2 = vertex2.rotate(1, new Line([1, 0], [0, 1]));
const vertexReflectionIn1 = vertex2.reflectionIn(vertex1);
const vertexReflectionIn2 = vertex2.reflectionIn(new Line([1, 0], [0, 1]));
const vertexReflectionIn3 = vertex2.reflectionIn(new Plane([1, 0], [0, 1]));
const vertexTo3D = vertex2.to3D();
const vertexInspect = vertex2.inspect();
const vertexSetElements1 = vertex2.setElements(vertex1);
const vertexSetElements2 = vertex2.setElements(vertex2);
const vertexIsConvex = vertex2.isConvex(new Polygon([[1, 2], [2, 3]], new Plane([1, 2], [1, 2])));
const vertexIsReflex = vertex2.isReflex(new Polygon([[1, 2], [2, 3]], new Plane([1, 2], [1, 2])));
const vertexType = vertex2.type(new Polygon([[1, 2], [2, 3]], new Plane([1, 2], [1, 2])));
// Matrix
const matrix1 = new Matrix([0, 1]);
const matrix2 = new Matrix([[1, 0], [0, 1]]);
const matrix3 = new Matrix(vector1);
const matrix4 = new Matrix(matrix2);
const matrixI = Matrix.I(1);
const matrixDiagonal1 = Matrix.Diagonal([0, 1]);
const matrixDiagonal2 = Matrix.Diagonal([[1, 0], [0, 1]]);
const matrixDiagonal3 = Matrix.Diagonal(vector1);
const matrixDiagonal4 = Matrix.Diagonal(matrix2);
const matrixRotation1 = Matrix.Rotation(1);
const matrixRotation2 = Matrix.Rotation(1, vector1);
const matrixRotationX = Matrix.RotationX(1);
const matrixRotationY = Matrix.RotationY(1);
const matrixRotationZ = Matrix.RotationZ(1);
const matrixRandom = Matrix.Random(1, 2);
const matrixZero = Matrix.Zero(1, 2);
const matrixElements = matrix2.elements;
const matrixE = matrix2.e(1, 2);
const matrixRow = matrix2.row(1);
const matrixCol = matrix2.col(2);
const matrixDimensions = matrix2.dimensions();
const matrixRows = matrix2.rows();
const matrixcols = matrix2.cols();
const matrixEql1 = matrix2.eql([0, 1]);
const matrixEql2 = matrix2.eql([[1, 0], [0, 1]]);
const matrixEql3 = matrix2.eql(vector1);
const matrixEql4 = matrix2.eql(matrix2);
const matrixDup = matrix2.dup();
const matrixMap = matrix2.map((x, i, j) => x * i * j);
const matrixIsSameSizeAs = matrix2.isSameSizeAs(matrix1);
const matrixAdd1 = matrix2.add(matrix1);
const matrixAdd2 = matrix2.add(vector1);
const matrixSubtract = matrix2.subtract(matrix1);
const matrixCanMultiplyFromLeft = matrix2.canMultiplyFromLeft(matrix1);
const matrixMultiply1 = matrix2.multiply(1);
const matrixMultiply2 = matrix2.multiply(matrix1);
const matrixMultiply = matrix2.multiply(vector1);
const matrixX1 = matrix2.x(1);
const matrixX2 = matrix2.x(matrix1);
const matrixX3 = matrix2.x(vector1);
const matrixMinor = matrix2.minor(1, 2, 3, 4);
const matrixTranspose = matrix2.transpose();
const matrixIsSquare = matrix2.isSquare();
const matrixMax = matrix2.max();
const matrixIndexOf = matrix2.indexOf(1);
const matrixDiagonal = matrix2.diagonal();
const matrixToRightTriangular = matrix2.toRightTriangular();
const matrixToUpperTriangular = matrix2.toUpperTriangular();
const matrixDeterminant = matrix2.determinant();
const matrixDet = matrix2.det();
const matrixIsSingular = matrix2.isSingular();
const matrixTrace = matrix2.trace();
const matrixTr = matrix2.tr();
const matrixRank = matrix2.rank();
const matrixRk = matrix2.rk();
const matrixAugment1 = matrix2.augment([0, 1]);
const matrixAugment2 = matrix2.augment([[1, 0], [0, 1]]);
const matrixAugment3 = matrix2.augment(vector1);
const matrixAugment4 = matrix2.augment(matrix2);
const matrixInverse = matrix2.inverse();
const matrixInv = matrix2.inv();
const matrixRound = matrix2.round();
const matrixSnapTo = matrix2.snapTo(1);
const matrixInspect = matrix2.inspect();
const matrixSetElements1 = matrix2.setElements([0, 1]);
const matrixSetElements2 = matrix2.setElements([[1, 0], [0, 1]]);
const matrixSetElements3 = matrix2.setElements(vector1);
const matrixSetElements4 = matrix2.setElements(matrix2);
// Line
const line1 = new Line([1, 0], [0, 1]);
const line2 = new Line(vector1, [0, 1]);
const line3 = new Line([1, 0], vector1);
const lineX = Line.X;
const lineY = Line.Y;
const lineZ = Line.Z;
const lineAnchor = line1.anchor;
const lineDirection = line1.direction;
const lineEql = line2.eql(line1);
const lineDup = line2.dup();
const lineTranslate1 = line2.translate(vector1);
const lineTranslate2 = line2.translate([1, 0]);
const lineIsParallelTo1 = line2.isParallelTo(line2);
const lineIsParallelTo2 = line2.isParallelTo(new Plane([1, 0], [0, 1]));
const lineDistanceFrom1 = line2.distanceFrom(vector1);
const lineDistanceFrom2 = line2.distanceFrom(line1);
const lineDistanceFrom3 = line2.distanceFrom(new Plane([1, 0], [0, 1]));
const lineContains = line2.contains(vector1);
const lineLiesIn = line2.liesIn(new Plane([1, 0], [0, 1]));
const lineIntersects1 = line2.intersects(line1);
const lineIntersects2 = line2.intersects(new Plane([1, 0], [0, 1]));
const lineIntersectionWith1 = line2.intersectionWith(line1);
const lineIntersectionWith2 = line2.intersectionWith(new Plane([1, 0], [0, 1]));
const linePointClosestTo1 = line2.pointClosestTo(vector1);
const linePointClosestTo2 = line2.pointClosestTo(line1);
const linePointClosestTo3 = line2.pointClosestTo([1, 0]);
const lineRotate1 = line2.rotate(1, vector1);
const lineRotate2 = line2.rotate(1, line1);
const lineReflectionIn1 = line2.reflectionIn(vector1);
const lineReflectionIn2 = line2.reflectionIn(line1);
const lineReflectionIn3 = line2.reflectionIn(new Plane([1, 0], [0, 1]));
const lineSetVectors1 = line2.setVectors([1, 0], [0, 1]);
const lineSetVectors2 = line2.setVectors(vector1, [0, 1]);
const lineSetVectors3 = line2.setVectors([1, 0], vector1);
// LineSegment
const lineSegment1 = new LineSegment([1, 0], [0, 1]);
const lineSegment2 = new LineSegment(vector1, [0, 1]);
const lineSegment3 = new LineSegment([1, 0], vector1);
const lineSegmentEql = lineSegment2.eql(lineSegment1);
const lineSegmentDup = lineSegment2.dup();
const lineSegmentLength = lineSegment2.length();
const lineSegmentToVector = lineSegment2.toVector();
const lineSegmentMidpoint = lineSegment2.midpoint();
const lineSegmentBisectingPlane = lineSegment2.bisectingPlane();
const lineSegmentTranslate1 = lineSegment2.translate(vector1);
const lineSegmentTranslate2 = lineSegment2.translate([1, 0]);
const lineSegmentIsParallelTo1 = lineSegment2.isParallelTo(line2);
const lineSegmentIsParallelTo2 = lineSegment2.isParallelTo(new Plane([1, 0], [0, 1]));
const lineSegmentDistanceFrom1 = lineSegment2.distanceFrom(vector1);
const lineSegmentDistanceFrom2 = lineSegment2.distanceFrom(line1);
const lineSegmentDistanceFrom3 = lineSegment2.distanceFrom(new Plane([1, 0], [0, 1]));
const lineSegmentContains1 = lineSegment2.contains(vector1);
const lineSegmentContains2 = lineSegment2.contains(line1);
const lineSegmentContains3 = lineSegment2.contains(new Plane([1, 0], [0, 1]));
const lineSegmentIntersects1 = lineSegment2.intersects(line1);
const lineSegmentIntersects2 = lineSegment2.intersects(new Plane([1, 0], [0, 1]));
const lineSegmentIntersectionWith1 = lineSegment2.intersectionWith(line1);
const lineSegmentIntersectionWith2 = lineSegment2.intersectionWith(new Plane([1, 0], [0, 1]));
const lineSegmentPointClosestTo1 = lineSegment2.pointClosestTo(vector1);
const lineSegmentPointClosestTo2 = lineSegment2.pointClosestTo(line1);
const lineSegmentPointClosestTo3 = lineSegment2.pointClosestTo([1, 0]);
const lineSegmentSetPoints1 = lineSegment2.setPoints([1, 2], [2, 1]);
const lineSegmentSetPoints2 = lineSegment2.setPoints(vector1, [2, 1]);
const lineSegmentSetPoints3 = lineSegment2.setPoints([1, 2], vector2);
// Plane
const plane1 = new Plane([1, 0], [0, 1]);
const plane2 = new Plane(vector1, [0, 1]);
const plane3 = new Plane([1, 0], vector1);
const plane4 = new Plane([1, 0], vector1, [0, 1]);
const plane5 = new Plane([1, 0], vector1, vector2);
const planeXY = Plane.XY;
const planeYZ = Plane.YZ;
const planeZX = Plane.ZX;
const planeYX = Plane.YX;
const planeFromPoints1 = Plane.fromPoints([[1, 2], [2, 3]]);
const planeFromPoints2 = Plane.fromPoints([vector1, vector2]);
const planeAnchor = plane1.anchor;
const planeNormal = plane1.normal;
const planeEql = plane2.eql(plane1);
const planeDup = plane2.dup();
const planeTranslate1 = plane2.translate(vector1);
const planeTranslate2 = plane2.translate([1, 0]);
const planeIsParallelTo1 = plane2.isParallelTo(line1);
const planeIsParallelTo2 = plane2.isParallelTo(plane1);
const planeIsPerpendicularTo = plane2.isPerpendicularTo(plane1);
const planeDistanceFrom1 = plane2.distanceFrom(vector1);
const planeDistanceFrom2 = plane2.distanceFrom(line1);
const planeDistanceFrom3 = plane2.distanceFrom(plane1);
const planeContains1 = plane2.contains(vector1);
const planeContains2 = plane2.contains(line1);
const planeIntersects1 = plane2.intersects(plane1);
const planeIntersects2 = plane2.intersects(line1);
const planeIntersectionWith1 = plane2.intersectionWith(line1);
const planeIntersectionWith2 = plane2.intersectionWith(plane1);
const planepointClosestTo1 = plane2.pointClosestTo(vector1);
const planepointClosestTo2 = plane2.pointClosestTo([1, 0]);
const planeRotate = plane2.rotate(1, line1);
const planeReflectionIn1 = plane2.reflectionIn(vector1);
const planeReflectionIn2 = plane2.reflectionIn(line1);
const planeReflectionIn3 = plane2.reflectionIn(plane1);
const planeSetVectors1 = plane2.setVectors([1, 0], [0, 1]);
const planeSetVectors2 = plane2.setVectors(vector1, [0, 1]);
const planeSetVectors3 = plane2.setVectors([1, 0], vector1);
const planeSetVectors4 = plane2.setVectors([1, 0], vector1, [0, 1]);
const planeSetVectors5 = plane2.setVectors([1, 0], vector1, vector2);
// LinkedListNode
const linkedListNode1 = new LinkedListNode(1);
const prev = linkedListNode1.prev;
const next = linkedListNode1.next;
const data = linkedListNode1.data;
// LinkedList
const linkedList1 = new LinkedList();
const linkedListNode2 = LinkedList.Node(2);
const linkedListCircular2 = LinkedList.Circular(2);
const linkedListLength = linkedList1.length;
const linkedListFirst = linkedList1.first;
const linkedListLast = linkedList1.last;
linkedList1.forEach((node, i) => node.data + i, linkedList1);
linkedList1.each((node, i) => node.data + i, linkedList1);
const linkedListAt = linkedList1.at(1);
const linkedListRandomNode = linkedList1.randomNode();
const linkedListToArray = linkedList1.toArray();
// CircularLinkedList
const circularLinkedList1 = new CircularLinkedList();
const circularLinkedList2 = CircularLinkedList.fromArray([1, 2, 3], false);
const circularLinkedListNode2 = CircularLinkedList.Node(2);
const circularLinkedListLength = circularLinkedList1.length;
const circularLinkedListFirst = circularLinkedList1.first;
const circularLinkedListLast = circularLinkedList1.last;
circularLinkedList1.forEach((node, i) => node.data + i, circularLinkedList1);
circularLinkedList1.each((node, i) => node.data + i, circularLinkedList1);
const circularLinkedListAt = circularLinkedList1.at(1);
const circularLinkedListRandomNode = circularLinkedList1.randomNode();
const circularLinkedListToArray = circularLinkedList1.toArray();
circularLinkedList1.append(linkedListNode1);
circularLinkedList1.prepend(linkedListNode1);
circularLinkedList1.insertBefore(linkedListNode1, linkedListNode2);
circularLinkedList1.insertAfter(linkedListNode1, linkedListNode2);
circularLinkedList1.remove(linkedListNode1);
const circularLinkedListWithData = circularLinkedList1.withData(1);
// Polygon
const polygon1 = new Polygon([[1, 2], [2, 2]], plane1);
const polygon2 = new Polygon([vector1, vector2], plane1);
const polygonVertices = polygon1.vertices;
const polygonV = polygon2.v(1);
const polygonNodeFor = polygon2.nodeFor(123);
const polygonDup = polygon2.dup();
const polygonTranslate1 = polygon2.translate([1, 2]);
const polygonTranslate2 = polygon2.translate(vector1);
const polygonRotate1 = polygon2.rotate(1, line1);
const polygonScale = polygon2.scale(1, [1, 2]);
polygon2.updateTrianglePlanes((plane) => plane);
const polygonIsTriangle = polygon2.isTriangle();
const polygonTrianglesForSurfaceIntegral = polygon2.trianglesForSurfaceIntegral();
const polygonArea = polygon2.area();
const polygonCentroid = polygon2.centroid();
const polygonProjectionOn = polygon2.projectionOn(plane1);
const polygonRemoveVertex = polygon2.removeVertex(123);
const polygonContains1 = polygon2.contains([1, 2]);
const polygonContains2 = polygon2.contains(vector1);
const polygonContainsByWindingNumber1 = polygon2.containsByWindingNumber([1, 2]);
const polygonContainsByWindingNumber2 = polygon2.containsByWindingNumber(vector1);
const polygonHasEdgeContaining1 = polygon2.hasEdgeContaining([1, 2]);
const polygonHasEdgeContaining2 = polygon2.hasEdgeContaining(vector1);
const polygonToTriangles = polygon2.toTriangles();
const polygonTriangulateByEarClipping = polygon2.triangulateByEarClipping();
const polygonSetVertices1 = polygon2.setVertices([[1, 2], [2, 2]], plane1);
const polygonSetVertices2 = polygon2.setVertices([vector1, vector2], plane1);
polygon2.populateVertexTypeLists();
polygon2.copyVertices();
polygon2.clearCache();
polygon2.setCache('a', 1);
const polygonInspect = polygon2.inspect();
// PRECISION
const precision = PRECISION;
// glUtils
const mht1 = mht(matrix1);
const makeLookAt1 = makeLookAt(1, 2, 3, 4, 5, 6, 7, 8, 9);
const makeOrtho1 = makeOrtho(1, 2, 3, 4, 5, 6);
const makePerspective1 = makePerspective(1, 2, 3, 4);
const makeFrustum1 = makeFrustum(1, 2, 3, 4, 5, 6);
| {
"content_hash": "b78dfe0c33317f5b0adcbf5be0172367",
"timestamp": "",
"source": "github",
"line_count": 383,
"max_line_length": 98,
"avg_line_length": 46.702349869451695,
"alnum_prop": 0.7676524850450047,
"repo_name": "georgemarshall/DefinitelyTyped",
"id": "a3982dc4bc2f59d79fdb48025c8fc733fa21fcc1",
"size": "17887",
"binary": false,
"copies": "52",
"ref": "refs/heads/master",
"path": "types/sylvester-es6/sylvester-es6-tests.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "16338312"
},
{
"name": "Ruby",
"bytes": "40"
},
{
"name": "Shell",
"bytes": "73"
},
{
"name": "TypeScript",
"bytes": "17728346"
}
],
"symlink_target": ""
} |
package com.intellij.openapi.command;
import java.util.EventListener;
public interface CommandListener extends EventListener {
default void commandStarted(CommandEvent event) {
}
default void beforeCommandFinished(CommandEvent event) {
}
default void commandFinished(CommandEvent event) {
}
default void undoTransparentActionStarted() {
}
default void beforeUndoTransparentActionFinished() {
}
default void undoTransparentActionFinished() {
}
} | {
"content_hash": "9c6eb1bf5cd0bb4e4eadb39c6db54759",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 58,
"avg_line_length": 19.833333333333332,
"alnum_prop": 0.773109243697479,
"repo_name": "jk1/intellij-community",
"id": "c4eb86325b981db97725179c75f25b3a4da7c9c7",
"size": "1076",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "platform/core-api/src/com/intellij/openapi/command/CommandListener.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
module Wukong
module Streamer
#
# Mix StructRecordizer into any streamer to make it accept a stream of
# objects -- the first field in each line is turned into a class and used to
# instantiate an object using the remaining fields on that line.
#
module StructRecordizer
#
# Turned the first field into a class name, then use the remaining fields
# on that line to instantiate the object to process.
#
def self.recordize rsrc, *fields
klass_name, suffix = rsrc.split('-', 2)
klass = Wukong.class_from_resource(klass_name) or return
# instantiate the class using the remaining fields on that line
begin
[ klass.new(*fields), suffix ]
rescue ArgumentError => e
warn "Couldn't instantiate: #{e} (#{[klass, fields].inspect})"
return
rescue Exception => e
raise [e, rsrc, fields].inspect
end
end
#
#
#
def recordize line
StructRecordizer.recordize *line.split("\t") unless line.blank?
end
end
#
# Processes file as a stream of objects -- the first field in each line is
# turned into a class and used to instantiate an object using the remaining
# fields on that line.
#
# See [StructRecordizer] for more.
#
class StructStreamer < Wukong::Streamer::Base
include StructRecordizer
end
end
end
| {
"content_hash": "dfcb50a9cc4b15e6a92e79adf89dcf72",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 80,
"avg_line_length": 30.48936170212766,
"alnum_prop": 0.6266573621772505,
"repo_name": "infochimps-labs/wukong",
"id": "f6c9a9fd9f2ea8d0926fa94175f976747ea63de0",
"size": "1457",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "old/wukong/streamer/struct_streamer.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "22245"
},
{
"name": "DOT",
"bytes": "9852"
},
{
"name": "JavaScript",
"bytes": "12966"
},
{
"name": "Perl",
"bytes": "187214"
},
{
"name": "Python",
"bytes": "652"
},
{
"name": "Ruby",
"bytes": "718772"
},
{
"name": "Shell",
"bytes": "4029"
}
],
"symlink_target": ""
} |
package iec61499
import (
"errors"
"fmt"
"strings"
)
//A ValidateError is returned when validation of a network of function block fails
type ValidateError struct {
Err error
Arg string
DebugInfo
}
func (v ValidateError) Error() string {
s := fmt.Sprintf("Error (File %v, Line %v): %s", v.SourceFile, v.SourceLine, v.Err.Error())
s = strings.Replace(s, "{{arg}}", v.Arg, -1)
return s
}
func newValidateError(err error, arg string, debug DebugInfo) *ValidateError {
return &ValidateError{
Err: err,
Arg: arg,
DebugInfo: debug,
}
}
var (
//ErrFbTypeNameNotUnique is used to indicate when a FBType name isn't unique in the set
ErrFbTypeNameNotUnique = errors.New("FBType Name '{{arg}}' is not unique in the set")
//ErrInterfaceNameNotUnique is used to indicate when an interface name isn't unique in a block
ErrInterfaceNameNotUnique = errors.New("Interface name '{{arg}}' is not unique in the FB")
//ErrUndefinedAssociatedDataPort is used when an associated data port (to an event) can't be located
ErrUndefinedAssociatedDataPort = errors.New("The associated data port '{{arg}}' can't be found")
//ErrInterfaceDataTypeNotValid is used to indicate when an interface data type isn't valid
ErrInterfaceDataTypeNotValid = errors.New("Interface data type '{{arg}}' is not valid")
//ErrCompositeBFBsDontGetEventDataAssociations is used to indicate when a CFB block thas been given event/data associations
ErrCompositeBFBsDontGetEventDataAssociations = errors.New("Composite FBs can't have event/data associations")
//ErrUndefinedAlgorithm is used to indicate that an algorithm was referenced that can't be found (so probably a typo has occured)
ErrUndefinedAlgorithm = errors.New("Can't find Algorithm with name '{{arg}}'")
//ErrUndefinedState is used to indicate that a state was referenced that can't be found (so probably a typo has occured)
ErrUndefinedState = errors.New("Can't find State with name '{{arg}}'")
//ErrOnlyBasicFBsGetTriggers is returned when triggers (event/data associations) are put on anything other than a BasicFB
ErrOnlyBasicFBsGetTriggers = errors.New("Only Basic FBs can have event/data associations/triggers")
//ErrStateNameNotUnique is returned when a state name in a bfb is not unique
ErrStateNameNotUnique = errors.New("The state name '{{arg}}' is not unique in the FB")
//ErrFbReferenceInvalidType is returned when an embedded child type in a CFB can't be found
ErrFbReferenceInvalidType = errors.New("The FBType of the FBReference (the instance type of an embedded FB) '{{arg}}' can't be found")
//ErrFbReferenceNameNotUnique is returned when an instance in the CFB has a non-unique name
ErrFbReferenceNameNotUnique = errors.New("The FBReference Name '{{arg}}' of the instance is not unique in the CFB")
)
//ValidateFBs will take a slice of FBs and check that they are valid
//It will check for the following, in this order:
// ALL FBs:
// - Type name unique in set
// - Interface names are unique in fb
// - Interface data types are valid
// - Interface associations (if present) are valid in fb (ie only bfbs get associations)
// BASIC FBs:
// - Internal data names don't conflict with interface names
// - Internal data types are valid
// COMPOSITE FBs:
// - CFB instance types exist
// - CFB instance names unique
// - CFB event/data connections valid based on instances
func ValidateFBs(fbs []FB) *ValidateError {
for i := 0; i < len(fbs); i++ {
oFBs := make([]FB, len(fbs))
copy(oFBs, fbs)
fb := fbs[i]
if err := validateFB(fb, append(oFBs[0:i], oFBs[i+1:]...)); err != nil {
return err
}
}
return nil
}
func validateFB(fb FB, otherFbs []FB) *ValidateError {
if err := fbTypeNamesUnique(fb, otherFbs); err != nil {
return err
}
if err := fbInterfaceNamesUniqueAndValidTypesAndAssociationsValid(fb, otherFbs); err != nil {
return err
}
if err := fbBFBStateMachineValid(fb, otherFbs); err != nil {
return err
}
if err := fbCFBNetworkValid(fb, otherFbs); err != nil {
return err
}
//check that the type name is not in the otherFbs
return nil
}
//fbTypeNamesUnique makes sure each overall fb name is unique
func fbTypeNamesUnique(fb FB, otherFbs []FB) *ValidateError {
for _, oFb := range otherFbs {
if oFb.Name == fb.Name {
return newValidateError(ErrFbTypeNameNotUnique, fb.Name, fb.DebugInfo)
}
}
return nil
}
//fbInterfaceNamesUniqueAndValidTypesAndAssociationsValid checks
// -that interface names don't overlap within a fb
// -that types are valid
// -that no associations are present except in bfbs
// -that any associations are with existing inputs
// (we don't use otherFbs in this function)
func fbInterfaceNamesUniqueAndValidTypesAndAssociationsValid(fb FB, otherFbs []FB) *ValidateError {
for _, e := range fb.EventInputs {
if fb.NameUseCounter(e.Name) > 1 {
return newValidateError(ErrInterfaceNameNotUnique, e.Name, e.DebugInfo)
}
if len(e.With) > 0 && fb.CompositeFB != nil {
return newValidateError(ErrCompositeBFBsDontGetEventDataAssociations, e.Name, e.DebugInfo)
}
for _, w := range e.With {
found := false
for _, v := range fb.InputVars {
if w.Var == v.Name {
found = true
break
}
}
if found == false {
return newValidateError(ErrUndefinedAssociatedDataPort, e.Name, e.DebugInfo)
}
}
}
for _, e := range fb.EventOutputs {
if fb.NameUseCounter(e.Name) > 1 {
return newValidateError(ErrInterfaceNameNotUnique, e.Name, e.DebugInfo)
}
if len(e.With) > 0 && fb.CompositeFB != nil {
return newValidateError(ErrCompositeBFBsDontGetEventDataAssociations, e.Name, e.DebugInfo)
}
for _, w := range e.With {
found := false
for _, v := range fb.OutputVars {
if w.Var == v.Name {
found = true
break
}
}
if found == false {
return newValidateError(ErrUndefinedAssociatedDataPort, e.Name, e.DebugInfo)
}
}
}
for _, v := range append(fb.InputVars, fb.OutputVars...) {
if fb.NameUseCounter(v.Name) > 1 {
return newValidateError(ErrInterfaceNameNotUnique, v.Name, v.DebugInfo)
}
if !isValidDataType(v.Type) {
return newValidateError(ErrInterfaceDataTypeNotValid, v.Type, v.DebugInfo)
}
}
return nil
}
func fbBFBStateMachineValid(fb FB, otherFBs []FB) *ValidateError {
if fb.BasicFB == nil { //blocks that aren't basicFBs aren't going to have invalid state machines!
return nil
}
for _, s := range fb.BasicFB.States {
//make sure all state names are unique
if fb.NameUseCounter(s.Name) > 1 {
return newValidateError(ErrStateNameNotUnique, s.Name, s.DebugInfo)
}
//make sure the ecActions are valid
for _, a := range s.ECActions {
if a.Algorithm != "" {
found := false
for _, al := range fb.BasicFB.Algorithms {
if al.Name == a.Algorithm {
found = true
break
}
}
if found == false {
return newValidateError(ErrUndefinedAlgorithm, a.Algorithm, a.DebugInfo)
}
}
if a.Output != "" {
found := false
for _, eo := range fb.EventOutputs {
if eo.Name == a.Output {
found = true
break
}
}
if found == false {
return newValidateError(ErrUndefinedEvent, a.Output, a.DebugInfo)
}
}
}
}
//make sure all transitions can be mapped
for _, t := range fb.BasicFB.Transitions {
//find their source and destination states
foundSource := false
foundDest := false
for _, s := range fb.BasicFB.States {
if s.Name == t.Source {
foundSource = true
}
if s.Name == t.Destination {
foundDest = true
}
if foundSource && foundDest {
break
}
}
if foundSource == false {
return newValidateError(ErrUndefinedState, t.Source, t.DebugInfo)
}
if foundDest == false {
return newValidateError(ErrUndefinedState, t.Destination, t.DebugInfo)
}
//TODO: make sure condition components are valid??
}
return nil
}
//isValidDataType returns true if string s is one of the valid IEC61499 event/data types
func isValidDataType(s string) bool {
s = strings.ToLower(s)
if s == "bool" ||
s == "byte" ||
s == "word" ||
s == "dword" ||
s == "lword" ||
s == "sint" ||
s == "usint" ||
s == "int" ||
s == "uint" ||
s == "dint" ||
s == "udint" ||
s == "lint" ||
s == "ulint" ||
s == "real" ||
s == "lreal" ||
s == "time" ||
s == "any" {
return true
}
return false
}
func fbCFBNetworkValid(fb FB, otherFBs []FB) *ValidateError {
if fb.CompositeFB == nil { //blocks that aren't compositeFBs aren't going to have invalid state machines!
return nil
}
cfb := fb.CompositeFB
//make sure all instances can be found in otherFBs
for i := 0; i < len(cfb.FBs); i++ {
found := false
for j := 0; j < len(otherFBs); j++ {
if otherFBs[j].Name == cfb.FBs[i].Type {
found = true
break
}
}
if found == false {
return newValidateError(ErrFbReferenceInvalidType, cfb.FBs[i].Type, cfb.FBs[i].DebugInfo)
}
}
//make sure each instance has a unique name
for i := 0; i < len(cfb.FBs); i++ {
for j := 0; j < len(cfb.FBs); j++ {
if i == j {
break
}
if cfb.FBs[i].Name == cfb.FBs[j].Name {
return newValidateError(ErrFbReferenceNameNotUnique, cfb.FBs[i].Name, cfb.FBs[i].DebugInfo)
}
}
}
//TODO: make sure each source/destination port of each {events, data connections} can be found
return nil
}
| {
"content_hash": "9260f20ffdfcc16b76e18f6662368e17",
"timestamp": "",
"source": "github",
"line_count": 316,
"max_line_length": 135,
"avg_line_length": 29.414556962025316,
"alnum_prop": 0.685207100591716,
"repo_name": "PRETgroup/goFB",
"id": "9cfb982c62b2eed3defba92c9b45b98b40945279",
"size": "9295",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iec61499/validate.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "55448"
},
{
"name": "Go",
"bytes": "604288"
},
{
"name": "Makefile",
"bytes": "158"
},
{
"name": "Shell",
"bytes": "153"
},
{
"name": "VHDL",
"bytes": "49921"
},
{
"name": "Verilog",
"bytes": "10079"
}
],
"symlink_target": ""
} |
//
// Pop3Command.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2022 .NET Foundation and Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Threading.Tasks;
namespace MailKit.Net.Pop3 {
/// <summary>
/// POP3 command handler.
/// </summary>
/// <remarks>
/// All exceptions thrown by the handler are considered fatal and will
/// force-disconnect the connection. If a non-fatal error occurs, set
/// it on the <see cref="Pop3Command.Exception"/> property.
/// </remarks>
delegate Task Pop3CommandHandler (Pop3Engine engine, Pop3Command pc, string text, bool doAsync, CancellationToken cancellationToken);
enum Pop3CommandStatus {
Queued = -5,
Active = -4,
Continue = -3,
ProtocolError = -2,
Error = -1,
Ok = 0
}
class Pop3Command
{
public Pop3CommandHandler Handler { get; private set; }
public Encoding Encoding { get; private set; }
public string Command { get; private set; }
// output
public Pop3CommandStatus Status { get; internal set; }
public ProtocolException Exception { get; set; }
public string StatusText { get; set; }
public object UserData { get; set; }
public Pop3Command (Pop3CommandHandler handler, Encoding encoding, string format, params object[] args)
{
Command = string.Format (CultureInfo.InvariantCulture, format, args);
Encoding = encoding;
Handler = handler;
}
static Exception CreatePop3Exception (Pop3Command pc)
{
var command = pc.Command.Split (' ')[0].TrimEnd ();
var message = string.Format ("POP3 server did not respond with a +OK response to the {0} command.", command);
if (pc.Status == Pop3CommandStatus.Error)
return new Pop3CommandException (message, pc.StatusText);
return new Pop3ProtocolException (message);
}
public void ThrowIfError ()
{
if (Status != Pop3CommandStatus.Ok)
throw CreatePop3Exception (this);
if (Exception != null)
throw Exception;
}
}
}
| {
"content_hash": "048c47d5bb21bab9ddbb81b22425332e",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 134,
"avg_line_length": 33.655913978494624,
"alnum_prop": 0.7169329073482428,
"repo_name": "jstedfast/MailKit",
"id": "0c86344db85d6de1f265e1e68763f4ad9e1b45e6",
"size": "3132",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MailKit/Net/Pop3/Pop3Command.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "177"
},
{
"name": "C#",
"bytes": "5965972"
},
{
"name": "PowerShell",
"bytes": "8949"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace Computas.CognitiveServices.Test.UWP
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
Xamarin.Forms.Forms.Init(e);
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| {
"content_hash": "233670bb12813d0aeb2f967f58f9804d",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 99,
"avg_line_length": 37.74766355140187,
"alnum_prop": 0.6236692250557069,
"repo_name": "kkho/Cognitive-Services-Computas-",
"id": "db1c57a6a867bbb0f094d776984712acb5e919e5",
"size": "4041",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Computas.CognitiveServices.Test/Computas.CognitiveServices.Test.UWP/App.xaml.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "108533"
}
],
"symlink_target": ""
} |
import createReducer, {
paginate,
fetchRequest,
fetchSuccessEntities,
fetchSuccess,
fetchFailure
// resetReducer
} from "./utilities"
import {
ROLETYPES_REQUEST,
ROLETYPES_SUCCESS,
ROLETYPES_FAILURE
// ROLETYPEIDS_SELECTED_RESET
} from "../actions/types"
// Slice Reducers
const roleTypes = createReducer(
{},
{
ROLETYPES_SUCCESS: fetchSuccessEntities
}
)
export const roleTypesBuffered = createReducer(
{},
{
ROLETYPES_REQUEST: fetchRequest,
ROLETYPES_SUCCESS: fetchSuccess,
ROLETYPES_FAILURE: fetchFailure
}
)
export const roleTypesPagination = paginate({
mapActionToKey: action => action.key,
types: [
ROLETYPES_REQUEST,
ROLETYPES_SUCCESS,
ROLETYPES_FAILURE
]
})
/*
export const roleTypeIDsSelected = createReducer(
[],
{
ROLETYPEIDS_SELECTED_RESET: resetReducer
}
)
*/
export default roleTypes
| {
"content_hash": "6475d5bab37024e45cd011fbf5243cf8",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 49,
"avg_line_length": 17.448979591836736,
"alnum_prop": 0.7298245614035088,
"repo_name": "MerinEREN/iiClient",
"id": "4f788ecd7b26816bbdc22ec5d382cf3fe026223d",
"size": "855",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/reducers/roleTypes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "624"
},
{
"name": "JavaScript",
"bytes": "2495112"
}
],
"symlink_target": ""
} |
<?php
namespace Buybrain\Buybrain\Util;
class Cast
{
/**
* @param mixed $input
* @return null|string|string[]
*/
public static function toString($input)
{
if ($input === null) {
return $input;
}
if (is_array($input)) {
return array_map([self::class, 'toString'], $input);
}
return (string)$input;
}
/**
* @param mixed $input
* @return null|int|int[]
*/
public static function toInt($input)
{
if ($input === null) {
return $input;
}
if (is_array($input)) {
return array_map([self::class, 'toInt'], $input);
}
return (int)$input;
}
}
| {
"content_hash": "49c8a6d1700a7cbfdbb4c33d29d59651",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 64,
"avg_line_length": 20.685714285714287,
"alnum_prop": 0.47513812154696133,
"repo_name": "buybrain/buybrain-sdk-pkp",
"id": "db80e8aa75c71ba18a7185fd37ca348edb94af06",
"size": "724",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Buybrain/Buybrain/Util/Cast.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "127909"
}
],
"symlink_target": ""
} |
package it.haefelinger.flaka.util;
/**
* A singleton factory for a Groovenizer instance.
*
* This factory is thread-safe.
*
* @author geronimo
*
*/
public class GroovenizerFactory {
/**
* The one and only instance.
*/
static Groovenizer instance;
static {
/* create instance on loading this class */
instance = new GroovenizerImpl();
}
/**
* Returns Groovenizer instance.
*
* This function will always return the very same instance.
* @return
*/
static public Groovenizer newInstance() {
return instance;
}
}
| {
"content_hash": "194b8f6b95baf29283576232e36690b8",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 61,
"avg_line_length": 17.424242424242426,
"alnum_prop": 0.6469565217391304,
"repo_name": "greg2001/ant-flaka",
"id": "9a5da3e6dd1d4d633e0f0e587daf5449a39626f7",
"size": "1192",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/it/haefelinger/flaka/util/GroovenizerFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "452700"
},
{
"name": "Python",
"bytes": "9263"
},
{
"name": "Shell",
"bytes": "1529"
},
{
"name": "XSLT",
"bytes": "9165"
}
],
"symlink_target": ""
} |
package com.thoughtworks.studios.shine.semweb;
public interface URIReference extends Resource {
String getURIText();
String getSPARQLForm();
}
| {
"content_hash": "1b0a634b97a40776377420192ce7ebce",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 48,
"avg_line_length": 15.6,
"alnum_prop": 0.75,
"repo_name": "MFAnderson/gocd",
"id": "4cb9947004260512eafa130621a0831f61696632",
"size": "756",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "server/src/com/thoughtworks/studios/shine/semweb/URIReference.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "8637"
},
{
"name": "CSS",
"bytes": "528991"
},
{
"name": "FreeMarker",
"bytes": "182"
},
{
"name": "Groovy",
"bytes": "18840"
},
{
"name": "HTML",
"bytes": "664995"
},
{
"name": "Java",
"bytes": "16802174"
},
{
"name": "JavaScript",
"bytes": "3011856"
},
{
"name": "NSIS",
"bytes": "19211"
},
{
"name": "PowerShell",
"bytes": "743"
},
{
"name": "Ruby",
"bytes": "3659389"
},
{
"name": "SQLPL",
"bytes": "9050"
},
{
"name": "Shell",
"bytes": "197638"
},
{
"name": "XSLT",
"bytes": "161277"
}
],
"symlink_target": ""
} |
<?php
/**
* Base class that represents a query for the 'biblio' table.
*
*
*
* @method BiblioQuery orderByAutoctr($order = Criteria::ASC) Order by the autoctr column
* @method BiblioQuery orderByRefno($order = Criteria::ASC) Order by the RefNo column
* @method BiblioQuery orderBySpeccode($order = Criteria::ASC) Order by the SpecCode column
* @method BiblioQuery orderBySyncode($order = Criteria::ASC) Order by the SynCode column
* @method BiblioQuery orderByRefpage($order = Criteria::ASC) Order by the RefPage column
* @method BiblioQuery orderByPagefirst($order = Criteria::ASC) Order by the PageFirst column
* @method BiblioQuery orderByPageinsort($order = Criteria::ASC) Order by the PageInSort column
* @method BiblioQuery orderByLocality($order = Criteria::ASC) Order by the Locality column
* @method BiblioQuery orderByDistribution($order = Criteria::ASC) Order by the Distribution column
* @method BiblioQuery orderByComment($order = Criteria::ASC) Order by the Comment column
* @method BiblioQuery orderByQuote($order = Criteria::ASC) Order by the Quote column
* @method BiblioQuery orderByEntered($order = Criteria::ASC) Order by the Entered column
* @method BiblioQuery orderByDateentered($order = Criteria::ASC) Order by the DateEntered column
* @method BiblioQuery orderByModified($order = Criteria::ASC) Order by the Modified column
* @method BiblioQuery orderByDatemodified($order = Criteria::ASC) Order by the DateModified column
* @method BiblioQuery orderByTs($order = Criteria::ASC) Order by the TS column
*
* @method BiblioQuery groupByAutoctr() Group by the autoctr column
* @method BiblioQuery groupByRefno() Group by the RefNo column
* @method BiblioQuery groupBySpeccode() Group by the SpecCode column
* @method BiblioQuery groupBySyncode() Group by the SynCode column
* @method BiblioQuery groupByRefpage() Group by the RefPage column
* @method BiblioQuery groupByPagefirst() Group by the PageFirst column
* @method BiblioQuery groupByPageinsort() Group by the PageInSort column
* @method BiblioQuery groupByLocality() Group by the Locality column
* @method BiblioQuery groupByDistribution() Group by the Distribution column
* @method BiblioQuery groupByComment() Group by the Comment column
* @method BiblioQuery groupByQuote() Group by the Quote column
* @method BiblioQuery groupByEntered() Group by the Entered column
* @method BiblioQuery groupByDateentered() Group by the DateEntered column
* @method BiblioQuery groupByModified() Group by the Modified column
* @method BiblioQuery groupByDatemodified() Group by the DateModified column
* @method BiblioQuery groupByTs() Group by the TS column
*
* @method BiblioQuery leftJoin($relation) Adds a LEFT JOIN clause to the query
* @method BiblioQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query
* @method BiblioQuery innerJoin($relation) Adds a INNER JOIN clause to the query
*
* @method Biblio findOne(PropelPDO $con = null) Return the first Biblio matching the query
* @method Biblio findOneOrCreate(PropelPDO $con = null) Return the first Biblio matching the query, or a new Biblio object populated from the query conditions when no match is found
*
* @method Biblio findOneByAutoctr(int $autoctr) Return the first Biblio filtered by the autoctr column
* @method Biblio findOneByRefno(int $RefNo) Return the first Biblio filtered by the RefNo column
* @method Biblio findOneBySpeccode(int $SpecCode) Return the first Biblio filtered by the SpecCode column
* @method Biblio findOneBySyncode(int $SynCode) Return the first Biblio filtered by the SynCode column
* @method Biblio findOneByRefpage(string $RefPage) Return the first Biblio filtered by the RefPage column
* @method Biblio findOneByPagefirst(int $PageFirst) Return the first Biblio filtered by the PageFirst column
* @method Biblio findOneByPageinsort(int $PageInSort) Return the first Biblio filtered by the PageInSort column
* @method Biblio findOneByLocality(string $Locality) Return the first Biblio filtered by the Locality column
* @method Biblio findOneByDistribution(string $Distribution) Return the first Biblio filtered by the Distribution column
* @method Biblio findOneByComment(string $Comment) Return the first Biblio filtered by the Comment column
* @method Biblio findOneByQuote(string $Quote) Return the first Biblio filtered by the Quote column
* @method Biblio findOneByEntered(int $Entered) Return the first Biblio filtered by the Entered column
* @method Biblio findOneByDateentered(string $DateEntered) Return the first Biblio filtered by the DateEntered column
* @method Biblio findOneByModified(int $Modified) Return the first Biblio filtered by the Modified column
* @method Biblio findOneByDatemodified(string $DateModified) Return the first Biblio filtered by the DateModified column
* @method Biblio findOneByTs(string $TS) Return the first Biblio filtered by the TS column
*
* @method array findByAutoctr(int $autoctr) Return Biblio objects filtered by the autoctr column
* @method array findByRefno(int $RefNo) Return Biblio objects filtered by the RefNo column
* @method array findBySpeccode(int $SpecCode) Return Biblio objects filtered by the SpecCode column
* @method array findBySyncode(int $SynCode) Return Biblio objects filtered by the SynCode column
* @method array findByRefpage(string $RefPage) Return Biblio objects filtered by the RefPage column
* @method array findByPagefirst(int $PageFirst) Return Biblio objects filtered by the PageFirst column
* @method array findByPageinsort(int $PageInSort) Return Biblio objects filtered by the PageInSort column
* @method array findByLocality(string $Locality) Return Biblio objects filtered by the Locality column
* @method array findByDistribution(string $Distribution) Return Biblio objects filtered by the Distribution column
* @method array findByComment(string $Comment) Return Biblio objects filtered by the Comment column
* @method array findByQuote(string $Quote) Return Biblio objects filtered by the Quote column
* @method array findByEntered(int $Entered) Return Biblio objects filtered by the Entered column
* @method array findByDateentered(string $DateEntered) Return Biblio objects filtered by the DateEntered column
* @method array findByModified(int $Modified) Return Biblio objects filtered by the Modified column
* @method array findByDatemodified(string $DateModified) Return Biblio objects filtered by the DateModified column
* @method array findByTs(string $TS) Return Biblio objects filtered by the TS column
*
* @package propel.generator.fbapp.om
*/
abstract class BaseBiblioQuery extends ModelCriteria
{
/**
* Initializes internal state of BaseBiblioQuery object.
*
* @param string $dbName The dabase name
* @param string $modelName The phpName of a model, e.g. 'Book'
* @param string $modelAlias The alias for the model in this query, e.g. 'b'
*/
public function __construct($dbName = null, $modelName = null, $modelAlias = null)
{
if (null === $dbName) {
$dbName = 'fbapp';
}
if (null === $modelName) {
$modelName = 'Biblio';
}
parent::__construct($dbName, $modelName, $modelAlias);
}
/**
* Returns a new BiblioQuery object.
*
* @param string $modelAlias The alias of a model in the query
* @param BiblioQuery|Criteria $criteria Optional Criteria to build the query from
*
* @return BiblioQuery
*/
public static function create($modelAlias = null, $criteria = null)
{
if ($criteria instanceof BiblioQuery) {
return $criteria;
}
$query = new BiblioQuery(null, null, $modelAlias);
if ($criteria instanceof Criteria) {
$query->mergeWith($criteria);
}
return $query;
}
/**
* Find object by primary key.
* Propel uses the instance pool to skip the database if the object exists.
* Go fast if the query is untouched.
*
* <code>
* $obj = $c->findPk(array(12, 34, 56), $con);
* </code>
*
* @param array $key Primary key to use for the query
A Primary key composition: [$RefNo, $SpecCode, $SynCode]
* @param PropelPDO $con an optional connection object
*
* @return Biblio|Biblio[]|mixed the result, formatted by the current formatter
*/
public function findPk($key, $con = null)
{
if ($key === null) {
return null;
}
if ((null !== ($obj = BiblioPeer::getInstanceFromPool(serialize(array((string) $key[0], (string) $key[1], (string) $key[2]))))) && !$this->formatter) {
// the object is already in the instance pool
return $obj;
}
if ($con === null) {
$con = Propel::getConnection(BiblioPeer::DATABASE_NAME, Propel::CONNECTION_READ);
}
$this->basePreSelect($con);
if ($this->formatter || $this->modelAlias || $this->with || $this->select
|| $this->selectColumns || $this->asColumns || $this->selectModifiers
|| $this->map || $this->having || $this->joins) {
return $this->findPkComplex($key, $con);
} else {
return $this->findPkSimple($key, $con);
}
}
/**
* Find object by primary key using raw SQL to go fast.
* Bypass doSelect() and the object formatter by using generated code.
*
* @param mixed $key Primary key to use for the query
* @param PropelPDO $con A connection object
*
* @return Biblio A model object, or null if the key is not found
* @throws PropelException
*/
protected function findPkSimple($key, $con)
{
$sql = 'SELECT `autoctr`, `RefNo`, `SpecCode`, `SynCode`, `RefPage`, `PageFirst`, `PageInSort`, `Locality`, `Distribution`, `Comment`, `Quote`, `Entered`, `DateEntered`, `Modified`, `DateModified`, `TS` FROM `biblio` WHERE `RefNo` = :p0 AND `SpecCode` = :p1 AND `SynCode` = :p2';
try {
$stmt = $con->prepare($sql);
$stmt->bindValue(':p0', $key[0], PDO::PARAM_INT);
$stmt->bindValue(':p1', $key[1], PDO::PARAM_INT);
$stmt->bindValue(':p2', $key[2], PDO::PARAM_INT);
$stmt->execute();
} catch (Exception $e) {
Propel::log($e->getMessage(), Propel::LOG_ERR);
throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), $e);
}
$obj = null;
if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$obj = new Biblio();
$obj->hydrate($row);
BiblioPeer::addInstanceToPool($obj, serialize(array((string) $key[0], (string) $key[1], (string) $key[2])));
}
$stmt->closeCursor();
return $obj;
}
/**
* Find object by primary key.
*
* @param mixed $key Primary key to use for the query
* @param PropelPDO $con A connection object
*
* @return Biblio|Biblio[]|mixed the result, formatted by the current formatter
*/
protected function findPkComplex($key, $con)
{
// As the query uses a PK condition, no limit(1) is necessary.
$criteria = $this->isKeepQuery() ? clone $this : $this;
$stmt = $criteria
->filterByPrimaryKey($key)
->doSelect($con);
return $criteria->getFormatter()->init($criteria)->formatOne($stmt);
}
/**
* Find objects by primary key
* <code>
* $objs = $c->findPks(array(array(12, 56), array(832, 123), array(123, 456)), $con);
* </code>
* @param array $keys Primary keys to use for the query
* @param PropelPDO $con an optional connection object
*
* @return PropelObjectCollection|Biblio[]|mixed the list of results, formatted by the current formatter
*/
public function findPks($keys, $con = null)
{
if ($con === null) {
$con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ);
}
$this->basePreSelect($con);
$criteria = $this->isKeepQuery() ? clone $this : $this;
$stmt = $criteria
->filterByPrimaryKeys($keys)
->doSelect($con);
return $criteria->getFormatter()->init($criteria)->format($stmt);
}
/**
* Filter the query by primary key
*
* @param mixed $key Primary key to use for the query
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByPrimaryKey($key)
{
$this->addUsingAlias(BiblioPeer::REFNO, $key[0], Criteria::EQUAL);
$this->addUsingAlias(BiblioPeer::SPECCODE, $key[1], Criteria::EQUAL);
$this->addUsingAlias(BiblioPeer::SYNCODE, $key[2], Criteria::EQUAL);
return $this;
}
/**
* Filter the query by a list of primary keys
*
* @param array $keys The list of primary key to use for the query
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByPrimaryKeys($keys)
{
if (empty($keys)) {
return $this->add(null, '1<>1', Criteria::CUSTOM);
}
foreach ($keys as $key) {
$cton0 = $this->getNewCriterion(BiblioPeer::REFNO, $key[0], Criteria::EQUAL);
$cton1 = $this->getNewCriterion(BiblioPeer::SPECCODE, $key[1], Criteria::EQUAL);
$cton0->addAnd($cton1);
$cton2 = $this->getNewCriterion(BiblioPeer::SYNCODE, $key[2], Criteria::EQUAL);
$cton0->addAnd($cton2);
$this->addOr($cton0);
}
return $this;
}
/**
* Filter the query on the autoctr column
*
* Example usage:
* <code>
* $query->filterByAutoctr(1234); // WHERE autoctr = 1234
* $query->filterByAutoctr(array(12, 34)); // WHERE autoctr IN (12, 34)
* $query->filterByAutoctr(array('min' => 12)); // WHERE autoctr >= 12
* $query->filterByAutoctr(array('max' => 12)); // WHERE autoctr <= 12
* </code>
*
* @param mixed $autoctr The value to use as filter.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByAutoctr($autoctr = null, $comparison = null)
{
if (is_array($autoctr)) {
$useMinMax = false;
if (isset($autoctr['min'])) {
$this->addUsingAlias(BiblioPeer::AUTOCTR, $autoctr['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($autoctr['max'])) {
$this->addUsingAlias(BiblioPeer::AUTOCTR, $autoctr['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(BiblioPeer::AUTOCTR, $autoctr, $comparison);
}
/**
* Filter the query on the RefNo column
*
* Example usage:
* <code>
* $query->filterByRefno(1234); // WHERE RefNo = 1234
* $query->filterByRefno(array(12, 34)); // WHERE RefNo IN (12, 34)
* $query->filterByRefno(array('min' => 12)); // WHERE RefNo >= 12
* $query->filterByRefno(array('max' => 12)); // WHERE RefNo <= 12
* </code>
*
* @param mixed $refno The value to use as filter.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByRefno($refno = null, $comparison = null)
{
if (is_array($refno)) {
$useMinMax = false;
if (isset($refno['min'])) {
$this->addUsingAlias(BiblioPeer::REFNO, $refno['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($refno['max'])) {
$this->addUsingAlias(BiblioPeer::REFNO, $refno['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(BiblioPeer::REFNO, $refno, $comparison);
}
/**
* Filter the query on the SpecCode column
*
* Example usage:
* <code>
* $query->filterBySpeccode(1234); // WHERE SpecCode = 1234
* $query->filterBySpeccode(array(12, 34)); // WHERE SpecCode IN (12, 34)
* $query->filterBySpeccode(array('min' => 12)); // WHERE SpecCode >= 12
* $query->filterBySpeccode(array('max' => 12)); // WHERE SpecCode <= 12
* </code>
*
* @param mixed $speccode The value to use as filter.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterBySpeccode($speccode = null, $comparison = null)
{
if (is_array($speccode)) {
$useMinMax = false;
if (isset($speccode['min'])) {
$this->addUsingAlias(BiblioPeer::SPECCODE, $speccode['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($speccode['max'])) {
$this->addUsingAlias(BiblioPeer::SPECCODE, $speccode['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(BiblioPeer::SPECCODE, $speccode, $comparison);
}
/**
* Filter the query on the SynCode column
*
* Example usage:
* <code>
* $query->filterBySyncode(1234); // WHERE SynCode = 1234
* $query->filterBySyncode(array(12, 34)); // WHERE SynCode IN (12, 34)
* $query->filterBySyncode(array('min' => 12)); // WHERE SynCode >= 12
* $query->filterBySyncode(array('max' => 12)); // WHERE SynCode <= 12
* </code>
*
* @param mixed $syncode The value to use as filter.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterBySyncode($syncode = null, $comparison = null)
{
if (is_array($syncode)) {
$useMinMax = false;
if (isset($syncode['min'])) {
$this->addUsingAlias(BiblioPeer::SYNCODE, $syncode['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($syncode['max'])) {
$this->addUsingAlias(BiblioPeer::SYNCODE, $syncode['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(BiblioPeer::SYNCODE, $syncode, $comparison);
}
/**
* Filter the query on the RefPage column
*
* Example usage:
* <code>
* $query->filterByRefpage('fooValue'); // WHERE RefPage = 'fooValue'
* $query->filterByRefpage('%fooValue%'); // WHERE RefPage LIKE '%fooValue%'
* </code>
*
* @param string $refpage The value to use as filter.
* Accepts wildcards (* and % trigger a LIKE)
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByRefpage($refpage = null, $comparison = null)
{
if (null === $comparison) {
if (is_array($refpage)) {
$comparison = Criteria::IN;
} elseif (preg_match('/[\%\*]/', $refpage)) {
$refpage = str_replace('*', '%', $refpage);
$comparison = Criteria::LIKE;
}
}
return $this->addUsingAlias(BiblioPeer::REFPAGE, $refpage, $comparison);
}
/**
* Filter the query on the PageFirst column
*
* Example usage:
* <code>
* $query->filterByPagefirst(1234); // WHERE PageFirst = 1234
* $query->filterByPagefirst(array(12, 34)); // WHERE PageFirst IN (12, 34)
* $query->filterByPagefirst(array('min' => 12)); // WHERE PageFirst >= 12
* $query->filterByPagefirst(array('max' => 12)); // WHERE PageFirst <= 12
* </code>
*
* @param mixed $pagefirst The value to use as filter.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByPagefirst($pagefirst = null, $comparison = null)
{
if (is_array($pagefirst)) {
$useMinMax = false;
if (isset($pagefirst['min'])) {
$this->addUsingAlias(BiblioPeer::PAGEFIRST, $pagefirst['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($pagefirst['max'])) {
$this->addUsingAlias(BiblioPeer::PAGEFIRST, $pagefirst['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(BiblioPeer::PAGEFIRST, $pagefirst, $comparison);
}
/**
* Filter the query on the PageInSort column
*
* Example usage:
* <code>
* $query->filterByPageinsort(1234); // WHERE PageInSort = 1234
* $query->filterByPageinsort(array(12, 34)); // WHERE PageInSort IN (12, 34)
* $query->filterByPageinsort(array('min' => 12)); // WHERE PageInSort >= 12
* $query->filterByPageinsort(array('max' => 12)); // WHERE PageInSort <= 12
* </code>
*
* @param mixed $pageinsort The value to use as filter.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByPageinsort($pageinsort = null, $comparison = null)
{
if (is_array($pageinsort)) {
$useMinMax = false;
if (isset($pageinsort['min'])) {
$this->addUsingAlias(BiblioPeer::PAGEINSORT, $pageinsort['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($pageinsort['max'])) {
$this->addUsingAlias(BiblioPeer::PAGEINSORT, $pageinsort['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(BiblioPeer::PAGEINSORT, $pageinsort, $comparison);
}
/**
* Filter the query on the Locality column
*
* Example usage:
* <code>
* $query->filterByLocality('fooValue'); // WHERE Locality = 'fooValue'
* $query->filterByLocality('%fooValue%'); // WHERE Locality LIKE '%fooValue%'
* </code>
*
* @param string $locality The value to use as filter.
* Accepts wildcards (* and % trigger a LIKE)
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByLocality($locality = null, $comparison = null)
{
if (null === $comparison) {
if (is_array($locality)) {
$comparison = Criteria::IN;
} elseif (preg_match('/[\%\*]/', $locality)) {
$locality = str_replace('*', '%', $locality);
$comparison = Criteria::LIKE;
}
}
return $this->addUsingAlias(BiblioPeer::LOCALITY, $locality, $comparison);
}
/**
* Filter the query on the Distribution column
*
* Example usage:
* <code>
* $query->filterByDistribution('fooValue'); // WHERE Distribution = 'fooValue'
* $query->filterByDistribution('%fooValue%'); // WHERE Distribution LIKE '%fooValue%'
* </code>
*
* @param string $distribution The value to use as filter.
* Accepts wildcards (* and % trigger a LIKE)
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByDistribution($distribution = null, $comparison = null)
{
if (null === $comparison) {
if (is_array($distribution)) {
$comparison = Criteria::IN;
} elseif (preg_match('/[\%\*]/', $distribution)) {
$distribution = str_replace('*', '%', $distribution);
$comparison = Criteria::LIKE;
}
}
return $this->addUsingAlias(BiblioPeer::DISTRIBUTION, $distribution, $comparison);
}
/**
* Filter the query on the Comment column
*
* Example usage:
* <code>
* $query->filterByComment('fooValue'); // WHERE Comment = 'fooValue'
* $query->filterByComment('%fooValue%'); // WHERE Comment LIKE '%fooValue%'
* </code>
*
* @param string $comment The value to use as filter.
* Accepts wildcards (* and % trigger a LIKE)
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByComment($comment = null, $comparison = null)
{
if (null === $comparison) {
if (is_array($comment)) {
$comparison = Criteria::IN;
} elseif (preg_match('/[\%\*]/', $comment)) {
$comment = str_replace('*', '%', $comment);
$comparison = Criteria::LIKE;
}
}
return $this->addUsingAlias(BiblioPeer::COMMENT, $comment, $comparison);
}
/**
* Filter the query on the Quote column
*
* Example usage:
* <code>
* $query->filterByQuote('fooValue'); // WHERE Quote = 'fooValue'
* $query->filterByQuote('%fooValue%'); // WHERE Quote LIKE '%fooValue%'
* </code>
*
* @param string $quote The value to use as filter.
* Accepts wildcards (* and % trigger a LIKE)
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByQuote($quote = null, $comparison = null)
{
if (null === $comparison) {
if (is_array($quote)) {
$comparison = Criteria::IN;
} elseif (preg_match('/[\%\*]/', $quote)) {
$quote = str_replace('*', '%', $quote);
$comparison = Criteria::LIKE;
}
}
return $this->addUsingAlias(BiblioPeer::QUOTE, $quote, $comparison);
}
/**
* Filter the query on the Entered column
*
* Example usage:
* <code>
* $query->filterByEntered(1234); // WHERE Entered = 1234
* $query->filterByEntered(array(12, 34)); // WHERE Entered IN (12, 34)
* $query->filterByEntered(array('min' => 12)); // WHERE Entered >= 12
* $query->filterByEntered(array('max' => 12)); // WHERE Entered <= 12
* </code>
*
* @param mixed $entered The value to use as filter.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByEntered($entered = null, $comparison = null)
{
if (is_array($entered)) {
$useMinMax = false;
if (isset($entered['min'])) {
$this->addUsingAlias(BiblioPeer::ENTERED, $entered['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($entered['max'])) {
$this->addUsingAlias(BiblioPeer::ENTERED, $entered['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(BiblioPeer::ENTERED, $entered, $comparison);
}
/**
* Filter the query on the DateEntered column
*
* Example usage:
* <code>
* $query->filterByDateentered('2011-03-14'); // WHERE DateEntered = '2011-03-14'
* $query->filterByDateentered('now'); // WHERE DateEntered = '2011-03-14'
* $query->filterByDateentered(array('max' => 'yesterday')); // WHERE DateEntered < '2011-03-13'
* </code>
*
* @param mixed $dateentered The value to use as filter.
* Values can be integers (unix timestamps), DateTime objects, or strings.
* Empty strings are treated as NULL.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByDateentered($dateentered = null, $comparison = null)
{
if (is_array($dateentered)) {
$useMinMax = false;
if (isset($dateentered['min'])) {
$this->addUsingAlias(BiblioPeer::DATEENTERED, $dateentered['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($dateentered['max'])) {
$this->addUsingAlias(BiblioPeer::DATEENTERED, $dateentered['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(BiblioPeer::DATEENTERED, $dateentered, $comparison);
}
/**
* Filter the query on the Modified column
*
* Example usage:
* <code>
* $query->filterByModified(1234); // WHERE Modified = 1234
* $query->filterByModified(array(12, 34)); // WHERE Modified IN (12, 34)
* $query->filterByModified(array('min' => 12)); // WHERE Modified >= 12
* $query->filterByModified(array('max' => 12)); // WHERE Modified <= 12
* </code>
*
* @param mixed $modified The value to use as filter.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByModified($modified = null, $comparison = null)
{
if (is_array($modified)) {
$useMinMax = false;
if (isset($modified['min'])) {
$this->addUsingAlias(BiblioPeer::MODIFIED, $modified['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($modified['max'])) {
$this->addUsingAlias(BiblioPeer::MODIFIED, $modified['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(BiblioPeer::MODIFIED, $modified, $comparison);
}
/**
* Filter the query on the DateModified column
*
* Example usage:
* <code>
* $query->filterByDatemodified('2011-03-14'); // WHERE DateModified = '2011-03-14'
* $query->filterByDatemodified('now'); // WHERE DateModified = '2011-03-14'
* $query->filterByDatemodified(array('max' => 'yesterday')); // WHERE DateModified < '2011-03-13'
* </code>
*
* @param mixed $datemodified The value to use as filter.
* Values can be integers (unix timestamps), DateTime objects, or strings.
* Empty strings are treated as NULL.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByDatemodified($datemodified = null, $comparison = null)
{
if (is_array($datemodified)) {
$useMinMax = false;
if (isset($datemodified['min'])) {
$this->addUsingAlias(BiblioPeer::DATEMODIFIED, $datemodified['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($datemodified['max'])) {
$this->addUsingAlias(BiblioPeer::DATEMODIFIED, $datemodified['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(BiblioPeer::DATEMODIFIED, $datemodified, $comparison);
}
/**
* Filter the query on the TS column
*
* Example usage:
* <code>
* $query->filterByTs('2011-03-14'); // WHERE TS = '2011-03-14'
* $query->filterByTs('now'); // WHERE TS = '2011-03-14'
* $query->filterByTs(array('max' => 'yesterday')); // WHERE TS < '2011-03-13'
* </code>
*
* @param mixed $ts The value to use as filter.
* Values can be integers (unix timestamps), DateTime objects, or strings.
* Empty strings are treated as NULL.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return BiblioQuery The current query, for fluid interface
*/
public function filterByTs($ts = null, $comparison = null)
{
if (is_array($ts)) {
$useMinMax = false;
if (isset($ts['min'])) {
$this->addUsingAlias(BiblioPeer::TS, $ts['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($ts['max'])) {
$this->addUsingAlias(BiblioPeer::TS, $ts['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(BiblioPeer::TS, $ts, $comparison);
}
/**
* Exclude object from result
*
* @param Biblio $biblio Object to remove from the list of results
*
* @return BiblioQuery The current query, for fluid interface
*/
public function prune($biblio = null)
{
if ($biblio) {
$this->addCond('pruneCond0', $this->getAliasedColName(BiblioPeer::REFNO), $biblio->getRefno(), Criteria::NOT_EQUAL);
$this->addCond('pruneCond1', $this->getAliasedColName(BiblioPeer::SPECCODE), $biblio->getSpeccode(), Criteria::NOT_EQUAL);
$this->addCond('pruneCond2', $this->getAliasedColName(BiblioPeer::SYNCODE), $biblio->getSyncode(), Criteria::NOT_EQUAL);
$this->combine(array('pruneCond0', 'pruneCond1', 'pruneCond2'), Criteria::LOGICAL_OR);
}
return $this;
}
}
| {
"content_hash": "eb6e11f8ebf1df6023bf384ddd8bfbfe",
"timestamp": "",
"source": "github",
"line_count": 911,
"max_line_length": 287,
"avg_line_length": 42.514818880351264,
"alnum_prop": 0.5899925124577212,
"repo_name": "royrusso/fishbase",
"id": "dbf1d7297d88abd4118a2f28307495cffd32698a",
"size": "38731",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "classes/fbapp/om/BaseBiblioQuery.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "54469"
},
{
"name": "JavaScript",
"bytes": "257574"
},
{
"name": "PHP",
"bytes": "43155398"
}
],
"symlink_target": ""
} |
package com.hello2morrow.sonargraph.integration.access.model;
import com.hello2morrow.sonargraph.integration.access.foundation.IEnumeration;
import com.hello2morrow.sonargraph.integration.access.foundation.Utility;
public enum DependencyPatternType implements IEnumeration
{
WILDCARD,
PARSER_DEPENDENCY_ENDPOINT;
@Override
public String getStandardName()
{
return Utility.convertConstantNameToStandardName(name());
}
@Override
public String getPresentationName()
{
return Utility.convertConstantNameToPresentationName(name());
}
} | {
"content_hash": "6da92994f3a3e5077ccebc4b1fffd569",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 78,
"avg_line_length": 25.695652173913043,
"alnum_prop": 0.7648054145516074,
"repo_name": "sonargraph/sonargraph-integration-access",
"id": "edd1fb517de2b0d2c4fe9ebb4d50cecddc538ca4",
"size": "1272",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/hello2morrow/sonargraph/integration/access/model/DependencyPatternType.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Arc",
"bytes": "1505"
},
{
"name": "Java",
"bytes": "879877"
}
],
"symlink_target": ""
} |
llvm::TargetOptions lld::initTargetOptionsFromCodeGenFlags() {
return ::InitTargetOptionsFromCodeGenFlags();
}
llvm::Optional<llvm::Reloc::Model> lld::getRelocModelFromCMModel() {
return getRelocModel();
}
llvm::Optional<llvm::CodeModel::Model> lld::getCodeModelFromCMModel() {
return getCodeModel();
}
std::string lld::getCPUStr() { return ::getCPUStr(); }
std::vector<std::string> lld::getMAttrs() { return ::MAttrs; }
| {
"content_hash": "eefca6654b67186293722670128c2932",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 71,
"avg_line_length": 28.733333333333334,
"alnum_prop": 0.7331786542923434,
"repo_name": "llvm-mirror/lld",
"id": "0137feb63f371d45669cab7d3939d5d78ca0dbad",
"size": "1540",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Common/TargetOptionsCommandFlags.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "2204226"
},
{
"name": "C++",
"bytes": "2893828"
},
{
"name": "CMake",
"bytes": "20776"
},
{
"name": "LLVM",
"bytes": "416895"
},
{
"name": "Python",
"bytes": "9667"
}
],
"symlink_target": ""
} |
namespace arc {
namespace {
class ArcMidisBridgeTest : public testing::Test {
protected:
ArcMidisBridgeTest()
: bridge_(ArcMidisBridge::GetForBrowserContextForTesting(&context_)) {}
ArcMidisBridgeTest(const ArcMidisBridgeTest&) = delete;
ArcMidisBridgeTest& operator=(const ArcMidisBridgeTest&) = delete;
~ArcMidisBridgeTest() override = default;
ArcMidisBridge* bridge() { return bridge_; }
private:
content::BrowserTaskEnvironment task_environment_;
ArcServiceManager arc_service_manager_;
TestBrowserContext context_;
ArcMidisBridge* const bridge_;
};
TEST_F(ArcMidisBridgeTest, ConstructDestruct) {
EXPECT_NE(nullptr, bridge());
}
} // namespace
} // namespace arc
| {
"content_hash": "2e93bb9d3c0af9465f0b227c9cb7150a",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 77,
"avg_line_length": 27.076923076923077,
"alnum_prop": 0.7514204545454546,
"repo_name": "chromium/chromium",
"id": "d15bc1fc5a36df636cba4c379ee148be47c9c21a",
"size": "1128",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "ash/components/arc/midis/arc_midis_bridge_unittest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?php
namespace Ballybran\Helpers\Security;
/**
* Class Val
* @package Ballybran\Helpers\Security
*/
class Val implements ValInterface
{
public function minlength(string $data, int $length)
{
if (strlen($data) < $length) {
return " (** minlength **) Your string " . $data . " can only be " . $length . " long";
}
}
public function maxlength(string $data, int $length)
{
if (strlen($data) > $length) {
return " (** maxlength **) Your string " . $data . " can only be " . $length . " long";
}
}
public function digit(string $data)
{
if (false == ctype_digit($data)) {
return "Your string " . $data . " must be a digit";
}
}
public function __call(string $name, $arguments)
{
throw new \Exception("$name does not exist inside of: " . __CLASS__);
}
public function isValidLenght(string $lenght, string $data, int $length)
{
if ($this->{$lenght}($data, $length)) {
return $this->{$lenght}($data, $length);
}
}
}
| {
"content_hash": "f2cc9ebdac68f082687632d9b05cd612",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 99,
"avg_line_length": 21.25,
"alnum_prop": 0.5357466063348416,
"repo_name": "knut7/framework",
"id": "d4e92304e66d8ade9ae2861219dca81aba12bfef",
"size": "1737",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Ballybran/Helpers/Security/Val.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "21456"
},
{
"name": "Dockerfile",
"bytes": "1800"
},
{
"name": "HTML",
"bytes": "99290"
},
{
"name": "JavaScript",
"bytes": "104667"
},
{
"name": "PHP",
"bytes": "515842"
}
],
"symlink_target": ""
} |
sudo sed -i '/Type=forking/a Restart=on-failure' /etc/systemd/system/$APPSYSTEMD || { echo -e $RED'Adding TYPE in SYSTEMD file failed.'$ENDCOLOR; exit 1; }
sudo sed -i "s@User=tautulli@User=$UNAME@g" /etc/systemd/system/$APPSYSTEMD || { echo -e $RED'Modifying USER in SYSTEMD file failed.'$ENDCOLOR; exit 1; }
sudo sed -i "s@Group=nogroup@Group=$UGROUP@g" /etc/systemd/system/$APPSYSTEMD || { echo -e $RED'Modifying GROUP in SYSTEMD file failed.'$ENDCOLOR; exit 1; }
sudo systemctl daemon-reload
sudo systemctl enable $APPSYSTEMD
| {
"content_hash": "beb22f982751c1b79297a670c51ecf65",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 157,
"avg_line_length": 89,
"alnum_prop": 0.7284644194756554,
"repo_name": "TommyE123/AtoMiC-ToolKit",
"id": "36fe5c24271060be05978a38fb894ac4bda86e5d",
"size": "593",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tautulli/tautulli-systemd-update.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "436843"
}
],
"symlink_target": ""
} |
<!-- HTML header for doxygen 1.8.18-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.4"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>OR-Tools: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="styleSheet.tmp.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="orLogo.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">OR-Tools
 <span id="projectnumber">9.4</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.4 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
var searchBox = new SearchBox("searchBox", "search",'Search','.html');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
$(document).ready(function(){initNavTree('classoperations__research_1_1glop_1_1_matrix_view.html',''); initResizable(); });
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle"><div class="title">MatrixView Member List</div></div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html">MatrixView</a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html#a7273cc492a51a1c5d45c620b32fce502">column</a>(ColIndex col) const</td><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html">MatrixView</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="odd"><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html#a3f219a081f88c22ae282ada4f0bdddd3">ComputeInfinityNorm</a>() const</td><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html">MatrixView</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html#a64fea3282d498f3eb2d4af70692bb117">ComputeOneNorm</a>() const</td><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html">MatrixView</a></td><td class="entry"></td></tr>
<tr class="odd"><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html#a8e12342fc420701fbffd97025421575a">IsEmpty</a>() const</td><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html">MatrixView</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html#a1f0797ca04f7cb50938328e7e027a18b">MatrixView</a>()</td><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html">MatrixView</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="odd"><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html#ac220f9bed6efccb65c2514e90d702638">MatrixView</a>(const SparseMatrix &matrix)</td><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html">MatrixView</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">explicit</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html#a41741829541d089f1c4d34f190884813">num_cols</a>() const</td><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html">MatrixView</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="odd"><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html#af69d9b7065a8f31604a8134be4307749">num_entries</a>() const</td><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html">MatrixView</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html#a960110e64357a3e69162ebf1f71959dd">num_rows</a>() const</td><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html">MatrixView</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="odd"><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html#adc9aa1d344fe9442ac3ba673b939db7c">PopulateFromBasis</a>(const MatrixView &matrix, const RowToColMapping &basis)</td><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html">MatrixView</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html#a495dfea7028bd3b07c1485d5c66b7001">PopulateFromMatrix</a>(const SparseMatrix &matrix)</td><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html">MatrixView</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="odd"><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html#a87c606b7a9b920de2d4b6aa5c3bc1a45">PopulateFromMatrixPair</a>(const SparseMatrix &matrix_a, const SparseMatrix &matrix_b)</td><td class="entry"><a class="el" href="classoperations__research_1_1glop_1_1_matrix_view.html">MatrixView</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
</table></div><!-- contents -->
</div><!-- doc-content -->
<!-- HTML footer for doxygen 1.8.18-->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.9.4 </li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "d32298f8814091f2108de10129b351f6",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 420,
"avg_line_length": 71.60504201680672,
"alnum_prop": 0.7054336345499355,
"repo_name": "or-tools/docs",
"id": "57e242055bc1296303775698c53fc1e2d01c7d90",
"size": "8521",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "docs/cpp/classoperations__research_1_1glop_1_1_matrix_view-members.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
// Copyright 2016 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.
package org.chromium.chrome.browser.offlinepages.downloads;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Browser;
import androidx.browser.customtabs.CustomTabsIntent;
import org.chromium.base.ApplicationStatus;
import org.chromium.base.ContextUtils;
import org.chromium.base.IntentUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.chrome.browser.ChromeTabbedActivity;
import org.chromium.chrome.browser.IntentHandler;
import org.chromium.chrome.browser.LaunchIntentDispatcher;
import org.chromium.chrome.browser.app.download.home.DownloadActivity;
import org.chromium.chrome.browser.browserservices.intents.BrowserServicesIntentDataProvider.CustomTabsUiType;
import org.chromium.chrome.browser.customtabs.CustomTabIntentDataProvider;
import org.chromium.chrome.browser.download.DownloadManagerService;
import org.chromium.chrome.browser.offlinepages.OfflinePageOrigin;
import org.chromium.chrome.browser.offlinepages.OfflinePageUtils;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tab.TabLaunchType;
import org.chromium.chrome.browser.tabmodel.AsyncTabCreationParams;
import org.chromium.chrome.browser.tabmodel.document.TabDelegate;
import org.chromium.components.offline_items_collection.LaunchLocation;
import org.chromium.content_public.browser.LoadUrlParams;
/**
* Serves as an interface between Download Home UI and offline page related items that are to be
* displayed in the downloads UI.
*/
@JNINamespace("offline_pages::android")
public class OfflinePageDownloadBridge {
private static OfflinePageDownloadBridge sInstance;
private static boolean sIsTesting;
private long mNativeOfflinePageDownloadBridge;
/**
* @return An {@link OfflinePageDownloadBridge} instance singleton. If one
* is not available this will create a new one.
*/
public static OfflinePageDownloadBridge getInstance() {
if (sInstance == null) {
sInstance = new OfflinePageDownloadBridge();
}
return sInstance;
}
private OfflinePageDownloadBridge() {
mNativeOfflinePageDownloadBridge = sIsTesting
? 0L
: OfflinePageDownloadBridgeJni.get().init(OfflinePageDownloadBridge.this);
}
/** Destroys the native portion of the bridge. */
public void destroy() {
if (mNativeOfflinePageDownloadBridge != 0) {
OfflinePageDownloadBridgeJni.get().destroy(
mNativeOfflinePageDownloadBridge, OfflinePageDownloadBridge.this);
mNativeOfflinePageDownloadBridge = 0;
}
}
/**
* 'Opens' the offline page identified by the given URL and offlineId by navigating to the saved
* local snapshot. No automatic redirection is happening based on the connection status. If the
* item with specified GUID is not found or can't be opened, nothing happens.
*/
@CalledByNative
private static void openItem(final String url, final long offlineId, final int location,
final boolean isIncognito, final boolean openInCct) {
OfflinePageUtils.getLoadUrlParamsForOpeningOfflineVersion(
url, offlineId, location, (params) -> {
if (params == null) return;
boolean openingFromDownloadsHome =
ApplicationStatus.getLastTrackedFocusedActivity()
instanceof DownloadActivity;
if (location == LaunchLocation.NET_ERROR_SUGGESTION) {
openItemInCurrentTab(offlineId, params);
} else if (openInCct && openingFromDownloadsHome) {
openItemInCct(offlineId, params, isIncognito);
} else {
openItemInNewTab(offlineId, params, isIncognito);
}
}, Profile.getLastUsedRegularProfile());
}
/**
* Opens the offline page identified by the given offlineId and the LoadUrlParams in the current
* tab. If no tab is current, the page is not opened.
*/
private static void openItemInCurrentTab(long offlineId, LoadUrlParams params) {
Activity activity = ApplicationStatus.getLastTrackedFocusedActivity();
if (activity == null) return;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(params.getUrl()));
IntentHandler.setIntentExtraHeaders(params.getExtraHeaders(), intent);
intent.putExtra(
Browser.EXTRA_APPLICATION_ID, activity.getApplicationContext().getPackageName());
intent.setPackage(activity.getApplicationContext().getPackageName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
IntentHandler.startActivityForTrustedIntent(intent);
}
/**
* Opens the offline page identified by the given offlineId and the LoadUrlParams in a new tab.
*/
private static void openItemInNewTab(
long offlineId, LoadUrlParams params, boolean isIncognito) {
ComponentName componentName = getComponentName();
AsyncTabCreationParams asyncParams = componentName == null
? new AsyncTabCreationParams(params)
: new AsyncTabCreationParams(params, componentName);
final TabDelegate tabDelegate = new TabDelegate(isIncognito);
tabDelegate.createNewTab(asyncParams, TabLaunchType.FROM_CHROME_UI, Tab.INVALID_TAB_ID);
}
/**
* Opens the offline page identified by the given offlineId and the LoadUrlParams in a CCT.
*/
private static void openItemInCct(long offlineId, LoadUrlParams params, boolean isIncognito) {
final Context context;
if (ApplicationStatus.hasVisibleActivities()) {
context = ApplicationStatus.getLastTrackedFocusedActivity();
} else {
context = ContextUtils.getApplicationContext();
}
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setShowTitle(true);
builder.addDefaultShareMenuItem();
CustomTabsIntent customTabIntent = builder.build();
customTabIntent.intent.setData(Uri.parse(params.getUrl()));
Intent intent = LaunchIntentDispatcher.createCustomTabActivityIntent(
context, customTabIntent.intent);
intent.setPackage(context.getPackageName());
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
intent.putExtra(CustomTabIntentDataProvider.EXTRA_UI_TYPE, CustomTabsUiType.OFFLINE_PAGE);
// TODO(crbug.com/1148275): Pass isIncognito boolean here after finding a way not to
// reload the downloaded page for Incognito CCT.
intent.putExtra(IntentHandler.EXTRA_OPEN_NEW_INCOGNITO_TAB, false);
IntentUtils.addTrustedIntentExtras(intent);
if (!(context instanceof Activity)) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
IntentHandler.setIntentExtraHeaders(params.getExtraHeaders(), intent);
context.startActivity(intent);
}
/**
* Starts download of the page currently open in the specified Tab.
* If tab's contents are not yet loaded completely, we'll wait for it
* to load enough for snapshot to be reasonable. If the Chrome is made
* background and killed, the background request remains that will
* eventually load the page in background and obtain its offline
* snapshot.
*
* @param tab a tab contents of which will be saved locally.
* @param origin the object encapsulating application origin of the request.
*/
public static void startDownload(Tab tab, OfflinePageOrigin origin) {
OfflinePageDownloadBridgeJni.get().startDownload(tab, origin.encodeAsJsonString());
}
/**
* Shows a "Downloading ..." toast for the requested items already scheduled for download.
*/
@CalledByNative
public static void showDownloadingToast() {
DownloadManagerService.getDownloadManagerService()
.getMessageUiController(/*otrProfileID=*/null)
.onDownloadStarted();
}
/**
* Method to ensure that the bridge is created for tests without calling the native portion of
* initialization.
* @param isTesting flag indicating whether the constructor will initialize native code.
*/
static void setIsTesting(boolean isTesting) {
sIsTesting = isTesting;
}
private static ComponentName getComponentName() {
if (!ApplicationStatus.hasVisibleActivities()) return null;
Activity activity = ApplicationStatus.getLastTrackedFocusedActivity();
if (activity instanceof ChromeTabbedActivity) {
return activity.getComponentName();
}
return null;
}
@NativeMethods
interface Natives {
long init(OfflinePageDownloadBridge caller);
void destroy(long nativeOfflinePageDownloadBridge, OfflinePageDownloadBridge caller);
void startDownload(Tab tab, String origin);
}
}
| {
"content_hash": "dcf8dbef04444149dc554373e8be43c5",
"timestamp": "",
"source": "github",
"line_count": 214,
"max_line_length": 110,
"avg_line_length": 44.30373831775701,
"alnum_prop": 0.7085750448264951,
"repo_name": "scheib/chromium",
"id": "a2ef8e85ee4af89e650b4330ac82b04da1fc0a9f",
"size": "9481",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "chrome/android/java/src/org/chromium/chrome/browser/offlinepages/downloads/OfflinePageDownloadBridge.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package archive
import xtime "go-common/library/time"
// const ArcReport
const (
ArcReportNew = int8(0)
ArcReportReject = int8(1)
ArcReportAccept = int8(2)
)
// ArcReport archive_report
type ArcReport struct {
Mid int64 `json:"mid"`
Aid int64 `json:"aid"`
Type int8 `json:"type"`
Reason string `json:"reason"`
Pics string `json:"pics"`
State int8 `json:"state"`
CTime xtime.Time `json:"ctime"`
MTime xtime.Time `json:"-"`
}
| {
"content_hash": "756bdcfe2d3bff2da3f38a563e54be64",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 37,
"avg_line_length": 22.045454545454547,
"alnum_prop": 0.6309278350515464,
"repo_name": "LQJJ/demo",
"id": "0f330aebebffec437fd16ab1fe3441a39869e53e",
"size": "485",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "126-go-common-master/app/service/main/videoup/model/archive/report.go",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5910716"
},
{
"name": "C++",
"bytes": "113072"
},
{
"name": "CSS",
"bytes": "10791"
},
{
"name": "Dockerfile",
"bytes": "934"
},
{
"name": "Go",
"bytes": "40121403"
},
{
"name": "Groovy",
"bytes": "347"
},
{
"name": "HTML",
"bytes": "359263"
},
{
"name": "JavaScript",
"bytes": "545384"
},
{
"name": "Makefile",
"bytes": "6671"
},
{
"name": "Mathematica",
"bytes": "14565"
},
{
"name": "Objective-C",
"bytes": "14900720"
},
{
"name": "Objective-C++",
"bytes": "20070"
},
{
"name": "PureBasic",
"bytes": "4152"
},
{
"name": "Python",
"bytes": "4490569"
},
{
"name": "Ruby",
"bytes": "44850"
},
{
"name": "Shell",
"bytes": "33251"
},
{
"name": "Swift",
"bytes": "463286"
},
{
"name": "TSQL",
"bytes": "108861"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<link href="../../JavaScript-ConsoleStyle/JavaScript-ConsoleStyle.css" rel="stylesheet" />
<title>Exchange Values</title>
</head>
<body>
<div>
<label for="first-number">Enter first number:</label>
<input type="text" id="first-number"/>
<label for="second-number">Enter second number:</label>
<input type="text" id="second-number"/>
<button id="check">Check</button>
</div>
<div id="js-console"></div>
<script src="../../JavaScript-Console/JavaScript-ConsoleScript.js"></script>
<script src="ExchangeValues.js"></script>
</body>
</html> | {
"content_hash": "fa8888afdcc85f2b32a3303813940ed8",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 94,
"avg_line_length": 31.5,
"alnum_prop": 0.6634920634920635,
"repo_name": "AdrianApostolov/TelerikAcademy",
"id": "c24ffe772b950c208b262c8d7592bcdaeeedf951",
"size": "630",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Homeworks/JavaScriptFundamentals/03.ConditionalStatements/01.ExchangeValues/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "21510"
},
{
"name": "C#",
"bytes": "1819391"
},
{
"name": "CSS",
"bytes": "158896"
},
{
"name": "HTML",
"bytes": "6010402"
},
{
"name": "JavaScript",
"bytes": "1395750"
},
{
"name": "Python",
"bytes": "3523"
},
{
"name": "SQLPL",
"bytes": "941"
},
{
"name": "Shell",
"bytes": "111"
},
{
"name": "XSLT",
"bytes": "3922"
}
],
"symlink_target": ""
} |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jbehave.desktop</groupId>
<artifactId>jbehave-desktop</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>org.jbehave.desktop</groupId>
<artifactId>jbehave-desktop-examples</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Jbehave-Desktop Examples</name>
<packaging>pom</packaging>
<description>Examples of using Jbehave-Desktop</description>
<properties>
<jbehave.version>3.3-SNAPSHOT</jbehave.version>
</properties>
<modules>
<module>desktop-example-swing-calculator</module>
</modules>
<developers>
<developer>
<id>cvgaviao</id>
<name>Cristiano Gavião</name>
<email>cvgaviao@gmail.com</email>
<timezone>-3</timezone>
</developer>
</developers>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.jbehave</groupId>
<artifactId>jbehave-maven-plugin</artifactId>
<version>${jbehave.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project> | {
"content_hash": "706205fc0ce52bfb47c79aecb9775fef",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 104,
"avg_line_length": 27.818181818181817,
"alnum_prop": 0.7116013071895425,
"repo_name": "fraisse/jbehave-desktop",
"id": "2c851b4386f252da844852d73a28ca8ef1b1fb0b",
"size": "1225",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "desktop-examples/pom.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package containerregistry
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// BuildTasksClient is the client for the BuildTasks methods of the Containerregistry service.
type BuildTasksClient struct {
BaseClient
}
// NewBuildTasksClient creates an instance of the BuildTasksClient client.
func NewBuildTasksClient(subscriptionID string) BuildTasksClient {
return NewBuildTasksClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewBuildTasksClientWithBaseURI creates an instance of the BuildTasksClient client.
func NewBuildTasksClientWithBaseURI(baseURI string, subscriptionID string) BuildTasksClient {
return BuildTasksClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Create creates a build task for a container registry with the specified parameters.
// Parameters:
// resourceGroupName - the name of the resource group to which the container registry belongs.
// registryName - the name of the container registry.
// buildTaskName - the name of the container registry build task.
// buildTaskCreateParameters - the parameters for creating a build task.
func (client BuildTasksClient) Create(ctx context.Context, resourceGroupName string, registryName string, buildTaskName string, buildTaskCreateParameters BuildTask) (result BuildTasksCreateFuture, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: registryName,
Constraints: []validation.Constraint{{Target: "registryName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "registryName", Name: validation.MinLength, Rule: 5, Chain: nil},
{Target: "registryName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}},
{TargetValue: buildTaskName,
Constraints: []validation.Constraint{{Target: "buildTaskName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "buildTaskName", Name: validation.MinLength, Rule: 5, Chain: nil},
{Target: "buildTaskName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}},
{TargetValue: buildTaskCreateParameters,
Constraints: []validation.Constraint{{Target: "buildTaskCreateParameters.BuildTaskProperties", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "buildTaskCreateParameters.BuildTaskProperties.Alias", Name: validation.Null, Rule: true, Chain: nil},
{Target: "buildTaskCreateParameters.BuildTaskProperties.SourceRepository", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "buildTaskCreateParameters.BuildTaskProperties.SourceRepository.RepositoryURL", Name: validation.Null, Rule: true, Chain: nil},
{Target: "buildTaskCreateParameters.BuildTaskProperties.SourceRepository.SourceControlAuthProperties", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "buildTaskCreateParameters.BuildTaskProperties.SourceRepository.SourceControlAuthProperties.Token", Name: validation.Null, Rule: true, Chain: nil}}},
}},
{Target: "buildTaskCreateParameters.BuildTaskProperties.Platform", Name: validation.Null, Rule: true, Chain: nil},
{Target: "buildTaskCreateParameters.BuildTaskProperties.Timeout", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "buildTaskCreateParameters.BuildTaskProperties.Timeout", Name: validation.InclusiveMaximum, Rule: 28800, Chain: nil},
{Target: "buildTaskCreateParameters.BuildTaskProperties.Timeout", Name: validation.InclusiveMinimum, Rule: 300, Chain: nil},
}},
}}}}}); err != nil {
return result, validation.NewError("containerregistry.BuildTasksClient", "Create", err.Error())
}
req, err := client.CreatePreparer(ctx, resourceGroupName, registryName, buildTaskName, buildTaskCreateParameters)
if err != nil {
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "Create", nil, "Failure preparing request")
return
}
result, err = client.CreateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "Create", result.Response(), "Failure sending request")
return
}
return
}
// CreatePreparer prepares the Create request.
func (client BuildTasksClient) CreatePreparer(ctx context.Context, resourceGroupName string, registryName string, buildTaskName string, buildTaskCreateParameters BuildTask) (*http.Request, error) {
pathParameters := map[string]interface{}{
"buildTaskName": autorest.Encode("path", buildTaskName),
"registryName": autorest.Encode("path", registryName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/buildTasks/{buildTaskName}", pathParameters),
autorest.WithJSON(buildTaskCreateParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client BuildTasksClient) CreateSender(req *http.Request) (future BuildTasksCreateFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
return
}
// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client BuildTasksClient) CreateResponder(resp *http.Response) (result BuildTask, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes a specified build task.
// Parameters:
// resourceGroupName - the name of the resource group to which the container registry belongs.
// registryName - the name of the container registry.
// buildTaskName - the name of the container registry build task.
func (client BuildTasksClient) Delete(ctx context.Context, resourceGroupName string, registryName string, buildTaskName string) (result BuildTasksDeleteFuture, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: registryName,
Constraints: []validation.Constraint{{Target: "registryName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "registryName", Name: validation.MinLength, Rule: 5, Chain: nil},
{Target: "registryName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}},
{TargetValue: buildTaskName,
Constraints: []validation.Constraint{{Target: "buildTaskName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "buildTaskName", Name: validation.MinLength, Rule: 5, Chain: nil},
{Target: "buildTaskName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("containerregistry.BuildTasksClient", "Delete", err.Error())
}
req, err := client.DeletePreparer(ctx, resourceGroupName, registryName, buildTaskName)
if err != nil {
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "Delete", nil, "Failure preparing request")
return
}
result, err = client.DeleteSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "Delete", result.Response(), "Failure sending request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client BuildTasksClient) DeletePreparer(ctx context.Context, resourceGroupName string, registryName string, buildTaskName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"buildTaskName": autorest.Encode("path", buildTaskName),
"registryName": autorest.Encode("path", registryName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/buildTasks/{buildTaskName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client BuildTasksClient) DeleteSender(req *http.Request) (future BuildTasksDeleteFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
return
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client BuildTasksClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get get the properties of a specified build task.
// Parameters:
// resourceGroupName - the name of the resource group to which the container registry belongs.
// registryName - the name of the container registry.
// buildTaskName - the name of the container registry build task.
func (client BuildTasksClient) Get(ctx context.Context, resourceGroupName string, registryName string, buildTaskName string) (result BuildTask, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: registryName,
Constraints: []validation.Constraint{{Target: "registryName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "registryName", Name: validation.MinLength, Rule: 5, Chain: nil},
{Target: "registryName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}},
{TargetValue: buildTaskName,
Constraints: []validation.Constraint{{Target: "buildTaskName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "buildTaskName", Name: validation.MinLength, Rule: 5, Chain: nil},
{Target: "buildTaskName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("containerregistry.BuildTasksClient", "Get", err.Error())
}
req, err := client.GetPreparer(ctx, resourceGroupName, registryName, buildTaskName)
if err != nil {
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client BuildTasksClient) GetPreparer(ctx context.Context, resourceGroupName string, registryName string, buildTaskName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"buildTaskName": autorest.Encode("path", buildTaskName),
"registryName": autorest.Encode("path", registryName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/buildTasks/{buildTaskName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client BuildTasksClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client BuildTasksClient) GetResponder(resp *http.Response) (result BuildTask, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List lists all the build tasks for a specified container registry.
// Parameters:
// resourceGroupName - the name of the resource group to which the container registry belongs.
// registryName - the name of the container registry.
// filter - the build task filter to apply on the operation.
// skipToken - $skipToken is supported on get list of build tasks, which provides the next page in the list of
// tasks.
func (client BuildTasksClient) List(ctx context.Context, resourceGroupName string, registryName string, filter string, skipToken string) (result BuildTaskListResultPage, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: registryName,
Constraints: []validation.Constraint{{Target: "registryName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "registryName", Name: validation.MinLength, Rule: 5, Chain: nil},
{Target: "registryName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("containerregistry.BuildTasksClient", "List", err.Error())
}
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx, resourceGroupName, registryName, filter, skipToken)
if err != nil {
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.btlr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "List", resp, "Failure sending request")
return
}
result.btlr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client BuildTasksClient) ListPreparer(ctx context.Context, resourceGroupName string, registryName string, filter string, skipToken string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"registryName": autorest.Encode("path", registryName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if len(filter) > 0 {
queryParameters["$filter"] = autorest.Encode("query", filter)
}
if len(skipToken) > 0 {
queryParameters["$skipToken"] = autorest.Encode("query", skipToken)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/buildTasks", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client BuildTasksClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client BuildTasksClient) ListResponder(resp *http.Response) (result BuildTaskListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client BuildTasksClient) listNextResults(lastResults BuildTaskListResult) (result BuildTaskListResult, err error) {
req, err := lastResults.buildTaskListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client BuildTasksClient) ListComplete(ctx context.Context, resourceGroupName string, registryName string, filter string, skipToken string) (result BuildTaskListResultIterator, err error) {
result.page, err = client.List(ctx, resourceGroupName, registryName, filter, skipToken)
return
}
// ListSourceRepositoryProperties get the source control properties for a build task.
// Parameters:
// resourceGroupName - the name of the resource group to which the container registry belongs.
// registryName - the name of the container registry.
// buildTaskName - the name of the container registry build task.
func (client BuildTasksClient) ListSourceRepositoryProperties(ctx context.Context, resourceGroupName string, registryName string, buildTaskName string) (result SourceRepositoryProperties, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: registryName,
Constraints: []validation.Constraint{{Target: "registryName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "registryName", Name: validation.MinLength, Rule: 5, Chain: nil},
{Target: "registryName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}},
{TargetValue: buildTaskName,
Constraints: []validation.Constraint{{Target: "buildTaskName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "buildTaskName", Name: validation.MinLength, Rule: 5, Chain: nil},
{Target: "buildTaskName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("containerregistry.BuildTasksClient", "ListSourceRepositoryProperties", err.Error())
}
req, err := client.ListSourceRepositoryPropertiesPreparer(ctx, resourceGroupName, registryName, buildTaskName)
if err != nil {
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "ListSourceRepositoryProperties", nil, "Failure preparing request")
return
}
resp, err := client.ListSourceRepositoryPropertiesSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "ListSourceRepositoryProperties", resp, "Failure sending request")
return
}
result, err = client.ListSourceRepositoryPropertiesResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "ListSourceRepositoryProperties", resp, "Failure responding to request")
}
return
}
// ListSourceRepositoryPropertiesPreparer prepares the ListSourceRepositoryProperties request.
func (client BuildTasksClient) ListSourceRepositoryPropertiesPreparer(ctx context.Context, resourceGroupName string, registryName string, buildTaskName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"buildTaskName": autorest.Encode("path", buildTaskName),
"registryName": autorest.Encode("path", registryName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/buildTasks/{buildTaskName}/listSourceRepositoryProperties", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSourceRepositoryPropertiesSender sends the ListSourceRepositoryProperties request. The method will close the
// http.Response Body if it receives an error.
func (client BuildTasksClient) ListSourceRepositoryPropertiesSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListSourceRepositoryPropertiesResponder handles the response to the ListSourceRepositoryProperties request. The method always
// closes the http.Response Body.
func (client BuildTasksClient) ListSourceRepositoryPropertiesResponder(resp *http.Response) (result SourceRepositoryProperties, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Update updates a build task with the specified parameters.
// Parameters:
// resourceGroupName - the name of the resource group to which the container registry belongs.
// registryName - the name of the container registry.
// buildTaskName - the name of the container registry build task.
// buildTaskUpdateParameters - the parameters for updating a build task.
func (client BuildTasksClient) Update(ctx context.Context, resourceGroupName string, registryName string, buildTaskName string, buildTaskUpdateParameters BuildTaskUpdateParameters) (result BuildTasksUpdateFuture, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: registryName,
Constraints: []validation.Constraint{{Target: "registryName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "registryName", Name: validation.MinLength, Rule: 5, Chain: nil},
{Target: "registryName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}},
{TargetValue: buildTaskName,
Constraints: []validation.Constraint{{Target: "buildTaskName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "buildTaskName", Name: validation.MinLength, Rule: 5, Chain: nil},
{Target: "buildTaskName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("containerregistry.BuildTasksClient", "Update", err.Error())
}
req, err := client.UpdatePreparer(ctx, resourceGroupName, registryName, buildTaskName, buildTaskUpdateParameters)
if err != nil {
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "Update", nil, "Failure preparing request")
return
}
result, err = client.UpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "containerregistry.BuildTasksClient", "Update", result.Response(), "Failure sending request")
return
}
return
}
// UpdatePreparer prepares the Update request.
func (client BuildTasksClient) UpdatePreparer(ctx context.Context, resourceGroupName string, registryName string, buildTaskName string, buildTaskUpdateParameters BuildTaskUpdateParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"buildTaskName": autorest.Encode("path", buildTaskName),
"registryName": autorest.Encode("path", registryName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPatch(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/buildTasks/{buildTaskName}", pathParameters),
autorest.WithJSON(buildTaskUpdateParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client BuildTasksClient) UpdateSender(req *http.Request) (future BuildTasksUpdateFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
return
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client BuildTasksClient) UpdateResponder(resp *http.Response) (result BuildTask, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| {
"content_hash": "7d31654cd8354f917d15a3c5dc581e8c",
"timestamp": "",
"source": "github",
"line_count": 583,
"max_line_length": 238,
"avg_line_length": 48.23670668953688,
"alnum_prop": 0.7662328426143233,
"repo_name": "seuffert/rclone",
"id": "ade76f52bcb19c9faf13d5f39eb549e84914cc2c",
"size": "28122",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/github.com/Azure/azure-sdk-for-go/services/preview/containerregistry/mgmt/2018-02-01/containerregistry/buildtasks.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "258"
},
{
"name": "Go",
"bytes": "2003268"
},
{
"name": "HTML",
"bytes": "493675"
},
{
"name": "Makefile",
"bytes": "7245"
},
{
"name": "Python",
"bytes": "6913"
},
{
"name": "Roff",
"bytes": "446311"
},
{
"name": "Shell",
"bytes": "2612"
}
],
"symlink_target": ""
} |
package org.apache.nifi.processors.aws.sqs;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.nifi.annotation.behavior.DynamicProperty;
import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.annotation.behavior.InputRequirement.Requirement;
import org.apache.nifi.annotation.behavior.SupportsBatching;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.SeeAlso;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.expression.ExpressionLanguageScope;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.util.StandardValidators;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.MessageAttributeValue;
import com.amazonaws.services.sqs.model.SendMessageBatchRequest;
import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry;
@SupportsBatching
@SeeAlso({ GetSQS.class, DeleteSQS.class })
@InputRequirement(Requirement.INPUT_REQUIRED)
@Tags({"Amazon", "AWS", "SQS", "Queue", "Put", "Publish"})
@CapabilityDescription("Publishes a message to an Amazon Simple Queuing Service Queue")
@DynamicProperty(name = "The name of a Message Attribute to add to the message", value = "The value of the Message Attribute",
description = "Allows the user to add key/value pairs as Message Attributes by adding a property whose name will become the name of "
+ "the Message Attribute and value will become the value of the Message Attribute", expressionLanguageScope = ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
public class PutSQS extends AbstractSQSProcessor {
public static final PropertyDescriptor DELAY = new PropertyDescriptor.Builder()
.name("Delay")
.description("The amount of time to delay the message before it becomes available to consumers")
.required(true)
.addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
.defaultValue("0 secs")
.build();
public static final List<PropertyDescriptor> properties = Collections.unmodifiableList(
Arrays.asList(QUEUE_URL, ACCESS_KEY, SECRET_KEY, CREDENTIALS_FILE, AWS_CREDENTIALS_PROVIDER_SERVICE,
REGION, DELAY, TIMEOUT, ENDPOINT_OVERRIDE, PROXY_HOST, PROXY_HOST_PORT));
private volatile List<PropertyDescriptor> userDefinedProperties = Collections.emptyList();
@Override
protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
return properties;
}
@Override
protected PropertyDescriptor getSupportedDynamicPropertyDescriptor(final String propertyDescriptorName) {
return new PropertyDescriptor.Builder()
.name(propertyDescriptorName)
.expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
.required(false)
.dynamic(true)
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.build();
}
@OnScheduled
public void setup(final ProcessContext context) {
userDefinedProperties = new ArrayList<>();
for (final PropertyDescriptor descriptor : context.getProperties().keySet()) {
if (descriptor.isDynamic()) {
userDefinedProperties.add(descriptor);
}
}
}
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
FlowFile flowFile = session.get();
if (flowFile == null) {
return;
}
final long startNanos = System.nanoTime();
final AmazonSQSClient client = getClient();
final SendMessageBatchRequest request = new SendMessageBatchRequest();
final String queueUrl = context.getProperty(QUEUE_URL).evaluateAttributeExpressions(flowFile).getValue();
request.setQueueUrl(queueUrl);
final Set<SendMessageBatchRequestEntry> entries = new HashSet<>();
final SendMessageBatchRequestEntry entry = new SendMessageBatchRequestEntry();
entry.setId(flowFile.getAttribute("uuid"));
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
session.exportTo(flowFile, baos);
final String flowFileContent = baos.toString();
entry.setMessageBody(flowFileContent);
final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
for (final PropertyDescriptor descriptor : userDefinedProperties) {
final MessageAttributeValue mav = new MessageAttributeValue();
mav.setDataType("String");
mav.setStringValue(context.getProperty(descriptor).evaluateAttributeExpressions(flowFile).getValue());
messageAttributes.put(descriptor.getName(), mav);
}
entry.setMessageAttributes(messageAttributes);
entry.setDelaySeconds(context.getProperty(DELAY).asTimePeriod(TimeUnit.SECONDS).intValue());
entries.add(entry);
request.setEntries(entries);
try {
client.sendMessageBatch(request);
} catch (final Exception e) {
getLogger().error("Failed to send messages to Amazon SQS due to {}; routing to failure", new Object[]{e});
flowFile = session.penalize(flowFile);
session.transfer(flowFile, REL_FAILURE);
return;
}
getLogger().info("Successfully published message to Amazon SQS for {}", new Object[]{flowFile});
session.transfer(flowFile, REL_SUCCESS);
final long transmissionMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
session.getProvenanceReporter().send(flowFile, queueUrl, transmissionMillis);
}
}
| {
"content_hash": "d7676780d2a8b58560cfa5559c70aeda",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 162,
"avg_line_length": 45.21897810218978,
"alnum_prop": 0.7228410008071025,
"repo_name": "apsaltis/nifi",
"id": "cfa32b412826918b2689cf93680178c1e2e122eb",
"size": "6996",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/sqs/PutSQS.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "20273"
},
{
"name": "CSS",
"bytes": "225299"
},
{
"name": "Clojure",
"bytes": "3993"
},
{
"name": "Dockerfile",
"bytes": "9921"
},
{
"name": "GAP",
"bytes": "30034"
},
{
"name": "Groovy",
"bytes": "1831015"
},
{
"name": "HTML",
"bytes": "574828"
},
{
"name": "Java",
"bytes": "35278353"
},
{
"name": "JavaScript",
"bytes": "2861994"
},
{
"name": "Lua",
"bytes": "983"
},
{
"name": "Python",
"bytes": "17954"
},
{
"name": "Ruby",
"bytes": "8028"
},
{
"name": "Shell",
"bytes": "80669"
},
{
"name": "XSLT",
"bytes": "5681"
}
],
"symlink_target": ""
} |
package v6_test
import (
"errors"
"code.cloudfoundry.org/cli/actor/actionerror"
"code.cloudfoundry.org/cli/actor/v3action"
"code.cloudfoundry.org/cli/api/cloudcontroller/ccversion"
"code.cloudfoundry.org/cli/command/commandfakes"
"code.cloudfoundry.org/cli/command/flag"
"code.cloudfoundry.org/cli/command/translatableerror"
. "code.cloudfoundry.org/cli/command/v6"
"code.cloudfoundry.org/cli/command/v6/v6fakes"
"code.cloudfoundry.org/cli/util/configv3"
"code.cloudfoundry.org/cli/util/ui"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gbytes"
)
var _ = Describe("v3-restart-app-instance Command", func() {
var (
cmd V3RestartAppInstanceCommand
testUI *ui.UI
fakeConfig *commandfakes.FakeConfig
fakeSharedActor *commandfakes.FakeSharedActor
fakeActor *v6fakes.FakeV3RestartAppInstanceActor
binaryName string
processType string
executeErr error
app string
)
BeforeEach(func() {
testUI = ui.NewTestUI(nil, NewBuffer(), NewBuffer())
fakeConfig = new(commandfakes.FakeConfig)
fakeSharedActor = new(commandfakes.FakeSharedActor)
fakeActor = new(v6fakes.FakeV3RestartAppInstanceActor)
binaryName = "faceman"
fakeConfig.BinaryNameReturns(binaryName)
app = "some-app"
processType = "some-special-type"
cmd = V3RestartAppInstanceCommand{
RequiredArgs: flag.AppInstance{AppName: app, Index: 6},
ProcessType: processType,
UI: testUI,
Config: fakeConfig,
SharedActor: fakeSharedActor,
Actor: fakeActor,
}
})
JustBeforeEach(func() {
executeErr = cmd.Execute(nil)
})
When("the API version is below the minimum", func() {
BeforeEach(func() {
fakeActor.CloudControllerAPIVersionReturns(ccversion.MinV3ClientVersion)
})
It("returns a MinimumAPIVersionNotMetError", func() {
Expect(executeErr).To(MatchError(translatableerror.MinimumCFAPIVersionNotMetError{
CurrentVersion: ccversion.MinV3ClientVersion,
MinimumVersion: ccversion.MinVersionApplicationFlowV3,
}))
})
It("displays the experimental warning", func() {
Expect(testUI.Err).To(Say("This command is in EXPERIMENTAL stage and may change without notice"))
})
})
When("checking target fails", func() {
BeforeEach(func() {
fakeActor.CloudControllerAPIVersionReturns(ccversion.MinVersionApplicationFlowV3)
fakeSharedActor.CheckTargetReturns(actionerror.NoOrganizationTargetedError{BinaryName: binaryName})
})
It("returns an error", func() {
Expect(executeErr).To(MatchError(actionerror.NoOrganizationTargetedError{BinaryName: binaryName}))
Expect(fakeSharedActor.CheckTargetCallCount()).To(Equal(1))
checkTargetedOrg, checkTargetedSpace := fakeSharedActor.CheckTargetArgsForCall(0)
Expect(checkTargetedOrg).To(BeTrue())
Expect(checkTargetedSpace).To(BeTrue())
})
})
When("the user is not logged in", func() {
var expectedErr error
BeforeEach(func() {
fakeActor.CloudControllerAPIVersionReturns(ccversion.MinVersionApplicationFlowV3)
expectedErr = errors.New("some current user error")
fakeConfig.CurrentUserReturns(configv3.User{}, expectedErr)
})
It("return an error", func() {
Expect(executeErr).To(Equal(expectedErr))
})
})
When("the user is logged in", func() {
BeforeEach(func() {
fakeActor.CloudControllerAPIVersionReturns(ccversion.MinVersionApplicationFlowV3)
fakeConfig.TargetedOrganizationReturns(configv3.Organization{
Name: "some-org",
})
fakeConfig.TargetedSpaceReturns(configv3.Space{
Name: "some-space",
GUID: "some-space-guid",
})
fakeConfig.CurrentUserReturns(configv3.User{Name: "steve"}, nil)
})
When("restarting the specified instance returns an error", func() {
BeforeEach(func() {
fakeActor.DeleteInstanceByApplicationNameSpaceProcessTypeAndIndexReturns(v3action.Warnings{"some-warning"}, errors.New("some-error"))
})
It("displays all warnings and returns the error", func() {
Expect(executeErr).To(MatchError("some-error"))
Expect(testUI.Out).To(Say("Restarting instance 6 of process some-special-type of app some-app in org some-org / space some-space as steve"))
Expect(testUI.Err).To(Say("some-warning"))
})
})
When("restarting the specified instance succeeds", func() {
BeforeEach(func() {
fakeActor.DeleteInstanceByApplicationNameSpaceProcessTypeAndIndexReturns(v3action.Warnings{"some-warning"}, nil)
})
It("deletes application process instance", func() {
Expect(fakeActor.DeleteInstanceByApplicationNameSpaceProcessTypeAndIndexCallCount()).To(Equal(1))
appName, spaceGUID, pType, index := fakeActor.DeleteInstanceByApplicationNameSpaceProcessTypeAndIndexArgsForCall(0)
Expect(appName).To(Equal(app))
Expect(spaceGUID).To(Equal("some-space-guid"))
Expect(pType).To(Equal("some-special-type"))
Expect(index).To(Equal(6))
})
It("displays all warnings and OK", func() {
Expect(executeErr).ToNot(HaveOccurred())
Expect(testUI.Out).To(Say("Restarting instance 6 of process some-special-type of app some-app in org some-org / space some-space as steve"))
Expect(testUI.Out).To(Say("OK"))
Expect(testUI.Err).To(Say("some-warning"))
})
})
})
})
| {
"content_hash": "c0d223c6a3e04a6b29c9b1d2f4acad28",
"timestamp": "",
"source": "github",
"line_count": 156,
"max_line_length": 144,
"avg_line_length": 33.6025641025641,
"alnum_prop": 0.733689431514689,
"repo_name": "odlp/antifreeze",
"id": "0b661a50fe29abaee31d80f1e6044877f8911321",
"size": "5242",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/github.com/cloudfoundry/cli/command/v6/v3_restart_app_instance_command_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "10174"
},
{
"name": "Shell",
"bytes": "1077"
}
],
"symlink_target": ""
} |
package org.joda.time;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.joda.time.chrono.BuddhistChronology;
import org.joda.time.chrono.CopticChronology;
import org.joda.time.chrono.GJChronology;
import org.joda.time.chrono.GregorianChronology;
import org.joda.time.chrono.ISOChronology;
import org.joda.time.chrono.LenientChronology;
import org.joda.time.chrono.StrictChronology;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/**
* This class is a Junit unit test for LocalDate.
*
* @author Stephen Colebourne
*/
public class TestLocalDate_Basics extends TestCase {
private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris");
private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London");
private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo");
private static final DateTimeZone NEW_YORK = DateTimeZone.forID("America/New_York");
// private static final int OFFSET = 1;
private static final GJChronology GJ_UTC = GJChronology.getInstanceUTC();
private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS);
private static final Chronology COPTIC_LONDON = CopticChronology.getInstance(LONDON);
private static final Chronology COPTIC_TOKYO = CopticChronology.getInstance(TOKYO);
private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC();
// private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS);
private static final Chronology ISO_LONDON = ISOChronology.getInstance(LONDON);
private static final Chronology ISO_NEW_YORK = ISOChronology.getInstance(NEW_YORK);
// private static final Chronology ISO_TOKYO = ISOChronology.getInstance(TOKYO);
// private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC();
private static final Chronology BUDDHIST_PARIS = BuddhistChronology.getInstance(PARIS);
private static final Chronology BUDDHIST_LONDON = BuddhistChronology.getInstance(LONDON);
private static final Chronology BUDDHIST_TOKYO = BuddhistChronology.getInstance(TOKYO);
// private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC();
/** Mock zone simulating Asia/Gaza cutover at midnight 2007-04-01 */
private static long CUTOVER_GAZA = 1175378400000L;
private static int OFFSET_GAZA = 7200000; // +02:00
private static final DateTimeZone MOCK_GAZA = new MockZone(CUTOVER_GAZA, OFFSET_GAZA, 3600);
private long TEST_TIME_NOW =
(31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY;
// private long TEST_TIME1 =
// (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY
// + 12L * DateTimeConstants.MILLIS_PER_HOUR
// + 24L * DateTimeConstants.MILLIS_PER_MINUTE;
//
// private long TEST_TIME2 =
// (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY
// + 14L * DateTimeConstants.MILLIS_PER_HOUR
// + 28L * DateTimeConstants.MILLIS_PER_MINUTE;
private DateTimeZone zone = null;
private Locale systemDefaultLocale = null;
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static TestSuite suite() {
return new TestSuite(TestLocalDate_Basics.class);
}
public TestLocalDate_Basics(String name) {
super(name);
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
zone = DateTimeZone.getDefault();
DateTimeZone.setDefault(LONDON);
systemDefaultLocale = Locale.getDefault();
Locale.setDefault(Locale.ENGLISH);
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(zone);
zone = null;
Locale.setDefault(systemDefaultLocale);
systemDefaultLocale = null;
}
//-----------------------------------------------------------------------
public void testGet_DateTimeFieldType() {
LocalDate test = new LocalDate();
assertEquals(1970, test.get(DateTimeFieldType.year()));
assertEquals(6, test.get(DateTimeFieldType.monthOfYear()));
assertEquals(9, test.get(DateTimeFieldType.dayOfMonth()));
assertEquals(2, test.get(DateTimeFieldType.dayOfWeek()));
assertEquals(160, test.get(DateTimeFieldType.dayOfYear()));
assertEquals(24, test.get(DateTimeFieldType.weekOfWeekyear()));
assertEquals(1970, test.get(DateTimeFieldType.weekyear()));
try {
test.get(null);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.get(DateTimeFieldType.hourOfDay());
fail();
} catch (IllegalArgumentException ex) {}
}
public void testSize() {
LocalDate test = new LocalDate();
assertEquals(3, test.size());
}
public void testGetFieldType_int() {
LocalDate test = new LocalDate(COPTIC_PARIS);
assertSame(DateTimeFieldType.year(), test.getFieldType(0));
assertSame(DateTimeFieldType.monthOfYear(), test.getFieldType(1));
assertSame(DateTimeFieldType.dayOfMonth(), test.getFieldType(2));
try {
test.getFieldType(-1);
} catch (IndexOutOfBoundsException ex) {}
try {
test.getFieldType(3);
} catch (IndexOutOfBoundsException ex) {}
}
public void testGetFieldTypes() {
LocalDate test = new LocalDate(COPTIC_PARIS);
DateTimeFieldType[] fields = test.getFieldTypes();
assertSame(DateTimeFieldType.year(), fields[0]);
assertSame(DateTimeFieldType.monthOfYear(), fields[1]);
assertSame(DateTimeFieldType.dayOfMonth(), fields[2]);
assertNotSame(test.getFieldTypes(), test.getFieldTypes());
}
public void testGetField_int() {
LocalDate test = new LocalDate(COPTIC_PARIS);
assertSame(COPTIC_UTC.year(), test.getField(0));
assertSame(COPTIC_UTC.monthOfYear(), test.getField(1));
assertSame(COPTIC_UTC.dayOfMonth(), test.getField(2));
try {
test.getField(-1);
} catch (IndexOutOfBoundsException ex) {}
try {
test.getField(3);
} catch (IndexOutOfBoundsException ex) {}
}
public void testGetFields() {
LocalDate test = new LocalDate(COPTIC_PARIS);
DateTimeField[] fields = test.getFields();
assertSame(COPTIC_UTC.year(), fields[0]);
assertSame(COPTIC_UTC.monthOfYear(), fields[1]);
assertSame(COPTIC_UTC.dayOfMonth(), fields[2]);
assertNotSame(test.getFields(), test.getFields());
}
public void testGetValue_int() {
LocalDate test = new LocalDate();
assertEquals(1970, test.getValue(0));
assertEquals(6, test.getValue(1));
assertEquals(9, test.getValue(2));
try {
test.getValue(-1);
} catch (IndexOutOfBoundsException ex) {}
try {
test.getValue(3);
} catch (IndexOutOfBoundsException ex) {}
}
public void testGetValues() {
LocalDate test = new LocalDate();
int[] values = test.getValues();
assertEquals(1970, values[0]);
assertEquals(6, values[1]);
assertEquals(9, values[2]);
assertNotSame(test.getValues(), test.getValues());
}
public void testIsSupported_DateTimeFieldType() {
LocalDate test = new LocalDate(COPTIC_PARIS);
assertEquals(true, test.isSupported(DateTimeFieldType.year()));
assertEquals(true, test.isSupported(DateTimeFieldType.monthOfYear()));
assertEquals(true, test.isSupported(DateTimeFieldType.dayOfMonth()));
assertEquals(true, test.isSupported(DateTimeFieldType.dayOfWeek()));
assertEquals(true, test.isSupported(DateTimeFieldType.dayOfYear()));
assertEquals(true, test.isSupported(DateTimeFieldType.weekOfWeekyear()));
assertEquals(true, test.isSupported(DateTimeFieldType.weekyear()));
assertEquals(true, test.isSupported(DateTimeFieldType.yearOfCentury()));
assertEquals(true, test.isSupported(DateTimeFieldType.yearOfEra()));
assertEquals(true, test.isSupported(DateTimeFieldType.centuryOfEra()));
assertEquals(true, test.isSupported(DateTimeFieldType.weekyearOfCentury()));
assertEquals(true, test.isSupported(DateTimeFieldType.era()));
assertEquals(false, test.isSupported(DateTimeFieldType.hourOfDay()));
assertEquals(false, test.isSupported((DateTimeFieldType) null));
}
public void testIsSupported_DurationFieldType() {
LocalDate test = new LocalDate(1970, 6, 9);
assertEquals(false, test.isSupported(DurationFieldType.eras()));
assertEquals(true, test.isSupported(DurationFieldType.centuries()));
assertEquals(true, test.isSupported(DurationFieldType.years()));
assertEquals(true, test.isSupported(DurationFieldType.months()));
assertEquals(true, test.isSupported(DurationFieldType.weekyears()));
assertEquals(true, test.isSupported(DurationFieldType.weeks()));
assertEquals(true, test.isSupported(DurationFieldType.days()));
assertEquals(false, test.isSupported(DurationFieldType.hours()));
assertEquals(false, test.isSupported((DurationFieldType) null));
}
@SuppressWarnings("deprecation")
public void testEqualsHashCode() {
LocalDate test1 = new LocalDate(1970, 6, 9, COPTIC_PARIS);
LocalDate test2 = new LocalDate(1970, 6, 9, COPTIC_PARIS);
assertEquals(true, test1.equals(test2));
assertEquals(true, test2.equals(test1));
assertEquals(true, test1.equals(test1));
assertEquals(true, test2.equals(test2));
assertEquals(true, test1.hashCode() == test2.hashCode());
assertEquals(true, test1.hashCode() == test1.hashCode());
assertEquals(true, test2.hashCode() == test2.hashCode());
LocalDate test3 = new LocalDate(1971, 6, 9);
assertEquals(false, test1.equals(test3));
assertEquals(false, test2.equals(test3));
assertEquals(false, test3.equals(test1));
assertEquals(false, test3.equals(test2));
assertEquals(false, test1.hashCode() == test3.hashCode());
assertEquals(false, test2.hashCode() == test3.hashCode());
assertEquals(false, test1.equals("Hello"));
assertEquals(true, test1.equals(new MockInstant()));
assertEquals(true, test1.equals(new YearMonthDay(1970, 6, 9, COPTIC_PARIS)));
assertEquals(true, test1.hashCode() == new YearMonthDay(1970, 6, 9, COPTIC_PARIS).hashCode());
assertEquals(false, test1.equals(MockPartial.EMPTY_INSTANCE));
}
class MockInstant extends MockPartial {
public Chronology getChronology() {
return COPTIC_UTC;
}
public DateTimeField[] getFields() {
return new DateTimeField[] {
COPTIC_UTC.year(),
COPTIC_UTC.monthOfYear(),
COPTIC_UTC.dayOfMonth(),
};
}
public int[] getValues() {
return new int[] {1970, 6, 9};
}
}
public void testEqualsHashCodeLenient() {
LocalDate test1 = new LocalDate(1970, 6, 9, LenientChronology.getInstance(COPTIC_PARIS));
LocalDate test2 = new LocalDate(1970, 6, 9, LenientChronology.getInstance(COPTIC_PARIS));
assertEquals(true, test1.equals(test2));
assertEquals(true, test2.equals(test1));
assertEquals(true, test1.equals(test1));
assertEquals(true, test2.equals(test2));
assertEquals(true, test1.hashCode() == test2.hashCode());
assertEquals(true, test1.hashCode() == test1.hashCode());
assertEquals(true, test2.hashCode() == test2.hashCode());
}
public void testEqualsHashCodeStrict() {
LocalDate test1 = new LocalDate(1970, 6, 9, StrictChronology.getInstance(COPTIC_PARIS));
LocalDate test2 = new LocalDate(1970, 6, 9, StrictChronology.getInstance(COPTIC_PARIS));
assertEquals(true, test1.equals(test2));
assertEquals(true, test2.equals(test1));
assertEquals(true, test1.equals(test1));
assertEquals(true, test2.equals(test2));
assertEquals(true, test1.hashCode() == test2.hashCode());
assertEquals(true, test1.hashCode() == test1.hashCode());
assertEquals(true, test2.hashCode() == test2.hashCode());
}
public void testEqualsHashCodeAPI() {
LocalDate test = new LocalDate(1970, 6, 9, COPTIC_PARIS);
int expected = 157;
expected = 23 * expected + 1970;
expected = 23 * expected + COPTIC_UTC.year().getType().hashCode();
expected = 23 * expected + 6;
expected = 23 * expected + COPTIC_UTC.monthOfYear().getType().hashCode();
expected = 23 * expected + 9;
expected = 23 * expected + COPTIC_UTC.dayOfMonth().getType().hashCode();
expected += COPTIC_UTC.hashCode();
assertEquals(expected, test.hashCode());
}
//-----------------------------------------------------------------------
@SuppressWarnings("deprecation")
public void testCompareTo() {
LocalDate test1 = new LocalDate(2005, 6, 2);
LocalDate test1a = new LocalDate(2005, 6, 2);
assertEquals(0, test1.compareTo(test1a));
assertEquals(0, test1a.compareTo(test1));
assertEquals(0, test1.compareTo(test1));
assertEquals(0, test1a.compareTo(test1a));
LocalDate test2 = new LocalDate(2005, 7, 2);
assertEquals(-1, test1.compareTo(test2));
assertEquals(+1, test2.compareTo(test1));
LocalDate test3 = new LocalDate(2005, 7, 2, GregorianChronology.getInstanceUTC());
assertEquals(-1, test1.compareTo(test3));
assertEquals(+1, test3.compareTo(test1));
assertEquals(0, test3.compareTo(test2));
DateTimeFieldType[] types = new DateTimeFieldType[] {
DateTimeFieldType.year(),
DateTimeFieldType.monthOfYear(),
DateTimeFieldType.dayOfMonth(),
};
int[] values = new int[] {2005, 6, 2};
Partial p = new Partial(types, values);
assertEquals(0, test1.compareTo(p));
assertEquals(0, test1.compareTo(new YearMonthDay(2005, 6, 2)));
try {
test1.compareTo(null);
fail();
} catch (NullPointerException ex) {}
// try {
// test1.compareTo(new Date());
// fail();
// } catch (ClassCastException ex) {}
try {
test1.compareTo(new TimeOfDay());
fail();
} catch (ClassCastException ex) {}
Partial partial = new Partial()
.with(DateTimeFieldType.centuryOfEra(), 1)
.with(DateTimeFieldType.halfdayOfDay(), 0)
.with(DateTimeFieldType.dayOfMonth(), 9);
try {
new LocalDate(1970, 6, 9).compareTo(partial);
fail();
} catch (ClassCastException ex) {}
}
//-----------------------------------------------------------------------
public void testIsEqual_LocalDate() {
LocalDate test1 = new LocalDate(2005, 6, 2);
LocalDate test1a = new LocalDate(2005, 6, 2);
assertEquals(true, test1.isEqual(test1a));
assertEquals(true, test1a.isEqual(test1));
assertEquals(true, test1.isEqual(test1));
assertEquals(true, test1a.isEqual(test1a));
LocalDate test2 = new LocalDate(2005, 7, 2);
assertEquals(false, test1.isEqual(test2));
assertEquals(false, test2.isEqual(test1));
LocalDate test3 = new LocalDate(2005, 7, 2, GregorianChronology.getInstanceUTC());
assertEquals(false, test1.isEqual(test3));
assertEquals(false, test3.isEqual(test1));
assertEquals(true, test3.isEqual(test2));
try {
new LocalDate(2005, 7, 2).isEqual(null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testIsBefore_LocalDate() {
LocalDate test1 = new LocalDate(2005, 6, 2);
LocalDate test1a = new LocalDate(2005, 6, 2);
assertEquals(false, test1.isBefore(test1a));
assertEquals(false, test1a.isBefore(test1));
assertEquals(false, test1.isBefore(test1));
assertEquals(false, test1a.isBefore(test1a));
LocalDate test2 = new LocalDate(2005, 7, 2);
assertEquals(true, test1.isBefore(test2));
assertEquals(false, test2.isBefore(test1));
LocalDate test3 = new LocalDate(2005, 7, 2, GregorianChronology.getInstanceUTC());
assertEquals(true, test1.isBefore(test3));
assertEquals(false, test3.isBefore(test1));
assertEquals(false, test3.isBefore(test2));
try {
new LocalDate(2005, 7, 2).isBefore(null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testIsAfter_LocalDate() {
LocalDate test1 = new LocalDate(2005, 6, 2);
LocalDate test1a = new LocalDate(2005, 6, 2);
assertEquals(false, test1.isAfter(test1a));
assertEquals(false, test1a.isAfter(test1));
assertEquals(false, test1.isAfter(test1));
assertEquals(false, test1a.isAfter(test1a));
LocalDate test2 = new LocalDate(2005, 7, 2);
assertEquals(false, test1.isAfter(test2));
assertEquals(true, test2.isAfter(test1));
LocalDate test3 = new LocalDate(2005, 7, 2, GregorianChronology.getInstanceUTC());
assertEquals(false, test1.isAfter(test3));
assertEquals(true, test3.isAfter(test1));
assertEquals(false, test3.isAfter(test2));
try {
new LocalDate(2005, 7, 2).isAfter(null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testWithField_DateTimeFieldType_int_1() {
LocalDate test = new LocalDate(2004, 6, 9);
LocalDate result = test.withField(DateTimeFieldType.year(), 2006);
assertEquals(new LocalDate(2004, 6, 9), test);
assertEquals(new LocalDate(2006, 6, 9), result);
}
public void testWithField_DateTimeFieldType_int_2() {
LocalDate test = new LocalDate(2004, 6, 9);
try {
test.withField(null, 6);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithField_DateTimeFieldType_int_3() {
LocalDate test = new LocalDate(2004, 6, 9);
try {
test.withField(DateTimeFieldType.hourOfDay(), 6);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithField_DateTimeFieldType_int_4() {
LocalDate test = new LocalDate(2004, 6, 9);
LocalDate result = test.withField(DateTimeFieldType.year(), 2004);
assertEquals(new LocalDate(2004, 6, 9), test);
assertSame(test, result);
}
//-----------------------------------------------------------------------
public void testWithFieldAdded_DurationFieldType_int_1() {
LocalDate test = new LocalDate(2004, 6, 9);
LocalDate result = test.withFieldAdded(DurationFieldType.years(), 6);
assertEquals(new LocalDate(2004, 6, 9), test);
assertEquals(new LocalDate(2010, 6, 9), result);
}
public void testWithFieldAdded_DurationFieldType_int_2() {
LocalDate test = new LocalDate(2004, 6, 9);
try {
test.withFieldAdded(null, 0);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithFieldAdded_DurationFieldType_int_3() {
LocalDate test = new LocalDate(2004, 6, 9);
try {
test.withFieldAdded(null, 6);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithFieldAdded_DurationFieldType_int_4() {
LocalDate test = new LocalDate(2004, 6, 9);
LocalDate result = test.withFieldAdded(DurationFieldType.years(), 0);
assertSame(test, result);
}
public void testWithFieldAdded_DurationFieldType_int_5() {
LocalDate test = new LocalDate(2004, 6, 9);
try {
test.withFieldAdded(DurationFieldType.hours(), 6);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testPlus_RP() {
LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
LocalDate result = test.plus(new Period(1, 2, 3, 4, 29, 6, 7, 8));
LocalDate expected = new LocalDate(2003, 7, 28, BUDDHIST_LONDON);
assertEquals(expected, result);
result = test.plus((ReadablePeriod) null);
assertSame(test, result);
}
public void testPlusYears_int() {
LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
LocalDate result = test.plusYears(1);
LocalDate expected = new LocalDate(2003, 5, 3, BUDDHIST_LONDON);
assertEquals(expected, result);
result = test.plusYears(0);
assertSame(test, result);
}
public void testPlusMonths_int() {
LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
LocalDate result = test.plusMonths(1);
LocalDate expected = new LocalDate(2002, 6, 3, BUDDHIST_LONDON);
assertEquals(expected, result);
result = test.plusMonths(0);
assertSame(test, result);
}
public void testPlusWeeks_int() {
LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
LocalDate result = test.plusWeeks(1);
LocalDate expected = new LocalDate(2002, 5, 10, BUDDHIST_LONDON);
assertEquals(expected, result);
result = test.plusWeeks(0);
assertSame(test, result);
}
public void testPlusDays_int() {
LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
LocalDate result = test.plusDays(1);
LocalDate expected = new LocalDate(2002, 5, 4, BUDDHIST_LONDON);
assertEquals(expected, result);
result = test.plusDays(0);
assertSame(test, result);
}
//-----------------------------------------------------------------------
public void testMinus_RP() {
LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
LocalDate result = test.minus(new Period(1, 1, 1, 1, 1, 1, 1, 1));
// TODO breaks because it subtracts millis now, and thus goes
// into the previous day
LocalDate expected = new LocalDate(2001, 3, 26, BUDDHIST_LONDON);
assertEquals(expected, result);
result = test.minus((ReadablePeriod) null);
assertSame(test, result);
}
public void testMinusYears_int() {
LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
LocalDate result = test.minusYears(1);
LocalDate expected = new LocalDate(2001, 5, 3, BUDDHIST_LONDON);
assertEquals(expected, result);
result = test.minusYears(0);
assertSame(test, result);
}
public void testMinusMonths_int() {
LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
LocalDate result = test.minusMonths(1);
LocalDate expected = new LocalDate(2002, 4, 3, BUDDHIST_LONDON);
assertEquals(expected, result);
result = test.minusMonths(0);
assertSame(test, result);
}
public void testMinusWeeks_int() {
LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
LocalDate result = test.minusWeeks(1);
LocalDate expected = new LocalDate(2002, 4, 26, BUDDHIST_LONDON);
assertEquals(expected, result);
result = test.minusWeeks(0);
assertSame(test, result);
}
public void testMinusDays_int() {
LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON);
LocalDate result = test.minusDays(1);
LocalDate expected = new LocalDate(2002, 5, 2, BUDDHIST_LONDON);
assertEquals(expected, result);
result = test.minusDays(0);
assertSame(test, result);
}
//-----------------------------------------------------------------------
public void testGetters() {
LocalDate test = new LocalDate(1970, 6, 9, GJ_UTC);
assertEquals(1970, test.getYear());
assertEquals(6, test.getMonthOfYear());
assertEquals(9, test.getDayOfMonth());
assertEquals(160, test.getDayOfYear());
assertEquals(2, test.getDayOfWeek());
assertEquals(24, test.getWeekOfWeekyear());
assertEquals(1970, test.getWeekyear());
assertEquals(70, test.getYearOfCentury());
assertEquals(20, test.getCenturyOfEra());
assertEquals(1970, test.getYearOfEra());
assertEquals(DateTimeConstants.AD, test.getEra());
}
//-----------------------------------------------------------------------
public void testWithers() {
LocalDate test = new LocalDate(1970, 6, 9, GJ_UTC);
check(test.withYear(2000), 2000, 6, 9);
check(test.withMonthOfYear(2), 1970, 2, 9);
check(test.withDayOfMonth(2), 1970, 6, 2);
check(test.withDayOfYear(6), 1970, 1, 6);
check(test.withDayOfWeek(6), 1970, 6, 13);
check(test.withWeekOfWeekyear(6), 1970, 2, 3);
check(test.withWeekyear(1971), 1971, 6, 15);
check(test.withYearOfCentury(60), 1960, 6, 9);
check(test.withCenturyOfEra(21), 2070, 6, 9);
check(test.withYearOfEra(1066), 1066, 6, 9);
check(test.withEra(DateTimeConstants.BC), -1970, 6, 9);
try {
test.withMonthOfYear(0);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.withMonthOfYear(13);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testToDateTimeAtStartOfDay() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);
DateTime test = base.toDateTimeAtStartOfDay();
check(base, 2005, 6, 9);
assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_LONDON), test);
}
public void testToDateTimeAtStartOfDay_avoidDST() {
LocalDate base = new LocalDate(2007, 4, 1);
DateTimeZone.setDefault(MOCK_GAZA);
DateTime test = base.toDateTimeAtStartOfDay();
check(base, 2007, 4, 1);
assertEquals(new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_GAZA), test);
}
//-----------------------------------------------------------------------
public void testToDateTimeAtStartOfDay_Zone() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);
DateTime test = base.toDateTimeAtStartOfDay(TOKYO);
check(base, 2005, 6, 9);
assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_TOKYO), test);
}
public void testToDateTimeAtStartOfDay_Zone_avoidDST() {
LocalDate base = new LocalDate(2007, 4, 1);
DateTime test = base.toDateTimeAtStartOfDay(MOCK_GAZA);
check(base, 2007, 4, 1);
assertEquals(new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_GAZA), test);
}
public void testToDateTimeAtStartOfDay_nullZone() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);
DateTime test = base.toDateTimeAtStartOfDay((DateTimeZone) null);
check(base, 2005, 6, 9);
assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_LONDON), test);
}
//-----------------------------------------------------------------------
@SuppressWarnings("deprecation")
public void testToDateTimeAtMidnight() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);
DateTime test = base.toDateTimeAtMidnight();
check(base, 2005, 6, 9);
assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_LONDON), test);
}
//-----------------------------------------------------------------------
@SuppressWarnings("deprecation")
public void testToDateTimeAtMidnight_Zone() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);
DateTime test = base.toDateTimeAtMidnight(TOKYO);
check(base, 2005, 6, 9);
assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_TOKYO), test);
}
@SuppressWarnings("deprecation")
public void testToDateTimeAtMidnight_nullZone() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);
DateTime test = base.toDateTimeAtMidnight((DateTimeZone) null);
check(base, 2005, 6, 9);
assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_LONDON), test);
}
//-----------------------------------------------------------------------
public void testToDateTimeAtCurrentTime() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9);
DateTimeUtils.setCurrentMillisFixed(dt.getMillis());
DateTime test = base.toDateTimeAtCurrentTime();
check(base, 2005, 6, 9);
DateTime expected = new DateTime(dt.getMillis(), COPTIC_LONDON);
expected = expected.year().setCopy(2005);
expected = expected.monthOfYear().setCopy(6);
expected = expected.dayOfMonth().setCopy(9);
assertEquals(expected, test);
}
//-----------------------------------------------------------------------
public void testToDateTimeAtCurrentTime_Zone() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9);
DateTimeUtils.setCurrentMillisFixed(dt.getMillis());
DateTime test = base.toDateTimeAtCurrentTime(TOKYO);
check(base, 2005, 6, 9);
DateTime expected = new DateTime(dt.getMillis(), COPTIC_TOKYO);
expected = expected.year().setCopy(2005);
expected = expected.monthOfYear().setCopy(6);
expected = expected.dayOfMonth().setCopy(9);
assertEquals(expected, test);
}
public void testToDateTimeAtCurrentTime_nullZone() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9);
DateTimeUtils.setCurrentMillisFixed(dt.getMillis());
DateTime test = base.toDateTimeAtCurrentTime((DateTimeZone) null);
check(base, 2005, 6, 9);
DateTime expected = new DateTime(dt.getMillis(), COPTIC_LONDON);
expected = expected.year().setCopy(2005);
expected = expected.monthOfYear().setCopy(6);
expected = expected.dayOfMonth().setCopy(9);
assertEquals(expected, test);
}
//-----------------------------------------------------------------------
public void testToLocalDateTime_LocalTime() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
LocalTime tod = new LocalTime(12, 13, 14, 15, COPTIC_TOKYO);
LocalDateTime test = base.toLocalDateTime(tod);
check(base, 2005, 6, 9);
LocalDateTime expected = new LocalDateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_UTC);
assertEquals(expected, test);
}
public void testToLocalDateTime_nullLocalTime() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
try {
base.toLocalDateTime((LocalTime) null);
fail();
} catch (IllegalArgumentException ex) {
// expected
}
}
public void testToLocalDateTime_wrongChronologyLocalTime() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
LocalTime tod = new LocalTime(12, 13, 14, 15, BUDDHIST_PARIS); // PARIS irrelevant
try {
base.toLocalDateTime(tod);
fail();
} catch (IllegalArgumentException ex) {
// expected
}
}
//-----------------------------------------------------------------------
public void testToDateTime_LocalTime() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
LocalTime tod = new LocalTime(12, 13, 14, 15, COPTIC_TOKYO);
DateTime test = base.toDateTime(tod);
check(base, 2005, 6, 9);
DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_LONDON);
assertEquals(expected, test);
}
public void testToDateTime_nullLocalTime() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
long now = new DateTime(2004, 5, 8, 12, 13, 14, 15, COPTIC_LONDON).getMillis();
DateTimeUtils.setCurrentMillisFixed(now);
DateTime test = base.toDateTime((LocalTime) null);
check(base, 2005, 6, 9);
DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_LONDON);
assertEquals(expected, test);
}
//-----------------------------------------------------------------------
public void testToDateTime_LocalTime_Zone() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
LocalTime tod = new LocalTime(12, 13, 14, 15, COPTIC_TOKYO);
DateTime test = base.toDateTime(tod, TOKYO);
check(base, 2005, 6, 9);
DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_TOKYO);
assertEquals(expected, test);
}
public void testToDateTime_LocalTime_nullZone() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
LocalTime tod = new LocalTime(12, 13, 14, 15, COPTIC_TOKYO);
DateTime test = base.toDateTime(tod, null);
check(base, 2005, 6, 9);
DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_LONDON);
assertEquals(expected, test);
}
public void testToDateTime_nullLocalTime_Zone() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
long now = new DateTime(2004, 5, 8, 12, 13, 14, 15, COPTIC_TOKYO).getMillis();
DateTimeUtils.setCurrentMillisFixed(now);
DateTime test = base.toDateTime((LocalTime) null, TOKYO);
check(base, 2005, 6, 9);
DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_TOKYO);
assertEquals(expected, test);
}
public void testToDateTime_LocalTime_Zone_dstGap() {
LocalDate base = new LocalDate(2014, 3, 30, ISO_LONDON);
LocalTime tod = new LocalTime(1, 30, 0, 0, ISO_LONDON);
try {
base.toDateTime(tod, LONDON);
fail();
} catch (IllegalInstantException ex) {}
}
public void testToDateTime_LocalTime_Zone_dstOverlap() {
LocalDate base = new LocalDate(2014, 10, 26, ISO_LONDON);
LocalTime tod = new LocalTime(1, 30, 0, 0, ISO_LONDON);
DateTime test = base.toDateTime(tod, LONDON);
DateTime expected = new DateTime(2014, 10, 26, 1, 30, ISO_LONDON).withEarlierOffsetAtOverlap();
assertEquals(expected, test);
}
public void testToDateTime_LocalTime_Zone_dstOverlap_NewYork() {
LocalDate base = new LocalDate(2007, 11, 4, ISO_NEW_YORK);
LocalTime tod = new LocalTime(1, 30, 0, 0, ISO_NEW_YORK);
DateTime test = base.toDateTime(tod, NEW_YORK);
DateTime expected = new DateTime(2007, 11, 4, 1, 30, ISO_NEW_YORK).withEarlierOffsetAtOverlap();
assertEquals(expected, test);
}
public void testToDateTime_wrongChronoLocalTime_Zone() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
LocalTime tod = new LocalTime(12, 13, 14, 15, BUDDHIST_TOKYO);
try {
base.toDateTime(tod, LONDON);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
@SuppressWarnings("deprecation")
public void testToDateMidnight() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);
DateMidnight test = base.toDateMidnight();
check(base, 2005, 6, 9);
assertEquals(new DateMidnight(2005, 6, 9, COPTIC_LONDON), test);
}
//-----------------------------------------------------------------------
@SuppressWarnings("deprecation")
public void testToDateMidnight_Zone() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);
DateMidnight test = base.toDateMidnight(TOKYO);
check(base, 2005, 6, 9);
assertEquals(new DateMidnight(2005, 6, 9, COPTIC_TOKYO), test);
}
@SuppressWarnings("deprecation")
public void testToDateMidnight_nullZone() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);
DateMidnight test = base.toDateMidnight((DateTimeZone) null);
check(base, 2005, 6, 9);
assertEquals(new DateMidnight(2005, 6, 9, COPTIC_LONDON), test);
}
//-----------------------------------------------------------------------
public void testToDateTime_RI() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS);
DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7);
DateTime test = base.toDateTime(dt);
check(base, 2005, 6, 9);
DateTime expected = dt;
expected = expected.year().setCopy(2005);
expected = expected.monthOfYear().setCopy(6);
expected = expected.dayOfMonth().setCopy(9);
assertEquals(expected, test);
}
public void testToDateTime_nullRI() {
LocalDate base = new LocalDate(2005, 6, 9);
DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7);
DateTimeUtils.setCurrentMillisFixed(dt.getMillis());
DateTime test = base.toDateTime((ReadableInstant) null);
check(base, 2005, 6, 9);
DateTime expected = dt;
expected = expected.year().setCopy(2005);
expected = expected.monthOfYear().setCopy(6);
expected = expected.dayOfMonth().setCopy(9);
assertEquals(expected, test);
}
//-----------------------------------------------------------------------
public void testToInterval() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
Interval test = base.toInterval();
check(base, 2005, 6, 9);
DateTime start = base.toDateTimeAtStartOfDay();
DateTime end = start.plus(Period.days(1));
Interval expected = new Interval(start, end);
assertEquals(expected, test);
}
//-----------------------------------------------------------------------
public void testToInterval_Zone() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
Interval test = base.toInterval(TOKYO);
check(base, 2005, 6, 9);
DateTime start = base.toDateTimeAtStartOfDay(TOKYO);
DateTime end = start.plus(Period.days(1));
Interval expected = new Interval(start, end);
assertEquals(expected, test);
}
public void testToInterval_Zone_noMidnight() {
LocalDate base = new LocalDate(2006, 4, 1, ISO_LONDON); // LONDON irrelevant
DateTimeZone gaza = DateTimeZone.forID("Asia/Gaza");
Interval test = base.toInterval(gaza);
check(base, 2006, 4, 1);
DateTime start = new DateTime(2006, 4, 1, 1, 0, 0, 0, gaza);
DateTime end = new DateTime(2006, 4, 2, 0, 0, 0, 0, gaza);
Interval expected = new Interval(start, end);
assertEquals(expected, test);
}
public void testToInterval_nullZone() {
LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant
Interval test = base.toInterval(null);
check(base, 2005, 6, 9);
DateTime start = base.toDateTimeAtStartOfDay(LONDON);
DateTime end = start.plus(Period.days(1));
Interval expected = new Interval(start, end);
assertEquals(expected, test);
}
//-----------------------------------------------------------------------
public void testToDate_summer() {
LocalDate base = new LocalDate(2005, 7, 9, COPTIC_PARIS);
Date test = base.toDate();
check(base, 2005, 7, 9);
GregorianCalendar gcal = new GregorianCalendar();
gcal.clear();
gcal.set(Calendar.YEAR, 2005);
gcal.set(Calendar.MONTH, Calendar.JULY);
gcal.set(Calendar.DAY_OF_MONTH, 9);
assertEquals(gcal.getTime(), test);
}
public void testToDate_winter() {
LocalDate base = new LocalDate(2005, 1, 9, COPTIC_PARIS);
Date test = base.toDate();
check(base, 2005, 1, 9);
GregorianCalendar gcal = new GregorianCalendar();
gcal.clear();
gcal.set(Calendar.YEAR, 2005);
gcal.set(Calendar.MONTH, Calendar.JANUARY);
gcal.set(Calendar.DAY_OF_MONTH, 9);
assertEquals(gcal.getTime(), test);
}
public void testToDate_springDST() {
LocalDate base = new LocalDate(2007, 4, 2);
SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight",
Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000);
TimeZone currentZone = TimeZone.getDefault();
try {
TimeZone.setDefault(testZone);
Date test = base.toDate();
check(base, 2007, 4, 2);
assertEquals("Mon Apr 02 01:00:00 GMT+02:00 2007", test.toString());
} finally {
TimeZone.setDefault(currentZone);
}
}
public void testToDate_springDST_2Hour40Savings() {
LocalDate base = new LocalDate(2007, 4, 2);
SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight",
Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000, (3600000 / 6) * 16);
TimeZone currentZone = TimeZone.getDefault();
try {
TimeZone.setDefault(testZone);
Date test = base.toDate();
check(base, 2007, 4, 2);
assertEquals("Mon Apr 02 02:40:00 GMT+03:40 2007", test.toString());
} finally {
TimeZone.setDefault(currentZone);
}
}
public void testToDate_autumnDST() {
LocalDate base = new LocalDate(2007, 10, 2);
SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight",
Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000);
TimeZone currentZone = TimeZone.getDefault();
try {
TimeZone.setDefault(testZone);
Date test = base.toDate();
check(base, 2007, 10, 2);
assertEquals("Tue Oct 02 00:00:00 GMT+02:00 2007", test.toString());
} finally {
TimeZone.setDefault(currentZone);
}
}
//-----------------------------------------------------------------------
public void testProperty() {
LocalDate test = new LocalDate(2005, 6, 9, GJ_UTC);
assertEquals(test.year(), test.property(DateTimeFieldType.year()));
assertEquals(test.monthOfYear(), test.property(DateTimeFieldType.monthOfYear()));
assertEquals(test.dayOfMonth(), test.property(DateTimeFieldType.dayOfMonth()));
assertEquals(test.dayOfWeek(), test.property(DateTimeFieldType.dayOfWeek()));
assertEquals(test.dayOfYear(), test.property(DateTimeFieldType.dayOfYear()));
assertEquals(test.weekOfWeekyear(), test.property(DateTimeFieldType.weekOfWeekyear()));
assertEquals(test.weekyear(), test.property(DateTimeFieldType.weekyear()));
assertEquals(test.yearOfCentury(), test.property(DateTimeFieldType.yearOfCentury()));
assertEquals(test.yearOfEra(), test.property(DateTimeFieldType.yearOfEra()));
assertEquals(test.centuryOfEra(), test.property(DateTimeFieldType.centuryOfEra()));
assertEquals(test.era(), test.property(DateTimeFieldType.era()));
try {
test.property(DateTimeFieldType.millisOfDay());
fail();
} catch (IllegalArgumentException ex) {}
try {
test.property(null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testSerialization() throws Exception {
LocalDate test = new LocalDate(1972, 6, 9, COPTIC_PARIS);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(test);
oos.close();
byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
LocalDate result = (LocalDate) ois.readObject();
ois.close();
assertEquals(test, result);
assertTrue(Arrays.equals(test.getValues(), result.getValues()));
assertTrue(Arrays.equals(test.getFields(), result.getFields()));
assertEquals(test.getChronology(), result.getChronology());
}
//-----------------------------------------------------------------------
public void testToString() {
LocalDate test = new LocalDate(2002, 6, 9);
assertEquals("2002-06-09", test.toString());
}
//-----------------------------------------------------------------------
public void testToString_String() {
LocalDate test = new LocalDate(2002, 6, 9);
assertEquals("2002 \ufffd\ufffd", test.toString("yyyy HH"));
assertEquals("2002-06-09", test.toString((String) null));
}
//-----------------------------------------------------------------------
public void testToString_String_Locale() {
LocalDate test = new LocalDate(1970, 6, 9);
assertEquals("Tue 9/6", test.toString("EEE d/M", Locale.ENGLISH));
assertEquals("mar. 9/6", test.toString("EEE d/M", Locale.FRENCH));
assertEquals("1970-06-09", test.toString(null, Locale.ENGLISH));
assertEquals("Tue 9/6", test.toString("EEE d/M", null));
assertEquals("1970-06-09", test.toString(null, null));
}
//-----------------------------------------------------------------------
public void testToString_DTFormatter() {
LocalDate test = new LocalDate(2002, 6, 9);
assertEquals("2002 \ufffd\ufffd", test.toString(DateTimeFormat.forPattern("yyyy HH")));
assertEquals("2002-06-09", test.toString((DateTimeFormatter) null));
}
//-----------------------------------------------------------------------
private void check(LocalDate test, int hour, int min, int sec) {
assertEquals(hour, test.getYear());
assertEquals(min, test.getMonthOfYear());
assertEquals(sec, test.getDayOfMonth());
}
}
| {
"content_hash": "eeccf90cd479e7fa97444be1b2ee66f7",
"timestamp": "",
"source": "github",
"line_count": 1145,
"max_line_length": 104,
"avg_line_length": 41.87336244541485,
"alnum_prop": 0.5960579831056418,
"repo_name": "tingting703/mp3_maven",
"id": "593cb3618dbe571bfc481e792a5b54c0493593e5",
"size": "48561",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "src/test/java/org/joda/time/TestLocalDate_Basics.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "988"
},
{
"name": "HTML",
"bytes": "16833"
},
{
"name": "Java",
"bytes": "5846018"
}
],
"symlink_target": ""
} |
package helmpath
import (
"path/filepath"
"k8s.io/client-go/util/homedir"
)
// dataHome defines the base directory relative to which user specific data files should be stored.
//
// If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share is used.
func dataHome() string {
return filepath.Join(homedir.HomeDir(), ".local", "share")
}
// configHome defines the base directory relative to which user specific configuration files should
// be stored.
//
// If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config is used.
func configHome() string {
return filepath.Join(homedir.HomeDir(), ".config")
}
// cacheHome defines the base directory relative to which user specific non-essential data files
// should be stored.
//
// If $XDG_CACHE_HOME is either not set or empty, a default equal to $HOME/.cache is used.
func cacheHome() string {
return filepath.Join(homedir.HomeDir(), ".cache")
}
| {
"content_hash": "203f541346bfb89fdcec3e0f708c245a",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 99,
"avg_line_length": 31.7,
"alnum_prop": 0.7350157728706624,
"repo_name": "operator-framework/operator-lifecycle-manager",
"id": "82fb4b6f1fec712ef513fc76e6af6c8190d8bdab",
"size": "1562",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "vendor/helm.sh/helm/v3/pkg/helmpath/lazypath_unix.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2078"
},
{
"name": "Go",
"bytes": "3367162"
},
{
"name": "Makefile",
"bytes": "10404"
},
{
"name": "Mustache",
"bytes": "515"
},
{
"name": "Shell",
"bytes": "19415"
},
{
"name": "Starlark",
"bytes": "11071"
}
],
"symlink_target": ""
} |
package org.estatio.fixture.currency;
import javax.inject.Inject;
import org.estatio.dom.currency.Currencies;
import org.estatio.dom.currency.Currency;
import org.estatio.fixture.EstatioFixtureScript;
public class CurrenciesRefData extends EstatioFixtureScript {
public static final String EUR = "EUR";
public static final String SEK = "SEK";
public static final String GBP = "GBP";
public static final String USD = "USD";
@Override
protected void execute(ExecutionContext executionContext) {
createCurrency(EUR, "Euro", executionContext);
createCurrency(SEK, "Swedish krona", executionContext);
createCurrency(GBP, "Pound sterling", executionContext);
createCurrency(USD, "US dollar", executionContext);
}
private void createCurrency(String reference, String name, ExecutionContext executionContext) {
final Currency currency = currencies.findOrCreateCurrency(reference, name);
executionContext.addResult(this, currency.getReference(), currency);
}
@Inject
Currencies currencies;
}
| {
"content_hash": "8227004ad79cb46857b717c8ded46d38",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 99,
"avg_line_length": 32.84848484848485,
"alnum_prop": 0.7370848708487084,
"repo_name": "kigsmtua/estatio",
"id": "9344aa27eaffc1e00a4f93390fee4b7a981d4ca9",
"size": "1724",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "estatioapp/fixture/src/main/java/org/estatio/fixture/currency/CurrenciesRefData.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Cucumber",
"bytes": "35931"
},
{
"name": "HTML",
"bytes": "14873"
},
{
"name": "Java",
"bytes": "3243397"
},
{
"name": "JavaScript",
"bytes": "47"
},
{
"name": "PLpgSQL",
"bytes": "970"
},
{
"name": "Shell",
"bytes": "1268"
}
],
"symlink_target": ""
} |
'use strict'
//from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
function isHtmlElement(o:any) {
return (
typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string"
)
}
//inspired by https://github.com/rstacruz/nprogress/blob/master/nprogress.js
enum BarElement {
barWrapper,
bar,
}
enum TransitionState {
running,
finished
}
enum TransitionType {
value,
visibility
}
enum ProgressbarStatus {
/**
* starting value (only once)
*/
initial,
/**
* displayed and 0 <= value < 1 (normally after .start was called)
*/
started,
/**
* displayed and value === 1 (normally after .done was called)
*/
finished
}
//from https://developer.mozilla.org/de/docs/Web/Events/transitionend
interface TransitionEndEvent extends Event {
target:EventTarget
type:string
bubbles:boolean
cancelable:boolean
propertyName:string
elapsedTime:number
pseudoElement:string
}
interface Settings {
/**
* an object with key-value pairs (key css style name [htmlObj.style.key], value style value) to style the bar
*/
css:any
/**
* an object with key-value pairs (key css style name [htmlObj.style.key], value style value) to style the bar wrapper
*/
cssWrapper:any
/**
* the css classes to add the the bar wrapper
*/
wrapperCssClasses?:string[]
/**
* the delay in ms, every tick the .inc method is called
*/
incrementTimeoutInMs?:number
/**
* the css classes to add to the bar
*/
cssClasses?:string[]
/**
* the transition for the bar when the value changes
* (must not be empty!)
*/
changeValueTransition?:string
/**
* the transition for the bar when animating from bigger to smaller value (backwards)
* (must not be empty!)
*/
changeValueBackTransition?:string
/**
* the transition for the bar wrapper when the visibility (not the css value) changes e.g. set height to 0
* (must not be empty!)
*/
changeVisibilityTransition?:string
/**
* the height of the bar (applied to barWrapper)
*/
height?:string
/**
* the wrapper background color (applied to barWrapper)
*/
wrapperBackgroundColor?:string
/**
* the background color (applied to the bar)
*/
backgroundColor?:string
/**
* the box shadow (applied to the bar)
*/
boxShadow?:string
/**
* the z index (applied to the barWrapper)
*/
zIndex?:string
/**
* the property name of the value property (property that changes when the value should change)
* transition callbacks (handled by the transition queue) only fired when a transition ends and the propertyName
* was equal to the changeValueProperty
* so this is only needed if we use multiple animations to change the value (then we need to wait for the longest)
* (default null to allow all properties)
*/
changeValueProperty?:string
/**
* the element that will used to change the value
* (default null to allow all properties)
*/
changeValueElement?:BarElement
/**
* the property name of the visibility property (property that changes when the visibility should change)
* transition callbacks (handled by the transition queue) only fired when a transition ends and the propertyName
* was equal to the changeValueProperty
* so this is only needed if we use multiple animations to change the visibility (then we need to wait for the longest)
* (default null to allow all properties)
*/
changeVisibilityProperty?:string
/**
* the element that will used to change the visibility
* (default barWrapper)
*/
changeVisibilityElement?:BarElement
/**
* function that applies the initial style to the bar wrapper (the initial styles)
* @param barWrapperDiv hte bar wrapper div
* @param shouldPositionTopMost true: no parent provided position at the top, false: parent provided
*/
applyInitialBarWrapperStyle?:(barWrapperDiv:HTMLDivElement, shouldPositionTopMost:boolean) => void
/**
* a function that is called after applyInitialBarWrapperStyle to do some minor changes on the bar wrapper style
* @param barWrapperDiv the bar wrapper
* @param shouldPositionTopMost true: no parent provided position at the top, false: parent provided
*/
extendInitialBarWrapperStyle?:(barWrapperDiv:HTMLDivElement, shouldPositionTopMost:boolean) => void
/**
* function that applies the initial style to the bar (the initial styles)
* @param barDiv the bar div
* @param shouldPositionTopMost true: no parent provided position at the top, false: parent provided
*/
applyInitialBarStyle?:(barDiv:HTMLDivElement, shouldPositionTopMost:boolean) => void
/**
* a function that is called after applyInitialBarStyle to do some minor changes on the bar style
* @param barDiv the bar
* @param shouldPositionTopMost true: no parent provided position at the top, false: parent provided
*/
extendInitialBarStyle?:(barDiv:HTMLDivElement, shouldPositionTopMost:boolean) => void
/**
* function that changes the visibility of the bar (wrapper)
* @param barWrapperDiv the bar wrapper
* @param barDiv the bar the bar
* @param newVisibility true: make visible, false: invisible
*/
changeBarVisibility?:(barWrapperDiv:HTMLDivElement, barDiv:HTMLDivElement, newVisibility:boolean) => void
/**
* function to change to value of the bar (set the right css values here)
* @param barWrapperDiv the bar wrapper
* @param barDiv the bar
* @param value the new value (0 <= value <= 100)
*/
changeValueFunc?:(barWrapperDiv:HTMLDivElement, barDiv:HTMLDivElement, value:number) => void
}
/**
* a class for the default settings (class because of functions)
*/
class DefaultSettings implements Settings {
/**
* an object with key-value pairs (key css style name [htmlObj.style.key], value style value) to style the bar
* (this will override other style settings in this class in the extendInitialBarWrapperStyle function)
*/
css = {
backgroundColor: '#29d', //github: #77b6f
boxShadow: '0 0 10px rgba(119,182,255,0.7)', //github
position: 'absolute',
left: '0',
right: '100%', //we will change only this value
top: '0',
bottom: '0'
}
/**
* an object with key-value pairs (key css style name [htmlObj.style.key], value style value) to style the bar wrapper
* (this will override other style settings in this class in the applyInitialBarWrapperStyle function)
*/
cssWrapper = {
height: '2px',
position: 'relative',
backgroundColor: 'transparent',
zIndex: '1050'
}
incrementTimeoutInMs = 300
wrapperCssClasses = []
cssClasses = []
//can't be set through css prop because user could change the html content of the bar & the wrapper
changeValueTransition = 'all 0.3s ease'
changeVisibilityTransition = 'all 0.2s ease'
//used when transitioning/animating backwards
changeValueBackTransition = 'all 0.05s linear'
changeValueProperty = null //null for all
changeValueElement = BarElement.bar
changeVisibilityProperty = null //null for all
changeVisibilityElement = BarElement.barWrapper
applyInitialBarWrapperStyle(barWrapperDiv:HTMLDivElement, shouldPositionTopMost:boolean) {
if (this.cssWrapper)
for (let key in this.cssWrapper) {
if (this.cssWrapper.hasOwnProperty(key) && barWrapperDiv.style[key] !== undefined) {
barWrapperDiv.style[key] = this.cssWrapper[key]
}
}
if (barWrapperDiv.style.transition) {
console.error('tinybar: the changeVisibilityTransition property must be set (not though css property) ')
}
barWrapperDiv.style.transition = this.changeVisibilityTransition
//override style...
if (shouldPositionTopMost) {
barWrapperDiv.style.position = 'fixed'
barWrapperDiv.style.left = '0'
barWrapperDiv.style.right = '0'
barWrapperDiv.style.top = '0'
}
this.extendInitialBarWrapperStyle(barWrapperDiv, shouldPositionTopMost)
}
extendInitialBarWrapperStyle(barWrapperDiv:HTMLDivElement, shouldPositionTopMost:boolean) {
//do nothing here...
}
applyInitialBarStyle(barDiv:HTMLDivElement, shouldPositionTopMost:boolean) {
if (this.css)
for (let key in this.css) {
if (this.css.hasOwnProperty(key) && barDiv.style[key] !== undefined) {
barDiv.style[key] = this.css[key]
}
}
if (barDiv.style.transition) {
console.error('tinybar: the changeValueTransition (& the changeValueBackTransition) property must be set (not though css property) ')
}
barDiv.style.transition = this.changeValueTransition
//let the user modify the style
this.extendInitialBarStyle(barDiv, shouldPositionTopMost)
}
extendInitialBarStyle(barDiv:HTMLDivElement, shouldPositionTopMost:boolean) {
//do nothing here...
}
changeBarVisibility(barWrapperDiv:HTMLDivElement, barDiv:HTMLDivElement, newVisibility:boolean) {
//use opacity here... looks nicer
if (newVisibility) {
//barWrapperDiv.style.height = this.height;
barWrapperDiv.style.opacity = '1';
}
else {
//barWrapperDiv.style.height = '0px';
barWrapperDiv.style.opacity = '0';
}
}
changeValueFunc(barWrapperDiv:HTMLDivElement, barDiv:HTMLDivElement, value:number) {
barDiv.style.right = (100 - value) + '%'
}
}
/**
* the global default (static) settings for a tiny bar
* @type {DefaultSettings}
*/
var defaultSettings = new DefaultSettings()
/**
* extends an obj with the values from ext (hasOwnProperty checked)
* @param obj
* @param ext
* @param recursively true: extend obj values also with extend (if obj values are objects too),
* false: only copy values (regardless of type)
* @return the extended obj
*/
function extendObject(obj:any, ext:any, recursively:boolean = true) {
for (let key in ext) {
if (ext.hasOwnProperty(key)) {
let value = ext[key]
if (recursively && typeof value === 'object' && value !== null) { //typeof null === 'object' !!
extendObject(obj[key], ext[key], recursively)
} else {
obj[key] = ext[key]
}
}
}
return obj
}
/**
* a tiny (progress) bar
*/
class TinyBar {
/**
* just the version
* (use as readonly)
* @type {string}
*/
version:string = '1.0.0'
/**
* the project name ... used for output
* @type {string}
*/
projectName:string = 'TinyBar'
/**
* the settings of the current progressbar
* @type {DefaultSettings}
*/
settings:Settings = new DefaultSettings()
/**
* the current status of the progressbar (initial | started | finished)
* (use as readonly)
* @type {ProgressbarStatus}
*/
status:ProgressbarStatus = ProgressbarStatus.initial
/**
* the current value of the progressbar
* (use as readonly)
* @type {number}
*/
value:number = 0
/**
* true: no parent provided so position at the top, false: parent id present
* (use as readonly)
* @type {boolean}
*/
shouldPositionTopMost:boolean = true
/**
* the html div that represents the bar wrapper
* (use as readonly)
* @type {null}
*/
barWrapper:HTMLDivElement = null
/**
* the html div element represents the bar
* (use as readonly)
* @type {null}
*/
bar:HTMLDivElement = null
/**
* a queue to help with the transition events
* (use as readonly)
* @type {null}
*/
transitionQueue:_TransitioQueue = null
/**
* used to store the handle for the interval cleanup when incrementing to infinity
* (use as readonly)
* @type {null}
*/
tricklingHandle = null
/**
* creates a new tiny (progress) bar
* @param settings the settings for the new tiny bar
* @param htmlParentDivId the parent div id OR the parent html div object OR null (to position the progressbar at the top)
* @param domElementsCreatedCallback called when the bar and bar wrapper are created and inserted in the dom
*/
constructor(settings?:Settings | string, htmlParentDivId?:string | Settings | HTMLElement, domElementsCreatedCallback?:() => void) {
//if first arg is a string assume that the second arg represents the settings...
if (typeof settings === 'string' || isHtmlElement(settings)) { //1. arg = html parent id or html parent object
let temp = <Settings>htmlParentDivId
htmlParentDivId = <string|HTMLElement>settings
settings = temp
//first apply settings
this._setSettings(<Settings>settings)
if (htmlParentDivId) {
this.shouldPositionTopMost = false
this._createBar(<string|HTMLElement>htmlParentDivId, false, domElementsCreatedCallback)
} else {
//create bar at the top
this.shouldPositionTopMost = true
this._createBar(document.body, true, domElementsCreatedCallback)
}
}
else if (typeof htmlParentDivId === 'string') { //1. arg = settings, 2. arg = html parent id
//first apply settings
this._setSettings(<Settings>settings)
if (htmlParentDivId) {
this.shouldPositionTopMost = false
this._createBar(htmlParentDivId, false, domElementsCreatedCallback)
} else {
//create bar at the top
this.shouldPositionTopMost = true
this._createBar(document.body, true, domElementsCreatedCallback)
}
} else { //1. arg & 2. arg does not match
//first apply settings
this._setSettings(<Settings>settings)
//create bar at the top
this.shouldPositionTopMost = true
this._createBar(document.body, true, domElementsCreatedCallback)
}
this.transitionQueue = new _TransitioQueue(this)
}
/**
* appends the html for the bar and the bar wrapper (applies the initial state
* @param parentHtmlElement the parent element where the tiny bar should be inserted (through appendChild)
* @param positionTopMost true: no parent provided position at the top, false: parent provided
* @param domElementsCreatedCallback called when the bar and bar wrapper are created and inserted in the dom
* @private
*/
private _createBar(parentHtmlElement:HTMLElement | string, positionTopMost:boolean, domElementsCreatedCallback?:() => void) {
//create wrapper div
let barWrapper = document.createElement('div')
for (let i = 0; i < this.settings.wrapperCssClasses.length; i++) {
let cssClass = this.settings.wrapperCssClasses[i];
barWrapper.classList.add(cssClass)
}
//create bar div
let bar = document.createElement('div')
for (let i = 0; i < this.settings.cssClasses.length; i++) {
let cssClass = this.settings.cssClasses[i];
bar.classList.add(cssClass)
}
this.settings.applyInitialBarWrapperStyle(barWrapper, positionTopMost)
this.settings.applyInitialBarStyle(bar, positionTopMost)
this.bar = bar
this.barWrapper = barWrapper
barWrapper.appendChild(bar)
if (typeof parentHtmlElement === 'string') {
document.getElementById(parentHtmlElement).appendChild(barWrapper)
}
else {
parentHtmlElement.appendChild(barWrapper)
}
if (domElementsCreatedCallback)
domElementsCreatedCallback.call(this)
}
/**
* sets the settings for this bar (call only once per setup ... when called a second time the
* settings from the first call are deleted)
* @param settings the settings
* @returns {TinyBar} the bar
*/
private _setSettings(settings:Settings) {
//apply the defaultSettings because this.settings is initialized
//with a new instance of DefaultSettings and the defaultSettings var could have changed
extendObject(this.settings, defaultSettings, true)
//then user settings if any
if (settings) {
extendObject(this.settings, settings, true)
}
/*
if (this.settings.changeValueElement === this.settings.changeVisibilityElement) {
if (this.settings.changeValueProperty === this.settings.changeVisibilityProperty) {
console.error(this.projectName + ': changeValueProperty can\'t be the same as changeVisibilityProperty ' +
'because we need to watch the transition events')
}
}
normally the bar is only animated by this class and only the appropriated properties so nully value should be ok
-> no filter for transitionend events in the transition queue
if (!this.settings.changeValueProperty) {
console.error(this.projectName + ': changeValueProperty needs to be set')
}
if (!this.settings.changeVisibilityProperty) {
console.error(this.projectName + ': changeVisibilityProperty needs to be set')
}
*/
if (!this.settings.changeValueTransition || !this.settings.changeVisibilityTransition) {
console.error(this.projectName + ': changeValueTransition and/or changeVisibilityTransition where not set ' +
'the is needed becase we need to watche the transition events')
}
//TODO maybe add more validation
return this
}
/**
* starts the bar and shows it
* @param startingValue the value to start with
* @param callback callback called when the animation has finished
* @returns {TinyBar}
*/
start(startingValue:number = 0.5, callback?:() => void) {
if (this.status === ProgressbarStatus.started)
return this
this.status = ProgressbarStatus.started
//clear all old queue actions (from old .done calls)
this.transitionQueue.valueChangedQueue = []
this.transitionQueue.visibilityChangedQueue = []
//make bar visible
this.settings.changeBarVisibility(this.barWrapper, this.bar, true)
//set starting value
this._go(startingValue, callback, true)
this.value = startingValue
return this
}
/**
* goes to the given percentage (0 <= percentage <= 100)
* @param value the value between 0 and 100 to go to
* @param callback called when the animation has finished
* @param hideBarWhenFinished when value >= 100 then the done method is called with this parameter as argument
*/
go(value:number, callback?:() => void, hideBarWhenFinished:boolean = true) {
//if (this.status !== ProgressbarStatus.started) return
//when the bar has finished and we call go to set the bar to a lower
// value then the status needs to be started
this.status = ProgressbarStatus.started
this._go(value, callback, hideBarWhenFinished)
}
/**
* goes to the given percentage (0 <= percentage <= 100)
* @param value the value between 0 and 100 to go to
* @param callback called when the value is set and the animation has finished
* @param hideBarWhenFinished when value >= 100 then the done method is called with this parameter as argument
* @private
*/
_go(value:number, callback:() => void, hideBarWhenFinished:boolean) {
var self = this
if (value >= 0) {
//&& this.status !== ProgressbarStatus.finished //when the bar finished then only allow .start
if (value <= this.value) {
this.transitionQueue.valueChangedQueue = []
this.transitionQueue.visibilityChangedQueue = []
this.clearAutoIncrement()
//when we want to go back transition/animate faster...
this._getValueChangingElement().style.transition = this.settings.changeValueBackTransition
this.transitionQueue._executeActionAfterTransition(TransitionType.value, () => {
this._getValueChangingElement().style.transition = this.settings.changeValueTransition
if (callback)
callback.call(self)
})
this.transitionQueue._beforeTransition(TransitionType.value)
this.settings.changeValueFunc(this.barWrapper, this.bar, value)
this.value = value
} else {
let myValue = Math.min(value, 100)
if (myValue === 100) {
this.done(hideBarWhenFinished, callback)
} else {
this.value = myValue
//when calling .start(true).done(false) multiple times
//then the done will call _go(0) -> 0 < 100 -> fast transition is set and nev
//this._getValueChangingElement().style.transition = this.settings.changeValueTransition
//provide callback
this.transitionQueue._executeActionAfterTransition(TransitionType.value, () => {
if (callback)
callback.call(self)
})
this.transitionQueue._beforeTransition(TransitionType.value)
this.settings.changeValueFunc(this.barWrapper, this.bar, myValue)
}
}
}
}
/**
* * increments the value by a random value but never reaches 100%
* taken from https://github.com/rstacruz/nprogress/blob/master/nprogress.js
* @param callback called when the value is set and the animation has finished
*/
inc(callback?:() => void) {
if (this.value >= 100) {
return
} else {
let amount = 0
if (this.value >= 0 && this.value < 25) {
// Start out between 3 - 6% increments
amount = (Math.random() * (5 - 3 + 1) + 3) / 100;
} else if (this.value >= 25 && this.value < 65) {
// increment between 0 - 3%
amount = (Math.random() * 3) / 100;
} else if (this.value >= 65 && this.value < 90) {
// increment between 0 - 2%
amount = (Math.random() * 2) / 100;
} else if (this.value >= 90 && this.value < 99) {
// finally, increment it .5 %
amount = 0.005;
} else {
// after 99%, don't increment:
amount = 0;
}
this._go(this.value + (amount * 100 / 2), callback, true)
}
}
/**
* finishes the bar
* @param hideBar true: hide the bar after finishing, false: not
* @param callback called when the transition has finished
* when hideBar = true then the callback is called after the hide transition has finished
* and the value has returned to 0,
* if hideBar = false then the callback is called after the value transition has finished
*/
done(hideBar:boolean = true, callback?:() => void) {
//if we havent started the bar yet do nothing...
if (this.status === ProgressbarStatus.initial) return
let self = this
this.transitionQueue.valueChangedQueue = []
this.transitionQueue.visibilityChangedQueue = []
//clear handle if any
this.clearAutoIncrement()
let hideFunc = () => {
//set the value to 0 after the visibility changed to invisible
// else when we call start the bar would animate from 100 to 0
self.transitionQueue._executeActionAfterTransition(TransitionType.visibility, () => {
//do not set the bar status to running...
//self._go(0,null, hideBar, false)
setTimeout(() => {
self._go(0, () => {
if (callback) callback.call(self)
}, hideBar)
}, 100)
})
self.transitionQueue._beforeTransition(TransitionType.visibility)
self.settings.changeBarVisibility(this.barWrapper, self.bar, false)
}
if (this.status === ProgressbarStatus.finished) {
if (hideBar)
hideFunc()
return
}
if (this.value !== 100) {
//queue because we want to let the value animation finish before hiding the bar
this.transitionQueue._executeActionAfterTransition(TransitionType.value, () => {
this.value = 100
self.status = ProgressbarStatus.finished
if (hideBar) {
//wait until bar is invisible and value returned to 0 then call the callback
hideFunc()
} else {
//bar wont hide so call the callback now
if (callback)
callback.call(self)
}
})
this.transitionQueue._beforeTransition(TransitionType.value)
this.settings.changeValueFunc(this.barWrapper, this.bar, 100)
} else {
if (hideBar) {
hideFunc()
}
}
}
/**
* starts automatically incrementing the value of the bar (calls .inc in a setInterval loop)
* @param callback called when the value is set and the animation has finished
*/
autoIncrement(callback?:() => void) {
//first clear old increment else we could lose the clear handle for the old increment
this.clearAutoIncrement()
this.tricklingHandle = setInterval(() => {
this.inc(callback)
}, this.settings.incrementTimeoutInMs)
}
/**
* clears the auto increment interval
* @private
*/
clearAutoIncrement() {
if (this.tricklingHandle) {
clearInterval(this.tricklingHandle)
this.tricklingHandle = null
}
}
/**
* returns the value that indicates the value of the tiny bar (relies on this.settings.changeValueElement)
* @returns {HTMLDivElement} the value that indicates the value of the tiny bar
* @private
*/
_getValueChangingElement():HTMLDivElement {
return this.settings.changeValueElement === BarElement.bar
? this.bar : this.barWrapper
}
}
/**
* a class to handle transition events and (queue) actions
*/
class _TransitioQueue {
/**
* the related tiny bar
*/
tinyBar:TinyBar
/**
* the transition state of the tiny bar
* @type {TransitionState}
*/
valueTransitionState:TransitionState = TransitionState.finished
/**
* the transition state of the tiny bar
* @type {TransitionState}
*/
visibilityTransitionState:TransitionState = TransitionState.finished
/**
* the change value transition start handler
* @type {null}
*/
changeValueTransitionStartHandler:() => void = null
/**
* the change value transition end handler
* @type {null}
*/
changeValueTransitionEndHandler:(transition:TransitionEndEvent) => void = null
/**
* the change visibility transition start handler
* @type {null}
*/
changeVisibilityTransitionStartHandler:() => void = null
/**
* the change visibility transition end handler
* @type {null}
*/
changeVisibilityTransitionEndHandler:(transition:TransitionEndEvent) => void = null
/**
* the queue with actions to to when the a value transition has finished
* (only the first item is used when a transition finished)
* @type {Array}
*/
valueChangedQueue:Array<() => void> = []
/**
* the queue with actions to to when the a visibility transition has finished
* (only the first item is used when a transition finished)
* @type {Array}
*/
visibilityChangedQueue:Array<() => void> = []
/**
* creates a new transition queue
* @param tinyBar the connected tiny bar
*/
constructor(tinyBar:TinyBar) {
this.tinyBar = tinyBar
this._setupQueue()
}
/**
* notifies the queue that a transition is started (no transitionStart event on js)
* @param transition the transition type
* @private
*/
_beforeTransition(transition:TransitionType) {
if (transition === TransitionType.value)
this.changeValueTransitionStartHandler()
else if (transition === TransitionType.visibility) {
this.changeVisibilityTransitionStartHandler()
}
}
/**
* enqueues an action which should be executed after an transition has started and finished
* (after finishing the action is executed)
* @param transition the transition to finish
* @param action the action to execute
* @private
*/
_executeActionAfterTransition(transition:TransitionType, action:() => void) {
if (transition === TransitionType.value)
this.valueChangedQueue.push(action)
else if (transition === TransitionType.visibility) {
this.visibilityChangedQueue.push(action)
}
}
/**
* sets all listeners up
* @private
*/
_setupQueue() {
let self = this
let transitionEndEvent = 'transitionend' //transitionend //webkitTransitionEnd
let changeValueElement = this.tinyBar.settings.changeValueElement === BarElement.bar
? this.tinyBar.bar : this.tinyBar.barWrapper
this.changeValueTransitionStartHandler = () => {
self.valueTransitionState = TransitionState.running
}
this.changeValueTransitionEndHandler = (trans:TransitionEndEvent) => {
//only do sth when the right property was transitioned
if (!self.tinyBar.settings.changeValueProperty //if nully value then allow all
|| trans.propertyName === self.tinyBar.settings.changeValueProperty) {
self.valueTransitionState = TransitionState.finished
if (self.valueChangedQueue.length > 0) {
let action = self.valueChangedQueue.shift()
action()
}
}
}
changeValueElement.addEventListener(transitionEndEvent, this.changeValueTransitionEndHandler)
let changeVisibilityElement = this.tinyBar.settings.changeVisibilityElement === BarElement.bar
? this.tinyBar.bar : this.tinyBar.barWrapper
this.changeVisibilityTransitionStartHandler = () => {
self.visibilityTransitionState = TransitionState.running
}
this.changeVisibilityTransitionEndHandler = (trans:TransitionEndEvent) => {
//only do sth when the right property was transitioned
if (!self.tinyBar.settings.changeVisibilityProperty //if nully value then allow all
|| trans.propertyName === self.tinyBar.settings.changeVisibilityProperty) {
self.visibilityTransitionState = TransitionState.finished
if (self.visibilityChangedQueue.length > 0) {
let action = self.visibilityChangedQueue.shift()
action()
}
}
}
changeVisibilityElement.addEventListener(transitionEndEvent, this.changeVisibilityTransitionEndHandler)
}
}
interface TinyBarExport {
TinyBar:new (settings?:Settings, htmlParentDivId?:string, domElementsCreatedCallback?:() => void) => TinyBar,
defaultSettings:Settings,
BarElement:BarElement,
TransitionState:TransitionState,
TransitionType:TransitionType,
ProgressbarStatus:ProgressbarStatus
}
var myExport = { //: TinyBarExport
TinyBar: TinyBar,
defaultSettings: defaultSettings,
BarElement: BarElement,
TransitionState: TransitionState,
TransitionType: TransitionType,
ProgressbarStatus: ProgressbarStatus
} | {
"content_hash": "c7450a0b6514ed6468ada7474180b886",
"timestamp": "",
"source": "github",
"line_count": 998,
"max_line_length": 145,
"avg_line_length": 32.98496993987976,
"alnum_prop": 0.6231051976062456,
"repo_name": "janisdd/tinybar",
"id": "a4bf42076375d5c9651bb4524adfd9434a4d3abc",
"size": "32919",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/tinyBar.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "29980"
},
{
"name": "TypeScript",
"bytes": "62003"
}
],
"symlink_target": ""
} |
namespace message_center {
class Notification;
class NotificationControlButtonsView;
} // namespace message_center
namespace ui {
class LayerTreeOwner;
}
namespace views {
class FocusTraversable;
class Widget;
} // namespace views
namespace ash {
class ArcNotificationSurface;
// ArcNotificationContentView is a view to host NotificationSurface and show the
// content in itself. This is implemented as a child of ArcNotificationView.
class ArcNotificationContentView
: public views::NativeViewHost,
public aura::WindowObserver,
public ArcNotificationItem::Observer,
public ArcNotificationSurfaceManager::Observer,
public views::WidgetObserver {
public:
METADATA_HEADER(ArcNotificationContentView);
ArcNotificationContentView(ArcNotificationItem* item,
const message_center::Notification& notification,
message_center::MessageView* message_view);
ArcNotificationContentView(const ArcNotificationContentView&) = delete;
ArcNotificationContentView& operator=(const ArcNotificationContentView&) = delete;
~ArcNotificationContentView() override;
void Update(const message_center::Notification& notification);
message_center::NotificationControlButtonsView* GetControlButtonsView();
void UpdateControlButtonsVisibility();
void UpdateCornerRadius(float top_radius, float bottom_radius);
void OnSlideChanged(bool in_progress);
void OnContainerAnimationStarted();
void OnContainerAnimationEnded();
void ActivateWidget(bool activate);
bool slide_in_progress() const { return slide_in_progress_; }
private:
friend class ArcNotificationViewTest;
friend class ArcNotificationContentViewTest;
FRIEND_TEST_ALL_PREFIXES(ArcNotificationContentViewTest,
ActivateWhenRemoteInputOpens);
class EventForwarder;
class MouseEnterExitHandler;
class SettingsButton;
class SlideHelper;
void CreateCloseButton();
void CreateSettingsButton();
void MaybeCreateFloatingControlButtons();
void SetSurface(ArcNotificationSurface* surface);
void UpdatePreferredSize();
void UpdateSnapshot();
void AttachSurface();
void SetExpanded(bool expanded);
bool IsExpanded() const;
void SetManuallyExpandedOrCollapsed(bool value);
bool IsManuallyExpandedOrCollapsed() const;
void ShowCopiedSurface();
void HideCopiedSurface();
// Generates a mask using |top_radius_| and |bottom_radius_| and installs it.
void UpdateMask(bool force_update);
// views::NativeViewHost
void ViewHierarchyChanged(
const views::ViewHierarchyChangedDetails& details) override;
void Layout() override;
void OnPaint(gfx::Canvas* canvas) override;
void OnMouseEntered(const ui::MouseEvent& event) override;
void OnMouseExited(const ui::MouseEvent& event) override;
void OnFocus() override;
void OnBlur() override;
void OnThemeChanged() override;
views::FocusTraversable* GetFocusTraversable() override;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
void OnAccessibilityEvent(ax::mojom::Event event) override;
void AddedToWidget() override;
void RemovedFromWidget() override;
void VisibilityChanged(View* starting_from, bool is_visible) override;
// aura::WindowObserver
void OnWindowBoundsChanged(aura::Window* window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds,
ui::PropertyChangeReason reason) override;
void OnWindowDestroying(aura::Window* window) override;
// views::WidgetObserver:
void OnWidgetClosing(views::Widget* widget) override;
void OnWidgetActivationChanged(views::Widget* widget, bool active) override;
// ArcNotificationItem::Observer
void OnItemDestroying() override;
void OnItemContentChanged(
arc::mojom::ArcNotificationShownContents content) override;
void OnRemoteInputActivationChanged(bool activated) override;
// ArcNotificationSurfaceManager::Observer:
void OnNotificationSurfaceAdded(ArcNotificationSurface* surface) override;
void OnNotificationSurfaceRemoved(ArcNotificationSurface* surface) override;
// If |item_| is null, we may be about to be destroyed. In this case,
// we have to be careful about what we do.
ArcNotificationItem* item_;
ArcNotificationSurface* surface_ = nullptr;
arc::mojom::ArcNotificationShownContents shown_content_ =
arc::mojom::ArcNotificationShownContents::CONTENTS_SHOWN;
// The flag to prevent an infinite loop of changing the visibility.
bool updating_control_buttons_visibility_ = false;
const std::string notification_key_;
// A pre-target event handler to forward events on the surface to this view.
// Using a pre-target event handler instead of a target handler on the surface
// window because it has descendant aura::Window and the events on them need
// to be handled as well.
// TODO(xiyuan): Revisit after exo::Surface no longer has an aura::Window.
std::unique_ptr<EventForwarder> event_forwarder_;
// A handler which observes mouse entered and exited events for the floating
// control buttons widget.
std::unique_ptr<ui::EventHandler> mouse_enter_exit_handler_;
// A helper to observe slide transform/animation and use surface layer copy
// when a slide is in progress and restore the surface when it finishes.
std::unique_ptr<SlideHelper> slide_helper_;
// Whether the notification is being slid or is at the origin. This stores the
// latest value of the |in_progress| from OnSlideChanged callback, which is
// called during both manual swipe and automatic slide on dismissing or
// resetting back to the origin.
// This value is synced with the visibility of the copied surface. If the
// value is true, the copied surface is visible instead of the original
// surface itself. Copied surgace doesn't have control buttons so they must be
// hidden if it's true.
// This value is stored in case of the change of surface. When a new surface
// sets, if this value is true, the copy of the new surface gets visible
// instead of the copied surface itself.
bool slide_in_progress_ = false;
// A control buttons on top of NotificationSurface. Needed because the
// aura::Window of NotificationSurface is added after hosting widget's
// RootView thus standard notification control buttons are always below
// it.
std::unique_ptr<views::Widget> floating_control_buttons_widget_;
// The message view which wrapps thie view. This must be the parent of this
// view.
message_center::MessageView* const message_view_;
// This view is owned by client (this).
message_center::NotificationControlButtonsView control_buttons_view_;
// Protects from call loops between Layout and OnWindowBoundsChanged.
bool in_layout_ = false;
// Widget which this view tree is currently attached to.
views::Widget* attached_widget_ = nullptr;
std::u16string accessible_name_;
// If it's true, the surface gets active when attached to this view.
bool activate_on_attach_ = false;
// Radiuses of rounded corners. These values are used in UpdateMask().
float top_radius_ = 0;
float bottom_radius_ = 0;
// Current insets of mask layer.
absl::optional<gfx::Insets> mask_insets_;
std::unique_ptr<ui::LayerTreeOwner> surface_copy_;
};
} // namespace ash
#endif // ASH_PUBLIC_CPP_EXTERNAL_ARC_MESSAGE_CENTER_ARC_NOTIFICATION_CONTENT_VIEW_H_
| {
"content_hash": "63a2fd845ef152599bb8a7ed1c323a1a",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 86,
"avg_line_length": 38.755208333333336,
"alnum_prop": 0.7494960354791023,
"repo_name": "ric2b/Vivaldi-browser",
"id": "910cdbd55feaf434964591bc60d508ab84bd7f7e",
"size": "8345",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chromium/ash/public/cpp/external_arc/message_center/arc_notification_content_view.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
import config, webui, BaseHTTPServer, urllib, sys, getopt, os
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
config = config.Config("config.ini")
ssh_user = None
def set_content_type(self, content_type):
self.send_header('Content-Type', content_type)
def run(self):
if self.path == '/':
self.send_response(301)
self.send_header('Location', '/pypi')
return
for scriptname in ('/mirrors', '/simple', '/pypi',
'/serversig', '/daytime', '/id'):
if self.path.startswith(scriptname):
rest = self.path[len(scriptname):]
break
else:
# invalid URL
return
# The text below is mostly copied from CGIHTTPServer
i = rest.rfind('?')
if i >= 0:
rest, query = rest[:i], rest[i+1:]
else:
query = ''
env = {}
#env['SERVER_SOFTWARE'] = self.version_string()
#env['SERVER_NAME'] = self.server.server_name
#env['SERVER_PORT'] = str(self.server.server_port)
env['GATEWAY_INTERFACE'] = 'CGI/1.1'
env['SERVER_PROTOCOL'] = self.protocol_version
env['REQUEST_METHOD'] = self.command
uqrest = urllib.unquote(rest)
env['PATH_INFO'] = uqrest
# env['PATH_TRANSLATED'] = self.translate_path(uqrest)
env['SCRIPT_NAME'] = scriptname
if query:
env['QUERY_STRING'] = query
host = self.address_string()
if host != self.client_address[0]:
env['REMOTE_HOST'] = host
env['REMOTE_ADDR'] = self.client_address[0]
if self.ssh_user:
# ignore authorization headers if this is a SSH client
authorization = None
env['SSH_USER'] = self.ssh_user
else:
authorization = self.headers.getheader("authorization")
if authorization:
env['HTTP_CGI_AUTHORIZATION'] = authorization
authorization = authorization.split()
if len(authorization) == 2:
import base64, binascii
env['AUTH_TYPE'] = authorization[0]
if self.headers.typeheader is None:
env['CONTENT_TYPE'] = self.headers.type
else:
env['CONTENT_TYPE'] = self.headers.typeheader
length = self.headers.getheader('content-length')
if length:
env['CONTENT_LENGTH'] = length
referer = self.headers.getheader('referer')
if referer:
env['HTTP_REFERER'] = referer
accept = []
for line in self.headers.getallmatchingheaders('accept'):
if line[:1] in "\t\n\r ":
accept.append(line.strip())
else:
accept = accept + line[7:].split(',')
env['HTTP_ACCEPT'] = ','.join(accept)
ua = self.headers.getheader('user-agent')
if ua:
env['HTTP_USER_AGENT'] = ua
co = filter(None, self.headers.getheaders('cookie'))
if co:
env['HTTP_COOKIE'] = ', '.join(co)
ac = self.headers.getheader('accept-encoding')
if ac:
env['HTTP_ACCEPT_ENCODING'] = ac
webui.WebUI(self, env).run()
do_GET = do_POST = run
class StdinoutHandler(RequestHandler):
def __init__(self, remote_user):
self.ssh_user = remote_user
try:
host,port,_ = os.environ['SSH_CLIENT'].split()
except KeyError:
host = port = ''
# request, client_address, server
RequestHandler.__init__(self, None, (host, port), None)
def setup(self):
self.rfile = sys.stdin
#import StringIO
#self.rfile = StringIO.StringIO('GET /pypi HTTP/1.0\r\n\r\n')
self.wfile = sys.stdout
def main():
os.umask(002) # make directories group-writable
port = 8000
remote_user = None
opts, args = getopt.getopt(sys.argv[1:], 'ir:p:',
['interactive', 'remote-user=', 'port='])
assert not args
for opt, val in opts:
if opt in ('-i', '--interactive'):
port = None
elif opt in ('-r','--remote-user'):
port = None # implies -i
remote_user = val
elif opt in ('-p', '--port'):
port = int(val)
if port:
httpd = BaseHTTPServer.HTTPServer(('',port), RequestHandler)
httpd.serve_forever()
else:
StdinoutHandler(remote_user)
if __name__=='__main__':
main()
| {
"content_hash": "ca815a13f12b1b9f744d0d95ff130bd0",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 73,
"avg_line_length": 35.46875,
"alnum_prop": 0.5378854625550661,
"repo_name": "techtonik/pydotorg.pypi",
"id": "94f7d319cd7cc8be30ebeffc5a462a4503d6c845",
"size": "4558",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "standalone.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "195"
},
{
"name": "CSS",
"bytes": "52191"
},
{
"name": "Makefile",
"bytes": "208"
},
{
"name": "PLpgSQL",
"bytes": "10792"
},
{
"name": "Python",
"bytes": "397864"
}
],
"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_51) on Fri Jul 19 02:59:43 EDT 2013 -->
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
Class Hierarchy (Solr 4.4.0 API)
</TITLE>
<META NAME="date" CONTENT="2013-07-19">
<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="Class Hierarchy (Solr 4.4.0 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="org/apache/solr/update/processor/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="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">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index.html?overview-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="overview-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 All Packages</H2>
</CENTER>
<DL>
<DT><B>Package Hierarchies:</B><DD><A HREF="org/apache/solr/update/processor/package-tree.html">org.apache.solr.update.processor</A></DL>
<HR>
<H2>
Class Hierarchy
</H2>
<UL>
<LI TYPE="circle">java.lang.<A HREF="http://download.oracle.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.apache.solr.update.processor.<A HREF="org/apache/solr/update/processor/DetectedLanguage.html" title="class in org.apache.solr.update.processor"><B>DetectedLanguage</B></A><LI TYPE="circle">org.apache.solr.update.processor.<A HREF="../solr-core/org/apache/solr/update/processor/UpdateRequestProcessor.html?is-external=true" title="class or interface in org.apache.solr.update.processor"><B>UpdateRequestProcessor</B></A><UL>
<LI TYPE="circle">org.apache.solr.update.processor.<A HREF="org/apache/solr/update/processor/LanguageIdentifierUpdateProcessor.html" title="class in org.apache.solr.update.processor"><B>LanguageIdentifierUpdateProcessor</B></A> (implements org.apache.solr.update.processor.<A HREF="org/apache/solr/update/processor/LangIdParams.html" title="interface in org.apache.solr.update.processor">LangIdParams</A>)
<UL>
<LI TYPE="circle">org.apache.solr.update.processor.<A HREF="org/apache/solr/update/processor/LangDetectLanguageIdentifierUpdateProcessor.html" title="class in org.apache.solr.update.processor"><B>LangDetectLanguageIdentifierUpdateProcessor</B></A><LI TYPE="circle">org.apache.solr.update.processor.<A HREF="org/apache/solr/update/processor/TikaLanguageIdentifierUpdateProcessor.html" title="class in org.apache.solr.update.processor"><B>TikaLanguageIdentifierUpdateProcessor</B></A></UL>
</UL>
<LI TYPE="circle">org.apache.solr.update.processor.<A HREF="../solr-core/org/apache/solr/update/processor/UpdateRequestProcessorFactory.html?is-external=true" title="class or interface in org.apache.solr.update.processor"><B>UpdateRequestProcessorFactory</B></A> (implements org.apache.solr.util.plugin.<A HREF="../solr-core/org/apache/solr/util/plugin/NamedListInitializedPlugin.html?is-external=true" title="class or interface in org.apache.solr.util.plugin">NamedListInitializedPlugin</A>)
<UL>
<LI TYPE="circle">org.apache.solr.update.processor.<A HREF="org/apache/solr/update/processor/LangDetectLanguageIdentifierUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><B>LangDetectLanguageIdentifierUpdateProcessorFactory</B></A> (implements org.apache.solr.update.processor.<A HREF="org/apache/solr/update/processor/LangIdParams.html" title="interface in org.apache.solr.update.processor">LangIdParams</A>, org.apache.solr.util.plugin.<A HREF="../solr-core/org/apache/solr/util/plugin/SolrCoreAware.html?is-external=true" title="class or interface in org.apache.solr.util.plugin">SolrCoreAware</A>)
<LI TYPE="circle">org.apache.solr.update.processor.<A HREF="org/apache/solr/update/processor/TikaLanguageIdentifierUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><B>TikaLanguageIdentifierUpdateProcessorFactory</B></A> (implements org.apache.solr.update.processor.<A HREF="org/apache/solr/update/processor/LangIdParams.html" title="interface in org.apache.solr.update.processor">LangIdParams</A>, org.apache.solr.util.plugin.<A HREF="../solr-core/org/apache/solr/util/plugin/SolrCoreAware.html?is-external=true" title="class or interface in org.apache.solr.util.plugin">SolrCoreAware</A>)
</UL>
</UL>
</UL>
<H2>
Interface Hierarchy
</H2>
<UL>
<LI TYPE="circle">org.apache.solr.update.processor.<A HREF="org/apache/solr/update/processor/LangIdParams.html" title="interface in org.apache.solr.update.processor"><B>LangIdParams</B></A></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="org/apache/solr/update/processor/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="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">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index.html?overview-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="overview-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>
<i>Copyright © 2000-2013 Apache Software Foundation. All Rights Reserved.</i>
<script src='/prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</BODY>
</HTML>
| {
"content_hash": "8303c0bd9815e7a14d169ccb61022ad9",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 631,
"avg_line_length": 51.15384615384615,
"alnum_prop": 0.6860365198711064,
"repo_name": "tenaciousjzh/titan-solr-cloud-test",
"id": "14e7a7b545e9247f68cbf4c48fa9f0b5597782e4",
"size": "9310",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "solr-4.4.0/docs/solr-langid/overview-tree.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "581261"
},
{
"name": "C++",
"bytes": "916659"
},
{
"name": "CSS",
"bytes": "851980"
},
{
"name": "Java",
"bytes": "3303267"
},
{
"name": "JavaScript",
"bytes": "8145789"
},
{
"name": "Perl",
"bytes": "296902"
},
{
"name": "Python",
"bytes": "93985"
},
{
"name": "Shell",
"bytes": "415395"
},
{
"name": "XSLT",
"bytes": "103322"
}
],
"symlink_target": ""
} |
<?php
namespace DCarbone\PHPFHIRGenerated\DSTU2\FHIRResource;
use DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRBundle\FHIRBundleEntry;
use DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRBundle\FHIRBundleLink;
use DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBundleType;
use DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRSignature;
use DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRUnsignedInt;
use DCarbone\PHPFHIRGenerated\DSTU2\FHIRResource;
use DCarbone\PHPFHIRGenerated\DSTU2\PHPFHIRConstants;
use DCarbone\PHPFHIRGenerated\DSTU2\PHPFHIRContainedTypeInterface;
use DCarbone\PHPFHIRGenerated\DSTU2\PHPFHIRTypeInterface;
/**
* A container for a collection of resources.
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* Class FHIRBundle
* @package \DCarbone\PHPFHIRGenerated\DSTU2\FHIRResource
*/
class FHIRBundle extends FHIRResource implements PHPFHIRContainedTypeInterface
{
// name of FHIR type this class describes
const FHIR_TYPE_NAME = PHPFHIRConstants::TYPE_NAME_BUNDLE;
const FIELD_ENTRY = 'entry';
const FIELD_LINK = 'link';
const FIELD_SIGNATURE = 'signature';
const FIELD_TOTAL = 'total';
const FIELD_TOTAL_EXT = '_total';
const FIELD_TYPE = 'type';
const FIELD_TYPE_EXT = '_type';
/** @var string */
private $_xmlns = 'http://hl7.org/fhir';
/**
* A container for a collection of resources.
*
* An entry in a bundle resource - will either contain a resource, or information
* about a resource (transactions and history only).
*
* @var null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRBundle\FHIRBundleEntry[]
*/
protected $entry = [];
/**
* A container for a collection of resources.
*
* A series of links that provide context to this bundle.
*
* @var null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRBundle\FHIRBundleLink[]
*/
protected $link = [];
/**
* A digital signature along with supporting context. The signature may be
* electronic/cryptographic in nature, or a graphical image representing a
* hand-written signature, or a signature process. Different Signature approaches
* have different utilities.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Digital Signature - base64 encoded. XML DigSIg or a JWT.
*
* @var null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRSignature
*/
protected $signature = null;
/**
* An integer with a value that is not negative (e.g. >= 0)
* If the element is present, it must have either a \@value, an \@id referenced from
* the Narrative, or extensions
*
* If a set of search matches, this is the total number of matches for the search
* (as opposed to the number of results in this bundle).
*
* @var null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRUnsignedInt
*/
protected $total = null;
/**
* Indicates the purpose of a bundle - how it was intended to be used.
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* Indicates the purpose of this bundle- how it was intended to be used.
*
* @var null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBundleType
*/
protected $type = null;
/**
* Validation map for fields in type Bundle
* @var array
*/
private static $_validationRules = [ ];
/**
* FHIRBundle Constructor
* @param null|array $data
*/
public function __construct($data = null)
{
if (null === $data || [] === $data) {
return;
}
if (!is_array($data)) {
throw new \InvalidArgumentException(sprintf(
'FHIRBundle::_construct - $data expected to be null or array, %s seen',
gettype($data)
));
}
parent::__construct($data);
if (isset($data[self::FIELD_ENTRY])) {
if (is_array($data[self::FIELD_ENTRY])) {
foreach($data[self::FIELD_ENTRY] as $v) {
if (null === $v) {
continue;
}
if ($v instanceof FHIRBundleEntry) {
$this->addEntry($v);
} else {
$this->addEntry(new FHIRBundleEntry($v));
}
}
} else if ($data[self::FIELD_ENTRY] instanceof FHIRBundleEntry) {
$this->addEntry($data[self::FIELD_ENTRY]);
} else {
$this->addEntry(new FHIRBundleEntry($data[self::FIELD_ENTRY]));
}
}
if (isset($data[self::FIELD_LINK])) {
if (is_array($data[self::FIELD_LINK])) {
foreach($data[self::FIELD_LINK] as $v) {
if (null === $v) {
continue;
}
if ($v instanceof FHIRBundleLink) {
$this->addLink($v);
} else {
$this->addLink(new FHIRBundleLink($v));
}
}
} else if ($data[self::FIELD_LINK] instanceof FHIRBundleLink) {
$this->addLink($data[self::FIELD_LINK]);
} else {
$this->addLink(new FHIRBundleLink($data[self::FIELD_LINK]));
}
}
if (isset($data[self::FIELD_SIGNATURE])) {
if ($data[self::FIELD_SIGNATURE] instanceof FHIRSignature) {
$this->setSignature($data[self::FIELD_SIGNATURE]);
} else {
$this->setSignature(new FHIRSignature($data[self::FIELD_SIGNATURE]));
}
}
if (isset($data[self::FIELD_TOTAL]) || isset($data[self::FIELD_TOTAL_EXT])) {
if (isset($data[self::FIELD_TOTAL])) {
$value = $data[self::FIELD_TOTAL];
} else {
$value = null;
}
if (isset($data[self::FIELD_TOTAL_EXT]) && is_array($data[self::FIELD_TOTAL_EXT])) {
$ext = $data[self::FIELD_TOTAL_EXT];
} else {
$ext = [];
}
if (null !== $value) {
if ($value instanceof FHIRUnsignedInt) {
$this->setTotal($value);
} else if (is_array($value)) {
$this->setTotal(new FHIRUnsignedInt(array_merge($ext, $value)));
} else {
$this->setTotal(new FHIRUnsignedInt([FHIRUnsignedInt::FIELD_VALUE => $value] + $ext));
}
} else if ([] !== $ext) {
$this->setTotal(new FHIRUnsignedInt($ext));
}
}
if (isset($data[self::FIELD_TYPE]) || isset($data[self::FIELD_TYPE_EXT])) {
if (isset($data[self::FIELD_TYPE])) {
$value = $data[self::FIELD_TYPE];
} else {
$value = null;
}
if (isset($data[self::FIELD_TYPE_EXT]) && is_array($data[self::FIELD_TYPE_EXT])) {
$ext = $data[self::FIELD_TYPE_EXT];
} else {
$ext = [];
}
if (null !== $value) {
if ($value instanceof FHIRBundleType) {
$this->setType($value);
} else if (is_array($value)) {
$this->setType(new FHIRBundleType(array_merge($ext, $value)));
} else {
$this->setType(new FHIRBundleType([FHIRBundleType::FIELD_VALUE => $value] + $ext));
}
} else if ([] !== $ext) {
$this->setType(new FHIRBundleType($ext));
}
}
}
/**
* @return string
*/
public function _getFHIRTypeName()
{
return self::FHIR_TYPE_NAME;
}
/**
* @return string
*/
public function _getFHIRXMLElementDefinition()
{
$xmlns = $this->_getFHIRXMLNamespace();
if (null !== $xmlns) {
$xmlns = " xmlns=\"{$xmlns}\"";
}
return "<Bundle{$xmlns}></Bundle>";
}
/**
* @return string
*/
public function _getResourceType()
{
return static::FHIR_TYPE_NAME;
}
/**
* A container for a collection of resources.
*
* An entry in a bundle resource - will either contain a resource, or information
* about a resource (transactions and history only).
*
* @return null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRBundle\FHIRBundleEntry[]
*/
public function getEntry()
{
return $this->entry;
}
/**
* A container for a collection of resources.
*
* An entry in a bundle resource - will either contain a resource, or information
* about a resource (transactions and history only).
*
* @param null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRBundle\FHIRBundleEntry $entry
* @return static
*/
public function addEntry(FHIRBundleEntry $entry = null)
{
$this->entry[] = $entry;
return $this;
}
/**
* A container for a collection of resources.
*
* An entry in a bundle resource - will either contain a resource, or information
* about a resource (transactions and history only).
*
* @param \DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRBundle\FHIRBundleEntry[] $entry
* @return static
*/
public function setEntry(array $entry = [])
{
$this->entry = [];
if ([] === $entry) {
return $this;
}
foreach($entry as $v) {
if ($v instanceof FHIRBundleEntry) {
$this->addEntry($v);
} else {
$this->addEntry(new FHIRBundleEntry($v));
}
}
return $this;
}
/**
* A container for a collection of resources.
*
* A series of links that provide context to this bundle.
*
* @return null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRBundle\FHIRBundleLink[]
*/
public function getLink()
{
return $this->link;
}
/**
* A container for a collection of resources.
*
* A series of links that provide context to this bundle.
*
* @param null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRBundle\FHIRBundleLink $link
* @return static
*/
public function addLink(FHIRBundleLink $link = null)
{
$this->link[] = $link;
return $this;
}
/**
* A container for a collection of resources.
*
* A series of links that provide context to this bundle.
*
* @param \DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRBundle\FHIRBundleLink[] $link
* @return static
*/
public function setLink(array $link = [])
{
$this->link = [];
if ([] === $link) {
return $this;
}
foreach($link as $v) {
if ($v instanceof FHIRBundleLink) {
$this->addLink($v);
} else {
$this->addLink(new FHIRBundleLink($v));
}
}
return $this;
}
/**
* A digital signature along with supporting context. The signature may be
* electronic/cryptographic in nature, or a graphical image representing a
* hand-written signature, or a signature process. Different Signature approaches
* have different utilities.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Digital Signature - base64 encoded. XML DigSIg or a JWT.
*
* @return null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRSignature
*/
public function getSignature()
{
return $this->signature;
}
/**
* A digital signature along with supporting context. The signature may be
* electronic/cryptographic in nature, or a graphical image representing a
* hand-written signature, or a signature process. Different Signature approaches
* have different utilities.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Digital Signature - base64 encoded. XML DigSIg or a JWT.
*
* @param null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRSignature $signature
* @return static
*/
public function setSignature(FHIRSignature $signature = null)
{
$this->signature = $signature;
return $this;
}
/**
* An integer with a value that is not negative (e.g. >= 0)
* If the element is present, it must have either a \@value, an \@id referenced from
* the Narrative, or extensions
*
* If a set of search matches, this is the total number of matches for the search
* (as opposed to the number of results in this bundle).
*
* @return null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRUnsignedInt
*/
public function getTotal()
{
return $this->total;
}
/**
* An integer with a value that is not negative (e.g. >= 0)
* If the element is present, it must have either a \@value, an \@id referenced from
* the Narrative, or extensions
*
* If a set of search matches, this is the total number of matches for the search
* (as opposed to the number of results in this bundle).
*
* @param null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRUnsignedInt $total
* @return static
*/
public function setTotal($total = null)
{
if (null === $total) {
$this->total = null;
return $this;
}
if ($total instanceof FHIRUnsignedInt) {
$this->total = $total;
return $this;
}
$this->total = new FHIRUnsignedInt($total);
return $this;
}
/**
* Indicates the purpose of a bundle - how it was intended to be used.
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* Indicates the purpose of this bundle- how it was intended to be used.
*
* @return null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBundleType
*/
public function getType()
{
return $this->type;
}
/**
* Indicates the purpose of a bundle - how it was intended to be used.
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* Indicates the purpose of this bundle- how it was intended to be used.
*
* @param null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBundleType $type
* @return static
*/
public function setType(FHIRBundleType $type = null)
{
$this->type = $type;
return $this;
}
/**
* Returns the validation rules that this type's fields must comply with to be considered "valid"
* The returned array is in ["fieldname[.offset]" => ["rule" => {constraint}]]
*
* @return array
*/
public function _getValidationRules()
{
return self::$_validationRules;
}
/**
* Validates that this type conforms to the specifications set forth for it by FHIR. An empty array must be seen as
* passing.
*
* @return array
*/
public function _getValidationErrors()
{
$errs = parent::_getValidationErrors();
$validationRules = $this->_getValidationRules();
if ([] !== ($vs = $this->getEntry())) {
foreach($vs as $i => $v) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[sprintf('%s.%d', self::FIELD_ENTRY, $i)] = $fieldErrs;
}
}
}
if ([] !== ($vs = $this->getLink())) {
foreach($vs as $i => $v) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[sprintf('%s.%d', self::FIELD_LINK, $i)] = $fieldErrs;
}
}
}
if (null !== ($v = $this->getSignature())) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[self::FIELD_SIGNATURE] = $fieldErrs;
}
}
if (null !== ($v = $this->getTotal())) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[self::FIELD_TOTAL] = $fieldErrs;
}
}
if (null !== ($v = $this->getType())) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[self::FIELD_TYPE] = $fieldErrs;
}
}
if (isset($validationRules[self::FIELD_ENTRY])) {
$v = $this->getEntry();
foreach($validationRules[self::FIELD_ENTRY] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_BUNDLE, self::FIELD_ENTRY, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_ENTRY])) {
$errs[self::FIELD_ENTRY] = [];
}
$errs[self::FIELD_ENTRY][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_LINK])) {
$v = $this->getLink();
foreach($validationRules[self::FIELD_LINK] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_BUNDLE, self::FIELD_LINK, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_LINK])) {
$errs[self::FIELD_LINK] = [];
}
$errs[self::FIELD_LINK][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_SIGNATURE])) {
$v = $this->getSignature();
foreach($validationRules[self::FIELD_SIGNATURE] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_BUNDLE, self::FIELD_SIGNATURE, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_SIGNATURE])) {
$errs[self::FIELD_SIGNATURE] = [];
}
$errs[self::FIELD_SIGNATURE][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_TOTAL])) {
$v = $this->getTotal();
foreach($validationRules[self::FIELD_TOTAL] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_BUNDLE, self::FIELD_TOTAL, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_TOTAL])) {
$errs[self::FIELD_TOTAL] = [];
}
$errs[self::FIELD_TOTAL][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_TYPE])) {
$v = $this->getType();
foreach($validationRules[self::FIELD_TYPE] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_BUNDLE, self::FIELD_TYPE, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_TYPE])) {
$errs[self::FIELD_TYPE] = [];
}
$errs[self::FIELD_TYPE][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_ID])) {
$v = $this->getId();
foreach($validationRules[self::FIELD_ID] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_ID, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_ID])) {
$errs[self::FIELD_ID] = [];
}
$errs[self::FIELD_ID][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_IMPLICIT_RULES])) {
$v = $this->getImplicitRules();
foreach($validationRules[self::FIELD_IMPLICIT_RULES] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_IMPLICIT_RULES, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_IMPLICIT_RULES])) {
$errs[self::FIELD_IMPLICIT_RULES] = [];
}
$errs[self::FIELD_IMPLICIT_RULES][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_LANGUAGE])) {
$v = $this->getLanguage();
foreach($validationRules[self::FIELD_LANGUAGE] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_LANGUAGE, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_LANGUAGE])) {
$errs[self::FIELD_LANGUAGE] = [];
}
$errs[self::FIELD_LANGUAGE][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_META])) {
$v = $this->getMeta();
foreach($validationRules[self::FIELD_META] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_META, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_META])) {
$errs[self::FIELD_META] = [];
}
$errs[self::FIELD_META][$rule] = $err;
}
}
}
return $errs;
}
/**
* @param \SimpleXMLElement|string|null $sxe
* @param null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRResource\FHIRBundle $type
* @param null|int $libxmlOpts
* @return null|\DCarbone\PHPFHIRGenerated\DSTU2\FHIRResource\FHIRBundle
*/
public static function xmlUnserialize($sxe = null, PHPFHIRTypeInterface $type = null, $libxmlOpts = 591872)
{
if (null === $sxe) {
return null;
}
if (is_string($sxe)) {
libxml_use_internal_errors(true);
$sxe = new \SimpleXMLElement($sxe, $libxmlOpts, false);
if ($sxe === false) {
throw new \DomainException(sprintf('FHIRBundle::xmlUnserialize - String provided is not parseable as XML: %s', implode(', ', array_map(function(\libXMLError $err) { return $err->message; }, libxml_get_errors()))));
}
libxml_use_internal_errors(false);
}
if (!($sxe instanceof \SimpleXMLElement)) {
throw new \InvalidArgumentException(sprintf('FHIRBundle::xmlUnserialize - $sxe value must be null, \\SimpleXMLElement, or valid XML string, %s seen', gettype($sxe)));
}
if (null === $type) {
$type = new FHIRBundle;
} elseif (!is_object($type) || !($type instanceof FHIRBundle)) {
throw new \RuntimeException(sprintf(
'FHIRBundle::xmlUnserialize - $type must be instance of \DCarbone\PHPFHIRGenerated\DSTU2\FHIRResource\FHIRBundle or null, %s seen.',
is_object($type) ? get_class($type) : gettype($type)
));
}
FHIRResource::xmlUnserialize($sxe, $type);
$xmlNamespaces = $sxe->getDocNamespaces(false, false);
if ([] !== $xmlNamespaces) {
$ns = reset($xmlNamespaces);
if (false !== $ns && '' !== $ns) {
$type->_xmlns = $ns;
}
}
$attributes = $sxe->attributes();
$children = $sxe->children();
if (isset($children->entry)) {
foreach($children->entry as $child) {
$type->addEntry(FHIRBundleEntry::xmlUnserialize($child));
}
}
if (isset($children->link)) {
foreach($children->link as $child) {
$type->addLink(FHIRBundleLink::xmlUnserialize($child));
}
}
if (isset($children->signature)) {
$type->setSignature(FHIRSignature::xmlUnserialize($children->signature));
}
if (isset($children->total)) {
$type->setTotal(FHIRUnsignedInt::xmlUnserialize($children->total));
}
if (isset($attributes->total)) {
$pt = $type->getTotal();
if (null !== $pt) {
$pt->setValue((string)$attributes->total);
} else {
$type->setTotal((string)$attributes->total);
}
}
if (isset($children->type)) {
$type->setType(FHIRBundleType::xmlUnserialize($children->type));
}
return $type;
}
/**
* @param null|\SimpleXMLElement $sxe
* @param null|int $libxmlOpts
* @return \SimpleXMLElement
*/
public function xmlSerialize(\SimpleXMLElement $sxe = null, $libxmlOpts = 591872)
{
if (null === $sxe) {
$sxe = new \SimpleXMLElement($this->_getFHIRXMLElementDefinition(), $libxmlOpts, false);
}
parent::xmlSerialize($sxe);
if ([] !== ($vs = $this->getEntry())) {
foreach($vs as $v) {
if (null === $v) {
continue;
}
$v->xmlSerialize($sxe->addChild(self::FIELD_ENTRY, null, $v->_getFHIRXMLNamespace()));
}
}
if ([] !== ($vs = $this->getLink())) {
foreach($vs as $v) {
if (null === $v) {
continue;
}
$v->xmlSerialize($sxe->addChild(self::FIELD_LINK, null, $v->_getFHIRXMLNamespace()));
}
}
if (null !== ($v = $this->getSignature())) {
$v->xmlSerialize($sxe->addChild(self::FIELD_SIGNATURE, null, $v->_getFHIRXMLNamespace()));
}
if (null !== ($v = $this->getTotal())) {
$v->xmlSerialize($sxe->addChild(self::FIELD_TOTAL, null, $v->_getFHIRXMLNamespace()));
}
if (null !== ($v = $this->getType())) {
$v->xmlSerialize($sxe->addChild(self::FIELD_TYPE, null, $v->_getFHIRXMLNamespace()));
}
return $sxe;
}
/**
* @return array
*/
public function jsonSerialize()
{
$a = parent::jsonSerialize();
if ([] !== ($vs = $this->getEntry())) {
$a[self::FIELD_ENTRY] = [];
foreach($vs as $v) {
if (null === $v) {
continue;
}
$a[self::FIELD_ENTRY][] = $v;
}
}
if ([] !== ($vs = $this->getLink())) {
$a[self::FIELD_LINK] = [];
foreach($vs as $v) {
if (null === $v) {
continue;
}
$a[self::FIELD_LINK][] = $v;
}
}
if (null !== ($v = $this->getSignature())) {
$a[self::FIELD_SIGNATURE] = $v;
}
if (null !== ($v = $this->getTotal())) {
$a[self::FIELD_TOTAL] = $v->getValue();
$enc = $v->jsonSerialize();
$cnt = count($enc);
if (0 < $cnt && (1 !== $cnt || (1 === $cnt && !array_key_exists(FHIRUnsignedInt::FIELD_VALUE, $enc)))) {
unset($enc[FHIRUnsignedInt::FIELD_VALUE]);
$a[self::FIELD_TOTAL_EXT] = $enc;
}
}
if (null !== ($v = $this->getType())) {
$a[self::FIELD_TYPE] = $v->getValue();
$enc = $v->jsonSerialize();
$cnt = count($enc);
if (0 < $cnt && (1 !== $cnt || (1 === $cnt && !array_key_exists(FHIRBundleType::FIELD_VALUE, $enc)))) {
unset($enc[FHIRBundleType::FIELD_VALUE]);
$a[self::FIELD_TYPE_EXT] = $enc;
}
}
if ([] !== ($vs = $this->_getFHIRComments())) {
$a[PHPFHIRConstants::JSON_FIELD_FHIR_COMMENTS] = $vs;
}
return [PHPFHIRConstants::JSON_FIELD_RESOURCE_TYPE => $this->_getResourceType()] + $a;
}
/**
* @return string
*/
public function __toString()
{
return self::FHIR_TYPE_NAME;
}
} | {
"content_hash": "e960fc85693e1d6609e518cf23e4a032",
"timestamp": "",
"source": "github",
"line_count": 771,
"max_line_length": 230,
"avg_line_length": 37.509727626459146,
"alnum_prop": 0.527627939142462,
"repo_name": "dcarbone/php-fhir-generated",
"id": "7d129e1ba21dad8f4a4e25278ca68af03d65c9f6",
"size": "31810",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/DCarbone/PHPFHIRGenerated/DSTU2/FHIRResource/FHIRBundle.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "113066525"
}
],
"symlink_target": ""
} |
<?php
namespace Joomla\Filter;
use Joomla\String\StringHelper;
/**
* InputFilter is a class for filtering input from any data source
*
* Forked from the php input filter library by: Daniel Morris <dan@rootcube.com>
* Original Contributors: Gianpaolo Racca, Ghislain Picard, Marco Wandschneider, Chris Tobin and Andrew Eddie.
*
* @since 1.0
*/
class InputFilter
{
/**
* A container for InputFilter instances.
*
* @var InputFilter[]
* @since 1.0
* @deprecated 2.0
*/
protected static $instances = array();
/**
* The array of permitted tags (white list).
*
* @var array
* @since 1.0
*/
public $tagsArray;
/**
* The array of permitted tag attributes (white list).
*
* @var array
* @since 1.0
*/
public $attrArray;
/**
* The method for sanitising tags: WhiteList method = 0 (default), BlackList method = 1
*
* @var integer
* @since 1.0
*/
public $tagsMethod;
/**
* The method for sanitising attributes: WhiteList method = 0 (default), BlackList method = 1
*
* @var integer
* @since 1.0
*/
public $attrMethod;
/**
* A flag for XSS checks. Only auto clean essentials = 0, Allow clean blacklisted tags/attr = 1
*
* @var integer
* @since 1.0
*/
public $xssAuto;
/**
* The list of the default blacklisted tags.
*
* @var array
* @since 1.0
*/
public $tagBlacklist = array(
'applet',
'body',
'bgsound',
'base',
'basefont',
'embed',
'frame',
'frameset',
'head',
'html',
'id',
'iframe',
'ilayer',
'layer',
'link',
'meta',
'name',
'object',
'script',
'style',
'title',
'xml',
);
/**
* The list of the default blacklisted tag attributes. All event handlers implicit.
*
* @var array
* @since 1.0
*/
public $attrBlacklist = array(
'action',
'background',
'codebase',
'dynsrc',
'lowsrc',
);
/**
* Constructor for InputFilter class.
*
* @param array $tagsArray List of user-defined tags
* @param array $attrArray List of user-defined attributes
* @param integer $tagsMethod WhiteList method = 0, BlackList method = 1
* @param integer $attrMethod WhiteList method = 0, BlackList method = 1
* @param integer $xssAuto Only auto clean essentials = 0, Allow clean blacklisted tags/attr = 1
*
* @since 1.0
*/
public function __construct($tagsArray = array(), $attrArray = array(), $tagsMethod = 0, $attrMethod = 0, $xssAuto = 1)
{
// Make sure user defined arrays are in lowercase
$tagsArray = array_map('strtolower', (array) $tagsArray);
$attrArray = array_map('strtolower', (array) $attrArray);
// Assign member variables
$this->tagsArray = $tagsArray;
$this->attrArray = $attrArray;
$this->tagsMethod = $tagsMethod;
$this->attrMethod = $attrMethod;
$this->xssAuto = $xssAuto;
}
/**
* Method to be called by another php script. Processes for XSS and
* specified bad code.
*
* @param mixed $source Input string/array-of-string to be 'cleaned'
* @param string $type The return type for the variable:
* INT: An integer, or an array of integers,
* UINT: An unsigned integer, or an array of unsigned integers,
* FLOAT: A floating point number, or an array of floating point numbers,
* BOOLEAN: A boolean value,
* WORD: A string containing A-Z or underscores only (not case sensitive),
* ALNUM: A string containing A-Z or 0-9 only (not case sensitive),
* CMD: A string containing A-Z, 0-9, underscores, periods or hyphens (not case sensitive),
* BASE64: A string containing A-Z, 0-9, forward slashes, plus or equals (not case sensitive),
* STRING: A fully decoded and sanitised string (default),
* HTML: A sanitised string,
* ARRAY: An array,
* PATH: A sanitised file path, or an array of sanitised file paths,
* TRIM: A string trimmed from normal, non-breaking and multibyte spaces
* USERNAME: Do not use (use an application specific filter),
* RAW: The raw string is returned with no filtering,
* unknown: An unknown filter will act like STRING. If the input is an array it will return an
* array of fully decoded and sanitised strings.
*
* @return mixed 'Cleaned' version of input parameter
*
* @since 1.0
*/
public function clean($source, $type = 'string')
{
// Handle the type constraint cases
switch (strtoupper($type))
{
case 'INT':
case 'INTEGER':
$pattern = '/[-+]?[0-9]+/';
if (is_array($source))
{
$result = array();
// Iterate through the array
foreach ($source as $eachString)
{
preg_match($pattern, (string) $eachString, $matches);
$result[] = isset($matches[0]) ? (int) $matches[0] : 0;
}
}
else
{
preg_match($pattern, (string) $source, $matches);
$result = isset($matches[0]) ? (int) $matches[0] : 0;
}
break;
case 'UINT':
$pattern = '/[-+]?[0-9]+/';
if (is_array($source))
{
$result = array();
// Iterate through the array
foreach ($source as $eachString)
{
preg_match($pattern, (string) $eachString, $matches);
$result[] = isset($matches[0]) ? abs((int) $matches[0]) : 0;
}
}
else
{
preg_match($pattern, (string) $source, $matches);
$result = isset($matches[0]) ? abs((int) $matches[0]) : 0;
}
break;
case 'FLOAT':
case 'DOUBLE':
$pattern = '/[-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?/';
if (is_array($source))
{
$result = array();
// Iterate through the array
foreach ($source as $eachString)
{
preg_match($pattern, (string) $eachString, $matches);
$result[] = isset($matches[0]) ? (float) $matches[0] : 0;
}
}
else
{
preg_match($pattern, (string) $source, $matches);
$result = isset($matches[0]) ? (float) $matches[0] : 0;
}
break;
case 'BOOL':
case 'BOOLEAN':
$result = (bool) $source;
break;
case 'WORD':
$pattern = '/[^A-Z_]/i';
if (is_array($source))
{
$result = array();
// Iterate through the array
foreach ($source as $eachString)
{
$result[] = (string) preg_replace($pattern, '', $eachString);
}
}
else
{
$result = (string) preg_replace($pattern, '', $source);
}
break;
case 'ALNUM':
$pattern = '/[^A-Z0-9]/i';
if (is_array($source))
{
$result = array();
// Iterate through the array
foreach ($source as $eachString)
{
$result[] = (string) preg_replace($pattern, '', $eachString);
}
}
else
{
$result = (string) preg_replace($pattern, '', $source);
}
break;
case 'CMD':
$pattern = '/[^A-Z0-9_\.-]/i';
if (is_array($source))
{
$result = array();
// Iterate through the array
foreach ($source as $eachString)
{
$cleaned = (string) preg_replace($pattern, '', $eachString);
$result[] = ltrim($cleaned, '.');
}
}
else
{
$result = (string) preg_replace($pattern, '', $source);
$result = ltrim($result, '.');
}
break;
case 'BASE64':
$pattern = '/[^A-Z0-9\/+=]/i';
if (is_array($source))
{
$result = array();
// Iterate through the array
foreach ($source as $eachString)
{
$result[] = (string) preg_replace($pattern, '', $eachString);
}
}
else
{
$result = (string) preg_replace($pattern, '', $source);
}
break;
case 'STRING':
if (is_array($source))
{
$result = array();
// Iterate through the array
foreach ($source as $eachString)
{
$result[] = (string) $this->remove($this->decode((string) $eachString));
}
}
else
{
$result = (string) $this->remove($this->decode((string) $source));
}
break;
case 'HTML':
if (is_array($source))
{
$result = array();
// Iterate through the array
foreach ($source as $eachString)
{
$result[] = (string) $this->remove((string) $eachString);
}
}
else
{
$result = (string) $this->remove((string) $source);
}
break;
case 'ARRAY':
$result = (array) $source;
break;
case 'PATH':
$pattern = '/^[A-Za-z0-9_\/-]+[A-Za-z0-9_\.-]*([\\\\\/][A-Za-z0-9_-]+[A-Za-z0-9_\.-]*)*$/';
if (is_array($source))
{
$result = array();
// Iterate through the array
foreach ($source as $eachString)
{
preg_match($pattern, (string) $eachString, $matches);
$result[] = isset($matches[0]) ? (string) $matches[0] : '';
}
}
else
{
preg_match($pattern, $source, $matches);
$result = isset($matches[0]) ? (string) $matches[0] : '';
}
break;
case 'TRIM':
if (is_array($source))
{
$result = array();
// Iterate through the array
foreach ($source as $eachString)
{
$cleaned = (string) trim($eachString);
$cleaned = StringHelper::trim($cleaned, chr(0xE3) . chr(0x80) . chr(0x80));
$result[] = StringHelper::trim($cleaned, chr(0xC2) . chr(0xA0));
}
}
else
{
$result = (string) trim($source);
$result = StringHelper::trim($result, chr(0xE3) . chr(0x80) . chr(0x80));
$result = StringHelper::trim($result, chr(0xC2) . chr(0xA0));
}
break;
case 'USERNAME':
$pattern = '/[\x00-\x1F\x7F<>"\'%&]/';
if (is_array($source))
{
$result = array();
// Iterate through the array
foreach ($source as $eachString)
{
$result[] = (string) preg_replace($pattern, '', $eachString);
}
}
else
{
$result = (string) preg_replace($pattern, '', $source);
}
break;
case 'RAW':
$result = $source;
break;
default:
// Are we dealing with an array?
if (is_array($source))
{
foreach ($source as $key => $value)
{
// Filter element for XSS and other 'bad' code etc.
if (is_string($value))
{
$source[$key] = $this->remove($this->decode($value));
}
}
$result = $source;
}
else
{
// Or a string?
if (is_string($source) && !empty($source))
{
// Filter source for XSS and other 'bad' code etc.
$result = $this->remove($this->decode($source));
}
else
{
// Not an array or string... return the passed parameter
$result = $source;
}
}
break;
}
return $result;
}
/**
* Function to determine if contents of an attribute are safe
*
* @param array $attrSubSet A 2 element array for attribute's name, value
*
* @return boolean True if bad code is detected
*
* @since 1.0
*/
public static function checkAttribute($attrSubSet)
{
$attrSubSet[0] = strtolower($attrSubSet[0]);
$attrSubSet[1] = strtolower($attrSubSet[1]);
return (((strpos($attrSubSet[1], 'expression') !== false) && ($attrSubSet[0]) == 'style') || (strpos($attrSubSet[1], 'javascript:') !== false) ||
(strpos($attrSubSet[1], 'behaviour:') !== false) || (strpos($attrSubSet[1], 'vbscript:') !== false) ||
(strpos($attrSubSet[1], 'mocha:') !== false) || (strpos($attrSubSet[1], 'livescript:') !== false));
}
/**
* Internal method to iteratively remove all unwanted tags and attributes
*
* @param string $source Input string to be 'cleaned'
*
* @return string 'Cleaned' version of input parameter
*
* @since 1.0
*/
protected function remove($source)
{
$loopCounter = 0;
// Iteration provides nested tag protection
while ($source != $this->cleanTags($source))
{
$source = $this->cleanTags($source);
$loopCounter++;
}
return $source;
}
/**
* Internal method to strip a string of certain tags
*
* @param string $source Input string to be 'cleaned'
*
* @return string 'Cleaned' version of input parameter
*
* @since 1.0
*/
protected function cleanTags($source)
{
// First, pre-process this for illegal characters inside attribute values
$source = $this->escapeAttributeValues($source);
// In the beginning we don't really have a tag, so everything is postTag
$preTag = null;
$postTag = $source;
$currentSpace = false;
// Setting to null to deal with undefined variables
$attr = '';
// Is there a tag? If so it will certainly start with a '<'.
$tagOpen_start = strpos($source, '<');
while ($tagOpen_start !== false)
{
// Get some information about the tag we are processing
$preTag .= substr($postTag, 0, $tagOpen_start);
$postTag = substr($postTag, $tagOpen_start);
$fromTagOpen = substr($postTag, 1);
$tagOpen_end = strpos($fromTagOpen, '>');
// Check for mal-formed tag where we have a second '<' before the first '>'
$nextOpenTag = (strlen($postTag) > $tagOpen_start) ? strpos($postTag, '<', $tagOpen_start + 1) : false;
if (($nextOpenTag !== false) && ($nextOpenTag < $tagOpen_end))
{
// At this point we have a mal-formed tag -- remove the offending open
$postTag = substr($postTag, 0, $tagOpen_start) . substr($postTag, $tagOpen_start + 1);
$tagOpen_start = strpos($postTag, '<');
continue;
}
// Let's catch any non-terminated tags and skip over them
if ($tagOpen_end === false)
{
$postTag = substr($postTag, $tagOpen_start + 1);
$tagOpen_start = strpos($postTag, '<');
continue;
}
// Do we have a nested tag?
$tagOpen_nested = strpos($fromTagOpen, '<');
if (($tagOpen_nested !== false) && ($tagOpen_nested < $tagOpen_end))
{
$preTag .= substr($postTag, 0, ($tagOpen_nested + 1));
$postTag = substr($postTag, ($tagOpen_nested + 1));
$tagOpen_start = strpos($postTag, '<');
continue;
}
// Let's get some information about our tag and setup attribute pairs
$tagOpen_nested = (strpos($fromTagOpen, '<') + $tagOpen_start + 1);
$currentTag = substr($fromTagOpen, 0, $tagOpen_end);
$tagLength = strlen($currentTag);
$tagLeft = $currentTag;
$attrSet = array();
$currentSpace = strpos($tagLeft, ' ');
// Are we an open tag or a close tag?
if (substr($currentTag, 0, 1) == '/')
{
// Close Tag
$isCloseTag = true;
list ($tagName) = explode(' ', $currentTag);
$tagName = substr($tagName, 1);
}
else
{
// Open Tag
$isCloseTag = false;
list ($tagName) = explode(' ', $currentTag);
}
/*
* Exclude all "non-regular" tagnames
* OR no tagname
* OR remove if xssauto is on and tag is blacklisted
*/
if ((!preg_match("/^[a-z][a-z0-9]*$/i", $tagName)) || (!$tagName) || ((in_array(strtolower($tagName), $this->tagBlacklist)) && ($this->xssAuto)))
{
$postTag = substr($postTag, ($tagLength + 2));
$tagOpen_start = strpos($postTag, '<');
// Strip tag
continue;
}
/*
* Time to grab any attributes from the tag... need this section in
* case attributes have spaces in the values.
*/
while ($currentSpace !== false)
{
$attr = '';
$fromSpace = substr($tagLeft, ($currentSpace + 1));
$nextEqual = strpos($fromSpace, '=');
$nextSpace = strpos($fromSpace, ' ');
$openQuotes = strpos($fromSpace, '"');
$closeQuotes = strpos(substr($fromSpace, ($openQuotes + 1)), '"') + $openQuotes + 1;
$startAtt = '';
$startAttPosition = 0;
// Find position of equal and open quotes ignoring
if (preg_match('#\s*=\s*\"#', $fromSpace, $matches, PREG_OFFSET_CAPTURE))
{
$startAtt = $matches[0][0];
$startAttPosition = $matches[0][1];
$closeQuotes = strpos(substr($fromSpace, ($startAttPosition + strlen($startAtt))), '"') + $startAttPosition + strlen($startAtt);
$nextEqual = $startAttPosition + strpos($startAtt, '=');
$openQuotes = $startAttPosition + strpos($startAtt, '"');
$nextSpace = strpos(substr($fromSpace, $closeQuotes), ' ') + $closeQuotes;
}
// Do we have an attribute to process? [check for equal sign]
if ($fromSpace != '/' && (($nextEqual && $nextSpace && $nextSpace < $nextEqual) || !$nextEqual))
{
if (!$nextEqual)
{
$attribEnd = strpos($fromSpace, '/') - 1;
}
else
{
$attribEnd = $nextSpace - 1;
}
// If there is an ending, use this, if not, do not worry.
if ($attribEnd > 0)
{
$fromSpace = substr($fromSpace, $attribEnd + 1);
}
}
if (strpos($fromSpace, '=') !== false)
{
// If the attribute value is wrapped in quotes we need to grab the substring from
// the closing quote, otherwise grab until the next space.
if (($openQuotes !== false) && (strpos(substr($fromSpace, ($openQuotes + 1)), '"') !== false))
{
$attr = substr($fromSpace, 0, ($closeQuotes + 1));
}
else
{
$attr = substr($fromSpace, 0, $nextSpace);
}
}
else
// No more equal signs so add any extra text in the tag into the attribute array [eg. checked]
{
if ($fromSpace != '/')
{
$attr = substr($fromSpace, 0, $nextSpace);
}
}
// Last Attribute Pair
if (!$attr && $fromSpace != '/')
{
$attr = $fromSpace;
}
// Add attribute pair to the attribute array
$attrSet[] = $attr;
// Move search point and continue iteration
$tagLeft = substr($fromSpace, strlen($attr));
$currentSpace = strpos($tagLeft, ' ');
}
// Is our tag in the user input array?
$tagFound = in_array(strtolower($tagName), $this->tagsArray);
// If the tag is allowed let's append it to the output string.
if ((!$tagFound && $this->tagsMethod) || ($tagFound && !$this->tagsMethod))
{
// Reconstruct tag with allowed attributes
if (!$isCloseTag)
{
// Open or single tag
$attrSet = $this->cleanAttributes($attrSet);
$preTag .= '<' . $tagName;
for ($i = 0, $count = count($attrSet); $i < $count; $i++)
{
$preTag .= ' ' . $attrSet[$i];
}
// Reformat single tags to XHTML
if (strpos($fromTagOpen, '</' . $tagName))
{
$preTag .= '>';
}
else
{
$preTag .= ' />';
}
}
else
// Closing tag
{
$preTag .= '</' . $tagName . '>';
}
}
// Find next tag's start and continue iteration
$postTag = substr($postTag, ($tagLength + 2));
$tagOpen_start = strpos($postTag, '<');
}
// Append any code after the end of tags and return
if ($postTag != '<')
{
$preTag .= $postTag;
}
return $preTag;
}
/**
* Internal method to strip a tag of certain attributes
*
* @param array $attrSet Array of attribute pairs to filter
*
* @return array Filtered array of attribute pairs
*
* @since 1.0
*/
protected function cleanAttributes($attrSet)
{
$newSet = array();
$count = count($attrSet);
// Iterate through attribute pairs
for ($i = 0; $i < $count; $i++)
{
// Skip blank spaces
if (!$attrSet[$i])
{
continue;
}
// Split into name/value pairs
$attrSubSet = explode('=', trim($attrSet[$i]), 2);
// Take the last attribute in case there is an attribute with no value
$attrSubSet_0 = explode(' ', trim($attrSubSet[0]));
$attrSubSet[0] = array_pop($attrSubSet_0);
// Remove all "non-regular" attribute names
// AND blacklisted attributes
if ((!preg_match('/[a-z]*$/i', $attrSubSet[0]))
|| (($this->xssAuto) && ((in_array(strtolower($attrSubSet[0]), $this->attrBlacklist))
|| (substr($attrSubSet[0], 0, 2) == 'on'))))
{
continue;
}
// XSS attribute value filtering
if (isset($attrSubSet[1]))
{
// Trim leading and trailing spaces
$attrSubSet[1] = trim($attrSubSet[1]);
// Strips unicode, hex, etc
$attrSubSet[1] = str_replace('&#', '', $attrSubSet[1]);
// Strip normal newline within attr value
$attrSubSet[1] = preg_replace('/[\n\r]/', '', $attrSubSet[1]);
// Strip double quotes
$attrSubSet[1] = str_replace('"', '', $attrSubSet[1]);
// Convert single quotes from either side to doubles (Single quotes shouldn't be used to pad attr values)
if ((substr($attrSubSet[1], 0, 1) == "'") && (substr($attrSubSet[1], (strlen($attrSubSet[1]) - 1), 1) == "'"))
{
$attrSubSet[1] = substr($attrSubSet[1], 1, (strlen($attrSubSet[1]) - 2));
}
// Strip slashes
$attrSubSet[1] = stripslashes($attrSubSet[1]);
}
else
{
continue;
}
// Autostrip script tags
if (self::checkAttribute($attrSubSet))
{
continue;
}
// Is our attribute in the user input array?
$attrFound = in_array(strtolower($attrSubSet[0]), $this->attrArray);
// If the tag is allowed lets keep it
if ((!$attrFound && $this->attrMethod) || ($attrFound && !$this->attrMethod))
{
// Does the attribute have a value?
if (empty($attrSubSet[1]) === false)
{
$newSet[] = $attrSubSet[0] . '="' . $attrSubSet[1] . '"';
}
elseif ($attrSubSet[1] === "0")
{
// Special Case
// Is the value 0?
$newSet[] = $attrSubSet[0] . '="0"';
}
else
{
// Leave empty attributes alone
$newSet[] = $attrSubSet[0] . '=""';
}
}
}
return $newSet;
}
/**
* Try to convert to plaintext
*
* @param string $source The source string.
*
* @return string Plaintext string
*
* @since 1.0
* @deprecated This method will be removed once support for PHP 5.3 is discontinued.
*/
protected function decode($source)
{
return html_entity_decode($source, ENT_QUOTES, 'UTF-8');
}
/**
* Escape < > and " inside attribute values
*
* @param string $source The source string.
*
* @return string Filtered string
*
* @since 1.0
*/
protected function escapeAttributeValues($source)
{
$alreadyFiltered = '';
$remainder = $source;
$badChars = array('<', '"', '>');
$escapedChars = array('<', '"', '>');
// Process each portion based on presence of =" and "<space>, "/>, or ">
// See if there are any more attributes to process
while (preg_match('#<[^>]*?=\s*?(\"|\')#s', $remainder, $matches, PREG_OFFSET_CAPTURE))
{
// Get the portion before the attribute value
$quotePosition = $matches[0][1];
$nextBefore = $quotePosition + strlen($matches[0][0]);
// Figure out if we have a single or double quote and look for the matching closing quote
// Closing quote should be "/>, ">, "<space>, or " at the end of the string
$quote = substr($matches[0][0], -1);
$pregMatch = ($quote == '"') ? '#(\"\s*/\s*>|\"\s*>|\"\s+|\"$)#' : "#(\'\s*/\s*>|\'\s*>|\'\s+|\'$)#";
// Get the portion after attribute value
if (preg_match($pregMatch, substr($remainder, $nextBefore), $matches, PREG_OFFSET_CAPTURE))
{
// We have a closing quote
$nextAfter = $nextBefore + $matches[0][1];
}
else
{
// No closing quote
$nextAfter = strlen($remainder);
}
// Get the actual attribute value
$attributeValue = substr($remainder, $nextBefore, $nextAfter - $nextBefore);
// Escape bad chars
$attributeValue = str_replace($badChars, $escapedChars, $attributeValue);
$attributeValue = $this->stripCssExpressions($attributeValue);
$alreadyFiltered .= substr($remainder, 0, $nextBefore) . $attributeValue . $quote;
$remainder = substr($remainder, $nextAfter + 1);
}
// At this point, we just have to return the $alreadyFiltered and the $remainder
return $alreadyFiltered . $remainder;
}
/**
* Remove CSS Expressions in the form of <property>:expression(...)
*
* @param string $source The source string.
*
* @return string Filtered string
*
* @since 1.0
*/
protected function stripCssExpressions($source)
{
// Strip any comments out (in the form of /*...*/)
$test = preg_replace('#\/\*.*\*\/#U', '', $source);
// Test for :expression
if (!stripos($test, ':expression'))
{
// Not found, so we are done
$return = $source;
}
else
{
// At this point, we have stripped out the comments and have found :expression
// Test stripped string for :expression followed by a '('
if (preg_match_all('#:expression\s*\(#', $test, $matches))
{
// If found, remove :expression
$test = str_ireplace(':expression', '', $test);
$return = $test;
}
}
return $return;
}
}
| {
"content_hash": "ce542a5c5dc2c3d812ec25a6a733b8d5",
"timestamp": "",
"source": "github",
"line_count": 949,
"max_line_length": 148,
"avg_line_length": 25.969441517386723,
"alnum_prop": 0.567336173666058,
"repo_name": "yaelduckwen/lo_imaginario",
"id": "d58e9491b44fec62d13a19d45fd593a4971994bd",
"size": "24864",
"binary": false,
"copies": "139",
"ref": "refs/heads/master",
"path": "web2/libraries/vendor/joomla/filter/src/InputFilter.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "468"
},
{
"name": "CSS",
"bytes": "6260484"
},
{
"name": "HTML",
"bytes": "104589"
},
{
"name": "Java",
"bytes": "14870"
},
{
"name": "JavaScript",
"bytes": "3918522"
},
{
"name": "PHP",
"bytes": "27434460"
},
{
"name": "PLpgSQL",
"bytes": "2393"
},
{
"name": "SQLPL",
"bytes": "17688"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.camel</groupId>
<artifactId>components</artifactId>
<version>2.18.0-SNAPSHOT</version>
</parent>
<artifactId>camel-etcd</artifactId>
<packaging>jar</packaging>
<name>Camel :: Etcd</name>
<description>Camel Etcd support</description>
<properties>
<camel.osgi.export.pkg>org.apache.camel.component.etcd.*</camel.osgi.export.pkg>
<camel.osgi.export.service>
org.apache.camel.spi.ComponentResolver;component=etc
</camel.osgi.export.service>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>${project.version}</version>
</dependency>
<!-- etcd -->
<dependency>
<groupId>org.mousio</groupId>
<artifactId>etcd4j</artifactId>
<version>${etcd4j-version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3-version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<scope>test</scope>
</dependency>
<!-- testing -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test-spring</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-http</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jetty</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>etcd-skip-tests</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>etcd-tests</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>false</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
| {
"content_hash": "ed3f9cc93669fc24053821ab7efa6141",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 105,
"avg_line_length": 29.978102189781023,
"alnum_prop": 0.6437789140491843,
"repo_name": "JYBESSON/camel",
"id": "036033873decf7ca8be1843a9dd46f00c27b792d",
"size": "4107",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "components/camel-etcd/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "106"
},
{
"name": "CSS",
"bytes": "30373"
},
{
"name": "Eagle",
"bytes": "5510"
},
{
"name": "Elm",
"bytes": "5970"
},
{
"name": "FreeMarker",
"bytes": "11410"
},
{
"name": "Groovy",
"bytes": "55890"
},
{
"name": "HTML",
"bytes": "177803"
},
{
"name": "Java",
"bytes": "54712350"
},
{
"name": "JavaScript",
"bytes": "90232"
},
{
"name": "Protocol Buffer",
"bytes": "578"
},
{
"name": "Python",
"bytes": "36"
},
{
"name": "Ruby",
"bytes": "4802"
},
{
"name": "Scala",
"bytes": "323024"
},
{
"name": "Shell",
"bytes": "18818"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "284394"
}
],
"symlink_target": ""
} |
/**
* line.cpp
* Implementation of singleton methods for LINE
*/
#include "curve.h"
VALUE sr_cLine;
SR_CURVE_INIT(Line, Line, line)
bool siren_line_install()
{
SR_CURVE_DEFINE(Line)
rb_define_method(sr_cLine, "initialize", RUBY_METHOD_FUNC(siren_curve_init), -1);
rb_define_method(sr_cLine, "dir", RUBY_METHOD_FUNC(siren_line_dir), -1);
return true;
}
VALUE siren_line_dir(int argc, VALUE* argv, VALUE self)
{
handle<Geom_Line> line = siren_line_get(self);
return siren_dir_to_ary(line->Lin().Direction());
}
| {
"content_hash": "34b0853b4109c70bc6303ddc1527a859",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 83,
"avg_line_length": 22.416666666666668,
"alnum_prop": 0.6747211895910781,
"repo_name": "dyama/ruby-siren",
"id": "433bcc962deeb37eb359689496926ddb77e39e18",
"size": "538",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ext/siren2/src/curve/line.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "31242"
},
{
"name": "C++",
"bytes": "139040"
},
{
"name": "Ruby",
"bytes": "28139"
},
{
"name": "Shell",
"bytes": "131"
}
],
"symlink_target": ""
} |
// @COPYRIGHT@
// Licensed under MIT license (LICENSE.txt)
// clxx/cl/functions/get_image_info.t.h
/** // doc: clxx/cl/functions/get_image_info.t.h {{{
* \file clxx/cl/functions/get_image_info.t.h
* \todo Write documentation
*/ // }}}
#ifndef CLXX_CL_FUNCTIONS_GET_IMAGE_INFO_T_H_INCLUDED
#define CLXX_CL_FUNCTIONS_GET_IMAGE_INFO_T_H_INCLUDED
#include <cxxtest/TestSuite.h>
#include <clxx/cl/functions.hpp>
#include <clxx/common/exceptions.hpp>
#include <clxx/cl/mock.hpp>
namespace clxx { class functions_get_image_info_test_suite; }
/** // doc: class clxx::functions_get_image_info_test_suite {{{
* \todo Write documentation
*/ // }}}
class clxx::functions_get_image_info_test_suite : public CxxTest::TestSuite
{
public:
////////////////////////////////////////////////////////////////////////////
// get_image_info()
////////////////////////////////////////////////////////////////////////////
/** // doc: test__get_image_info() {{{
* \todo Write documentation
*/ // }}}
void test__get_image_info( )
{
T::Dummy_clGetImageInfo mock(CL_SUCCESS);
get_image_info ((cl_mem)0x395, image_info_t::format, 5, (void*)0x124, (size_t*)0x934);
TS_ASSERT(mock.called_once_with((cl_mem)0x395, (cl_mem_info)CL_IMAGE_FORMAT, 5, (void*)0x124, (size_t*)0x934));
}
/** // doc: test__get_image_info__invalid_value() {{{
* \todo Write documentation
*/ // }}}
void test__get_image_info__invalid_value( )
{
T::Dummy_clGetImageInfo mock(CL_INVALID_VALUE);
TS_ASSERT_THROWS(get_image_info((cl_mem)NULL, image_info_t::format, 0, nullptr, nullptr),clerror_no<status_t::invalid_value>);
}
/** // doc: test__get_image_info__invalid_mem_object() {{{
* \todo Write documentation
*/ // }}}
void test__get_image_info__invalid_mem_object( )
{
T::Dummy_clGetImageInfo mock(CL_INVALID_MEM_OBJECT);
TS_ASSERT_THROWS(get_image_info((cl_mem)NULL, image_info_t::format, 0, nullptr, nullptr),clerror_no<status_t::invalid_mem_object>);
}
/** // doc: test__get_image_info__out_of_resources() {{{
* \todo Write documentation
*/ // }}}
void test__get_image_info__out_of_resources( )
{
T::Dummy_clGetImageInfo mock(CL_OUT_OF_RESOURCES);
TS_ASSERT_THROWS(get_image_info((cl_mem)NULL, image_info_t::format, 0, nullptr, nullptr),clerror_no<status_t::out_of_resources>);
}
/** // doc: test__get_image_info__out_of_host_memory() {{{
* \todo Write documentation
*/ // }}}
void test__get_image_info__out_of_host_memory( )
{
T::Dummy_clGetImageInfo mock(CL_OUT_OF_HOST_MEMORY);
TS_ASSERT_THROWS(get_image_info((cl_mem)NULL, image_info_t::format, 0, nullptr, nullptr),clerror_no<status_t::out_of_host_memory>);
}
/** // doc: test__get_image_info__unexpected_clerror() {{{
* \todo Write documentation
*/ // }}}
void test__get_image_info__unexpected_clerror( )
{
T::Dummy_clGetImageInfo mock(-0x1234567);
TS_ASSERT_THROWS(get_image_info((cl_mem)NULL, image_info_t::format, 0, nullptr, nullptr), unexpected_clerror);
}
};
#endif /* CLXX_CL_FUNCTIONS_GET_IMAGE_INFO_T_H_INCLUDED */
// vim: set expandtab tabstop=2 shiftwidth=2:
// vim: set foldmethod=marker foldcolumn=4:
| {
"content_hash": "98dcb40a27e8de1e27adf96ac1d19021",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 135,
"avg_line_length": 38.48192771084337,
"alnum_prop": 0.6224170319348779,
"repo_name": "ptomulik/clxx",
"id": "8410279bb486d93d9a27b2799f1711d36e58212c",
"size": "3194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/clxx/cl/functions/get_image_info.t.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2086"
},
{
"name": "C++",
"bytes": "3146905"
},
{
"name": "CSS",
"bytes": "25435"
},
{
"name": "HTML",
"bytes": "692939"
},
{
"name": "Python",
"bytes": "17108"
},
{
"name": "Shell",
"bytes": "1183"
}
],
"symlink_target": ""
} |
@import UIKit;
@interface GLAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| {
"content_hash": "12fd474a932e61fbb5bbb39fd662f92f",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 62,
"avg_line_length": 19.142857142857142,
"alnum_prop": 0.7835820895522388,
"repo_name": "gaoli/GLChart",
"id": "e083b4bb8dcae0e62f9b7c6b3e4cbd15885e9969",
"size": "134",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Example/GLChart/GLAppDelegate.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "71464"
},
{
"name": "Ruby",
"bytes": "1244"
},
{
"name": "Shell",
"bytes": "17078"
}
],
"symlink_target": ""
} |
namespace Urho3D
{
class Sound;
/// Ogg Vorbis sound stream.
class URHO3D_API OggVorbisSoundStream : public SoundStream
{
public:
/// Construct from an Ogg Vorbis compressed sound.
OggVorbisSoundStream(const Sound* sound);
/// Destruct.
~OggVorbisSoundStream();
/// Seek to sample number. Return true on success.
virtual bool Seek(unsigned sample_number);
/// Produce sound data into destination. Return number of bytes produced. Called by SoundSource from the mixing thread.
virtual unsigned GetData(signed char* dest, unsigned numBytes);
protected:
/// Decoder state.
void* decoder_;
/// Compressed sound data.
SharedArrayPtr<signed char> data_;
/// Compressed sound data size in bytes.
unsigned dataSize_;
};
}
| {
"content_hash": "42b002523f9edf1ae8d1920708b591f5",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 123,
"avg_line_length": 25.866666666666667,
"alnum_prop": 0.7074742268041238,
"repo_name": "fire/Urho3D-1",
"id": "83e3fda9b92871f4215667958c61fdbd4b26813f",
"size": "1989",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Source/Urho3D/Audio/OggVorbisSoundStream.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "1358047"
},
{
"name": "Batchfile",
"bytes": "19519"
},
{
"name": "C++",
"bytes": "8043806"
},
{
"name": "CMake",
"bytes": "434239"
},
{
"name": "GLSL",
"bytes": "161353"
},
{
"name": "HLSL",
"bytes": "185424"
},
{
"name": "HTML",
"bytes": "1375"
},
{
"name": "Java",
"bytes": "78058"
},
{
"name": "Lua",
"bytes": "501285"
},
{
"name": "MAXScript",
"bytes": "94704"
},
{
"name": "Objective-C",
"bytes": "6539"
},
{
"name": "Ruby",
"bytes": "64751"
},
{
"name": "Shell",
"bytes": "26397"
}
],
"symlink_target": ""
} |
// Package cdsbalancer implements a balancer to handle CDS responses.
package cdsbalancer
import (
"encoding/json"
"errors"
"fmt"
"google.golang.org/grpc/balancer"
"google.golang.org/grpc/balancer/base"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/tls/certprovider"
"google.golang.org/grpc/internal/buffer"
xdsinternal "google.golang.org/grpc/internal/credentials/xds"
"google.golang.org/grpc/internal/envconfig"
"google.golang.org/grpc/internal/grpclog"
"google.golang.org/grpc/internal/grpcsync"
"google.golang.org/grpc/internal/pretty"
internalserviceconfig "google.golang.org/grpc/internal/serviceconfig"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/serviceconfig"
"google.golang.org/grpc/xds/internal/balancer/clusterresolver"
"google.golang.org/grpc/xds/internal/balancer/outlierdetection"
"google.golang.org/grpc/xds/internal/balancer/ringhash"
"google.golang.org/grpc/xds/internal/xdsclient"
"google.golang.org/grpc/xds/internal/xdsclient/xdsresource"
)
const (
cdsName = "cds_experimental"
)
var (
errBalancerClosed = errors.New("cdsBalancer is closed")
// newChildBalancer is a helper function to build a new cluster_resolver
// balancer and will be overridden in unittests.
newChildBalancer = func(cc balancer.ClientConn, opts balancer.BuildOptions) (balancer.Balancer, error) {
builder := balancer.Get(clusterresolver.Name)
if builder == nil {
return nil, fmt.Errorf("xds: no balancer builder with name %v", clusterresolver.Name)
}
// We directly pass the parent clientConn to the underlying
// cluster_resolver balancer because the cdsBalancer does not deal with
// subConns.
return builder.Build(cc, opts), nil
}
buildProvider = buildProviderFunc
)
func init() {
balancer.Register(bb{})
}
// bb implements the balancer.Builder interface to help build a cdsBalancer.
// It also implements the balancer.ConfigParser interface to help parse the
// JSON service config, to be passed to the cdsBalancer.
type bb struct{}
// Build creates a new CDS balancer with the ClientConn.
func (bb) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer {
b := &cdsBalancer{
bOpts: opts,
updateCh: buffer.NewUnbounded(),
closed: grpcsync.NewEvent(),
done: grpcsync.NewEvent(),
xdsHI: xdsinternal.NewHandshakeInfo(nil, nil),
}
b.logger = prefixLogger((b))
b.logger.Infof("Created")
var creds credentials.TransportCredentials
switch {
case opts.DialCreds != nil:
creds = opts.DialCreds
case opts.CredsBundle != nil:
creds = opts.CredsBundle.TransportCredentials()
}
if xc, ok := creds.(interface{ UsesXDS() bool }); ok && xc.UsesXDS() {
b.xdsCredsInUse = true
}
b.logger.Infof("xDS credentials in use: %v", b.xdsCredsInUse)
b.clusterHandler = newClusterHandler(b)
b.ccw = &ccWrapper{
ClientConn: cc,
xdsHI: b.xdsHI,
}
go b.run()
return b
}
// Name returns the name of balancers built by this builder.
func (bb) Name() string {
return cdsName
}
// lbConfig represents the loadBalancingConfig section of the service config
// for the cdsBalancer.
type lbConfig struct {
serviceconfig.LoadBalancingConfig
ClusterName string `json:"Cluster"`
}
// ParseConfig parses the JSON load balancer config provided into an
// internal form or returns an error if the config is invalid.
func (bb) ParseConfig(c json.RawMessage) (serviceconfig.LoadBalancingConfig, error) {
var cfg lbConfig
if err := json.Unmarshal(c, &cfg); err != nil {
return nil, fmt.Errorf("xds: unable to unmarshal lbconfig: %s, error: %v", string(c), err)
}
return &cfg, nil
}
// ccUpdate wraps a clientConn update received from gRPC (pushed from the
// xdsResolver). A valid clusterName causes the cdsBalancer to register a CDS
// watcher with the xdsClient, while a non-nil error causes it to cancel the
// existing watch and propagate the error to the underlying cluster_resolver
// balancer.
type ccUpdate struct {
clusterName string
err error
}
// scUpdate wraps a subConn update received from gRPC. This is directly passed
// on to the cluster_resolver balancer.
type scUpdate struct {
subConn balancer.SubConn
state balancer.SubConnState
}
type exitIdle struct{}
// cdsBalancer implements a CDS based LB policy. It instantiates a
// cluster_resolver balancer to further resolve the serviceName received from
// CDS, into localities and endpoints. Implements the balancer.Balancer
// interface which is exposed to gRPC and implements the balancer.ClientConn
// interface which is exposed to the cluster_resolver balancer.
type cdsBalancer struct {
ccw *ccWrapper // ClientConn interface passed to child LB.
bOpts balancer.BuildOptions // BuildOptions passed to child LB.
updateCh *buffer.Unbounded // Channel for gRPC and xdsClient updates.
xdsClient xdsclient.XDSClient // xDS client to watch Cluster resource.
clusterHandler *clusterHandler // To watch the clusters.
childLB balancer.Balancer
logger *grpclog.PrefixLogger
closed *grpcsync.Event
done *grpcsync.Event
// The certificate providers are cached here to that they can be closed when
// a new provider is to be created.
cachedRoot certprovider.Provider
cachedIdentity certprovider.Provider
xdsHI *xdsinternal.HandshakeInfo
xdsCredsInUse bool
}
// handleClientConnUpdate handles a ClientConnUpdate received from gRPC. Good
// updates lead to registration of a CDS watch. Updates with error lead to
// cancellation of existing watch and propagation of the same error to the
// cluster_resolver balancer.
func (b *cdsBalancer) handleClientConnUpdate(update *ccUpdate) {
// We first handle errors, if any, and then proceed with handling the
// update, only if the status quo has changed.
if err := update.err; err != nil {
b.handleErrorFromUpdate(err, true)
return
}
b.clusterHandler.updateRootCluster(update.clusterName)
}
// handleSecurityConfig processes the security configuration received from the
// management server, creates appropriate certificate provider plugins, and
// updates the HandhakeInfo which is added as an address attribute in
// NewSubConn() calls.
func (b *cdsBalancer) handleSecurityConfig(config *xdsresource.SecurityConfig) error {
// If xdsCredentials are not in use, i.e, the user did not want to get
// security configuration from an xDS server, we should not be acting on the
// received security config here. Doing so poses a security threat.
if !b.xdsCredsInUse {
return nil
}
// Security config being nil is a valid case where the management server has
// not sent any security configuration. The xdsCredentials implementation
// handles this by delegating to its fallback credentials.
if config == nil {
// We need to explicitly set the fields to nil here since this might be
// a case of switching from a good security configuration to an empty
// one where fallback credentials are to be used.
b.xdsHI.SetRootCertProvider(nil)
b.xdsHI.SetIdentityCertProvider(nil)
b.xdsHI.SetSANMatchers(nil)
return nil
}
bc := b.xdsClient.BootstrapConfig()
if bc == nil || bc.CertProviderConfigs == nil {
// Bootstrap did not find any certificate provider configs, but the user
// has specified xdsCredentials and the management server has sent down
// security configuration.
return errors.New("xds: certificate_providers config missing in bootstrap file")
}
cpc := bc.CertProviderConfigs
// A root provider is required whether we are using TLS or mTLS.
rootProvider, err := buildProvider(cpc, config.RootInstanceName, config.RootCertName, false, true)
if err != nil {
return err
}
// The identity provider is only present when using mTLS.
var identityProvider certprovider.Provider
if name, cert := config.IdentityInstanceName, config.IdentityCertName; name != "" {
var err error
identityProvider, err = buildProvider(cpc, name, cert, true, false)
if err != nil {
return err
}
}
// Close the old providers and cache the new ones.
if b.cachedRoot != nil {
b.cachedRoot.Close()
}
if b.cachedIdentity != nil {
b.cachedIdentity.Close()
}
b.cachedRoot = rootProvider
b.cachedIdentity = identityProvider
// We set all fields here, even if some of them are nil, since they
// could have been non-nil earlier.
b.xdsHI.SetRootCertProvider(rootProvider)
b.xdsHI.SetIdentityCertProvider(identityProvider)
b.xdsHI.SetSANMatchers(config.SubjectAltNameMatchers)
return nil
}
func buildProviderFunc(configs map[string]*certprovider.BuildableConfig, instanceName, certName string, wantIdentity, wantRoot bool) (certprovider.Provider, error) {
cfg, ok := configs[instanceName]
if !ok {
return nil, fmt.Errorf("certificate provider instance %q not found in bootstrap file", instanceName)
}
provider, err := cfg.Build(certprovider.BuildOptions{
CertName: certName,
WantIdentity: wantIdentity,
WantRoot: wantRoot,
})
if err != nil {
// This error is not expected since the bootstrap process parses the
// config and makes sure that it is acceptable to the plugin. Still, it
// is possible that the plugin parses the config successfully, but its
// Build() method errors out.
return nil, fmt.Errorf("xds: failed to get security plugin instance (%+v): %v", cfg, err)
}
return provider, nil
}
func outlierDetectionToConfig(od *xdsresource.OutlierDetection) *outlierdetection.LBConfig { // Already validated - no need to return error
if od == nil {
// "If the outlier_detection field is not set in the Cluster message, a
// "no-op" outlier_detection config will be generated, with interval set
// to the maximum possible value and all other fields unset." - A50
return &outlierdetection.LBConfig{
Interval: 1<<63 - 1,
}
}
// "if the enforcing_success_rate field is set to 0, the config
// success_rate_ejection field will be null and all success_rate_* fields
// will be ignored." - A50
var sre *outlierdetection.SuccessRateEjection
if od.EnforcingSuccessRate != 0 {
sre = &outlierdetection.SuccessRateEjection{
StdevFactor: od.SuccessRateStdevFactor,
EnforcementPercentage: od.EnforcingSuccessRate,
MinimumHosts: od.SuccessRateMinimumHosts,
RequestVolume: od.SuccessRateRequestVolume,
}
}
// "If the enforcing_failure_percent field is set to 0 or null, the config
// failure_percent_ejection field will be null and all failure_percent_*
// fields will be ignored." - A50
var fpe *outlierdetection.FailurePercentageEjection
if od.EnforcingFailurePercentage != 0 {
fpe = &outlierdetection.FailurePercentageEjection{
Threshold: od.FailurePercentageThreshold,
EnforcementPercentage: od.EnforcingFailurePercentage,
MinimumHosts: od.FailurePercentageMinimumHosts,
RequestVolume: od.FailurePercentageRequestVolume,
}
}
return &outlierdetection.LBConfig{
Interval: od.Interval,
BaseEjectionTime: od.BaseEjectionTime,
MaxEjectionTime: od.MaxEjectionTime,
MaxEjectionPercent: od.MaxEjectionPercent,
SuccessRateEjection: sre,
FailurePercentageEjection: fpe,
}
}
// handleWatchUpdate handles a watch update from the xDS Client. Good updates
// lead to clientConn updates being invoked on the underlying cluster_resolver balancer.
func (b *cdsBalancer) handleWatchUpdate(update clusterHandlerUpdate) {
if err := update.err; err != nil {
b.logger.Warningf("Watch error from xds-client %p: %v", b.xdsClient, err)
b.handleErrorFromUpdate(err, false)
return
}
b.logger.Infof("Watch update from xds-client %p, content: %+v, security config: %v", b.xdsClient, pretty.ToJSON(update.updates), pretty.ToJSON(update.securityCfg))
// Process the security config from the received update before building the
// child policy or forwarding the update to it. We do this because the child
// policy may try to create a new subConn inline. Processing the security
// configuration here and setting up the handshakeInfo will make sure that
// such attempts are handled properly.
if err := b.handleSecurityConfig(update.securityCfg); err != nil {
// If the security config is invalid, for example, if the provider
// instance is not found in the bootstrap config, we need to put the
// channel in transient failure.
b.logger.Warningf("Invalid security config update from xds-client %p: %v", b.xdsClient, err)
b.handleErrorFromUpdate(err, false)
return
}
// The first good update from the watch API leads to the instantiation of an
// cluster_resolver balancer. Further updates/errors are propagated to the existing
// cluster_resolver balancer.
if b.childLB == nil {
childLB, err := newChildBalancer(b.ccw, b.bOpts)
if err != nil {
b.logger.Errorf("Failed to create child policy of type %s, %v", clusterresolver.Name, err)
return
}
b.childLB = childLB
b.logger.Infof("Created child policy %p of type %s", b.childLB, clusterresolver.Name)
}
dms := make([]clusterresolver.DiscoveryMechanism, len(update.updates))
for i, cu := range update.updates {
switch cu.ClusterType {
case xdsresource.ClusterTypeEDS:
dms[i] = clusterresolver.DiscoveryMechanism{
Type: clusterresolver.DiscoveryMechanismTypeEDS,
Cluster: cu.ClusterName,
EDSServiceName: cu.EDSServiceName,
MaxConcurrentRequests: cu.MaxRequests,
}
if cu.LRSServerConfig == xdsresource.ClusterLRSServerSelf {
bootstrapConfig := b.xdsClient.BootstrapConfig()
parsedName := xdsresource.ParseName(cu.ClusterName)
if parsedName.Scheme == xdsresource.FederationScheme {
// Is a federation resource name, find the corresponding
// authority server config.
if cfg, ok := bootstrapConfig.Authorities[parsedName.Authority]; ok {
dms[i].LoadReportingServer = cfg.XDSServer
}
} else {
// Not a federation resource name, use the default
// authority.
dms[i].LoadReportingServer = bootstrapConfig.XDSServer
}
}
case xdsresource.ClusterTypeLogicalDNS:
dms[i] = clusterresolver.DiscoveryMechanism{
Type: clusterresolver.DiscoveryMechanismTypeLogicalDNS,
Cluster: cu.ClusterName,
DNSHostname: cu.DNSHostName,
}
default:
b.logger.Infof("unexpected cluster type %v when handling update from cluster handler", cu.ClusterType)
}
if envconfig.XDSOutlierDetection {
dms[i].OutlierDetection = outlierDetectionToConfig(cu.OutlierDetection)
}
}
lbCfg := &clusterresolver.LBConfig{
DiscoveryMechanisms: dms,
}
// lbPolicy is set only when the policy is ringhash. The default (when it's
// not set) is roundrobin. And similarly, we only need to set XDSLBPolicy
// for ringhash (it also defaults to roundrobin).
if lbp := update.lbPolicy; lbp != nil {
lbCfg.XDSLBPolicy = &internalserviceconfig.BalancerConfig{
Name: ringhash.Name,
Config: &ringhash.LBConfig{
MinRingSize: lbp.MinimumRingSize,
MaxRingSize: lbp.MaximumRingSize,
},
}
}
ccState := balancer.ClientConnState{
ResolverState: xdsclient.SetClient(resolver.State{}, b.xdsClient),
BalancerConfig: lbCfg,
}
if err := b.childLB.UpdateClientConnState(ccState); err != nil {
b.logger.Errorf("xds: cluster_resolver balancer.UpdateClientConnState(%+v) returned error: %v", ccState, err)
}
}
// run is a long-running goroutine which handles all updates from gRPC. All
// methods which are invoked directly by gRPC or xdsClient simply push an
// update onto a channel which is read and acted upon right here.
func (b *cdsBalancer) run() {
for {
select {
case u := <-b.updateCh.Get():
b.updateCh.Load()
switch update := u.(type) {
case *ccUpdate:
b.handleClientConnUpdate(update)
case *scUpdate:
// SubConn updates are passthrough and are simply handed over to
// the underlying cluster_resolver balancer.
if b.childLB == nil {
b.logger.Errorf("xds: received scUpdate {%+v} with no cluster_resolver balancer", update)
break
}
b.childLB.UpdateSubConnState(update.subConn, update.state)
case exitIdle:
if b.childLB == nil {
b.logger.Errorf("xds: received ExitIdle with no child balancer")
break
}
// This implementation assumes the child balancer supports
// ExitIdle (but still checks for the interface's existence to
// avoid a panic if not). If the child does not, no subconns
// will be connected.
if ei, ok := b.childLB.(balancer.ExitIdler); ok {
ei.ExitIdle()
}
}
case u := <-b.clusterHandler.updateChannel:
b.handleWatchUpdate(u)
case <-b.closed.Done():
b.clusterHandler.close()
if b.childLB != nil {
b.childLB.Close()
b.childLB = nil
}
if b.cachedRoot != nil {
b.cachedRoot.Close()
}
if b.cachedIdentity != nil {
b.cachedIdentity.Close()
}
b.logger.Infof("Shutdown")
b.done.Fire()
return
}
}
}
// handleErrorFromUpdate handles both the error from parent ClientConn (from
// resolver) and the error from xds client (from the watcher). fromParent is
// true if error is from parent ClientConn.
//
// If the error is connection error, it's passed down to the child policy.
// Nothing needs to be done in CDS (e.g. it doesn't go into fallback).
//
// If the error is resource-not-found:
// - If it's from resolver, it means LDS resources were removed. The CDS watch
// should be canceled.
// - If it's from xds client, it means CDS resource were removed. The CDS
// watcher should keep watching.
//
// In both cases, the error will be forwarded to the child balancer. And if
// error is resource-not-found, the child balancer will stop watching EDS.
func (b *cdsBalancer) handleErrorFromUpdate(err error, fromParent bool) {
// This is not necessary today, because xds client never sends connection
// errors.
if fromParent && xdsresource.ErrType(err) == xdsresource.ErrorTypeResourceNotFound {
b.clusterHandler.close()
}
if b.childLB != nil {
if xdsresource.ErrType(err) != xdsresource.ErrorTypeConnection {
// Connection errors will be sent to the child balancers directly.
// There's no need to forward them.
b.childLB.ResolverError(err)
}
} else {
// If child balancer was never created, fail the RPCs with
// errors.
b.ccw.UpdateState(balancer.State{
ConnectivityState: connectivity.TransientFailure,
Picker: base.NewErrPicker(err),
})
}
}
// UpdateClientConnState receives the serviceConfig (which contains the
// clusterName to watch for in CDS) and the xdsClient object from the
// xdsResolver.
func (b *cdsBalancer) UpdateClientConnState(state balancer.ClientConnState) error {
if b.closed.HasFired() {
b.logger.Warningf("xds: received ClientConnState {%+v} after cdsBalancer was closed", state)
return errBalancerClosed
}
if b.xdsClient == nil {
c := xdsclient.FromResolverState(state.ResolverState)
if c == nil {
return balancer.ErrBadResolverState
}
b.xdsClient = c
}
b.logger.Infof("Received update from resolver, balancer config: %+v", pretty.ToJSON(state.BalancerConfig))
// The errors checked here should ideally never happen because the
// ServiceConfig in this case is prepared by the xdsResolver and is not
// something that is received on the wire.
lbCfg, ok := state.BalancerConfig.(*lbConfig)
if !ok {
b.logger.Warningf("xds: unexpected LoadBalancingConfig type: %T", state.BalancerConfig)
return balancer.ErrBadResolverState
}
if lbCfg.ClusterName == "" {
b.logger.Warningf("xds: no clusterName found in LoadBalancingConfig: %+v", lbCfg)
return balancer.ErrBadResolverState
}
b.updateCh.Put(&ccUpdate{clusterName: lbCfg.ClusterName})
return nil
}
// ResolverError handles errors reported by the xdsResolver.
func (b *cdsBalancer) ResolverError(err error) {
if b.closed.HasFired() {
b.logger.Warningf("xds: received resolver error {%v} after cdsBalancer was closed", err)
return
}
b.updateCh.Put(&ccUpdate{err: err})
}
// UpdateSubConnState handles subConn updates from gRPC.
func (b *cdsBalancer) UpdateSubConnState(sc balancer.SubConn, state balancer.SubConnState) {
if b.closed.HasFired() {
b.logger.Warningf("xds: received subConn update {%v, %v} after cdsBalancer was closed", sc, state)
return
}
b.updateCh.Put(&scUpdate{subConn: sc, state: state})
}
// Close cancels the CDS watch, closes the child policy and closes the
// cdsBalancer.
func (b *cdsBalancer) Close() {
b.closed.Fire()
<-b.done.Done()
}
func (b *cdsBalancer) ExitIdle() {
b.updateCh.Put(exitIdle{})
}
// ccWrapper wraps the balancer.ClientConn passed to the CDS balancer at
// creation and intercepts the NewSubConn() and UpdateAddresses() call from the
// child policy to add security configuration required by xDS credentials.
//
// Other methods of the balancer.ClientConn interface are not overridden and
// hence get the original implementation.
type ccWrapper struct {
balancer.ClientConn
// The certificate providers in this HandshakeInfo are updated based on the
// received security configuration in the Cluster resource.
xdsHI *xdsinternal.HandshakeInfo
}
// NewSubConn intercepts NewSubConn() calls from the child policy and adds an
// address attribute which provides all information required by the xdsCreds
// handshaker to perform the TLS handshake.
func (ccw *ccWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) {
newAddrs := make([]resolver.Address, len(addrs))
for i, addr := range addrs {
newAddrs[i] = xdsinternal.SetHandshakeInfo(addr, ccw.xdsHI)
}
return ccw.ClientConn.NewSubConn(newAddrs, opts)
}
func (ccw *ccWrapper) UpdateAddresses(sc balancer.SubConn, addrs []resolver.Address) {
newAddrs := make([]resolver.Address, len(addrs))
for i, addr := range addrs {
newAddrs[i] = xdsinternal.SetHandshakeInfo(addr, ccw.xdsHI)
}
ccw.ClientConn.UpdateAddresses(sc, newAddrs)
}
| {
"content_hash": "6956084b2540f62715ab40588065b50a",
"timestamp": "",
"source": "github",
"line_count": 593,
"max_line_length": 165,
"avg_line_length": 36.99494097807757,
"alnum_prop": 0.7366213875467226,
"repo_name": "knative/eventing",
"id": "d057ed66a53c83ec809df53af1793ffb914cdd00",
"size": "22534",
"binary": false,
"copies": "8",
"ref": "refs/heads/main",
"path": "vendor/google.golang.org/grpc/xds/internal/balancer/cdsbalancer/cdsbalancer.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "3696443"
},
{
"name": "Shell",
"bytes": "45068"
}
],
"symlink_target": ""
} |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.jps.incremental.storage;
import com.intellij.util.Function;
import com.intellij.util.containers.CollectionFactory;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.IOUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.incremental.relativizer.PathRelativizerService;
import org.jetbrains.jps.javac.Iterators;
import java.io.*;
import java.util.*;
/**
* @author Eugene Zhuravlev
*/
public final class OneToManyPathsMapping extends AbstractStateStorage<String, Collection<String>> {
private final PathRelativizerService myRelativizer;
public OneToManyPathsMapping(File storePath, PathRelativizerService relativizer) throws IOException {
super(storePath, PathStringDescriptor.INSTANCE, new PathCollectionExternalizer());
myRelativizer = relativizer;
}
@Override
public void update(@NotNull String keyPath, @NotNull Collection<String> boundPaths) throws IOException {
super.update(normalizePath(keyPath), normalizePaths(boundPaths));
}
public final void update(@NotNull String keyPath, @NotNull String boundPath) throws IOException {
super.update(normalizePath(keyPath), Collections.singleton(normalizePath(boundPath)));
}
public final void appendData(@NotNull String keyPath, @NotNull String boundPath) throws IOException {
super.appendData(normalizePath(keyPath), Collections.singleton(normalizePath(boundPath)));
}
@Override
public void appendData(@NotNull String keyPath, @NotNull Collection<String> boundPaths) throws IOException {
super.appendData(normalizePath(keyPath), normalizePaths(boundPaths));
}
@Nullable
@Override
public Collection<String> getState(@NotNull String keyPath) throws IOException {
Collection<String> collection = super.getState(normalizePath(keyPath));
return collection != null ? ContainerUtil.map(collection, toFull()) : null;
}
@NotNull
public Iterator<String> getStateIterator(@NotNull String keyPath) throws IOException {
Collection<String> collection = super.getState(normalizePath(keyPath));
return collection == null? Collections.emptyIterator() : Iterators.map(collection.iterator(), toFull());
}
@Override
public void remove(@NotNull String keyPath) throws IOException {
super.remove(normalizePath(keyPath));
}
@Override
public Collection<String> getKeys() throws IOException {
return ContainerUtil.map(super.getKeys(), toFull());
}
@Override
public Iterator<String> getKeysIterator() throws IOException {
return Iterators.map(super.getKeysIterator(), toFull());
}
public final void removeData(@NotNull String keyPath, @NotNull String boundPath) throws IOException {
final Collection<String> outputPaths = getState(keyPath);
if (outputPaths != null) {
final boolean removed = outputPaths.remove(normalizePath(boundPath));
if (outputPaths.isEmpty()) {
remove(keyPath);
}
else {
if (removed) {
update(keyPath, outputPaths);
}
}
}
}
private static class PathCollectionExternalizer implements DataExternalizer<Collection<String>> {
@Override
public void save(@NotNull DataOutput out, Collection<String> value) throws IOException {
for (String str : value) {
IOUtil.writeUTF(out, str);
}
}
@Override
public Collection<String> read(@NotNull DataInput in) throws IOException {
final Set<String> result = CollectionFactory.createFilePathLinkedSet();
final DataInputStream stream = (DataInputStream)in;
while (stream.available() > 0) {
final String str = IOUtil.readUTF(stream);
result.add(str);
}
return result;
}
}
@NotNull
private Function<String, String> toFull() {
return s -> myRelativizer.toFull(s);
}
private String normalizePath(@NotNull String path) {
return myRelativizer.toRelative(path);
}
private Collection<String> normalizePaths(Collection<String> outputs) {
Collection<String> normalized = new ArrayList<>(outputs.size());
for (String out : outputs) {
normalized.add(normalizePath(out));
}
return normalized;
}
}
| {
"content_hash": "68b0b53b7e68651b79376fd8a370930b",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 140,
"avg_line_length": 34.98412698412698,
"alnum_prop": 0.7366152450090744,
"repo_name": "allotria/intellij-community",
"id": "cab44da7f3faf35c266f9b791e4e04b4ef598db5",
"size": "4408",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "jps/jps-builders/src/org/jetbrains/jps/incremental/storage/OneToManyPathsMapping.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "20665"
},
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "Batchfile",
"bytes": "60580"
},
{
"name": "C",
"bytes": "195249"
},
{
"name": "C#",
"bytes": "1264"
},
{
"name": "C++",
"bytes": "195810"
},
{
"name": "CMake",
"bytes": "1675"
},
{
"name": "CSS",
"bytes": "201445"
},
{
"name": "CoffeeScript",
"bytes": "1759"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "Groovy",
"bytes": "3197810"
},
{
"name": "HLSL",
"bytes": "57"
},
{
"name": "HTML",
"bytes": "1891055"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "164463076"
},
{
"name": "JavaScript",
"bytes": "570364"
},
{
"name": "Jupyter Notebook",
"bytes": "93222"
},
{
"name": "Kotlin",
"bytes": "4240307"
},
{
"name": "Lex",
"bytes": "147047"
},
{
"name": "Makefile",
"bytes": "2352"
},
{
"name": "NSIS",
"bytes": "51270"
},
{
"name": "Objective-C",
"bytes": "27941"
},
{
"name": "Perl",
"bytes": "903"
},
{
"name": "Perl6",
"bytes": "26"
},
{
"name": "Protocol Buffer",
"bytes": "6680"
},
{
"name": "Python",
"bytes": "25385564"
},
{
"name": "Roff",
"bytes": "37534"
},
{
"name": "Ruby",
"bytes": "1217"
},
{
"name": "Scala",
"bytes": "11698"
},
{
"name": "Shell",
"bytes": "65705"
},
{
"name": "Smalltalk",
"bytes": "338"
},
{
"name": "TeX",
"bytes": "25473"
},
{
"name": "Thrift",
"bytes": "1846"
},
{
"name": "TypeScript",
"bytes": "9469"
},
{
"name": "Visual Basic",
"bytes": "77"
},
{
"name": "XSLT",
"bytes": "113040"
}
],
"symlink_target": ""
} |
.. complexity documentation master file, created by
sphinx-quickstart on Tue Jul 9 22:26:36 2013.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to Package Lib Tool's documentation!
======================================
Contents:
.. toctree::
:maxdepth: 2
readme
installation
usage
contributing
authors
history
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
| {
"content_hash": "7ed64a59dd610b3441cb567bee87034f",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 76,
"avg_line_length": 19.692307692307693,
"alnum_prop": 0.630859375,
"repo_name": "weijia/libtool",
"id": "4a1cf720b04b2ba3071fcbf32425464eaff2e9a3",
"size": "512",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/index.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "1270"
},
{
"name": "Python",
"bytes": "27400"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "619fdcebb29d0fb4d3287612b3e2da24",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "0a2e1678c54698006b0ac81c37fcba221f8ed84e",
"size": "174",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Rosa/Rosa borkhausenii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
.animate-switch-container {
position: relative;
background: white;
border: 1px solid black;
height: 40px;
overflow: hidden;
}
.animate-switch {
padding: 10px;
}
.animate-switch.ng-animate {
transition: all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.animate-switch.ng-leave.ng-leave-active,
.animate-switch.ng-enter {
top: -50px;
}
.animate-switch.ng-leave,
.animate-switch.ng-enter.ng-enter-active {
top: 0;
} | {
"content_hash": "3a6905a7f50bdc0e648cb48fb471ea40",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 66,
"avg_line_length": 17.258064516129032,
"alnum_prop": 0.6355140186915887,
"repo_name": "mudunuriRaju/tlr-live",
"id": "e467d5c91c796caa9a53fe1c98c12c230acd8ec0",
"size": "535",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "tollbackend/web/js/angular-1.5.5/docs/examples/example-example94/animations.css",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "4530"
},
{
"name": "Batchfile",
"bytes": "1026"
},
{
"name": "CSS",
"bytes": "1066564"
},
{
"name": "HTML",
"bytes": "12357995"
},
{
"name": "JavaScript",
"bytes": "1884350"
},
{
"name": "Makefile",
"bytes": "2397"
},
{
"name": "PHP",
"bytes": "1062404"
},
{
"name": "Ruby",
"bytes": "6337"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>idt: 21 s 🏆</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.1 / idt - 1.0.1</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
idt
<small>
1.0.1
<span class="label label-success">21 s 🏆</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-09-15 02:05:39 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-15 02:05:39 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.11.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.11.2 Official release 4.11.2
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "yeqianchuan@gmail.com"
homepage: "https://github.com/ccyip/coq-idt"
dev-repo: "git+https://github.com/ccyip/coq-idt.git"
bug-reports: "https://github.com/ccyip/coq-idt/issues"
license: "MIT"
authors: [
"Qianchuan Ye"
"Benjamin Delaware"
]
build: [
[make "-j%{jobs}%"]
]
install: [make "install"]
depends: [
"coq" {>= "8.12" & < "8.14~"}
"coq-metacoq-template" {>= "1.0~beta2+8.12"}
]
synopsis: "Inductive Definition Transformers"
description: """
This Coq library allows you to transform an inductive definition to another
inductive definition, by providing a constructor transformer tactic. It can be
used to generate boilerplate lemmas for backward and forward reasoning, and to
generate inductive types with many similar cases.
"""
tags: [
"category:Miscellaneous/Coq Extensions"
"date:2022-01-10"
"logpath:idt"
]
url {
src: "https://github.com/ccyip/coq-idt/archive/refs/tags/v1.0.1.tar.gz"
checksum: "sha256=d20305953c31842e33aaea318f8f84c4ad7314cb0e525d6663240abcad21099b"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-idt.1.0.1 coq.8.13.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-idt.1.0.1 coq.8.13.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>6 m 27 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-idt.1.0.1 coq.8.13.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>21 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 171 K</p>
<ul>
<li>88 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/idt/idt.vo</code></li>
<li>57 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/idt/all.vo</code></li>
<li>17 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/idt/idt.glob</code></li>
<li>9 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/idt/idt.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/idt/all.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/idt/all.v</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-idt.1.0.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "10b230aa3f6f57241c5dd2ca51a82ebd",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 159,
"avg_line_length": 42.41142857142857,
"alnum_prop": 0.5450013473457289,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "a6c960767a134a873e42d9ef5dac6be77731ac98",
"size": "7447",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.11.2-2.0.7/released/8.13.1/idt/1.0.1.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
Configuration References
===========================
The description of options that you can pass in the datagrid configuration is available below.
## Setting Options
To set datagrid options, define them under the datagrid_name.options path.
``` yaml
datagrids:
acme-demo-datagrid:
options:
```
## Options List
### base_datagrid_class
```yaml
base_datagrid_class: Acme\Bundle\AcmeBundle\Grid\CustomEntityDatagrid
```
This option can be used to change the default datagrid implementation to a custom class.
### entity_pagination:
- values: true|false
- default: true
Enables pagination UI for a collection of entities when these entities are part of a data set of a datagrid.
Please take a look at [OroEntityPaginationBundle](./../../../../EntityPaginationBundle/README.md) for more information.
### export
- values: true|false
- default: false
When set to `true`, grid export button will be shown.
More information of export configuration is available in the [exportExtension](./extensions/export.md) topic.
### frontend
- values: true|false
- default: false
Set the flag to 'true' to display the datagrid on the frontend. If set to 'false', the datagrid will be hidden.
### mass_actions
Detailed information on the mass action extension is available in the [Mass action extension](./extensions/mass_action.md) topic.
### toolbarOptions
Detailed information on toolbars is available in the [toolbarExtension](./extensions/toolbar.md) and [pagerExtension](./extensions/pager.md) topics.
### jsmodules
```yaml
jsmodules:
- your/builder/amd/module/name
```
Adds given JS files to the datagrid. JS files should have the 'init' method which will be called when the grid builder finishes building the grid.
### routerEnabled
- values: true|false
- default: true
When set to `false` datagrid will not keep its state (e.g. filtering and/or sorting parameters) in the URL.
### rowSelection
``` yaml
rowSelection:
dataField: id
columnName: hasContact
selectors:
included: '#appendContacts'
excluded: '#removeContacts'
```
More information on row selection and an example of its usage are available in the [Advanced grid configuration (How to's)](./advanced_grid_configuration.md#solution-1) article.
| {
"content_hash": "44f4c6fcc6a51e0c38c8045f45f1b49b",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 177,
"avg_line_length": 28.7625,
"alnum_prop": 0.7253368100825728,
"repo_name": "orocrm/platform",
"id": "f035d5ec0479c198825ee50c69bb60730e3abac0",
"size": "2301",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Oro/Bundle/DataGridBundle/Resources/doc/backend/configuration_reference.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "618485"
},
{
"name": "Gherkin",
"bytes": "158217"
},
{
"name": "HTML",
"bytes": "1648915"
},
{
"name": "JavaScript",
"bytes": "3326127"
},
{
"name": "PHP",
"bytes": "37828618"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Notifications">
<CheckBoxPreference
android:title="@string/notifications"
android:key="@string/notifications_key"
android:summaryOn="@string/on"
android:summaryOff="@string/off"
android:defaultValue="true">
</CheckBoxPreference>
<CheckBoxPreference
android:title="@string/sound_title"
android:key="@string/sound_key"
android:defaultValue="true"
android:dependency="@string/notifications_key">
</CheckBoxPreference>
<CheckBoxPreference
android:title="@string/vibration_title"
android:key="@string/vibration_key"
android:defaultValue="true"
android:dependency="@string/notifications_key">
</CheckBoxPreference>
</PreferenceCategory>
<ListPreference
android:title="@string/choose_title"
android:key="@string/choose_dialog_key"
android:dialogTitle="@string/choose_dialog_title"
android:entries="@array/preference_values"
android:entryValues="@array/keys"
android:dependency="@string/notifications_key"
android:defaultValue="@string/at_time_key">
</ListPreference>
<!--
<CheckBoxPreference
android:title="@string/geo_positioning"
android:key="@string/geo_positioning_key"
android:defaultValue="true"
android:enabled="false">
</CheckBoxPreference>
<EditTextPreference
android:title="@string/location"
android:key="@string/location_key"
android:summary="@string/location_summary"
android:defaultValue="@string/location_default"
android:enabled="false">
</EditTextPreference>
-->
</PreferenceScreen> | {
"content_hash": "f874781891da98861023e5b8f0b4606c",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 77,
"avg_line_length": 38.48,
"alnum_prop": 0.6408523908523909,
"repo_name": "runningcode/UmbrellaAlarm",
"id": "ace3c9c8535f885f7d6c31ac5cd173e783768c2a",
"size": "1924",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UmbrellaAlarm/src/main/res/xml/preferences.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "598"
},
{
"name": "Java",
"bytes": "33628"
},
{
"name": "Shell",
"bytes": "2314"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<link href="../css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="../css/froala_editor.min.css" rel="stylesheet" type="text/css">
<link href="../css/froala_reset.min.css" rel="stylesheet" type="text/css">
<style>
body {
text-align: center;
}
section {
width: 80%;
margin: auto;
text-align: left;
}
</style>
</head>
<body>
<section id="editor">
<a href="#" class="edit">Link To Test on</a>
<div class="edit2">Hello people. Here we are on the moon.</div>
</section>
<script src="../js/libs/jquery-1.10.2.min.js"></script>
<script src="../js/libs/beautify/beautify-html.js"></script>
<script src="../js/froala_editor.min.js"></script>
<!--[if lt IE 9]>
<script src="../js/froala_editor_ie8.min.js"></script>
<![endif]-->
<script src="../js/froala_editor.min.js"></script>
<script src="../js/plugins/tables.min.js"></script>
<script src="../js/plugins/colors.min.js"></script>
<script src="../js/plugins/fonts/fonts.min.js"></script>
<script src="../js/plugins/fonts/font_family.min.js"></script>
<script src="../js/plugins/fonts/font_size.min.js"></script>
<script src="../js/plugins/block_styles.min.js"></script>
<script src="../js/plugins/video.min.js"></script>
<script>
$(function(){
$('.edit').editable({unlinkButton: false, linkList: [
{
body: 'Google',
title: 'An awesome search engine',
href: 'http://google.com',
nofollow: true,
blank: true
},
{
body: 'Froala',
title: 'An website builder for everyone',
href: 'http://froala.com',
nofollow: false,
blank: false
}
]})
$('.edit2').editable()
});
</script>
</body>
</html>
| {
"content_hash": "eb946699010d624b333c87bc463c7084",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 76,
"avg_line_length": 29.106060606060606,
"alnum_prop": 0.5429463820926601,
"repo_name": "StephR74/3asyReport",
"id": "e0a3a0735e0c747c33b3e83d50d69ed869972f03",
"size": "1921",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Somfy/EasyReportBundle/Resources/public/plugins/froala/examples/init_on_link_unlink_button_disabled.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "90426"
},
{
"name": "JavaScript",
"bytes": "228861"
},
{
"name": "PHP",
"bytes": "46892"
}
],
"symlink_target": ""
} |
package host
import "github.com/opencontainers/runc/libcontainer/configs"
// DefaultCapabilities is the default list of capabilities which are set inside
// a container, taken from:
// https://github.com/opencontainers/runc/blob/v1.0.0-rc1/libcontainer/SPEC.md#security
var DefaultCapabilities = []string{
"CAP_NET_RAW",
"CAP_NET_BIND_SERVICE",
"CAP_DAC_OVERRIDE",
"CAP_SETFCAP",
"CAP_SETPCAP",
"CAP_SETGID",
"CAP_SETUID",
"CAP_MKNOD",
"CAP_CHOWN",
"CAP_FOWNER",
"CAP_FSETID",
"CAP_KILL",
"CAP_SYS_CHROOT",
}
// DefaultAllowedDevices is the default list of devices containers are allowed
// to access
var DefaultAllowedDevices = configs.DefaultAllowedDevices
| {
"content_hash": "e624c0944dacdfff0f302a060d3e839c",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 87,
"avg_line_length": 25.96153846153846,
"alnum_prop": 0.7437037037037038,
"repo_name": "philiplb/flynn",
"id": "8e57681d249391edee7bfbc71a2b0524c277ad58",
"size": "700",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "host/types/defaults.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "31455"
},
{
"name": "Go",
"bytes": "2803136"
},
{
"name": "HTML",
"bytes": "11767"
},
{
"name": "JavaScript",
"bytes": "367416"
},
{
"name": "Makefile",
"bytes": "602"
},
{
"name": "Ruby",
"bytes": "1908"
},
{
"name": "Shell",
"bytes": "131222"
}
],
"symlink_target": ""
} |
package com.github.agourlay.cornichon.kafka
import com.github.agourlay.cornichon.core.SessionKey
import com.github.agourlay.cornichon.json.CornichonJson._
import com.github.agourlay.cornichon.json.JsonSteps.JsonStepBuilder
import com.github.agourlay.cornichon.steps.regular.assertStep.{ AssertStep, Assertion, GenericEqualityAssertion }
case class KafkaStepBuilder(sessionKey: String) {
def topic_is(expected: String) = AssertStep(
title = s"topic is $expected",
action = sc => Assertion.either {
for {
actualTopic <- sc.session.getJsonStringField(s"$sessionKey-topic")
resolvedExpectedTopic <- sc.fillPlaceholders(expected)
} yield GenericEqualityAssertion(resolvedExpectedTopic, actualTopic)
}
)
def message_value = JsonStepBuilder(SessionKey(s"$sessionKey-value"), Some("kafka message value"))
def key_is(expected: String) = AssertStep(
title = s"key is $expected",
action = sc => Assertion.either {
for {
actualKey <- sc.session.getJsonStringField(s"$sessionKey-key")
resolvedExpectedKey <- sc.fillPlaceholders(expected)
} yield GenericEqualityAssertion(resolvedExpectedKey, actualKey)
}
)
}
| {
"content_hash": "d389402bdab7a8fa02cbb0fbc9803a9e",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 113,
"avg_line_length": 39.666666666666664,
"alnum_prop": 0.7394957983193278,
"repo_name": "agourlay/cornichon",
"id": "601b307adce053e53e5027e40e59e671859ca9f8",
"size": "1190",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cornichon-kafka/src/main/scala/com/github/agourlay/cornichon/kafka/KafkaStepBuilder.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "249"
},
{
"name": "Scala",
"bytes": "650252"
}
],
"symlink_target": ""
} |
class CreateLoanMunitionLogs < ActiveRecord::Migration
def change
create_table :loan_munition_logs do |t|
t.references :loan, index: true
t.references :munition, index: true
t.references :reserve, index: true
t.integer :amount
t.timestamps null: false
end
end
end
| {
"content_hash": "ddcd9dcf61babd963206e4e29a8cec2b",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 54,
"avg_line_length": 25.583333333333332,
"alnum_prop": 0.6807817589576547,
"repo_name": "DiegoCorrea/SoldadinhodeChumbo",
"id": "8ae146fa2b868e5fdc0f21dd2100ea02691ecfa5",
"size": "307",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/migrate/20161010020649_create_loan_munition_logs.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6165"
},
{
"name": "HTML",
"bytes": "37061"
},
{
"name": "JavaScript",
"bytes": "1032"
},
{
"name": "Ruby",
"bytes": "92783"
}
],
"symlink_target": ""
} |
namespace Toscana.Engine
{
internal class ToscaFloatDataTypeConverter : IToscaDataTypeValueConverter
{
public bool CanConvert(string dataTypeName)
{
return dataTypeName == "float";
}
public bool TryParse(object dataTypeValue, out object result)
{
if (dataTypeValue == null)
{
result = null;
return false;
}
float valueAsFloat;
var canParse = float.TryParse(dataTypeValue.ToString(), out valueAsFloat);
result = valueAsFloat;
return canParse;
}
}
} | {
"content_hash": "62f18fc5d35b8415779a2d0c3e32d99f",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 86,
"avg_line_length": 27.695652173913043,
"alnum_prop": 0.5525902668759811,
"repo_name": "johnathanvidu/Toscana",
"id": "f6243974b7029d570529eaf11448b9e4272dc533",
"size": "639",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Toscana/Engine/ToscaFloatDataTypeConverter.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "194"
},
{
"name": "C#",
"bytes": "373987"
},
{
"name": "CSS",
"bytes": "406167"
},
{
"name": "GCC Machine Description",
"bytes": "40"
},
{
"name": "HTML",
"bytes": "2935794"
},
{
"name": "JavaScript",
"bytes": "66729"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
namespace MaxMind.GeoIP2
{
/// <summary>
/// Options class for WebServiceClient.
/// </summary>
public class WebServiceClientOptions
{
/// <summary>
/// Your MaxMind account ID.
/// </summary>
public int AccountId { get; set; }
/// <summary>
/// Your MaxMind license key.
/// </summary>
public string LicenseKey { get; set; } = string.Empty;
/// <summary>
/// List of locale codes to use in name property from most preferred to least preferred.
/// </summary>
public IEnumerable<string>? Locales { get; set; }
/// <summary>
/// Timeout in milliseconds for connection to web service. The default is 3000.
/// </summary>
public int Timeout { get; set; } = 3000;
/// <summary>
/// The host to use when accessing the service.
/// </summary>
public string Host { get; set; } = "geoip.maxmind.com";
/// <summary>
/// If set, the client will use HTTP instead of HTTPS. Please note
/// that MaxMind servers require HTTPS.
/// </summary>
public bool DisableHttps { get; set; } = false;
}
}
| {
"content_hash": "71f9c0b56b5568330e152a19414d8290",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 96,
"avg_line_length": 30.390243902439025,
"alnum_prop": 0.557784911717496,
"repo_name": "maxmind/GeoIP2-dotnet",
"id": "2a40a9e35074d727fb50e2acd439dd0d768cb43d",
"size": "1248",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "MaxMind.GeoIP2/WebServiceClientOptions.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "221881"
},
{
"name": "Dockerfile",
"bytes": "134"
},
{
"name": "Makefile",
"bytes": "1139"
},
{
"name": "PowerShell",
"bytes": "1425"
}
],
"symlink_target": ""
} |
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[DWNetworking postUrlString:@"当输入的请求地址为http://或者https://开头时,则不自动抛弃baseUrl" params:nil resultCallBack:^(id success, NSError *error, BOOL isCache) {
}];
}
- (IBAction)cleanAllCache:(id)sender {
NSLog(@"%@", [DWNetworking getCachesPath]);
[DWNetworking cleanAllCache];
NSLog(@"缓存:%lldKB", [DWNetworking getCachesSize]);
}
@end
| {
"content_hash": "99fea7ce72923ebc65e65896dee939a5",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 150,
"avg_line_length": 23.166666666666668,
"alnum_prop": 0.685251798561151,
"repo_name": "CoderDwang/DWNetworking",
"id": "3bda1e098eb0d8bc05a7d8e40912c1ae6f4da926",
"size": "798",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DWNetworkingDemo/ViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "20920"
},
{
"name": "Ruby",
"bytes": "905"
}
],
"symlink_target": ""
} |
#include "stdafx.h"
#include "System\Array.h"
#include "System\Object.h"
#include "System\Int32.h"
| {
"content_hash": "35e5c6548384a0b5df3a2916ec4a84af",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 26,
"avg_line_length": 25,
"alnum_prop": 0.72,
"repo_name": "xiongfang/UL",
"id": "c72401d47af016ebc88921a8b2e0bd222a2fd86f",
"size": "102",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UL/CppApp/System/Array.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "46983"
},
{
"name": "C#",
"bytes": "756985"
},
{
"name": "C++",
"bytes": "110616"
},
{
"name": "Lua",
"bytes": "13204"
}
],
"symlink_target": ""
} |
package main
import (
"github.com/spf13/cobra"
"github.com/coreos/mantle/sdk"
"github.com/coreos/mantle/sdk/omaha"
)
var (
buildCmd = &cobra.Command{
Use: "build [object]",
Short: "Build something",
}
buildUpdateCmd = &cobra.Command{
Use: "update",
Short: "Build an image update payload",
Run: runBuildUpdate,
}
)
func init() {
buildCmd.AddCommand(buildUpdateCmd)
root.AddCommand(buildCmd)
}
func runBuildUpdate(cmd *cobra.Command, args []string) {
if len(args) != 0 {
plog.Fatalf("Unrecognized arguments: %v", args)
}
err := omaha.GenerateFullUpdate(sdk.BuildImageDir("", ""))
if err != nil {
plog.Fatalf("Building full update failed: %v", err)
}
}
| {
"content_hash": "db425517af2795febc66d89a29b6769b",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 59,
"avg_line_length": 19.166666666666668,
"alnum_prop": 0.6753623188405797,
"repo_name": "marineam/mantle",
"id": "257baff004828f13f1fa40b108061d143f900622",
"size": "1280",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "cmd/cork/build.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "945342"
},
{
"name": "Protocol Buffer",
"bytes": "8331"
},
{
"name": "Shell",
"bytes": "2533"
}
],
"symlink_target": ""
} |
"""
ABP analyzer and graphics tests
"""
cases = [
('Run Pymodel Graphics to generate dot file from FSM model, no need use pma',
'pmg.py ABP'),
('Generate SVG file from dot',
'dotsvg ABP'),
# Now display ABP.dot in browser
('Run PyModel Analyzer to generate FSM from original FSM, should be the same',
'pma.py ABP'),
('Run PyModel Graphics to generate a file of graphics commands from new FSM',
'pmg.py ABPFSM'),
('Generate an svg file from the graphics commands',
'dotsvg ABPFSM'),
# Now display ABPFSM.svg in browser, should look the same as ABP.svg
]
| {
"content_hash": "72d9f98e3cfab3d9c294da53322e3d50",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 82,
"avg_line_length": 25.541666666666668,
"alnum_prop": 0.6541598694942904,
"repo_name": "nfredrik/pyModelStuff",
"id": "3582ef463bc23bae59174a0b2b8c276b24a2439a",
"size": "613",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/abp/test_graphics.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Perl",
"bytes": "107"
},
{
"name": "Python",
"bytes": "64694"
},
{
"name": "Ruby",
"bytes": "128"
}
],
"symlink_target": ""
} |
var albumServer = require('album-server')
albumMgr = require('album-manager');
var ALBUMS_DIR = './gallery';
// DI-style initialization
// Create album manager (service object)
var albums = albumMgr.create(ALBUMS_DIR);
// Fire up the server on port 8080
var server = albumServer.create(albums);
server.listen(8080);
console.log('Server listening on localhost:8080...')
| {
"content_hash": "b2972151d76d2eda981595e58efb22bb",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 52,
"avg_line_length": 25.2,
"alnum_prop": 0.7275132275132276,
"repo_name": "joerx/node-gallery",
"id": "aae8aba6aa28dba66ac7e4d805c1a39f36ecad8f",
"size": "378",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "819"
}
],
"symlink_target": ""
} |
@interface ViewController() <SLRecognizerDelegate>
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[[SLRecognizer sharedInstance] initWithAppId:@"appId" appSecret:@"appSecret"];
[SLRecognizer sharedInstance].delegate = self;
[[SLRecognizer sharedInstance] enable];
}
#pragma mark SLRecognizerDelegate
- (void)recognizer:(SLRecognizer *)recognizer code:(NSString *)code
{
NSLog(@"code = %@", code);
NSString *token = [[SLRecognizer sharedInstance] getTokenWithCode:code];
NSLog(@"token = %@", token); // 有效时间5分钟。
}
@end
| {
"content_hash": "95f4583a5c6dc8136cd73079678d4cde",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 82,
"avg_line_length": 24.5,
"alnum_prop": 0.7074829931972789,
"repo_name": "soundlinks/Soundlinks-iOS-SDK",
"id": "c4976b7cafcc4a8119c21c83f7d1932984c2bf45",
"size": "784",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SoundlinksSDKExample/SoundlinksSDKExample/ViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "4977"
},
{
"name": "Ruby",
"bytes": "539"
}
],
"symlink_target": ""
} |
package commands
import (
cmdkit "github.com/ipfs/go-ipfs-cmdkit"
cmds "github.com/ipfs/go-ipfs-cmds"
)
var DiagCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Generate diagnostic reports.",
},
Subcommands: map[string]*cmds.Command{
"sys": sysDiagCmd,
"cmds": ActiveReqsCmd,
},
}
| {
"content_hash": "ed12d0d721ed1b654044736070e909ff",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 42,
"avg_line_length": 18,
"alnum_prop": 0.7026143790849673,
"repo_name": "Luzifer/go-ipfs",
"id": "bfd75caac54fdd606e6ba53dd95cb58a8ae624dd",
"size": "306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/commands/diag.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "3481"
},
{
"name": "Go",
"bytes": "953333"
},
{
"name": "Groovy",
"bytes": "6317"
},
{
"name": "Makefile",
"bytes": "18671"
},
{
"name": "PureBasic",
"bytes": "29"
},
{
"name": "Python",
"bytes": "788"
},
{
"name": "Shell",
"bytes": "420212"
}
],
"symlink_target": ""
} |
<?php
/**
* Short description for class.
*
* @package Cake.Test.Fixture
*/
class MessageFixture extends CakeTestFixture {
/**
* name property
*
* @var string 'Message'
*/
public $name = 'Message';
/**
* fields property
*
* @var array
*/
public $fields = array(
'id' => array('type' => 'integer', 'key' => 'primary'),
'thread_id' => array('type' => 'integer', 'null' => false),
'name' => array('type' => 'string', 'null' => false)
);
/**
* records property
*
* @var array
*/
public $records = array(
array('thread_id' => 1, 'name' => 'Thread 1, Message 1'),
array('thread_id' => 2, 'name' => 'Thread 2, Message 1'),
array('thread_id' => 3, 'name' => 'Thread 3, Message 1')
);
}
| {
"content_hash": "6daea59639b836b88df9c179408ddd49",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 61,
"avg_line_length": 18.487179487179485,
"alnum_prop": 0.5589459084604715,
"repo_name": "soug-jp/account-book",
"id": "cd1f47552a674d817b4597beb8604c55b989226d",
"size": "1367",
"binary": false,
"copies": "19",
"ref": "refs/heads/master",
"path": "lib/Cake/Test/Fixture/MessageFixture.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "143"
},
{
"name": "PHP",
"bytes": "6640940"
},
{
"name": "Shell",
"bytes": "2113"
}
],
"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.
using System.Collections.Immutable;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.UseLocalFunction
{
/// <summary>
/// Looks for code of the form:
///
/// Func<int, int> fib = n =>
/// {
/// if (n <= 2)
/// return 1
///
/// return fib(n - 1) + fib(n - 2);
/// }
///
/// and converts it to:
///
/// int fib(int n)
/// {
/// if (n <= 2)
/// return 1
///
/// return fib(n - 1) + fib(n - 2);
/// }
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpUseLocalFunctionDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
public CSharpUseLocalFunctionDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseLocalFunctionDiagnosticId,
CSharpCodeStyleOptions.PreferLocalOverAnonymousFunction,
LanguageNames.CSharp,
new LocalizableResourceString(
nameof(FeaturesResources.Use_local_function), FeaturesResources.ResourceManager, typeof(FeaturesResources)))
{
}
protected override void InitializeWorker(AnalysisContext context)
{
context.RegisterCompilationStartAction(compilationContext =>
{
var compilation = compilationContext.Compilation;
var expressionTypeOpt = compilation.GetTypeByMetadataName(typeof(Expression<>).FullName);
context.RegisterSyntaxNodeAction(ctx => SyntaxNodeAction(ctx, expressionTypeOpt),
SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.AnonymousMethodExpression);
});
}
private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext, INamedTypeSymbol expressionTypeOpt)
{
var options = syntaxContext.Options;
var syntaxTree = syntaxContext.Node.SyntaxTree;
var cancellationToken = syntaxContext.CancellationToken;
var styleOption = options.GetOption(CSharpCodeStyleOptions.PreferLocalOverAnonymousFunction, syntaxTree, cancellationToken);
if (!styleOption.Value)
{
// Bail immediately if the user has disabled this feature.
return;
}
// Local functions are only available in C# 7.0 and above. Don't offer this refactoring
// in projects targeting a lesser version.
if (((CSharpParseOptions)syntaxTree.Options).LanguageVersion < LanguageVersion.CSharp7)
{
return;
}
var severity = styleOption.Notification.Severity;
var anonymousFunction = (AnonymousFunctionExpressionSyntax)syntaxContext.Node;
var semanticModel = syntaxContext.SemanticModel;
if (!CheckForPattern(semanticModel, anonymousFunction, cancellationToken,
out var localDeclaration))
{
return;
}
if (localDeclaration.Declaration.Variables.Count != 1)
{
return;
}
if (!(localDeclaration.Parent is BlockSyntax block))
{
return;
}
// If there are compiler error on the declaration we can't reliably
// tell that the refactoring will be accurate, so don't provide any
// code diagnostics
if (localDeclaration.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error))
{
return;
}
var local = semanticModel.GetDeclaredSymbol(localDeclaration.Declaration.Variables[0], cancellationToken);
if (local == null)
{
return;
}
var delegateType = semanticModel.GetTypeInfo(anonymousFunction, cancellationToken).ConvertedType as INamedTypeSymbol;
if (!delegateType.IsDelegateType() ||
delegateType.DelegateInvokeMethod == null ||
!CanReplaceDelegateWithLocalFunction(delegateType, localDeclaration, semanticModel, cancellationToken))
{
return;
}
if (!CanReplaceAnonymousWithLocalFunction(semanticModel, expressionTypeOpt, local, block, anonymousFunction, out var referenceLocations, cancellationToken))
{
return;
}
// Looks good!
var additionalLocations = ImmutableArray.Create(
localDeclaration.GetLocation(),
anonymousFunction.GetLocation());
additionalLocations = additionalLocations.AddRange(referenceLocations);
if (severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) < ReportDiagnostic.Hidden)
{
// If the diagnostic is not hidden, then just place the user visible part
// on the local being initialized with the lambda.
syntaxContext.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
localDeclaration.Declaration.Variables[0].Identifier.GetLocation(),
severity,
additionalLocations,
properties: null));
}
else
{
// If the diagnostic is hidden, place it on the entire construct.
syntaxContext.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
localDeclaration.GetLocation(),
severity,
additionalLocations,
properties: null));
var anonymousFunctionStatement = anonymousFunction.GetAncestor<StatementSyntax>();
if (localDeclaration != anonymousFunctionStatement)
{
syntaxContext.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
anonymousFunctionStatement.GetLocation(),
severity,
additionalLocations,
properties: null));
}
}
}
private bool CheckForPattern(
SemanticModel semanticModel,
AnonymousFunctionExpressionSyntax anonymousFunction,
CancellationToken cancellationToken,
out LocalDeclarationStatementSyntax localDeclaration)
{
// Look for:
//
// Type t = <anonymous function>
// var t = (Type)(<anonymous function>)
//
// Type t = null;
// t = <anonymous function>
return CheckForSimpleLocalDeclarationPattern(semanticModel, anonymousFunction, cancellationToken, out localDeclaration) ||
CheckForCastedLocalDeclarationPattern(semanticModel, anonymousFunction, cancellationToken, out localDeclaration) ||
CheckForLocalDeclarationAndAssignment(semanticModel, anonymousFunction, cancellationToken, out localDeclaration);
}
private bool CheckForSimpleLocalDeclarationPattern(
SemanticModel semanticModel,
AnonymousFunctionExpressionSyntax anonymousFunction,
CancellationToken cancellationToken,
out LocalDeclarationStatementSyntax localDeclaration)
{
// Type t = <anonymous function>
if (anonymousFunction.IsParentKind(SyntaxKind.EqualsValueClause) &&
anonymousFunction.Parent.IsParentKind(SyntaxKind.VariableDeclarator) &&
anonymousFunction.Parent.Parent.IsParentKind(SyntaxKind.VariableDeclaration) &&
anonymousFunction.Parent.Parent.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement))
{
localDeclaration = (LocalDeclarationStatementSyntax)anonymousFunction.Parent.Parent.Parent.Parent;
if (!localDeclaration.Declaration.Type.IsVar)
{
return true;
}
}
localDeclaration = null;
return false;
}
private bool CanReplaceAnonymousWithLocalFunction(
SemanticModel semanticModel, INamedTypeSymbol expressionTypeOpt, ISymbol local, BlockSyntax block,
AnonymousFunctionExpressionSyntax anonymousFunction, out ImmutableArray<Location> referenceLocations, CancellationToken cancellationToken)
{
// Check all the references to the anonymous function and disallow the conversion if
// they're used in certain ways.
var references = ArrayBuilder<Location>.GetInstance();
referenceLocations = ImmutableArray<Location>.Empty;
var anonymousFunctionStart = anonymousFunction.SpanStart;
foreach (var descendentNode in block.DescendantNodes())
{
var descendentStart = descendentNode.Span.Start;
if (descendentStart <= anonymousFunctionStart)
{
// This node is before the local declaration. Can ignore it entirely as it could
// not be an access to the local.
continue;
}
if (descendentNode.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax identifierName))
{
if (identifierName.Identifier.ValueText == local.Name &&
local.Equals(semanticModel.GetSymbolInfo(identifierName, cancellationToken).GetAnySymbol()))
{
if (identifierName.IsWrittenTo())
{
// Can't change this to a local function if it is assigned to.
return false;
}
var nodeToCheck = identifierName.WalkUpParentheses();
if (nodeToCheck.Parent is BinaryExpressionSyntax)
{
// Can't change this if they're doing things like delegate addition with
// the lambda.
return false;
}
if (nodeToCheck.Parent is InvocationExpressionSyntax invocationExpression)
{
references.Add(invocationExpression.GetLocation());
}
else if (nodeToCheck.Parent is MemberAccessExpressionSyntax memberAccessExpression)
{
if (memberAccessExpression.Parent is InvocationExpressionSyntax explicitInvocationExpression &&
memberAccessExpression.Name.Identifier.ValueText == WellKnownMemberNames.DelegateInvokeName)
{
references.Add(explicitInvocationExpression.GetLocation());
}
else
{
// They're doing something like "del.ToString()". Can't do this with a
// local function.
return false;
}
}
else
{
references.Add(nodeToCheck.GetLocation());
}
var convertedType = semanticModel.GetTypeInfo(nodeToCheck, cancellationToken).ConvertedType;
if (!convertedType.IsDelegateType())
{
// We can't change this anonymous function into a local function if it is
// converted to a non-delegate type (i.e. converted to 'object' or
// 'System.Delegate'). Local functions are not convertible to these types.
// They're only convertible to other delegate types.
return false;
}
if (nodeToCheck.IsInExpressionTree(semanticModel, expressionTypeOpt, cancellationToken))
{
// Can't reference a local function inside an expression tree.
return false;
}
}
}
}
referenceLocations = references.ToImmutableAndFree();
return true;
}
private bool CheckForCastedLocalDeclarationPattern(
SemanticModel semanticModel,
AnonymousFunctionExpressionSyntax anonymousFunction,
CancellationToken cancellationToken,
out LocalDeclarationStatementSyntax localDeclaration)
{
// var t = (Type)(<anonymous function>)
var containingStatement = anonymousFunction.GetAncestor<StatementSyntax>();
if (containingStatement.IsKind(SyntaxKind.LocalDeclarationStatement))
{
localDeclaration = (LocalDeclarationStatementSyntax)containingStatement;
if (localDeclaration.Declaration.Variables.Count == 1)
{
var variableDeclarator = localDeclaration.Declaration.Variables[0];
if (variableDeclarator.Initializer != null)
{
var value = variableDeclarator.Initializer.Value.WalkDownParentheses();
if (value is CastExpressionSyntax castExpression)
{
if (castExpression.Expression.WalkDownParentheses() == anonymousFunction)
{
return true;
}
}
}
}
}
localDeclaration = null;
return false;
}
private bool CheckForLocalDeclarationAndAssignment(
SemanticModel semanticModel,
AnonymousFunctionExpressionSyntax anonymousFunction,
CancellationToken cancellationToken,
out LocalDeclarationStatementSyntax localDeclaration)
{
// Type t = null;
// t = <anonymous function>
if (anonymousFunction.IsParentKind(SyntaxKind.SimpleAssignmentExpression) &&
anonymousFunction.Parent.IsParentKind(SyntaxKind.ExpressionStatement) &&
anonymousFunction.Parent.Parent.IsParentKind(SyntaxKind.Block))
{
var assignment = (AssignmentExpressionSyntax)anonymousFunction.Parent;
if (assignment.Left.IsKind(SyntaxKind.IdentifierName))
{
var expressionStatement = (ExpressionStatementSyntax)assignment.Parent;
var block = (BlockSyntax)expressionStatement.Parent;
var expressionStatementIndex = block.Statements.IndexOf(expressionStatement);
if (expressionStatementIndex >= 1)
{
var previousStatement = block.Statements[expressionStatementIndex - 1];
if (previousStatement.IsKind(SyntaxKind.LocalDeclarationStatement))
{
localDeclaration = (LocalDeclarationStatementSyntax)previousStatement;
if (localDeclaration.Declaration.Variables.Count == 1)
{
var variableDeclarator = localDeclaration.Declaration.Variables[0];
if (variableDeclarator.Initializer == null ||
variableDeclarator.Initializer.Value.IsKind(
SyntaxKind.NullLiteralExpression,
SyntaxKind.DefaultLiteralExpression,
SyntaxKind.DefaultExpression))
{
var identifierName = (IdentifierNameSyntax)assignment.Left;
if (variableDeclarator.Identifier.ValueText == identifierName.Identifier.ValueText)
{
return true;
}
}
}
}
}
}
}
localDeclaration = null;
return false;
}
private static bool CanReplaceDelegateWithLocalFunction(
INamedTypeSymbol delegateType,
LocalDeclarationStatementSyntax localDeclaration,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var delegateContainingType = delegateType.ContainingType;
if (delegateContainingType is null || !delegateContainingType.IsGenericType)
{
return true;
}
var delegateTypeParamNames = delegateType.GetAllTypeParameters().Select(p => p.Name).ToImmutableHashSet();
var localEnclosingSymbol = semanticModel.GetEnclosingSymbol(localDeclaration.SpanStart, cancellationToken);
while (localEnclosingSymbol != null)
{
if (localEnclosingSymbol.Equals(delegateContainingType))
{
return true;
}
var typeParams = localEnclosingSymbol.GetTypeParameters();
if (typeParams.Any())
{
if (typeParams.Any(p => delegateTypeParamNames.Contains(p.Name)))
{
return false;
}
}
localEnclosingSymbol = localEnclosingSymbol.ContainingType;
}
return true;
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
}
}
| {
"content_hash": "c25c0e30375d6f27470f1426c8d5a254",
"timestamp": "",
"source": "github",
"line_count": 417,
"max_line_length": 168,
"avg_line_length": 45.39808153477218,
"alnum_prop": 0.5587132216998574,
"repo_name": "agocke/roslyn",
"id": "9108474b7907badc10e4d5169a1d09c79bc81b12",
"size": "18933",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Features/CSharp/Portable/UseLocalFunction/CSharpUseLocalFunctionDiagnosticAnalyzer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "289100"
},
{
"name": "Batchfile",
"bytes": "9059"
},
{
"name": "C#",
"bytes": "126326705"
},
{
"name": "C++",
"bytes": "5602"
},
{
"name": "CMake",
"bytes": "8276"
},
{
"name": "Dockerfile",
"bytes": "2450"
},
{
"name": "F#",
"bytes": "549"
},
{
"name": "PowerShell",
"bytes": "237208"
},
{
"name": "Shell",
"bytes": "94927"
},
{
"name": "Visual Basic .NET",
"bytes": "70527543"
}
],
"symlink_target": ""
} |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.autofill.prefeditor;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MenuItem;
import androidx.appcompat.widget.Toolbar;
import org.chromium.chrome.R;
/** Simple class for displaying a toolbar in the editor dialog. */
public class EditorDialogToolbar extends Toolbar {
private boolean mShowDeleteMenuItem = true;
/** Constructor for when the toolbar is inflated from XML. */
public EditorDialogToolbar(Context context, AttributeSet attrs) {
super(context, attrs);
inflateMenu(R.menu.prefeditor_editor_menu);
updateMenu();
}
/** Sets whether or not the the delete menu item will be shown. */
public void setShowDeleteMenuItem(boolean state) {
mShowDeleteMenuItem = state;
updateMenu();
}
/** Updates what is displayed in the menu. */
public void updateMenu() {
Menu menu = getMenu();
MenuItem deleteMenuItem = menu.findItem(R.id.delete_menu_id);
if (deleteMenuItem != null) deleteMenuItem.setVisible(mShowDeleteMenuItem);
}
}
| {
"content_hash": "213ababbe6c88190c5754ebaddd45899",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 83,
"avg_line_length": 32.025,
"alnum_prop": 0.7142857142857143,
"repo_name": "nwjs/chromium.src",
"id": "2b001aa811d67085399fa6c76b38575e7ea193c2",
"size": "1281",
"binary": false,
"copies": "6",
"ref": "refs/heads/nw70",
"path": "chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorDialogToolbar.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
@class DVTDotSeparatedVersion, NSString;
@interface DVTDownloadableDependency : NSObject <NSCoding>
{
NSString *_identifier;
DVTDotSeparatedVersion *_minVersion;
}
@property(readonly) DVTDotSeparatedVersion *minVersion; // @synthesize minVersion=_minVersion;
@property(readonly) NSString *identifier; // @synthesize identifier=_identifier;
- (void).cxx_destruct;
- (id)propertyList;
- (id)initWithPropertyList:(id)arg1 error:(id *)arg2;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (id)description;
- (id)initWithIdentifier:(id)arg1 minVersion:(id)arg2;
@end
| {
"content_hash": "743cf52ca230882824cbab7c2984d25b",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 94,
"avg_line_length": 29.6,
"alnum_prop": 0.7584459459459459,
"repo_name": "pitatensai/FBSimulatorControl",
"id": "9b916dc26f49375a2eb9d5a9acf287ca3ae185a8",
"size": "775",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "PrivateHeaders/DVTFoundation/DVTDownloadableDependency.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Objective-C",
"bytes": "767441"
},
{
"name": "Ruby",
"bytes": "189"
}
],
"symlink_target": ""
} |
{% extends "base.html" %}
{% block title %}
{{ SITENAME }} | Projects
{% endblock %}
{% block content %}
{% if pages %}
<ul class="post-list" id="projects" itemscope itemtype="http://schema.org/Blog">
{% for article in articles|selectattr("project") %}
{% include 'article_short.html' %}
{% endfor %}
</ul>
{% endif %}
{% endblock content %}
| {
"content_hash": "ec1729188f764d12274d1c8ebf30ec5f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 84,
"avg_line_length": 28.46153846153846,
"alnum_prop": 0.581081081081081,
"repo_name": "NikhilKalige/mytheme",
"id": "55aed130f1c13c12d474db30a31a686fc45bd453",
"size": "370",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templates/projects.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package alec_wam.CrystalMod.entities.animals;
import net.minecraft.client.model.ModelCow;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.client.registry.IRenderFactory;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class RenderCrystalCow extends RenderLiving<EntityCrystalCow>
{
private static final ResourceLocation[] COW_TEXTURE = new ResourceLocation[]{new ResourceLocation("crystalmod:textures/entities/cow/blue_cow.png"), new ResourceLocation("crystalmod:textures/entities/cow/red_cow.png"), new ResourceLocation("crystalmod:textures/entities/cow/green_cow.png"), new ResourceLocation("crystalmod:textures/entities/cow/dark_cow.png"), new ResourceLocation("crystalmod:textures/entities/cow/pure_cow.png")};
public RenderCrystalCow(RenderManager renderManagerIn)
{
super(renderManagerIn, new ModelCow(), 0.7F);
this.addLayer(new LayerCrystalCowCrystals(this));
}
/**
* Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture.
*/
@Override
protected ResourceLocation getEntityTexture(EntityCrystalCow entity)
{
return COW_TEXTURE[entity.getColor()];
}
public static final Factory FACTORY = new Factory();
public static class Factory implements IRenderFactory<EntityCrystalCow> {
@Override
public Render<? super EntityCrystalCow> createRenderFor(RenderManager manager) {
return new RenderCrystalCow(manager);
}
}
}
| {
"content_hash": "b414cd8e4c8485ddd5dbfba64dbb93ff",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 436,
"avg_line_length": 45.35,
"alnum_prop": 0.7508269018743109,
"repo_name": "Alec-WAM/CrystalMod",
"id": "14a18e37b83ef4a9bae66c03eb6c56a204c586e5",
"size": "1814",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/alec_wam/CrystalMod/entities/animals/RenderCrystalCow.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "36"
},
{
"name": "Java",
"bytes": "6735638"
}
],
"symlink_target": ""
} |
#include "hal.h"
/**
* @brief PAL setup.
* @details Digital I/O ports static configuration as defined in @p board.h.
* This variable is used by the HAL when initializing the PAL driver.
*/
#if HAL_USE_PAL || defined(__DOXYGEN__)
const PALConfig pal_default_config =
{
{VAL_GPIOA_MODER, VAL_GPIOA_OTYPER, VAL_GPIOA_OSPEEDR, VAL_GPIOA_PUPDR, VAL_GPIOA_ODR, VAL_GPIOA_AFRL, VAL_GPIOA_AFRH},
{VAL_GPIOB_MODER, VAL_GPIOB_OTYPER, VAL_GPIOB_OSPEEDR, VAL_GPIOB_PUPDR, VAL_GPIOB_ODR, VAL_GPIOB_AFRL, VAL_GPIOB_AFRH},
{VAL_GPIOC_MODER, VAL_GPIOC_OTYPER, VAL_GPIOC_OSPEEDR, VAL_GPIOC_PUPDR, VAL_GPIOC_ODR, VAL_GPIOC_AFRL, VAL_GPIOC_AFRH},
{VAL_GPIOD_MODER, VAL_GPIOD_OTYPER, VAL_GPIOD_OSPEEDR, VAL_GPIOD_PUPDR, VAL_GPIOD_ODR, VAL_GPIOD_AFRL, VAL_GPIOD_AFRH},
{VAL_GPIOE_MODER, VAL_GPIOE_OTYPER, VAL_GPIOE_OSPEEDR, VAL_GPIOE_PUPDR, VAL_GPIOE_ODR, VAL_GPIOE_AFRL, VAL_GPIOE_AFRH},
{VAL_GPIOF_MODER, VAL_GPIOF_OTYPER, VAL_GPIOF_OSPEEDR, VAL_GPIOF_PUPDR, VAL_GPIOF_ODR, VAL_GPIOF_AFRL, VAL_GPIOF_AFRH},
{VAL_GPIOG_MODER, VAL_GPIOG_OTYPER, VAL_GPIOG_OSPEEDR, VAL_GPIOG_PUPDR, VAL_GPIOG_ODR, VAL_GPIOG_AFRL, VAL_GPIOG_AFRH},
{VAL_GPIOH_MODER, VAL_GPIOH_OTYPER, VAL_GPIOH_OSPEEDR, VAL_GPIOH_PUPDR, VAL_GPIOH_ODR, VAL_GPIOH_AFRL, VAL_GPIOH_AFRH},
{VAL_GPIOI_MODER, VAL_GPIOI_OTYPER, VAL_GPIOI_OSPEEDR, VAL_GPIOI_PUPDR, VAL_GPIOI_ODR, VAL_GPIOI_AFRL, VAL_GPIOI_AFRH}
};
#endif
/*
* Early initialization code.
* This initialization must be performed just after stack setup and before
* any other initialization.
*/
void __early_init(void) {
stm32_clock_init();
}
/*
* Board-specific initialization code.
*/
void boardInit(void) {
}
#if HAL_USE_SDC
/**
* @brief Insertion monitor function.
*
* @param[in] sdcp pointer to the @p SDCDriver object
*
* @notapi
*/
bool sdc_lld_is_card_inserted(SDCDriver *sdcp) {
(void)sdcp;
return !palReadPad(GPIOE, GPIOE_SDIO_DETECT);
}
/**
* @brief Protection detection.
* @note Not supported, always not protected.
*
* @param[in] sdcp pointer to the @p SDCDriver object
*
* @notapi
*/
bool sdc_lld_is_write_protected(SDCDriver *sdcp) {
(void)sdcp;
return FALSE;
}
#endif /* HAL_USE_SDC */
| {
"content_hash": "8156d1425539eb97ea4ea77d3d65d3db",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 121,
"avg_line_length": 32.205882352941174,
"alnum_prop": 0.6995433789954338,
"repo_name": "marcoveeneman/ChibiOS-Tiva",
"id": "49cb4045459b4c5d73c45468efd2f61d2559cd2a",
"size": "2815",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "os/hal/boards/NONSTANDARD_STM32F4_BARTHESS1/board.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "263835"
},
{
"name": "C",
"bytes": "18046967"
},
{
"name": "C++",
"bytes": "529003"
},
{
"name": "Objective-C",
"bytes": "1604902"
}
],
"symlink_target": ""
} |
package com.anriku.imcheck.MainInterface.View.GroupSet;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import com.anriku.imcheck.MainInterface.Interface.GroupSet.IGroupModifyAct;
import com.anriku.imcheck.MainInterface.Interface.GroupSet.IGroupModifyPre;
import com.anriku.imcheck.MainInterface.Presenter.GroupSet.GroupModifyPresenter;
import com.anriku.imcheck.R;
import com.anriku.imcheck.databinding.ActivityGroupModifyBinding;
public class GroupModifyActivity extends AppCompatActivity implements IGroupModifyAct {
private IGroupModifyPre iGroupModifyPre;
private ActivityGroupModifyBinding binding;
private String obj;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this,R.layout.activity_group_modify);
iGroupModifyPre = new GroupModifyPresenter(this);
binding.acGroupModifyTb.setTitle("");
setSupportActionBar(binding.acGroupModifyTb);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setHomeAsUpIndicator(R.mipmap.back);
actionBar.setDisplayHomeAsUpEnabled(true);
}
Intent intent = getIntent();
obj = intent.getStringExtra("id");
iGroupModifyPre.setNameAndDesc(this,binding,obj);
iGroupModifyPre.changeNameAndDesc(this,binding,obj);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
default:
break;
}
return true;
}
}
| {
"content_hash": "692a78f07d3627a6c5c3a7dc19d8bb5e",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 87,
"avg_line_length": 34.592592592592595,
"alnum_prop": 0.7210920770877944,
"repo_name": "Anriku/IMCheck",
"id": "f146c0f2e62452364f5cd3e1e3727a19872e6b92",
"size": "1868",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/anriku/imcheck/MainInterface/View/GroupSet/GroupModifyActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "248143"
}
],
"symlink_target": ""
} |
angular.module("appExpedientes",["ngRoute"])
.config(function($routeProvider){
$routeProvider.when("/area",{templateUrl:"views/datosArea.html"})
.when("/area/lista",{templateUrl:"views/listaAreas.html"});
})
.controller("areaController",function($scope,areaService){
$scope.titulo = "Gestión de Areas";
$scope.listaAreas = areaService.listarAreas();
//[{"nombre":"Un Area"},{"nombre":"Salud e higiene"}]; //Aárea de prueva {"nombre":"Un Area"}
$scope.area = undefined;
$scope.isEditing=false;
$scope.cxtInfo=0;
$scope.msg="";
$scope.cancelar = function(){
$scope.area=undefined;
$scope.isEditing=!$scope.isEditing;
$scope.cxtInfo=0;
$scope.msg="";
}
$scope.editar = function(unArea){
$scope.isEditing=true;
$scope.area=unArea;
$scope.cxtInfo=0;
$scope.msg="";
}
$scope.guardar = function(){
if( $scope.listaAreas.indexOf($scope.area) < 0){
if($scope.area.nombre){
//$scope.listaAreas.push($scope.area);
areaService.addArea($scope.area);
$scope.cxtInfo=1;
$scope.msg="Operación de inserción exitosa.";
$scope.area=undefined;
$scope.isEditing=!$scope.isEditing;
}else{
$scope.cxtInfo=2;
$scope.msg="Operación de inserción fallida, debe especificar un nombre.";
}
}else if($scope.area.nombre && $scope.isEditing){
//Edition
$scope.cxtInfo=1;
$scope.msg="La operación de edición fue exitosa.";
$scope.area=undefined;
$scope.isEditing=!$scope.isEditing;
}else{
$scope.mensaje = "Hubo un problema, el área no puede tener nombre nulo";
$scope.area=undefined;
$scope.isEditing=!$scope.isEditing;
}
}
$scope.nueva = function(){
$scope.area={};
$scope.isEditing=!$scope.isEditing;
$scope.cxtInfo=0;
$scope.msg="";
console.log($scope.area);
}
$scope.borrar = function(unArea){
var idx = $scope.listaAreas.indexOf(unArea);
if( idx >= 0 && confirm("¿Desea borrar el área: "+unArea.nombre+"?")){
//$scope.listaAreas.splice(idx,1);
areaService.borrarArea(idx);
}
$scope.isEditing=false;
$scope.cxtInfo=0;
$scope.msg="";
}
});
| {
"content_hash": "2fe7395dad8612ce7d83e5c549918801",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 101,
"avg_line_length": 39.125,
"alnum_prop": 0.48562300319488816,
"repo_name": "cmacarpio/HTML5JS",
"id": "87dad19ecdac8eedf78260a72c5030f1cc0d8c51",
"size": "2828",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Clase04/lab07/ng-expedientes/app/app.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5014"
},
{
"name": "HTML",
"bytes": "21985"
},
{
"name": "JavaScript",
"bytes": "586589"
}
],
"symlink_target": ""
} |
import sys
_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1"))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name="google/cloud/bigquery/storage_v1beta1/proto/table_reference.proto",
package="google.cloud.bigquery.storage.v1beta1",
syntax="proto3",
serialized_pb=_b(
'\nAgoogle/cloud/bigquery/storage_v1beta1/proto/table_reference.proto\x12%google.cloud.bigquery.storage.v1beta1\x1a\x1fgoogle/protobuf/timestamp.proto"J\n\x0eTableReference\x12\x12\n\nproject_id\x18\x01 \x01(\t\x12\x12\n\ndataset_id\x18\x02 \x01(\t\x12\x10\n\x08table_id\x18\x03 \x01(\t"C\n\x0eTableModifiers\x12\x31\n\rsnapshot_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x8e\x01\n)com.google.cloud.bigquery.storage.v1beta1B\x13TableReferenceProtoZLgoogle.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta1;storageb\x06proto3'
),
dependencies=[google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR],
)
_TABLEREFERENCE = _descriptor.Descriptor(
name="TableReference",
full_name="google.cloud.bigquery.storage.v1beta1.TableReference",
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name="project_id",
full_name="google.cloud.bigquery.storage.v1beta1.TableReference.project_id",
index=0,
number=1,
type=9,
cpp_type=9,
label=1,
has_default_value=False,
default_value=_b("").decode("utf-8"),
message_type=None,
enum_type=None,
containing_type=None,
is_extension=False,
extension_scope=None,
options=None,
file=DESCRIPTOR,
),
_descriptor.FieldDescriptor(
name="dataset_id",
full_name="google.cloud.bigquery.storage.v1beta1.TableReference.dataset_id",
index=1,
number=2,
type=9,
cpp_type=9,
label=1,
has_default_value=False,
default_value=_b("").decode("utf-8"),
message_type=None,
enum_type=None,
containing_type=None,
is_extension=False,
extension_scope=None,
options=None,
file=DESCRIPTOR,
),
_descriptor.FieldDescriptor(
name="table_id",
full_name="google.cloud.bigquery.storage.v1beta1.TableReference.table_id",
index=2,
number=3,
type=9,
cpp_type=9,
label=1,
has_default_value=False,
default_value=_b("").decode("utf-8"),
message_type=None,
enum_type=None,
containing_type=None,
is_extension=False,
extension_scope=None,
options=None,
file=DESCRIPTOR,
),
],
extensions=[],
nested_types=[],
enum_types=[],
options=None,
is_extendable=False,
syntax="proto3",
extension_ranges=[],
oneofs=[],
serialized_start=141,
serialized_end=215,
)
_TABLEMODIFIERS = _descriptor.Descriptor(
name="TableModifiers",
full_name="google.cloud.bigquery.storage.v1beta1.TableModifiers",
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name="snapshot_time",
full_name="google.cloud.bigquery.storage.v1beta1.TableModifiers.snapshot_time",
index=0,
number=1,
type=11,
cpp_type=10,
label=1,
has_default_value=False,
default_value=None,
message_type=None,
enum_type=None,
containing_type=None,
is_extension=False,
extension_scope=None,
options=None,
file=DESCRIPTOR,
)
],
extensions=[],
nested_types=[],
enum_types=[],
options=None,
is_extendable=False,
syntax="proto3",
extension_ranges=[],
oneofs=[],
serialized_start=217,
serialized_end=284,
)
_TABLEMODIFIERS.fields_by_name[
"snapshot_time"
].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
DESCRIPTOR.message_types_by_name["TableReference"] = _TABLEREFERENCE
DESCRIPTOR.message_types_by_name["TableModifiers"] = _TABLEMODIFIERS
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
TableReference = _reflection.GeneratedProtocolMessageType(
"TableReference",
(_message.Message,),
dict(
DESCRIPTOR=_TABLEREFERENCE,
__module__="google.cloud.bigquery.storage_v1beta1.proto.table_reference_pb2",
__doc__="""Table reference that includes just the 3 strings needed to identify a
table.
Attributes:
project_id:
The assigned project ID of the project.
dataset_id:
The ID of the dataset in the above project.
table_id:
The ID of the table in the above dataset.
""",
# @@protoc_insertion_point(class_scope:google.cloud.bigquery.storage.v1beta1.TableReference)
),
)
_sym_db.RegisterMessage(TableReference)
TableModifiers = _reflection.GeneratedProtocolMessageType(
"TableModifiers",
(_message.Message,),
dict(
DESCRIPTOR=_TABLEMODIFIERS,
__module__="google.cloud.bigquery.storage_v1beta1.proto.table_reference_pb2",
__doc__="""All fields in this message optional.
Attributes:
snapshot_time:
The snapshot time of the table. If not set, interpreted as
now.
""",
# @@protoc_insertion_point(class_scope:google.cloud.bigquery.storage.v1beta1.TableModifiers)
),
)
_sym_db.RegisterMessage(TableModifiers)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(
descriptor_pb2.FileOptions(),
_b(
"\n)com.google.cloud.bigquery.storage.v1beta1B\023TableReferenceProtoZLgoogle.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta1;storage"
),
)
# @@protoc_insertion_point(module_scope)
| {
"content_hash": "6adced89cff4ebdd58047804f43dd72d",
"timestamp": "",
"source": "github",
"line_count": 199,
"max_line_length": 560,
"avg_line_length": 32.5678391959799,
"alnum_prop": 0.6340070976701127,
"repo_name": "dhermes/gcloud-python",
"id": "5208450f5deae1866048e7a1d79c26b08b20accd",
"size": "6617",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "bigquery_storage/google/cloud/bigquery_storage_v1beta1/proto/table_reference_pb2.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3366"
},
{
"name": "PowerShell",
"bytes": "7195"
},
{
"name": "Protocol Buffer",
"bytes": "95635"
},
{
"name": "Python",
"bytes": "2871895"
},
{
"name": "Shell",
"bytes": "4683"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Fbns\Network;
class NetworkType
{
public const NONE = -1;
public const MOBILE = 0;
public const WIFI = 1;
public const MOBILE_MMS = 2;
public const MOBILE_SUPL = 3;
public const MOBILE_DUN = 4;
public const MOBILE_HIPRI = 5;
public const WIMAX = 6;
public const BLUETOOTH = 7;
public const DUMMY = 8;
public const ETHERNET = 9;
public const MOBILE_FOTA = 10;
public const MOBILE_IMS = 11;
public const MOBILE_CBS = 12;
public const WIFI_P2P = 13;
public const MOBILE_IA = 14;
public const MOBILE_EMERGENCY = 15;
public const PROXY = 16;
public const VPN = 17;
}
| {
"content_hash": "1890a10c05510282881b8ce8e0f1e024",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 39,
"avg_line_length": 24.357142857142858,
"alnum_prop": 0.6451612903225806,
"repo_name": "valga/fbns-react",
"id": "d144108dc8f067d47db315f91fd3f8faaaa4cf59",
"size": "682",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Network/NetworkType.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "122449"
}
],
"symlink_target": ""
} |
package cgroup
import (
"bufio"
"bytes"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/elastic/gosigar/util"
)
var clockTicks = uint64(util.GetClockTicks())
// CPUAccountingSubsystem contains metrics from the "cpuacct" subsystem.
type CPUAccountingSubsystem struct {
Metadata
TotalNanos uint64 `json:"total_nanos"`
UsagePerCPU []uint64 `json:"usage_percpu_nanos"`
// CPU time statistics for tasks in this cgroup.
Stats CPUAccountingStats `json:"stats,omitempty"`
}
// CPUAccountingStats contains the stats reported from the cpuacct subsystem.
type CPUAccountingStats struct {
UserNanos uint64 `json:"user_nanos"`
SystemNanos uint64 `json:"system_nanos"`
}
// get reads metrics from the "cpuacct" subsystem. path is the filepath to the
// cgroup hierarchy to read.
func (cpuacct *CPUAccountingSubsystem) get(path string) error {
if err := cpuacctStat(path, cpuacct); err != nil {
return err
}
if err := cpuacctUsage(path, cpuacct); err != nil {
return err
}
if err := cpuacctUsagePerCPU(path, cpuacct); err != nil {
return err
}
return nil
}
func cpuacctStat(path string, cpuacct *CPUAccountingSubsystem) error {
f, err := os.Open(filepath.Join(path, "cpuacct.stat"))
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
t, v, err := parseCgroupParamKeyValue(sc.Text())
if err != nil {
return err
}
switch t {
case "user":
cpuacct.Stats.UserNanos = convertJiffiesToNanos(v)
case "system":
cpuacct.Stats.SystemNanos = convertJiffiesToNanos(v)
}
}
return nil
}
func cpuacctUsage(path string, cpuacct *CPUAccountingSubsystem) error {
var err error
cpuacct.TotalNanos, err = parseUintFromFile(path, "cpuacct.usage")
if err != nil {
return err
}
return nil
}
func cpuacctUsagePerCPU(path string, cpuacct *CPUAccountingSubsystem) error {
contents, err := ioutil.ReadFile(filepath.Join(path, "cpuacct.usage_percpu"))
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
var values []uint64
usages := bytes.Fields(contents)
for _, usage := range usages {
value, err := parseUint(usage)
if err != nil {
return err
}
values = append(values, value)
}
cpuacct.UsagePerCPU = values
return nil
}
func convertJiffiesToNanos(j uint64) uint64 {
return (j * uint64(time.Second)) / clockTicks
}
| {
"content_hash": "99a3f8cfba55ea4f686a1bcc95bf8e28",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 78,
"avg_line_length": 21.357142857142858,
"alnum_prop": 0.7044314381270903,
"repo_name": "knz/gosigar",
"id": "70893b4f8f1a1d1c6ac7ee8bf4eefee5885945a9",
"size": "2392",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cgroup/cpuacct.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "134024"
}
],
"symlink_target": ""
} |
import abc
class BaseWSGIContainer(object):
__metaclass__ = abc.ABCMeta
DESCRIPTION = abc.abstractproperty
@abc.abstractproperty
def name(self):
pass
@abc.abstractmethod
def send_request(self):
"""Should be implemented by subclasses""" | {
"content_hash": "5c0cbbe31975a44e872b9dfb2336e904",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 43,
"avg_line_length": 18.714285714285715,
"alnum_prop": 0.7099236641221374,
"repo_name": "rishimishra/flask_tornado",
"id": "eb6a4d85ef8f71f07f227552415ea2786881ad47",
"size": "262",
"binary": false,
"copies": "1",
"ref": "refs/heads/firstbranch",
"path": "app/base.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "3212"
}
],
"symlink_target": ""
} |
"""Pyxie's image packing implementation. Based on greedy algorithm described
in this stack overflow question:
http://stackoverflow.com/questions/1213394/algorithm-needed-for-packing-\
rectangles-in-a-fairly-optimal-way
Start with the largest rectangle. Add the next largest rectangle to the place
that extends the pack region as little as possible. Repeat until you have
placed the smallest rectangle.
The coordinate system used here has the origin (0, 0) at the top-left.
"""
__all__ = ['Rectangle', 'Field', 'VerticalField']
class Rectangle(object):
def __init__(self, x, y, data=None):
self.x, self.y = x, y
self.data = data
def __repr__(self):
return '<Rectangle %d, %d>' % (self.x, self.y)
class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y
class Line(object):
"""A very simplistic grid line class, where all lines are either vertical
or horizontal."""
def __init__(self, p1, p2):
"""Make sure that p1.x is the left-most top-most point in the line."""
if p1.x == p2.x: # vertical
self.vertical = True
if p1.y < p2.y: self.p1, self.p2 = p1, p2
else: self.p1, self.p2 = p2, p1
elif p1.y == p2.y: # horizontal
self.vertical = False
if p1.x < p2.x: self.p1, self.p2 = p1, p2
else: self.p1, self.p2 = p2, p1
else:
raise Exception("Line objects can only have horizontal or vertical lines.")
def overlap(self, p1, p2):
"""Return True if there's any overlap between this line and _region_,
which is assumed to be a span if we are horizontal and a range if are
vertical. There is overlap if any of the points of either line exists
within the other line."""
if self.vertical:
y1, y2 = self.p1.y, self.p2.y
return (p1 > y1 and p1 < y2) or (p2 > y1 and p2 < y2) or\
(y1 > p1 and y1 < p2) or (y2 > p1 and y2 < p2)
x1, x2 = self.p1.x, self.p2.x
return (p1 > x1 and p1 < x2) or (p2 > x1 and p2 < x2) or\
(x1 > p1 and x1 < p2) or (x2 > p1 and x2 < p2)
def __contains__(self, p):
"""Return whether or not this line contains a point p."""
if self.vertical: # vertical line
if p.x == self.p1.x and p.y >= self.p1.y and p.y <= self.p2.y:
return True
return False
else:
if p.y == self.p1.y and p.x >= self.p1.x and p.x <= self.p2.x:
return True
return False
def __repr__(self):
return '<Line (%d, %d) -> (%d, %d) %s >' % (self.p1.x, self.p1.y,
self.p2.x, self.p2.y, '|' if self.vertical else '-')
class PositionedRectangle(object):
"""A rectangle positioned within a field. Has the coordinates of the
rectangle and whether or not there's another rectangle positioned at
its top-right or bottom-left corner."""
def __init__(self, x, y, rect):
self.x, self.y, self.rect = x, y, rect
self.bl, self.tr = None, None
def __contains__(self, point):
"""This positioned rectangle contains point (x,y) if x is between
the left-most x and the right-most x, and y is between the top-most
y and bottoom-most y."""
if (point.x > self.x) and (point.x < (self.x + self.rect.x)) and\
(point.y > self.y) and (point.y < (self.y + self.rect.y)):
return True
return False
def __repr__(self):
return '<pRect @ (%d, %d), %dx%d (tr/bl: %r, %r)>' % (self.x, self.y,
self.rect.x, self.rect.y, self.tr, self.bl)
class Field(object):
def __init__(self):
self.x, self.y = 0, 0
self.rectangles = []
def area(self):
return self.x * self.y
def add_rectangle(self, rectangle):
"""Attempt to add a rectangle to this field increasing the packed area
as little as possible. To do this, it goes over all of the other
rectangles, attempts to add to bottom left or top right corner, then
checks for collisions. If a position is found that does not create a
collision and does not increase the area of the Field, it is used.
Otherwise, the "optimal" solution found is used. This is very time
intensive, but we should never be dealing with a great deal of images."""
if not self.rectangles:
self.rectangles.append(PositionedRectangle(0, 0, rectangle))
self.x, self.y = self.calculate_bounds()
return
attempts = []
for rect in self.rectangles:
for placement in (self.bottom_left, self.top_right):
result = placement(rect, rectangle)
if result is 0:
placement(rect, rectangle, place=True)
return
# if we didn't have a collision
if result is not None:
attempts.append((result, -self.rectangles.index(rect), placement, rect))
attempts.sort()
if not attempts:
import ipdb; ipdb.set_trace();
result, blah, placement, rect = attempts[0]
#print "Area increasing from %d to %d" % (self.area(), result)
placement(rect, rectangle, place=True)
self.x, self.y = self.calculate_bounds()
def bottom_left(self, placed, new, place=False):
"""Attempt to place a new rectangle on the bottom left corner of a
previously placed rectangle. Return the amt that the overall area of
the field would increase, or None if a collision is detected."""
if place:
self.mark_corners(placed.x, placed.y + placed.rect.y, new)
self.rectangles.append(PositionedRectangle(placed.x, placed.y + placed.rect.y, new))
self.x, self.y = self.calculate_bounds()
return
if placed.bl:
return None
# the corner we're adding it to is here:
corner = (placed.x, placed.y + placed.rect.y)
if not self.collision(corner, new):
return self.new_area(corner, new)
def top_right(self, placed, new, place=False):
if place:
self.mark_corners(placed.x + placed.rect.x, placed.y, new)
self.rectangles.append(PositionedRectangle(placed.x + placed.rect.x, placed.y, new))
self.x, self.y = self.calculate_bounds()
return
if placed.tr:
return None
corner = (placed.x + placed.rect.x, placed.y)
if not self.collision(corner, new):
return self.new_area(corner, new)
def mark_corners(self, x, y, rect):
"""Find all of the rectangles whose top-right or bottom-left corner are
"occupied" by the new rectangle, and mark them appropriately."""
left = Line(Point(x, y), Point(x, y + rect.y))
top = Line(Point(x, y), Point(x + rect.x, y))
# print "Adding rectangle %r to %d, %d (t/l: %s, %s)" % (rect, x, y, top, left)
# for every rectangle, if the top right or bottom left corners are in
# these lines, mark them as blocked
for pos in self.rectangles:
if not pos.tr:
p = Point(pos.x + pos.rect.x, pos.y)
if p in top or p in left:
pos.tr = True
if not pos.bl:
p = Point(pos.x, pos.y + pos.rect.y)
if p in top or p in left:
pos.bl = True
return True
def new_area(self, corner, new):
"""Return the new area of the field given a rectangle is positioned
with its top left corner at `corner`."""
if isinstance(corner, tuple):
corner = Point(*corner)
x, y = self.calculate_bounds(self.rectangles + [PositionedRectangle(corner.x, corner.y, new)])
return x * y
def calculate_bounds(self, rectangles=None):
"""Calculate x/y bounds for a field with the given rectangles. If
rectangles is None, calculate it for self's rectangles."""
if rectangles is None:
rectangles = self.rectangles
def span(rectangles):
# only rectangles without another positioned in the top right
possibilities = [r for r in rectangles if not r.tr]
return max([(r.x + r.rect.x) for r in possibilities])
def range(rectangles):
# only rectangles without another positioned in the bottom left
possibilities = [r for r in rectangles if not r.bl]
return max([(r.y + r.rect.y) for r in possibilities])
return span(rectangles), range(rectangles)
def collision(self, corner, new):
def collide(rect, top, left):
"""If any of these lines intersect with any other rectangles, it's
a collision."""
# if the x components and y components of the rectangle overlap, then
# the rectangles overlap; if they don't, then they don't.
# first, we need to check an edge case:
# it's possible for the rectangle to overlap in some way, but only
# at the top-left corner; so we check that if the top left corners
# are the same, and if they are, return false
#+-------+-+
#| | |
#+-------+ |
#+---------+
if top.p1.x == rect.x and top.p1.y == rect.y:
return True
# if the top-left point is the same, and the left & top lines go in
# the same direction, they collide
if not top.overlap(rect.x, rect.x + rect.rect.x):
return False
if not left.overlap(rect.y, rect.y + rect.rect.y):
return False
return True
p = Point(*corner)
# lines representing the top, bottom, and left line of where this rectangle would be
left = Line(Point(p.x, p.y), Point(p.x, p.y + new.y))
# bottom = Line(Point(p.x, p.y + new.y), Point(p.x + new.x, p.y + new.y))
top = Line(Point(p.x, p.y), Point(p.x + new.x, p.y))
for rect in self.rectangles:
if collide(rect, top, left):
return True
return False
class VerticalField(Field):
"""A field that only packs itself vertically."""
def __init__(self, padding=0):
super(VerticalField, self).__init__()
self.padding = padding
def add_rectangle(self, rectangle):
"""Add a rectangle to this field underneath the previous rectangle."""
if not self.rectangles:
self.rectangles.append(PositionedRectangle(0, 0, rectangle))
self.x, self.y = self.calculate_bounds()
return
self.bottom_left(self.rectangles[-1], rectangle, place=True)
self.x, self.y = self.calculate_bounds()
def bottom_left(self, placed, new, place=False):
"""Attempt to place a new rectangle on the bottom left corner of a
previously placed rectangle. Return the amt that the overall area of
the field would increase, or None if a collision is detected."""
# self.mark_corners(placed.x, placed.y + placed.rect.y, new)
self.rectangles.append(PositionedRectangle(placed.x, placed.y + placed.rect.y + self.padding, new))
self.x, self.y = self.calculate_bounds()
class HorizontalField(Field):
"""A field that only packs itself horizontally."""
def __init__(self, padding=0):
super(HorizontalField, self).__init__()
self.padding = padding
def add_rectangle(self, rectangle):
"""Add a rectangle to this field underneath the previous rectangle."""
if not self.rectangles:
self.rectangles.append(PositionedRectangle(0, 0, rectangle))
self.x, self.y = self.calculate_bounds()
return
self.top_right(self.rectangles[-1], rectangle, place=True)
self.x, self.y = self.calculate_bounds()
def top_right(self, placed, new, place=False):
"""Place a rectangle off the top right of a previous one, with
applied x-padding."""
self.rectangles.append(PositionedRectangle(placed.x + placed.rect.x + self.padding, 0, new))
self.x, self.y = self.calculate_bounds()
class BoxField(Field):
"""A field that packs itself into a box, ie for rounded corner use."""
def __init__(self, xpadding=0, ypadding=0):
super(BoxField, self).__init__()
self.xpadding = xpadding
self.ypadding = ypadding
def add_rectangle(self, rectangle):
"""Add a rectangle to this field. Note that this field only packs
in boxes, starting from the top left and going clockwise."""
if not self.rectangles:
self.rectangles.append(PositionedRectangle(0, 0, rectangle))
elif len(self.rectangles) == 1: # top right
tl = self.rectangles[0]
self.rectangles.append(PositionedRectangle(tl.rect.x + self.xpadding, 0, rectangle))
elif len(self.rectangles) == 2: # bottom right
tl, tr = self.rectangles
# find the max value we'd need to get the vertical padding we want
# even if that padding is from the top-left rectangle
maxy = max([tl.rect.y, tr.rect.y])
# adjust the x positioning so that the bottom right corner of this
# rectangle goes into the bottom right
xadjust = tr.rect.x - rectangle.x
self.rectangles.append(PositionedRectangle(tr.x, maxy + self.ypadding, rectangle))
elif len(self.rectangles) == 3: # bottom left
br = self.rectangles[-1]
# get a height adjustment so that the bottom-left corner of this
# rectangle goes into the bottom-left corner
yadjust = br.rect.y - rectangle.y
self.rectangles.append(PositionedRectangle(0, br.y + yadjust, rectangle))
else:
raise Exception("BoxField can only accept 4 rectangles; "
"You've packed too many images!")
self.x, self.y = self.calculate_bounds()
class AlternatingField(Field):
"""A field that packs vertically, alternating from left ot right. This
is useful for buttons that have a left-side and a right side."""
def __init__(self, padding=0):
super(AlternatingField, self).__init__()
self.padding = padding
def add_rectangle(self, rectangle):
"""Rectangles must be sorted width-wise for this!"""
if not self.rectangles:
self.rectangles.append(PositionedRectangle(0, 0, rectangle))
self.align = 'right'
elif self.align == 'right':
# align this rectangle along the right edge; the max width of the
# sprite is already determined by the first rectangle, which must be
# the widest rectangle
xpos = self.x - rectangle.x
self.rectangles.append(PositionedRectangle(xpos, self.y + self.padding, rectangle))
self.align = 'left'
elif self.align == 'left':
self.rectangles.append(PositionedRectangle(0, self.y + self.padding, rectangle))
self.align = 'right'
self.x, self.y = self.calculate_bounds()
| {
"content_hash": "4105058f1a10d9861dd8dfa55e424bba",
"timestamp": "",
"source": "github",
"line_count": 344,
"max_line_length": 107,
"avg_line_length": 44.35755813953488,
"alnum_prop": 0.5907333377023396,
"repo_name": "shopwiki/pyxie",
"id": "a1ccdffe622c98ed756b7e597b1d956bef018fdd",
"size": "15306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pyxie/packer.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "37819"
}
],
"symlink_target": ""
} |
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.12
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.pjsip.pjsua2;
public class SWIGTYPE_p_pj_bool_t {
private transient long swigCPtr;
protected SWIGTYPE_p_pj_bool_t(long cPtr, @SuppressWarnings("unused") boolean futureUse) {
swigCPtr = cPtr;
}
protected SWIGTYPE_p_pj_bool_t() {
swigCPtr = 0;
}
protected static long getCPtr(SWIGTYPE_p_pj_bool_t obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}
| {
"content_hash": "852da8e4440b3006ef1b0778268a6e83",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 92,
"avg_line_length": 29.346153846153847,
"alnum_prop": 0.5425950196592398,
"repo_name": "symeonmattes/pjsip",
"id": "141157b42cef47b01f7465f5c731ba2967f0f8dd",
"size": "763",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/android/api/pjsua2/SWIGTYPE_p_pj_bool_t.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2595813"
},
{
"name": "C++",
"bytes": "523871"
},
{
"name": "Java",
"bytes": "861553"
},
{
"name": "JavaScript",
"bytes": "3456"
},
{
"name": "Objective-C",
"bytes": "99065"
},
{
"name": "Shell",
"bytes": "545"
}
],
"symlink_target": ""
} |
package collections;// collections/SetOfInteger.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;
public class SetOfInteger {
public static void main(String[] args) {
Random rand = new Random(47);
Set<Integer> intset = new HashSet<>();
for(int i = 0; i < 10000; i++)
intset.add(rand.nextInt(30));
System.out.println(intset);
}
}
/* Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
*/
| {
"content_hash": "f67321207ce6deeb51ea462ece6ba5aa",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 63,
"avg_line_length": 32.526315789473685,
"alnum_prop": 0.6375404530744336,
"repo_name": "mayonghui2112/helloWorld",
"id": "bdb6fbf7d84bc95ecde727b86e2a6439c258e984",
"size": "618",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "sourceCode/javase/onJava8/src/main/java/collections/SetOfInteger.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AngelScript",
"bytes": "521"
},
{
"name": "Batchfile",
"bytes": "39234"
},
{
"name": "C",
"bytes": "22329"
},
{
"name": "C++",
"bytes": "13466"
},
{
"name": "CSS",
"bytes": "61000"
},
{
"name": "Go",
"bytes": "6819"
},
{
"name": "Groovy",
"bytes": "8821"
},
{
"name": "HTML",
"bytes": "9234922"
},
{
"name": "Java",
"bytes": "21874329"
},
{
"name": "JavaScript",
"bytes": "46483"
},
{
"name": "NSIS",
"bytes": "42042"
},
{
"name": "Objective-C++",
"bytes": "26102"
},
{
"name": "PLpgSQL",
"bytes": "3746"
},
{
"name": "Perl",
"bytes": "13860"
},
{
"name": "Python",
"bytes": "33132"
},
{
"name": "Shell",
"bytes": "51005"
},
{
"name": "TSQL",
"bytes": "50756"
},
{
"name": "XSLT",
"bytes": "38702"
}
],
"symlink_target": ""
} |
namespace Hotcakes.Commerce.Utilities
{
public enum SortDirection
{
Ascending = -1,
Descending = 1
}
} | {
"content_hash": "3762ae02fab57d27144ceb91f383b2e4",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 37,
"avg_line_length": 16.25,
"alnum_prop": 0.6,
"repo_name": "HotcakesCommerce/core",
"id": "f473201df0f6635acbf4d74cfe7fa7cb7cd8a30a",
"size": "1392",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Libraries/Hotcakes.Commerce/Utilities/SortDirection.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "2267142"
},
{
"name": "Batchfile",
"bytes": "373"
},
{
"name": "C#",
"bytes": "11194618"
},
{
"name": "CSS",
"bytes": "1952419"
},
{
"name": "HTML",
"bytes": "873593"
},
{
"name": "JavaScript",
"bytes": "4896110"
},
{
"name": "Smalltalk",
"bytes": "2410"
},
{
"name": "Visual Basic",
"bytes": "16681"
},
{
"name": "XSLT",
"bytes": "10409"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Iced.Intel;
namespace Iced.UnitTests.Intel.FormatterTests {
public readonly struct FormatterTestCase {
public readonly int Bitness;
public readonly string HexBytes;
public readonly ulong IP;
public readonly Code Code;
public readonly DecoderOptions Options;
public FormatterTestCase(int bitness, string hexBytes, ulong ip, Code code, DecoderOptions options) {
Bitness = bitness;
HexBytes = hexBytes;
IP = ip;
Code = code;
Options = options;
}
}
static class FormatterTestCases {
static (FormatterTestCase[] tests, HashSet<int> ignored) tests16;
static (FormatterTestCase[] tests, HashSet<int> ignored) tests32;
static (FormatterTestCase[] tests, HashSet<int> ignored) tests64;
static (FormatterTestCase[] tests, HashSet<int> ignored) tests16_Misc;
static (FormatterTestCase[] tests, HashSet<int> ignored) tests32_Misc;
static (FormatterTestCase[] tests, HashSet<int> ignored) tests64_Misc;
public static (FormatterTestCase[] tests, HashSet<int> ignored) GetTests(int bitness, bool isMisc) {
if (isMisc) {
return bitness switch {
16 => GetTests(ref tests16_Misc, bitness, isMisc),
32 => GetTests(ref tests32_Misc, bitness, isMisc),
64 => GetTests(ref tests64_Misc, bitness, isMisc),
_ => throw new ArgumentOutOfRangeException(nameof(bitness)),
};
}
else {
return bitness switch {
16 => GetTests(ref tests16, bitness, isMisc),
32 => GetTests(ref tests32, bitness, isMisc),
64 => GetTests(ref tests64, bitness, isMisc),
_ => throw new ArgumentOutOfRangeException(nameof(bitness)),
};
}
}
static (FormatterTestCase[] tests, HashSet<int> ignored) GetTests(ref (FormatterTestCase[] tests, HashSet<int> ignored) data, int bitness, bool isMisc) {
if (data.tests is null) {
var filename = "InstructionInfos" + bitness;
if (isMisc)
filename += "_Misc";
data.ignored = new HashSet<int>();
data.tests = GetTests(filename, bitness, data.ignored).ToArray();
}
return data;
}
static readonly char[] sep = new[] { ',' };
static IEnumerable<FormatterTestCase> GetTests(string filename, int bitness, HashSet<int> ignored) {
int lineNo = 0;
int testCaseNo = 0;
filename = FileUtils.GetFormatterFilename(filename);
foreach (var line in File.ReadLines(filename)) {
lineNo++;
if (line.Length == 0 || line[0] == '#')
continue;
var parts = line.Split(sep);
DecoderOptions options;
if (parts.Length == 2)
options = default;
else if (parts.Length == 3) {
if (!ToEnumConverter.TryDecoderOptions(parts[2].Trim(), out options))
throw new InvalidOperationException($"Invalid line #{lineNo} in file {filename}");
}
else
throw new InvalidOperationException($"Invalid line #{lineNo} in file {filename}");
var hexBytes = parts[0].Trim();
var codeStr = parts[1].Trim();
var ip = bitness switch {
16 => DecoderConstants.DEFAULT_IP16,
32 => DecoderConstants.DEFAULT_IP32,
64 => DecoderConstants.DEFAULT_IP64,
_ => throw new InvalidOperationException(),
};
if (CodeUtils.IsIgnored(codeStr))
ignored.Add(testCaseNo);
else {
if (!ToEnumConverter.TryCode(codeStr, out var code))
throw new InvalidOperationException($"Invalid line #{lineNo} in file {filename}");
yield return new FormatterTestCase(bitness, hexBytes, ip, code, options);
}
testCaseNo++;
}
}
public static IEnumerable<object[]> GetFormatData(int bitness, string formatterDir, string formattedStringsFile, bool isMisc = false) {
var data = GetTests(bitness, isMisc);
var formattedStrings = FileUtils.ReadRawStrings(Path.Combine(formatterDir, $"Test{bitness}_{formattedStringsFile}")).ToArray();
return GetFormatData(data.tests, data.ignored, formattedStrings);
}
static IEnumerable<object[]> GetFormatData(FormatterTestCase[] tests, HashSet<int> ignored, string[] formattedStrings) {
formattedStrings = Utils.Filter(formattedStrings, ignored);
if (tests.Length != formattedStrings.Length)
throw new ArgumentException($"(tests.Length) {tests.Length} != (formattedStrings.Length) {formattedStrings.Length} . tests[0].HexBytes = {(tests.Length == 0 ? "<EMPTY>" : tests[0].HexBytes)} & formattedStrings[0] = {(formattedStrings.Length == 0 ? "<EMPTY>" : formattedStrings[0])}");
var res = new object[tests.Length][];
for (int i = 0; i < tests.Length; i++)
res[i] = new object[3] { i, tests[i], formattedStrings[i] };
return res;
}
public static IEnumerable<object[]> GetFormatData(int bitness, (string hexBytes, Instruction instruction)[] tests, string formatterDir, string formattedStringsFile) {
var formattedStrings = FileUtils.ReadRawStrings(Path.Combine(formatterDir, $"Test{bitness}_{formattedStringsFile}")).ToArray();
return GetFormatData(tests, formattedStrings);
}
static IEnumerable<object[]> GetFormatData((string hexBytes, Instruction instruction)[] tests, string[] formattedStrings) {
if (tests.Length != formattedStrings.Length)
throw new ArgumentException($"(tests.Length) {tests.Length} != (formattedStrings.Length) {formattedStrings.Length} . tests[0].hexBytes = {(tests.Length == 0 ? "<EMPTY>" : tests[0].hexBytes)} & formattedStrings[0] = {(formattedStrings.Length == 0 ? "<EMPTY>" : formattedStrings[0])}");
var res = new object[tests.Length][];
for (int i = 0; i < tests.Length; i++)
res[i] = new object[3] { i, tests[i].instruction, formattedStrings[i] };
return res;
}
}
}
#endif
| {
"content_hash": "8c1870843bfd29cd5a1b7cec8165a806",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 288,
"avg_line_length": 43.05384615384615,
"alnum_prop": 0.6978738609969627,
"repo_name": "0xd4d/iced",
"id": "463120c8f83d0eb78b8a71165419ce32e119d08e",
"size": "5735",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/csharp/Intel/Iced.UnitTests/Intel/FormatterTests/FormatterTestCases.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "21527949"
},
{
"name": "JavaScript",
"bytes": "111606"
},
{
"name": "Python",
"bytes": "1109586"
},
{
"name": "Rust",
"bytes": "9702345"
},
{
"name": "Shell",
"bytes": "25063"
}
],
"symlink_target": ""
} |
package com.gemstone.gemfire.cache.query;
/**
* Thrown if a region referenced by name in a query cannot be found.
*
* @author Eric Zoerner
* @since 4.0
*/
public class RegionNotFoundException extends NameResolutionException {
private static final long serialVersionUID = 592495934010222373L;
/**
* Construct an instance of RegionNotFoundException
* @param msg the error message
*/
public RegionNotFoundException(String msg) {
super(msg);
}
/**
* Constructs an instance of RegionNotFoundException
* @param msg the error message
* @param cause a Throwable that is a cause of this exception
*/
public RegionNotFoundException(String msg, Throwable cause) {
super(msg, cause);
}
}
| {
"content_hash": "bb5c7d86409a18c331ce16cce4559941",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 70,
"avg_line_length": 24.6,
"alnum_prop": 0.7113821138211383,
"repo_name": "sshcherbakov/incubator-geode",
"id": "4ae94e36cc7269164bdf525c09bbc0261ad28f4c",
"size": "1540",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "gemfire-core/src/main/java/com/gemstone/gemfire/cache/query/RegionNotFoundException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1741"
},
{
"name": "CSS",
"bytes": "54202"
},
{
"name": "Groovy",
"bytes": "4066"
},
{
"name": "HTML",
"bytes": "124114"
},
{
"name": "Java",
"bytes": "26687060"
},
{
"name": "JavaScript",
"bytes": "315581"
},
{
"name": "Scala",
"bytes": "237708"
},
{
"name": "Shell",
"bytes": "11132"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.