file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
SmilesGenerator.js
", ($fz = function (atom, bs, allowConnectionsToOutsideWorld) { if (atom.getElementNumber () == 1 && atom.getEdges ().length > 0) atom = this.atoms[atom.getBondedAtomIndex (0)]; this.bsSelected = J.util.JmolMolecule.getBranchBitSet (this.atoms, atom.getIndex (), J.util.BSUtil.copy (bs), null, -1, true, false); bs....
} } if (!this.htRings.isEmpty ()) { this.dumpRingKeys (sb, this.htRings); throw new J.smiles.InvalidSmilesException ("//* ?ring error? *//\n" + sb); }return sb.toString (); }, $fz.isPrivate = true, $fz), "J.util.JmolNode,JU.BS,~B"); $_M(c$, "getBondStereochemistry", ($fz = function (bond, atomFrom) { if (bon...
this.prevSp2Atoms = null; this.prevAtom = null; while ((atom = this.getSmiles (sb, atom, allowConnectionsToOutsideWorld, true)) != null) {
random_line_split
account_move_line.py
, copy=False) def _copy_data_extend_business_fields(self, values): # OVERRIDE to copy the 'sale_line_ids' field as well. super(AccountMoveLine, self)._copy_data_extend_business_fields(values) values['sale_line_ids'] = [(6, None, self.sale_line_ids.ids)] def _prepare_analytic_line(self)...
values['so_line'] = sale_line.id return values_list def _sale_can_be_reinvoice(self): """ determine if the generated analytic line should be reinvoiced or not. For Vendor Bill flow, if the product has a 'erinvoice policy' and is a cost, then we will find the SO on ...
""" Note: This method is called only on the move.line that having an analytic account, and so that should create analytic entries. """ values_list = super(AccountMoveLine, self)._prepare_analytic_line() # filter the move lines that can be reinvoiced: a cost (negative amount) analyti...
identifier_body
account_move_line.py
(models.Model): _inherit = 'account.move.line' sale_line_ids = fields.Many2many( 'sale.order.line', 'sale_order_line_invoice_rel', 'invoice_line_id', 'order_line_id', string='Sales Order Lines', readonly=True, copy=False) def _copy_data_extend_business_fields(self, values):...
AccountMoveLine
identifier_name
account_move_line.py
=True, copy=False) def _copy_data_extend_business_fields(self, values): # OVERRIDE to copy the 'sale_line_ids' field as well. super(AccountMoveLine, self)._copy_data_extend_business_fields(values) values['sale_line_ids'] = [(6, None, self.sale_line_ids.ids)] def _prepare_analytic_line(...
def _sale_create_reinvoice_sale_line(self): sale_order_map = self._sale_determine_order() sale_line_values_to_create = [] # the list of creation values of sale line to create. existing_sale_line_cache = {} # in the sales_price-delivery case, we can reuse the same sale line. This cache wi...
random_line_split
account_move_line.py
, copy=False) def _copy_data_extend_business_fields(self, values): # OVERRIDE to copy the 'sale_line_ids' field as well. super(AccountMoveLine, self)._copy_data_extend_business_fields(values) values['sale_line_ids'] = [(6, None, self.sale_line_ids.ids)] def _prepare_analytic_line(self)...
# raise if the sale order is not currenlty open if sale_order.state != 'sale': message_unconfirmed = _('The Sales Order %s linked to the Analytic Account %s must be validated before registering expenses.') messages = { 'draft': message_unconf...
continue
conditional_block
test_sensor.py
"""Tests for the Abode sensor device.""" from homeassistant.components.abode import ATTR_DEVICE_ID from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_FRIENDLY_NAME, ATTR_UNIT_OF_MEASUREMENT, DEVICE_CLASS_HUMIDITY, PERCENTAGE,...
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == TEMP_CELSIUS
"""Test the sensor attributes are correct.""" await setup_platform(hass, SENSOR_DOMAIN) state = hass.states.get("sensor.environment_sensor_humidity") assert state.state == "32.0" assert state.attributes.get(ATTR_DEVICE_ID) == "RF:02148e70" assert not state.attributes.get("battery_low") assert n...
identifier_body
test_sensor.py
"""Tests for the Abode sensor device.""" from homeassistant.components.abode import ATTR_DEVICE_ID from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_FRIENDLY_NAME, ATTR_UNIT_OF_MEASUREMENT, DEVICE_CLASS_HUMIDITY, PERCENTAGE,...
(hass): """Tests that the devices are registered in the entity registry.""" await setup_platform(hass, SENSOR_DOMAIN) entity_registry = er.async_get(hass) entry = entity_registry.async_get("sensor.environment_sensor_humidity") assert entry.unique_id == "13545b21f4bdcd33d9abd461f8443e65-humidity" ...
test_entity_registry
identifier_name
test_sensor.py
"""Tests for the Abode sensor device.""" from homeassistant.components.abode import ATTR_DEVICE_ID from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_FRIENDLY_NAME, ATTR_UNIT_OF_MEASUREMENT, DEVICE_CLASS_HUMIDITY, PERCENTAGE,...
from homeassistant.helpers import entity_registry as er from .common import setup_platform async def test_entity_registry(hass): """Tests that the devices are registered in the entity registry.""" await setup_platform(hass, SENSOR_DOMAIN) entity_registry = er.async_get(hass) entry = entity_registry....
)
random_line_split
image.ios.ts
import imageCommon = require("ui/image/image-common"); import dependencyObservable = require("ui/core/dependency-observable"); import proxy = require("ui/core/proxy"); import definition = require("ui/image"); import enums = require("ui/enums"); import utils = require("utils/utils"); import trace = require("trace"); im...
var resultH = Math.floor(nativeHeight * scale.height); measureWidth = finiteWidth ? Math.min(resultW, width) : resultW; measureHeight = finiteHeight ? Math.min(resultH, height) : resultH; trace.write("Image stretch: " + this.stretch + ", nativeWidth: " +...
// We don't call super because we measure native view with specific size. var width = utils.layout.getMeasureSpecSize(widthMeasureSpec); var widthMode = utils.layout.getMeasureSpecMode(widthMeasureSpec); var height = utils.layout.getMeasureSpecSize(heightMeasureSpec); var ...
identifier_body
image.ios.ts
import imageCommon = require("ui/image/image-common"); import dependencyObservable = require("ui/core/dependency-observable"); import proxy = require("ui/core/proxy"); import definition = require("ui/image"); import enums = require("ui/enums"); import utils = require("utils/utils"); import trace = require("trace"); im...
}
return { width: scaleW, height: scaleH }; }
random_line_split
image.ios.ts
import imageCommon = require("ui/image/image-common"); import dependencyObservable = require("ui/core/dependency-observable"); import proxy = require("ui/core/proxy"); import definition = require("ui/image"); import enums = require("ui/enums"); import utils = require("utils/utils"); import trace = require("trace"); im...
easureWidth: number, measureHeight: number, widthIsFinite: boolean, heightIsFinite: boolean, nativeWidth: number, nativeHeight: number, imageStretch: string): { width: number; height: number } { var scaleW = 1; var scaleH = 1; if ((imageStretch === enums.Stretch.aspectFill || imageStretch === e...
mputeScaleFactor(m
identifier_name
automation.ts
import { Config } from './config'; async function NewAutomation(config: Config) { if (process.platform === 'linux' && config.getEnv() === 'production') { const piswitch = await import('piswitch'); const childProcess = await import('child_process'); childProcess.execSync('gpio export 17 out'); piswi...
, }; } } export { NewAutomation, };
{ console.log('Lights OFF'); }
identifier_body
automation.ts
import { Config } from './config'; async function
(config: Config) { if (process.platform === 'linux' && config.getEnv() === 'production') { const piswitch = await import('piswitch'); const childProcess = await import('child_process'); childProcess.execSync('gpio export 17 out'); piswitch.setup({ mode: 'sys', // alternative: change to gpio an...
NewAutomation
identifier_name
automation.ts
import { Config } from './config'; async function NewAutomation(config: Config) { if (process.platform === 'linux' && config.getEnv() === 'production') { const piswitch = await import('piswitch'); const childProcess = await import('child_process'); childProcess.execSync('gpio export 17 out'); piswi...
} function on() { // process.nextTick(() => send('001001110000101010000111')); process.nextTick(() => send('001001110000101010001111')); } function off() { // process.nextTick(() => send('001001110000101010000110')); process.nextTick(() => send('001001110000101010001110')); ...
{ piswitch.send(code); // console.log(code, i); }
conditional_block
automation.ts
import { Config } from './config'; async function NewAutomation(config: Config) { if (process.platform === 'linux' && config.getEnv() === 'production') { const piswitch = await import('piswitch'); const childProcess = await import('child_process'); childProcess.execSync('gpio export 17 out'); piswi...
function on() { // process.nextTick(() => send('001001110000101010000111')); process.nextTick(() => send('001001110000101010001111')); } function off() { // process.nextTick(() => send('001001110000101010000110')); process.nextTick(() => send('001001110000101010001110')); } ...
} }
random_line_split
verify-topo-devices.py
#! /usr/bin/env python import requests import sys import urllib from requests.auth import HTTPBasicAuth if len(sys.argv) != 5: print "usage: verify-topo-links onos-node cluster-id first-index last-index" sys.exit(1) node = sys.argv[1] cluster = sys.argv[2] first = int(sys.argv[3]) last = int(sys.argv[4]) f...
if found == last - first: sys.exit(0) print "Found " + str(found) + " matches, need " + str(last - first) sys.exit(2)
lookingFor = "of:" + format(deviceIndex, '016x') print lookingFor for arrayIndex in range(0, len(topoJson["devices"])): device = topoJson["devices"][arrayIndex] if device == lookingFor: found = found + 1 print "Match found for " + device break
conditional_block
verify-topo-devices.py
#! /usr/bin/env python import requests import sys import urllib from requests.auth import HTTPBasicAuth if len(sys.argv) != 5: print "usage: verify-topo-links onos-node cluster-id first-index last-index" sys.exit(1) node = sys.argv[1] cluster = sys.argv[2] first = int(sys.argv[3]) last = int(sys.argv[4]) f...
topoRequest = requests.get('http://' + node + ':8181/onos/v1/topology/clusters/' + cluster + "/devices", auth=HTTPBasicAuth('onos', 'rocks')) if topoRequest.status_code != 200: print topoRequest.text sys.exit(1) topoJson = topoR...
random_line_split
Textarea.js
(function() { var inputEx = YAHOO.inputEx, Event = YAHOO.util.Event; /** * @class Create a textarea input * @extends inputEx.Field * @constructor * @param {Object} options Added options: * <ul> * <li>rows: rows attribute</li> * <li>cols: cols attribute</li> * </ul> */ inputEx.Textarea = function(opt...
renderComponent: function() { // This element wraps the input node in a float: none div this.wrapEl = inputEx.cn('div', {className: 'inputEx-StringField-wrapper'}); // Attributes of the input field var attributes = {}; attributes.id = this.divEl.id?this.divEl.id+'-field':Y...
/** * Render an 'INPUT' DOM node */
random_line_split
cmd.py
# mako/cmd.py # Copyright 2006-2021 the Mako authors and contributors <see AUTHORS file> # # This module is part of Mako and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from argparse import ArgumentParser from os.path import dirname from os.path import isfile import sys from...
(): sys.stderr.write(exceptions.text_error_template().render()) sys.exit(1) def cmdline(argv=None): parser = ArgumentParser() parser.add_argument( "--var", default=[], action="append", help="variable (can be used multiple times, use name=value)", ) parser.add_a...
_exit
identifier_name
cmd.py
# mako/cmd.py # Copyright 2006-2021 the Mako authors and contributors <see AUTHORS file> # # This module is part of Mako and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from argparse import ArgumentParser from os.path import dirname from os.path import isfile import sys from...
else: filename = options.input if not isfile(filename): raise SystemExit("error: can't find %s" % filename) lookup_dirs = options.template_dir or [dirname(filename)] lookup = TemplateLookup(lookup_dirs) try: template = Template( filena...
lookup_dirs = options.template_dir or ["."] lookup = TemplateLookup(lookup_dirs) try: template = Template( sys.stdin.read(), lookup=lookup, output_encoding=output_encoding, ) except: _exit()
conditional_block
cmd.py
# mako/cmd.py # Copyright 2006-2021 the Mako authors and contributors <see AUTHORS file> # # This module is part of Mako and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from argparse import ArgumentParser from os.path import dirname from os.path import isfile import sys from...
"--var", default=[], action="append", help="variable (can be used multiple times, use name=value)", ) parser.add_argument( "--template-dir", default=[], action="append", help="Directory to use for template lookup (multiple " "directories ma...
random_line_split
cmd.py
# mako/cmd.py # Copyright 2006-2021 the Mako authors and contributors <see AUTHORS file> # # This module is part of Mako and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from argparse import ArgumentParser from os.path import dirname from os.path import isfile import sys from...
def cmdline(argv=None): parser = ArgumentParser() parser.add_argument( "--var", default=[], action="append", help="variable (can be used multiple times, use name=value)", ) parser.add_argument( "--template-dir", default=[], action="append", ...
sys.stderr.write(exceptions.text_error_template().render()) sys.exit(1)
identifier_body
main.js
var BlendFileReaderSample; (function (BlendFileReaderSample) { window.onload = function () { var xhr = new XMLHttpRequest(); xhr.open('GET', 'sample.blend'); xhr.responseType = 'arraybuffer'; xhr.addEventListener('load', function (e) { var blendFile = BlendFileReader.read...
(address) { var tempText = '00000000' + address.toString(16); return tempText.substr(tempText.length - 8); } function ouputSample(blendFile) { var file_element = document.getElementById('file'); var dna_element = document.getElementById('dna'); var blocks_element = docume...
getAddressText
identifier_name
main.js
var BlendFileReaderSample; (function (BlendFileReaderSample) { window.onload = function () { var xhr = new XMLHttpRequest(); xhr.open('GET', 'sample.blend'); xhr.responseType = 'arraybuffer'; xhr.addEventListener('load', function (e) { var blendFile = BlendFileReader.read...
result.push(''); } dna_element.innerHTML = result.join('<br/>'); // Data blocks result = []; result.push('[All data blocks]'); for (var _d = 0, _e = blendFile.bheadList; _d < _e.length; _d++) { var bhead = _e[_d]; var typeInfo = blendF...
{ var fieldInfo = _c[_b]; result.push('&emsp;' + fieldInfo.definitionName + ': ' + fieldInfo.typeName + ' ' + fieldInfo.offset); }
conditional_block
main.js
var BlendFileReaderSample; (function (BlendFileReaderSample) { window.onload = function () { var xhr = new XMLHttpRequest(); xhr.open('GET', 'sample.blend'); xhr.responseType = 'arraybuffer'; xhr.addEventListener('load', function (e) { var blendFile = BlendFileReader.read...
function ouputSample(blendFile) { var file_element = document.getElementById('file'); var dna_element = document.getElementById('dna'); var blocks_element = document.getElementById('blocks'); var content_element = document.getElementById('content'); var result = []; ...
{ var tempText = '00000000' + address.toString(16); return tempText.substr(tempText.length - 8); }
identifier_body
main.js
var BlendFileReaderSample; (function (BlendFileReaderSample) { window.onload = function () { var xhr = new XMLHttpRequest(); xhr.open('GET', 'sample.blend'); xhr.responseType = 'arraybuffer'; xhr.addEventListener('load', function (e) { var blendFile = BlendFileReader.read...
var tempText = '00000000' + address.toString(16); return tempText.substr(tempText.length - 8); } function ouputSample(blendFile) { var file_element = document.getElementById('file'); var dna_element = document.getElementById('dna'); var blocks_element = document.getElemen...
xhr.send(); }; function getAddressText(address) {
random_line_split
farmglue.py
""" Glue for interfacing with a farm object """ import os import ast from .constants import HealthStatus def imagesAndStatuses(outputDir): """ Return a dictionary of images and corresponding human assigned statuses from output. """ controlPath = os.path.join(outputDir, 'controls', 'HealthImageryControl...
segStatus = _pickStatus(control[fieldname][segname]['healthStatus']) segRGBTiff = os.path.join(seg, 'rgb', 'rgb.tif') segRGBPng = os.path.join(seg, 'rgb', 'rgb.png') #choose png if it exists, as it'll save us converting later if os.path.exists(segRGBPng): ...
continue
conditional_block
farmglue.py
""" Glue for interfacing with a farm object """ import os import ast from .constants import HealthStatus def imagesAndStatuses(outputDir): """ Return a dictionary of images and corresponding human assigned statuses from output. """ controlPath = os.path.join(outputDir, 'controls', 'HealthImageryControl...
(controlPath): """ Load and format the control, discarding irrelevant information like the latest date. """ with open(controlPath) as f: c = ast.literal_eval(f.read()) control = {} for f, v in c.items(): subdict = {s.pop('name'): s for s in v[1]} control[f] = subdict ...
_loadControl
identifier_name
farmglue.py
""" Glue for interfacing with a farm object """ import os import ast from .constants import HealthStatus def imagesAndStatuses(outputDir):
segRGBPng = os.path.join(seg, 'rgb', 'rgb.png') #choose png if it exists, as it'll save us converting later if os.path.exists(segRGBPng): images[segRGBPng] = segStatus else: images[segRGBTiff] = segStatus return images def _pickStat...
""" Return a dictionary of images and corresponding human assigned statuses from output. """ controlPath = os.path.join(outputDir, 'controls', 'HealthImageryControl.txt') fieldsPath = os.path.join(outputDir, 'fields') control = _loadControl(controlPath) images = {} for field in _dirs(field...
identifier_body
farmglue.py
""" Glue for interfacing with a farm object """ import os import ast from .constants import HealthStatus def imagesAndStatuses(outputDir): """
Return a dictionary of images and corresponding human assigned statuses from output. """ controlPath = os.path.join(outputDir, 'controls', 'HealthImageryControl.txt') fieldsPath = os.path.join(outputDir, 'fields') control = _loadControl(controlPath) images = {} for field in _dirs(fieldsPat...
random_line_split
_user-route-access-service.ts
<%# Copyright 2013-2018 the original author or authors from the JHipster project. This file is part of the JHipster project, see http://www.jhipster.tech/ for more information. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You ma...
export class UserRouteAccessService implements CanActivate { constructor(private router: Router, <%_ if (authenticationType !== 'oauth2') { _%> private loginModalService: LoginModalService, <%_ } else { _%> private loginService: LoginService, ...
import { StateStorageService } from './state-storage.service'; @Injectable()
random_line_split
_user-route-access-service.ts
<%# Copyright 2013-2018 the original author or authors from the JHipster project. This file is part of the JHipster project, see http://www.jhipster.tech/ for more information. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You ma...
this.stateStorageService.storeUrl(url); this.router.navigate(['accessdenied']).then(() => { // only show the login dialog, if the user hasn't logged in yet if (!account) { <%_ if (authenticationType !== 'oauth2') { _%> thi...
{ return principal.hasAnyAuthority(authorities).then((response) => { if (response) { return true; } return false; }); }
conditional_block
run_test.py
#!/usr/bin/python """ Testing the database connection ------------------------------- Connect to the surver and request a list of device IDs """ from numpy import * set_printoptions(precision=5, suppress=True) from .db_utils import get_cursor def dev_ids(cur): try: cur.execute("""SELECT DIS...
cur = get_cursor(False) IDs = dev_ids(cur) print(str(IDs)) for i in IDs: i_d = i[0] c = num_trace(cur,i_d)[0] print("[%d] trace: %d" % (i_d, c))
try: cur.execute("""SELECT COUNT(*) from averaged_location WHERE device_id = %s """, (str(d_id),)) except: return "I can't SELECT from device_data" return cur.fetchall()[0]
identifier_body
run_test.py
#!/usr/bin/python
""" Testing the database connection ------------------------------- Connect to the surver and request a list of device IDs """ from numpy import * set_printoptions(precision=5, suppress=True) from .db_utils import get_cursor def dev_ids(cur): try: cur.execute("""SELECT DISTINCT device_id fro...
random_line_split
run_test.py
#!/usr/bin/python """ Testing the database connection ------------------------------- Connect to the surver and request a list of device IDs """ from numpy import * set_printoptions(precision=5, suppress=True) from .db_utils import get_cursor def
(cur): try: cur.execute("""SELECT DISTINCT device_id from device_data""") except: return "I can't SELECT from device_data" return cur.fetchall() def num_trace(cur, d_id): try: cur.execute("""SELECT COUNT(*) from averaged_location WHERE device_id = %s """, (str(d_id),)) ex...
dev_ids
identifier_name
run_test.py
#!/usr/bin/python """ Testing the database connection ------------------------------- Connect to the surver and request a list of device IDs """ from numpy import * set_printoptions(precision=5, suppress=True) from .db_utils import get_cursor def dev_ids(cur): try: cur.execute("""SELECT DIS...
i_d = i[0] c = num_trace(cur,i_d)[0] print("[%d] trace: %d" % (i_d, c))
conditional_block
countBy.js
/** * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> * Build: `lodash modularize underscore exports="amd" -o ./underscore/` * Copyright 2012-2014 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.6.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2014 Jeremy Ashkenas, DocumentCloud...
* * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); * // => { '4': 1, '6': 2 } * * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { (hasOwnProperty.call(result, key) ? result[...
* @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); * // => { '4': 1, '6': 2 }
random_line_split
checks.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Different checks done during the style sharing process in order to determine //! quickly whether it's worth to...
/// Whether two elements have the same same presentational attributes. pub fn have_same_presentational_hints<E>( target: &mut StyleSharingTarget<E>, candidate: &mut StyleSharingCandidate<E> ) -> bool where E: TElement, { target.pres_hints() == candidate.pres_hints() } /// Whether a given element has ...
{ match (target.style_attribute(), candidate.style_attribute()) { (None, None) => true, (Some(_), None) | (None, Some(_)) => false, (Some(a), Some(b)) => &*a as *const _ == &*b as *const _ } }
identifier_body
checks.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Different checks done during the style sharing process in order to determine //! quickly whether it's worth to...
} } /// Whether two elements have the same same presentational attributes. pub fn have_same_presentational_hints<E>( target: &mut StyleSharingTarget<E>, candidate: &mut StyleSharingCandidate<E> ) -> bool where E: TElement, { target.pres_hints() == candidate.pres_hints() } /// Whether a given eleme...
random_line_split
checks.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Different checks done during the style sharing process in order to determine //! quickly whether it's worth to...
<E>( target: &mut StyleSharingTarget<E>, candidate: &mut StyleSharingCandidate<E>, ) -> bool where E: TElement, { target.class_list() == candidate.class_list() } /// Whether a given element and a candidate match the same set of "revalidation" /// selectors. /// /// Revalidation selectors are those that...
have_same_class
identifier_name
colorbars.py
# -*- coding: utf-8 -*- # desc = 'Color bars' phash = '' def plot():
orientation='horizontal' ) cb1.set_label('Some Units') # The second example illustrates the use of a ListedColormap, a # BoundaryNorm, and extended ends to show the "over" and "under" value # colors. cmap = mpl.colors.ListedColormap(['r', 'g', 'b', 'c']) cmap.set_over('0.25') ...
import matplotlib as mpl from matplotlib import pyplot as pp from matplotlib import style import numpy as np # Make a figure and axes with dimensions as desired. fig, ax = pp.subplots(3) # Set the colormap and norm to correspond to the data for which # the colorbar will be used. cmap = ...
identifier_body
colorbars.py
# -*- coding: utf-8 -*- # desc = 'Color bars' phash = '' def plot(): import matplotlib as mpl from matplotlib import pyplot as pp from matplotlib import style import numpy as np # Make a figure and axes with dimensions as desired. fig, ax = pp.subplots(3) # Set the colormap and norm to co...
norm=norm, orientation='horizontal' ) cb1.set_label('Some Units') # The second example illustrates the use of a ListedColormap, a # BoundaryNorm, and extended ends to show the "over" and "under" value # colors. cmap = mpl.colors.ListedColormap(['r', 'g', 'b', 'c']) cmap....
cmap=cmap,
random_line_split
colorbars.py
# -*- coding: utf-8 -*- # desc = 'Color bars' phash = '' def
(): import matplotlib as mpl from matplotlib import pyplot as pp from matplotlib import style import numpy as np # Make a figure and axes with dimensions as desired. fig, ax = pp.subplots(3) # Set the colormap and norm to correspond to the data for which # the colorbar will be used. ...
plot
identifier_name
models.py
# -*- coding: utf-8 -*- from openerp import models, fields, api, osv # We just create a new model class mother(models.Model): _name = 'test.inherit.mother' _columns = {
'name': osv.fields.char('Name', required=True), } surname = fields.Char(compute='_compute_surname') state = fields.Selection([('a', 'A'), ('b', 'B')]) @api.one @api.depends('name') def _compute_surname(self): self.surname = self.name or '' # We want to inherits from the parent...
# check interoperability of field inheritance with old-style fields
random_line_split
models.py
# -*- coding: utf-8 -*- from openerp import models, fields, api, osv # We just create a new model class mother(models.Model): _name = 'test.inherit.mother' _columns = { # check interoperability of field inheritance with old-style fields 'name': osv.fields.char('Name', required=True), } ...
class mother(models.Model): _inherit = 'test.inherit.mother' # extend again the selection of the state field state = fields.Selection(selection_add=[('d', 'D')]) class daughter(models.Model): _inherit = 'test.inherit.daughter' # simply redeclare the field without adding any option templat...
super(mother, self)._compute_surname()
conditional_block
models.py
# -*- coding: utf-8 -*- from openerp import models, fields, api, osv # We just create a new model class
(models.Model): _name = 'test.inherit.mother' _columns = { # check interoperability of field inheritance with old-style fields 'name': osv.fields.char('Name', required=True), } surname = fields.Char(compute='_compute_surname') state = fields.Selection([('a', 'A'), ('b', 'B')]) ...
mother
identifier_name
models.py
# -*- coding: utf-8 -*- from openerp import models, fields, api, osv # We just create a new model class mother(models.Model): _name = 'test.inherit.mother' _columns = { # check interoperability of field inheritance with old-style fields 'name': osv.fields.char('Name', required=True), } ...
# We want to inherits from the parent model and we add some fields # in the child object class daughter(models.Model): _name = 'test.inherit.daughter' _inherits = {'test.inherit.mother': 'template_id'} template_id = fields.Many2one('test.inherit.mother', 'Template', requ...
self.surname = self.name or ''
identifier_body
210System.running.js
var should = require('should'); var path = require('path'); var _ = require('underscore'); var Graft = require('../server'); var utils = require('./utils'); var sinon = require('sinon'); var testPort = 8924; function setupSpies()
function restoreSpies() { Graft.Server.trigger.restore(); } describe('Systems: Running', function() { before(setupSpies); before(function() { Graft.system('ServerOnly', 'server-only', { kind: 'server_only' }); Graft.system('ClientToo', 'client-too', { kind...
{ sinon.spy(Graft.Server, 'trigger'); }
identifier_body
210System.running.js
var should = require('should'); var path = require('path'); var _ = require('underscore'); var Graft = require('../server'); var utils = require('./utils'); var sinon = require('sinon'); var testPort = 8924; function
() { sinon.spy(Graft.Server, 'trigger'); } function restoreSpies() { Graft.Server.trigger.restore(); } describe('Systems: Running', function() { before(setupSpies); before(function() { Graft.system('ServerOnly', 'server-only', { kind: 'server_only' }); Graft.system...
setupSpies
identifier_name
210System.running.js
var should = require('should'); var path = require('path');
var utils = require('./utils'); var sinon = require('sinon'); var testPort = 8924; function setupSpies() { sinon.spy(Graft.Server, 'trigger'); } function restoreSpies() { Graft.Server.trigger.restore(); } describe('Systems: Running', function() { before(setupSpies); before(function() { ...
var _ = require('underscore'); var Graft = require('../server');
random_line_split
recursion_limit_deref.rs
// Test that the recursion limit can be changed and that the compiler // suggests a fix. In this case, we have a long chain of Deref impls // which will cause an overflow during the autoderef loop. #![allow(dead_code)] #![recursion_limit="10"] macro_rules! link { ($outer:ident, $inner:ident) => { struct $...
; impl Bottom { fn new() -> Bottom { Bottom } } link!(Top, A); link!(A, B); link!(B, C); link!(C, D); link!(D, E); link!(E, F); link!(F, G); link!(G, H); link!(H, I); link!(I, J); link!(J, K); link!(K, Bottom); fn main() { let t = Top::new(); let x: &Bottom = &t; //~ ERROR mismatched types ...
Bottom
identifier_name
recursion_limit_deref.rs
// Test that the recursion limit can be changed and that the compiler // suggests a fix. In this case, we have a long chain of Deref impls // which will cause an overflow during the autoderef loop. #![allow(dead_code)] #![recursion_limit="10"] macro_rules! link { ($outer:ident, $inner:ident) => { struct $...
{ let t = Top::new(); let x: &Bottom = &t; //~ ERROR mismatched types //~^ error recursion limit }
identifier_body
recursion_limit_deref.rs
// Test that the recursion limit can be changed and that the compiler // suggests a fix. In this case, we have a long chain of Deref impls // which will cause an overflow during the autoderef loop. #![allow(dead_code)] #![recursion_limit="10"] macro_rules! link { ($outer:ident, $inner:ident) => { struct $...
&self.0 } } } } struct Bottom; impl Bottom { fn new() -> Bottom { Bottom } } link!(Top, A); link!(A, B); link!(B, C); link!(C, D); link!(D, E); link!(E, F); link!(F, G); link!(G, H); link!(H, I); link!(I, J); link!(J, K); link!(K, Bottom); fn main() { let t...
impl std::ops::Deref for $outer { type Target = $inner; fn deref(&self) -> &$inner {
random_line_split
NetSimDnsTable.js
/** * @overview UI table of local subnet, displaying hostname => address map. */ 'use strict'; var markup = require('./NetSimDnsTable.html.ejs'); var DnsMode = require('./NetSimConstants').DnsMode; /** * Generator and controller for DNS network lookup table component. * Shows different amounts of information depe...
};
this.addressTableData_ = tableContents; this.render();
random_line_split
languageService.ts
import {Injectable} from 'angular2/core'; import {Http, Headers, Response} from 'angular2/http'; import {Observable} from "rxjs/Observable"; import {ILanguage, IFormat, IOperation} from '../interfaces' @Injectable() export class LanguageService { constructor(public http: Http) { } getLanguage(languagePath:...
(error: Response) { // in a real world app, we may send the server to some remote logging infrastructure // instead of just logging it to the console // return Observable.throw(error.json().error || 'Server error'); return Observable.throw('Server error'); } }
handleError
identifier_name
languageService.ts
import {Injectable} from 'angular2/core'; import {Http, Headers, Response} from 'angular2/http'; import {Observable} from "rxjs/Observable"; import {ILanguage, IFormat, IOperation} from '../interfaces' @Injectable() export class LanguageService { constructor(public http: Http) { } getLanguage(languagePath:...
let url = '/api/convert' + languageId; let body = 'currentFormat='+currentFormat + '&desiredFormat='+ desiredFormat + '&fileUri='+ '' + '&content='+ encodeURIComponent(content); let headers = new Headers(); headers.append('Content-Type', 'application/...
.map(res => res.json()) .catch(this.handleError); } convertLanguage(languageId: string, currentFormat: string, desiredFormat: string, content: string, fileUri: string ){
random_line_split
languageService.ts
import {Injectable} from 'angular2/core'; import {Http, Headers, Response} from 'angular2/http'; import {Observable} from "rxjs/Observable"; import {ILanguage, IFormat, IOperation} from '../interfaces' @Injectable() export class LanguageService { constructor(public http: Http) { } getLanguage(languagePath:...
}
{ // in a real world app, we may send the server to some remote logging infrastructure // instead of just logging it to the console // return Observable.throw(error.json().error || 'Server error'); return Observable.throw('Server error'); }
identifier_body
storage.py
#!/usr/bin/env python # 2015 Copyright (C) White # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 2 of the License. # # This program is distributed in the hope that it will be useful, #...
except: return False
return True
random_line_split
storage.py
#!/usr/bin/env python # 2015 Copyright (C) White # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 2 of the License. # # This program is distributed in the hope that it will be useful, #...
description = description or description.strip() if description: config['description'] = description site_page = int(site_page) if site_page >= 0: config['site_page'] = site_page posts_per_page = int(posts_per_page) ...
config['sitename'] = sitename
conditional_block
storage.py
#!/usr/bin/env python # 2015 Copyright (C) White # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 2 of the License. # # This program is distributed in the hope that it will be useful, #...
(self): return self.pair_repo.find('system') def update_site_meta(self, sitename, description, site_page, posts_per_page, auto_published_comments, comment_moderation_keys): meta = self.site_meta() config = meta.json_value() try: sitename = sit...
site_meta
identifier_name
storage.py
#!/usr/bin/env python # 2015 Copyright (C) White # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 2 of the License. # # This program is distributed in the hope that it will be useful, #...
def update_site_meta(self, sitename, description, site_page, posts_per_page, auto_published_comments, comment_moderation_keys): meta = self.site_meta() config = meta.json_value() try: sitename = sitename or sitename.strip() if sitename: ...
return self.pair_repo.find('system')
identifier_body
lib.rs
// =================================================================
// // Changes made to this file will be overwritten. If changes are // required to the generated code, the service_crategen project // must be updated to generate the changes. // // ================================================================= #![doc( html_logo_url = "https://raw.githubusercontent.com/rusoto...
// // * WARNING * // // This file is generated!
random_line_split
server.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ɵAnimationEngine} from '@angular/animations/browser'; import {PlatformLocation, ViewportScroller, ɵNullViewp...
return getDOM().createHtmlDocument(); } } /** * @experimental */ export const platformServer = createPlatformFactory(platformCore, 'server', INTERNAL_SERVER_PLATFORM_PROVIDERS); /** * The server platform that supports the runtime compiler. * * @experimental */ export const platformDynamicServer = crea...
parseDocument(config.document, config.url); } else {
conditional_block
server.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ɵAnimationEngine} from '@angular/animations/browser'; import {PlatformLocation, ViewportScroller, ɵNullViewp...
on _document(injector: Injector) { let config: PlatformConfig|null = injector.get(INITIAL_CONFIG, null); if (config && config.document) { return parseDocument(config.document, config.url); } else { return getDOM().createHtmlDocument(); } } /** * @experimental */ export const platformServer = crea...
{ } functi
identifier_name
server.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ɵAnimationEngine} from '@angular/animations/browser'; import {PlatformLocation, ViewportScroller, ɵNullViewp...
} export function instantiateServerRendererFactory( renderer: RendererFactory2, engine: ɵAnimationEngine, zone: NgZone) { return new ɵAnimationRendererFactory(renderer, engine, zone); } export const SERVER_RENDER_PROVIDERS: Provider[] = [ ServerRendererFactory2, { provide: RendererFactory2, useFacto...
]; function initDominoAdapter(injector: Injector) { return () => { DominoAdapter.makeCurrent(); };
random_line_split
server.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ɵAnimationEngine} from '@angular/animations/browser'; import {PlatformLocation, ViewportScroller, ɵNullViewp...
function instantiateServerRendererFactory( renderer: RendererFactory2, engine: ɵAnimationEngine, zone: NgZone) { return new ɵAnimationRendererFactory(renderer, engine, zone); } export const SERVER_RENDER_PROVIDERS: Provider[] = [ ServerRendererFactory2, { provide: RendererFactory2, useFactory: instan...
n () => { DominoAdapter.makeCurrent(); }; } export
identifier_body
jquery.initialize-0.1.0.js
/*! * jquery.initialize. An basic element initializer plugin for jQuery. * * Copyright (c) 2014 Barış Güler * http://hwclass.github.io * * Licensed under MIT * http://www.opensource.org/licenses/mit-license.php * * http://docs.jquery.com/Plugins/Authoring * jQuery authoring guidelines * * Launch : July 201...
return this; } })(jQuery);
}
random_line_split
jquery.initialize-0.1.0.js
/*! * jquery.initialize. An basic element initializer plugin for jQuery. * * Copyright (c) 2014 Barış Güler * http://hwclass.github.io * * Licensed under MIT * http://www.opensource.org/licenses/mit-license.php * * http://docs.jquery.com/Plugins/Authoring * jQuery authoring guidelines * * Launch : July 201...
return this; } })(jQuery);
setEvents(); }
conditional_block
make-script.py
import os import subprocess from pathlib import Path import pyinstaller_versionfile import tomli packaging_path = Path(__file__).resolve().parent def get_version() -> str: project_dir = Path(__file__).resolve().parent.parent f = project_dir / "pyproject.toml" return str(tomli.loads(f.read_text())["tool"...
file.write("from gaphor.ui import main\n") file.write("import sys\n") file.write("main(sys.argv)\n") def make_file_version_info(): win_packaging_path = packaging_path / "windows" metadata = win_packaging_path / "versionfile_metadata.yml" file_version_out = win_packaging_path / "f...
file.write(f"import {entrypoint.split(':')[0]}\n")
conditional_block
make-script.py
import os import subprocess from pathlib import Path import pyinstaller_versionfile import tomli packaging_path = Path(__file__).resolve().parent def get_version() -> str: project_dir = Path(__file__).resolve().parent.parent f = project_dir / "pyproject.toml" return str(tomli.loads(f.read_text())["tool"...
file.write(f"import {entrypoint.split(':')[0]}\n") file.write("from gaphor.ui import main\n") file.write("import sys\n") file.write("main(sys.argv)\n") def make_file_version_info(): win_packaging_path = packaging_path / "windows" metadata = win_packaging_path / "versi...
pyproject_toml = packaging_path.parent / "pyproject.toml" with open(pyproject_toml, "rb") as f: toml = tomli.load(f) gaphor_script = packaging_path / "gaphor-script.py" with open(gaphor_script, "w") as file: # https://github.com/pyinstaller/pyinstaller/issues/6100 # On one Windows ...
identifier_body
make-script.py
import os import subprocess from pathlib import Path import pyinstaller_versionfile import tomli packaging_path = Path(__file__).resolve().parent def get_version() -> str: project_dir = Path(__file__).resolve().parent.parent f = project_dir / "pyproject.toml" return str(tomli.loads(f.read_text())["tool"...
(): os.chdir(packaging_path) subprocess.run(["pyinstaller", "-y", "gaphor.spec"])
make_pyinstaller
identifier_name
make-script.py
import os import subprocess from pathlib import Path import pyinstaller_versionfile import tomli packaging_path = Path(__file__).resolve().parent def get_version() -> str: project_dir = Path(__file__).resolve().parent.parent f = project_dir / "pyproject.toml" return str(tomli.loads(f.read_text())["tool"...
version=version, ) def make_pyinstaller(): os.chdir(packaging_path) subprocess.run(["pyinstaller", "-y", "gaphor.spec"])
output_file=file_version_out, input_file=metadata,
random_line_split
TcpServer.py
# coding=utf-8 import time import datetime __author__ = 'JIE' #! /usr/bin/env python #coding=utf-8 from tornado.tcpserver import TCPServer from tornado.ioloop import IOLoop class Connection(object): clients = set() def __init__(self, stream, address): Connection.clients.add(self) self._stream...
def send_message(self, data): self._stream.write(data) def on_close(self): print "A user has left the chat room.", self._address Connection.clients.remove(self) class ChatServer(TCPServer): def handle_stream(self, stream, address): print "New connection :", address, strea...
print "User said:", data[:-1], self._address for conn in Connection.clients: conn.send_message(data) self.read_message()
identifier_body
TcpServer.py
# coding=utf-8 import time import datetime __author__ = 'JIE' #! /usr/bin/env python #coding=utf-8 from tornado.tcpserver import TCPServer from tornado.ioloop import IOLoop class Connection(object): clients = set() def __init__(self, stream, address): Connection.clients.add(self) self._stream...
conn.send_message(data) self.read_message() def send_message(self, data): self._stream.write(data) def on_close(self): print "A user has left the chat room.", self._address Connection.clients.remove(self) class ChatServer(TCPServer): def handle_stream(self, str...
def broadcast_messages(self, data): print "User said:", data[:-1], self._address for conn in Connection.clients:
random_line_split
TcpServer.py
# coding=utf-8 import time import datetime __author__ = 'JIE' #! /usr/bin/env python #coding=utf-8 from tornado.tcpserver import TCPServer from tornado.ioloop import IOLoop class Connection(object): clients = set() def __init__(self, stream, address): Connection.clients.add(self) self._stream...
print "Server start ......" server = ChatServer() server.listen(8000) IOLoop.instance().start()
conditional_block
TcpServer.py
# coding=utf-8 import time import datetime __author__ = 'JIE' #! /usr/bin/env python #coding=utf-8 from tornado.tcpserver import TCPServer from tornado.ioloop import IOLoop class Connection(object): clients = set() def __init__(self, stream, address): Connection.clients.add(self) self._stream...
(self, stream, address): print "New connection :", address, stream Connection(stream, address) print "connection num is:", len(Connection.clients) if __name__ == '__main__': print "Server start ......" server = ChatServer() server.listen(8000) IOLoop.instance().start()
handle_stream
identifier_name
memory.py
#!/usr/bin/env python """VFS Handler which provides access to the raw physical memory. Memory access is provided by use of a special driver. Note that it is preferred to use this VFS handler rather than directly access the raw handler since this handler protects the system from access to unmapped memory regions such a...
(self, length): """Read from the memory device, null padding the ranges.""" to_read = min(length, self.size - self.offset) result = self.address_space.read(self.offset, to_read) self.offset += len(result) return result
Read
identifier_name
memory.py
#!/usr/bin/env python """VFS Handler which provides access to the raw physical memory. Memory access is provided by use of a special driver. Note that it is preferred to use this VFS handler rather than directly access the raw handler since this handler protects the system from access to unmapped memory regions such a...
return fd def IsDirectory(self): return False def Stat(self): result = rdf_client.StatEntry(st_size=self.size, pathspec=self.pathspec) return result def GetMemoryInformation(self): result = rdf_rekall_types.MemoryInformation( cr3=self.session.GetPa...
return cls(base_fd=None, full_pathspec=full_pathspec)
conditional_block
memory.py
#!/usr/bin/env python """VFS Handler which provides access to the raw physical memory. Memory access is provided by use of a special driver. Note that it is preferred to use this VFS handler rather than directly access the raw handler since this handler protects the system from access to unmapped memory regions such a...
@classmethod def Open(cls, fd, component, pathspec=None, full_pathspec=None, progress_callback=None): if fd is None: return cls(base_fd=None, full_pathspec=full_pathspec) return fd def IsDirectory(self): return False def Stat(self): result = rdf_client.StatEntry(st_size=self...
super(MemoryVFS, self).__init__(None, progress_callback=progress_callback, full_pathspec=full_pathspec) if base_fd is not None: raise IOError("Memory handler can not be stacked on another handler.") self.pathspec = full_pathspec self.session = session.Session(filen...
identifier_body
memory.py
#!/usr/bin/env python """VFS Handler which provides access to the raw physical memory. Memory access is provided by use of a special driver. Note that it is preferred to use this VFS handler rather than directly access the raw handler since this handler protects the system from access to unmapped memory regions such a...
raise IOError("Unable to open device") self.size = self.address_space.end() @classmethod def Open(cls, fd, component, pathspec=None, full_pathspec=None, progress_callback=None): if fd is None: return cls(base_fd=None, full_pathspec=full_pathspec) return fd def IsDirectory(sel...
self.address_space = load_as_plugin.GetPhysicalAddressSpace() if not self.address_space:
random_line_split
Component.js
/********************************************************************* Component.js This file is part of Heliwidgets library for Helios framework. __Copying:___________________________________________________________ Copyright 2008, 2009 Dmitry Prokashev Heliwidgets is free software: you can red...
__Description:_______________________________________________________ Defines heliwidgets.Component Widget used for creating a widget which will contain some component, defined in Platform API. __Objects declared:__________________________________________________ heliwidgets.Component ...
along with the Heliwidgets library. If not, see <http://www.gnu.org/licenses/>.
random_line_split
questiongroup-list.component_notused.ts
import { Component, OnInit , Output, Input, EventEmitter} from '@angular/core'; import { QuestionGroup } from '../../model/questiongroup.ts'; @Component({ selector: 'questiongroup-list', template : ` <mat-list-item> <mat-icon mat-list-icon>folder</mat-icon> <h4 matLine >{questi...
ngOnInit() {} removeAnswer():void{ console.log(this.answer); this.onSelectData.emit(this.answer); } changeSelected(data:any):void{ console.log(data); console.log(data.checked); console.log("changeSelected()"); } }
{ }
identifier_body
questiongroup-list.component_notused.ts
import { Component, OnInit , Output, Input, EventEmitter} from '@angular/core'; import { QuestionGroup } from '../../model/questiongroup.ts'; @Component({ selector: 'questiongroup-list', template : ` <mat-list-item> <mat-icon mat-list-icon>folder</mat-icon> <h4 matLine >{questi...
() { } ngOnInit() {} removeAnswer():void{ console.log(this.answer); this.onSelectData.emit(this.answer); } changeSelected(data:any):void{ console.log(data); console.log(data.checked); console.log("changeSelected()"); } }
constructor
identifier_name
questiongroup-list.component_notused.ts
import { Component, OnInit , Output, Input, EventEmitter} from '@angular/core'; import { QuestionGroup } from '../../model/questiongroup.ts'; @Component({ selector: 'questiongroup-list', template : ` <mat-list-item> <mat-icon mat-list-icon>folder</mat-icon> <h4 matLine >{questi...
console.log("changeSelected()"); } }
console.log(data); console.log(data.checked);
random_line_split
yubiserve.py
crc = crc ^ 0x8408 self.OTPcrc = crc return [crc] def isCRCValid(self): return (self.OTPcrc == 0xf0b8) def aes128ecb_decrypt(self, aeskey, aesdata): return AES.new(aeskey.decode('hex'), AES.MODE_ECB).decrypt(aesdata.decode('hex')).encode('hex') def getResult(self): return self.validationResult def ge...
print "unhandled exception" print repr(e) return self class YubiServeHandler (BaseHTTPServer.BaseHTTPRequestHandler): __base = BaseHTTPServer.BaseHTTPRequestHandler __base_handle = __base.handle server_version = 'Yubiserve/3.1' global config #try: if config['yubiDB'] == 'sqlite3': con =...
print "unhandled MySQL exception" print e sys.exit(1) except Exception, e:
random_line_split
yubiserve.py
self.OTPcrc = crc return [crc] def isCRCValid(self): return (self.OTPcrc == 0xf0b8) def aes128ecb_decrypt(self, aeskey, aesdata): return AES.new(aeskey.decode('hex'), AES.MODE_ECB).decrypt(aesdata.decode('hex')).encode('hex') def getResult(self): return self.validationResult def getResponse(self): retu...
crc = crc ^ 0x8408
conditional_block
yubiserve.py
def isCRCValid(self): return (self.OTPcrc == 0xf0b8) def aes128ecb_decrypt(self, aeskey, aesdata): return AES.new(aeskey.decode('hex'), AES.MODE_ECB).decrypt(aesdata.decode('hex')).encode('hex') def getResult(self): return self.validationResult def getResponse(self): return self.validationResponse def val...
crc = 0xffff; for i in range(0, 16): b = self.hexdec(self.plaintext[i*2] + self.plaintext[(i*2)+1]) crc = crc ^ (b & 0xff) for j in range(0, 8): n = crc & 1 crc = crc >> 1 if n != 0: crc = crc ^ 0x8408 self.OTPcrc = crc return [crc]
identifier_body
yubiserve.py
crc = crc ^ 0x8408 self.OTPcrc = crc return [crc] def
(self): return (self.OTPcrc == 0xf0b8) def aes128ecb_decrypt(self, aeskey, aesdata): return AES.new(aeskey.decode('hex'), AES.MODE_ECB).decrypt(aesdata.decode('hex')).encode('hex') def getResult(self): return self.validationResult def getResponse(self): return self.validationResponse def validateOTP(self, O...
isCRCValid
identifier_name
shift.ts
import {statementType} from "../_utils"; import * as Statements from "../../../src/abap/statements/"; const tests = [ "SHIFT ls_param-field.", "SHIFT lv_range LEFT BY sy-fdpos PLACES.", "SHIFT lv_qty RIGHT.", "SHIFT lv_bits LEFT CIRCULAR BY iv_places PLACES.", "SHIFT lv_content BY 1022 PLACES LEFT IN BYTE MO...
"SHIFT classname LEFT UP TO '='.", "SHIFT bytes BY places PLACES RIGHT IN BYTE MODE.", "SHIFT r_json RIGHT CIRCULAR.", "SHIFT lv_field UP TO '-'.", ]; statementType(tests, "SHIFT", Statements.Shift);
"SHIFT l_xstr LEFT DELETING LEADING cl_abap_char_utilities=>byte_order_mark_utf8 IN BYTE MODE.", "SHIFT lv_syindex RIGHT DELETING TRAILING space.", "SHIFT lv_cols BY 1 PLACES LEFT.", "SHIFT lv_temp UP TO '/' LEFT.",
random_line_split
where2.py
*c) if (x<mid_cos): return leaf(m,one,node._kids[0]) else: return leaf(m,one,node._kids[1]) return node """ This code needs some helper functions. _Dist_ uses the standard Euclidean measure. Note that you tune what it uses to define the niches (decisions or objectives) using the _what_ parameter...
m.eval(m,it) new, w = 0, 0 for c in m.objectives: val = it.cells[c] w += abs(m.w[c]) tmp = norm(m,c,val) if m.w[c] < 0: tmp = 1 - tmp new += (tmp**2) it.score = (new**0.5) / (w**0.5) it.scored = True
conditional_block
where2.py
1 between decisions" n = len(i.cells) deltas = 0 for c in what(m): n1 = norm(m, c, i.cells[c]) n2 = norm(m, c, j.cells[c]) if (hasattr(m,'weights') and len(m.weights)!=0) : inc = (m.weights[c] * (n1 - n2))**2 else : inc = (n1-n2)**2 deltas += inc n += abs(m.w[c]) return...
seed(1) told=N() if (not rows): rows = m._rows for r in rows: s = scores(m,r) told += s global The The=defaults().update(verbose = True, minSize = len(rows)**0.5, prune = False, wriggle = 0.3*told.sd()) return where2(m, rows,verbose = verbose)
identifier_body
where2.py
.. |.. 12 |.. |.. |.. |.. 6. |.. |.. |.. |.. 6. |.. 47 |.. |.. 23 |.. |.. |.. 11 |.. |.. |.. |.. 5. |.. |.. |.. |.. 6. |.. |.. |.. 12 |.. |.. |.. |.. 6. |.. |.. |.. |.. 6. |.. |.. 24 |.. |.. |.. 12 |.. |.. |.. |.. 6. |.. |.. |.. |.. 6. |.. |.. |.. 12 |.. |...
random_line_split
where2.py
of midpoint, used for future testing mid_element = lst[mid] west = wests[0] east = easts[-1] return wests,west, easts,east,c, mid_element """ We select the leaf in which the test node belongs by comparing the projection of test node between the extreme nodes """ def leaf(m,one,node): if node._kids: ea...
some
identifier_name
EmojiBlot.ts
/** * @author Stéphane (slafleche) LaFlèche <stephane.l@vanillaforums.com> * @copyright 2009-2019 Vanilla Forums Inc. * @license GPL-2.0-only */ import Embed from "quill/blots/embed"; import { setData, getData, convertToSafeEmojiCharacters, isEmojiSupported } from "@vanilla/dom-utils"; export default class Em
xtends Embed { public static className = "safeEmoji"; public static blotName = "emoji"; public static tagName = "span"; public static create(data) { const node = super.create(data) as HTMLElement; if (isEmojiSupported()) { node.innerHTML = data.emojiChar; node.cl...
ojiBlot e
identifier_name
EmojiBlot.ts
/** * @author Stéphane (slafleche) LaFlèche <stephane.l@vanillaforums.com> * @copyright 2009-2019 Vanilla Forums Inc. * @license GPL-2.0-only */ import Embed from "quill/blots/embed"; import { setData, getData, convertToSafeEmojiCharacters, isEmojiSupported } from "@vanilla/dom-utils"; export default class EmojiB...
lse { node.innerHTML = convertToSafeEmojiCharacters(data.emojiChar); } setData(node, "data", data); return node; } public static value(node) { return getData(node, "data"); } }
node.innerHTML = data.emojiChar; node.classList.add("nativeEmoji"); } e
conditional_block
EmojiBlot.ts
/** * @author Stéphane (slafleche) LaFlèche <stephane.l@vanillaforums.com> * @copyright 2009-2019 Vanilla Forums Inc. * @license GPL-2.0-only */ import Embed from "quill/blots/embed"; import { setData, getData, convertToSafeEmojiCharacters, isEmojiSupported } from "@vanilla/dom-utils"; export default class EmojiB...
setData(node, "data", data); return node; } public static value(node) { return getData(node, "data"); } }
node.innerHTML = convertToSafeEmojiCharacters(data.emojiChar); }
random_line_split
main.rs
/* Aurélien DESBRIÈRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations // Borrowing Aliasing in Rust struct Point { x: i32, y: i32, z: i32 } fn ma
{ let mut point = Point { x: 0, y: 0, z: 0 }; { let borrowed_point = &point; let another_borrow = &point; // Data can be accessed via the references an the original owner println!("Point has coordiantes: ({}, {}, {})", borrowed_point.x, another_borrow.y, point...
in()
identifier_name
main.rs
/* Aurélien DESBRIÈRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations // Borrowing Aliasing in Rust struct Point { x: i32, y: i32, z: i32 } fn main() {
// Change data via mutable reference mutable_borrow.x = 5; mutable_borrow.y = 2; mutable_borrow.z = 1; // Error! Can't borrow `point` as immutable because it's currently // borrowed as mutable. //let y = &point.y. // TODO ^ Try uncommenting this line ...
let mut point = Point { x: 0, y: 0, z: 0 }; { let borrowed_point = &point; let another_borrow = &point; // Data can be accessed via the references an the original owner println!("Point has coordiantes: ({}, {}, {})", borrowed_point.x, another_borrow.y, point.z)...
identifier_body
main.rs
/* Aurélien DESBRIÈRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations // Borrowing Aliasing in Rust struct Point { x: i32, y: i32, z: i32 } fn main() { let mut point = Point { x: 0, y: 0, z: 0 }; { let borrowed_point = &point; let another_borrow = &point; ...
mutable_borrow.x = 5; mutable_borrow.y = 2; mutable_borrow.z = 1; // Error! Can't borrow `point` as immutable because it's currently // borrowed as mutable. //let y = &point.y. // TODO ^ Try uncommenting this line // Error! Can't print because `println!`...
{ let mutable_borrow = &mut point; // Change data via mutable reference
random_line_split
phenome.py
# Copyright (C) 2016 William Langhoff WildBill567@users.noreply.github.com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your optio...
for idx, val in enumerate(self.hidden_nodes): pos[val] = (idx, 2) nx.draw_networkx_nodes(self.graph, pos, nodelist=self.input_nodes, node_color='r') nx.draw_networkx_nodes(self.graph, pos, n...
pos[val] = (idx, 4)
conditional_block