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
mock_transport.ts
// tslint:disable:no-console import chalk from "chalk"; import { EventEmitter } from "events"; import { assert } from "node-opcua-assert"; import { display_trace_from_this_projet_only, hexDump, make_debugLog } from "node-opcua-debug"; import { analyseExtensionObject } from "node-opcua-packet-analyzer"; import { GetEndp...
} debugLog("\nFAKE SERVER RECEIVED"); debugLog(hexDump(data)); let replies = []; if (reply instanceof Buffer) { replies.push(reply); } else { replies = reply; } ...
{ return; }
conditional_block
mock_transport.ts
// tslint:disable:no-console import chalk from "chalk"; import { EventEmitter } from "events"; import { assert } from "node-opcua-assert"; import { display_trace_from_this_projet_only, hexDump, make_debugLog } from "node-opcua-debug"; import { analyseExtensionObject } from "node-opcua-packet-analyzer"; import { GetEndp...
this._mockTransport.server.on("data", (data: Buffer) => { let reply = this._replies[this._counter]; this._counter++; if (reply) { if (_.isFunction(reply)) { reply = reply.call(this); // console.log(" interpreting repl...
this._mockTransport = new DirectTransport(); this._mockTransport.initialize(() => { console.log("initialized"); });
random_line_split
mock_transport.ts
// tslint:disable:no-console import chalk from "chalk"; import { EventEmitter } from "events"; import { assert } from "node-opcua-assert"; import { display_trace_from_this_projet_only, hexDump, make_debugLog } from "node-opcua-debug"; import { analyseExtensionObject } from "node-opcua-packet-analyzer"; import { GetEndp...
extends EventEmitter { private _replies: any; private _mockTransport: DirectTransport; private _counter: number; constructor(expectedReplies: any) { super(); this._replies = expectedReplies; this._counter = 0; this._mockTransport = new DirectTransport(); thi...
MockServerTransport
identifier_name
mock_transport.ts
// tslint:disable:no-console import chalk from "chalk"; import { EventEmitter } from "events"; import { assert } from "node-opcua-assert"; import { display_trace_from_this_projet_only, hexDump, make_debugLog } from "node-opcua-debug"; import { analyseExtensionObject } from "node-opcua-packet-analyzer"; import { GetEndp...
// console.log(" interpreting reply as a function" + reply); if (!reply) { return; } } debugLog("\nFAKE SERVER RECEIVED"); debugLog(hexDump(data)); let replies = []; ...
{ super(); this._replies = expectedReplies; this._counter = 0; this._mockTransport = new DirectTransport(); this._mockTransport.initialize(() => { console.log("initialized"); }); this._mockTransport.server.on("data", (data: Buffer) => { ...
identifier_body
loadregions.py
import io, tempfile from django.core import management from django.contrib.gis.gdal import DataSource from django.contrib.gis.utils import LayerMapping from locations.models import Region class Command(management.BaseCommand): help = 'Allows the import of regions' def check_current_status(self): ""...
region_shp = '../data/kx-nz-regional-councils-2012-yearly-pattern-SHP/nz-regional-councils-2012-yearly-pattern.shp' lm = LayerMapping( Region, region_shp, region_mapping, transform=False, encoding='utf-8', ) lm.save(strict=True...
region_mapping = {'name': 'NAME', 'polygon': 'POLYGON'}
random_line_split
loadregions.py
import io, tempfile from django.core import management from django.contrib.gis.gdal import DataSource from django.contrib.gis.utils import LayerMapping from locations.models import Region class Command(management.BaseCommand): help = 'Allows the import of regions' def check_current_status(self): ""...
self.stdout.write('\nImport cancelled!')
conditional_block
loadregions.py
import io, tempfile from django.core import management from django.contrib.gis.gdal import DataSource from django.contrib.gis.utils import LayerMapping from locations.models import Region class Command(management.BaseCommand): help = 'Allows the import of regions' def check_current_status(self): ""...
def handle(self, *args, **options): self.check_current_status() confirm = input('\nReady to import? Type \'yes\' to continue: ') #confirm = 'yes' # for debugging if confirm == 'yes': self.do_import() else: self.stdout.write('\nImport cancelled!')
""" Imports objects into database """ self.stdout.write(self.style.MIGRATE_HEADING('\nBeginning import:')) region_mapping = {'name': 'NAME', 'polygon': 'POLYGON'} region_shp = '../data/kx-nz-regional-councils-2012-yearly-pattern-SHP/nz-regional-councils-2012-yearly-pattern.shp' lm = L...
identifier_body
loadregions.py
import io, tempfile from django.core import management from django.contrib.gis.gdal import DataSource from django.contrib.gis.utils import LayerMapping from locations.models import Region class Command(management.BaseCommand): help = 'Allows the import of regions' def
(self): """ Outputs information about objects currently in database """ self.stdout.write(self.style.MIGRATE_HEADING('Current status:')) self.stdout.write('Region: %d' % Region.objects.count()) def do_import(self): """ Imports objects into database """ self.stdout.write(self...
check_current_status
identifier_name
tlf.tsx
import * as React from 'react' import * as Styles from '../../../styles' import * as Constants from '../../../constants/fs' import * as Types from '../../../constants/types/fs' import {rowStyles, StillCommon, StillCommonProps} from './common' import * as Kb from '../../../common-adapters' import {useFsPathMetadata, Tlf...
return null } const Tlf = (props: TlfProps) => ( <> {!!props.loadPathMetadata && <FsPathMetadataLoader path={props.path} />} <StillCommon path={props.path} onOpen={props.disabled ? undefined : props.onOpen} inDestinationPicker={props.inDestinationPicker} mixedMode={props.mixedMode} ...
</Kb.Box> ) const FsPathMetadataLoader = ({path}: {path: Types.Path}) => { useFsPathMetadata(path)
random_line_split
jquery-fullheight.js
(function ($) { 'use strict'; // Device check for limiting resize handling. var IS_DEVICE = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); function FullHeight(el, options)
this.allowDeviceHeightResize = !( options.allowDeviceHeightResize === null || options.allowDeviceHeightResize === false || options.allowDeviceHeightResize === 'false' ); this.lastWidth = this.container.innerWidth(); this.timerResize = 0; this.container.on('resize.yrkup3.fullheight', $.proxy(this, '_...
{ this.el = $(el); var data = {}; $.each(this.el.data(), function (attr, value) { if (/^fullheight/.test(attr)) { var key = attr.replace('fullheight', '').toLowerCase(); data[key] = value; } }); options = $.extend({}, FullHeight.defaults, options, data); this.debug = options.debug; this.con...
identifier_body
jquery-fullheight.js
(function ($) { 'use strict'; // Device check for limiting resize handling. var IS_DEVICE = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); function
(el, options) { this.el = $(el); var data = {}; $.each(this.el.data(), function (attr, value) { if (/^fullheight/.test(attr)) { var key = attr.replace('fullheight', '').toLowerCase(); data[key] = value; } }); options = $.extend({}, FullHeight.defaults, options, data); this.debug = options.deb...
FullHeight
identifier_name
jquery-fullheight.js
(function ($) { 'use strict'; // Device check for limiting resize handling. var IS_DEVICE = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); function FullHeight(el, options) { this.el = $(el); var data = {}; $.each(this.el.data(), function (attr, value) { if (...
if (newHeight !== this.lastHeight) { if (this.debug) { console.log('set `' + this.property + '` to ' + newHeight); } this.el.css(this.property, newHeight); this.lastHeight = newHeight; } }; FullHeight.prototype.dispose = function () { if (this.debug) { console.log('dispose'); } this.con...
{ newHeight = this.container.innerHeight() - (this.el.offset().top - offset.top); }
conditional_block
jquery-fullheight.js
(function ($) { 'use strict'; // Device check for limiting resize handling. var IS_DEVICE = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); function FullHeight(el, options) { this.el = $(el); var data = {}; $.each(this.el.data(), function (attr, value) { if (...
// Run command if (typeof options == 'string') { data[options](); } }); return this; }; })(jQuery);
random_line_split
it.js
/* * Ample SDK - JavaScript GUI Framework * * Copyright (c) 2012 Sergey Ilinsky, Zingus J. Rinkle * Dual licensed under the MIT and GPL licenses. * See: http://www.amplesdk.com/about/licensing/ * */ ample.locale.addCultureInfo("it", { messages: { // window/dialog/wizard "xul.dialog.button.acc...
"xul.editor.button.subscript": "Sposta il Testo in alto (Apice)", "xul.editor.button.superscript": "Sposta il Testo in basso (Pedice)", "xul.editor.button.fontsize": "Cambia la Dimensione del Carattere", "xul.editor.button.fontname": "Cambia il Tipo di Carattere", "xul.editor.button.formatbloc...
"xul.editor.button.unlink": "Rimuovi il Link", "xul.editor.button.bold": "Rendi grassetto il Testo selezionato", "xul.editor.button.italic": "Rendi corsivo il Testo selezionato", "xul.editor.button.underline": "Sottolinea il Testo selezionato", "xul.editor.button.strikethrough": "Sbarra i...
random_line_split
labelFile.py
for more details. # # You should have received a copy of the GNU General Public License # along with Labelme. If not, see <http://www.gnu.org/licenses/>. # #from PyQt4.QtGui import * #from PyQt4.QtCore import * from PySide.QtGui import * from PySide.QtCore import * from lib import newIcon import json import os.pat...
#paraT = pars[k].get('Value') #shapes.append((u'__P__:'+paraT+str(len(linesOK[k])), pointsFromBox(pars[k]), [255, 255, 224, 128], [255, 255, 224, 32])) for xl in linesOK[k]: if xl != []: for line in xl: shapes...
self.imagePath = img if not os.path.isfile(img): self.imagePath = os.path.join(os.path.split(filename)[0], img) with open(self.imagePath, "rb") as image_file: self.imageData = image_file.read() self.lineColor = DEFAULT_LINE_COLOR_LIST #RM: got from an example, RGB_Alph...
conditional_block
labelFile.py
for more details. # # You should have received a copy of the GNU General Public License # along with Labelme. If not, see <http://www.gnu.org/licenses/>. # #from PyQt4.QtGui import * #from PyQt4.QtCore import * from PySide.QtGui import * from PySide.QtCore import * from lib import newIcon import json import os.pat...
if xl != []: for line in xl: shapes.append((line.get('Value'), pointsFromBox(line), DEFAULT_LINE_COLOR_LIST, None)) self.shapes = (x for x in shapes) else: raise LabelFileError('Did not find any lines in %s'%filename) #except E...
#paraT = u'' #else: #paraT = pars[k].get('Value') #shapes.append((u'__P__:'+paraT+str(len(linesOK[k])), pointsFromBox(pars[k]), [255, 255, 224, 128], [255, 255, 224, 32])) for xl in linesOK[k]:
random_line_split
labelFile.py
for more details. # # You should have received a copy of the GNU General Public License # along with Labelme. If not, see <http://www.gnu.org/licenses/>. # #from PyQt4.QtGui import * #from PyQt4.QtCore import * from PySide.QtGui import * from PySide.QtCore import * from lib import newIcon import json import os.pat...
BB = QDialogButtonBox class LabelTagDialog(QDialog): def __init__(self, text="Enter object label", parent=None): super(LabelTagDialog, self).__init__(parent) layout = QVBoxLayout() self.buttonBox = bb = BB(BB.Ok, Qt.Horizontal, self) bb.button(BB.Ok).setIcon(newIcon('done')) ...
return min([x[1] for x in points])
identifier_body
labelFile.py
for more details. # # You should have received a copy of the GNU General Public License # along with Labelme. If not, see <http://www.gnu.org/licenses/>. # #from PyQt4.QtGui import * #from PyQt4.QtCore import * from PySide.QtGui import * from PySide.QtCore import * from lib import newIcon import json import os.pat...
(self, text="Enter object label", parent=None): super(LabelTagDialog, self).__init__(parent) layout = QVBoxLayout() self.buttonBox = bb = BB(BB.Ok, Qt.Horizontal, self) bb.button(BB.Ok).setIcon(newIcon('done')) #bb.button(BB.Cancel).setIcon(newIcon('undo')) bb.accepted.co...
__init__
identifier_name
js_Vi4nRccq-C68GfAxeNC_ncfO17N8Lk7sVRcdSvOYu8w.js
/** * JavaScript behaviors for the front-end display of webforms. */ (function ($) { Drupal.behaviors.webform = Drupal.behaviors.webform || {}; Drupal.behaviors.webform.attach = function(context) { // Calendar datepicker behavior. Drupal.webform.datepicker(context); }; Drupal.webform = Drupal.webform || {}; ...
}, beforeShow: function(input, inst) { // Get the select list values. var year = $webformDatepicker.find('select.year, input.year').val(); var month = $webformDatepicker.find('select.month').val(); var day = $webformDatepicker.find('select.day').val(); // If empty, d...
$webformDatepicker.find('select.month').val(+date[1]); $webformDatepicker.find('select.day').val(+date[2]);
random_line_split
js_Vi4nRccq-C68GfAxeNC_ncfO17N8Lk7sVRcdSvOYu8w.js
/** * JavaScript behaviors for the front-end display of webforms. */ (function ($) { Drupal.behaviors.webform = Drupal.behaviors.webform || {}; Drupal.behaviors.webform.attach = function(context) { // Calendar datepicker behavior. Drupal.webform.datepicker(context); }; Drupal.webform = Drupal.webform || {}; ...
return height; }; })(jQuery); ;
{ height -= $('#toolbar').get(0).filters.item("DXImageTransform.Microsoft.Shadow").strength; }
conditional_block
seed_comments.js
/* * Copyright 2012-present, Polis Technology Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights for non-commercial use can be found in the PATENTS file * in the sam...
return Object.assign({}, state, { loading: true, error: false, success: false }); case types.SUBMIT_SEED_COMMENT_SUCCESS: return Object.assign({}, state, { loading: false, seedText: "", error: false, success: true }); case types.SUBMIT_SEED_COMMENT_ERROR: ...
random_line_split
audio.py
#!/usr/bin/python3 # # Copyright © 2017 jared <jared@jared-devstation> # from pydub import AudioSegment, scipy_effects, effects import os import settings, util # combine two audio samples with a crossfade def c
acc, file2, CROSSFADE_DUR=100): util.debug_print('combining ' + file2) sample2 = AudioSegment.from_wav(file2) output = acc.append(sample2, crossfade=CROSSFADE_DUR) output = effects.normalize(output) return output # combine audio samples with crossfade, from within program def combine_prog_samples(a...
ombine_samples(
identifier_name
audio.py
#!/usr/bin/python3 # # Copyright © 2017 jared <jared@jared-devstation> # from pydub import AudioSegment, scipy_effects, effects import os import settings, util # combine two audio samples with a crossfade def combine_samples(acc, file2, CROSSFADE_DUR=100): util.debug_print('combining ' + file2) sample2 = Audi...
## add a sample to an existing wav #def add_sample(fname, samplefile, CROSSFADE_DUR=100): # new_file = combine_samples(fname, samplefile, CROSSFADE_DUR)[0] # os.rename(fname, 'old_' + fname) # os.rename(new_file, fname) # return new_file[1]
urr_file = AudioSegment.from_file(fname) low_seg = scipy_effects.low_pass_filter(curr_file, settings.LOW_FREQUENCY_LIM).export(fname + '_low.wav', 'wav') mid_seg = scipy_effects.band_pass_filter(curr_file, settings.LOW_FREQUENCY_LIM, settings.HIGH_FREQUENCY_LIM).export(fname + '_mid.wav', 'wav') high_seg = ...
identifier_body
audio.py
#!/usr/bin/python3 # # Copyright © 2017 jared <jared@jared-devstation> # from pydub import AudioSegment, scipy_effects, effects import os import settings, util # combine two audio samples with a crossfade def combine_samples(acc, file2, CROSSFADE_DUR=100): util.debug_print('combining ' + file2) sample2 = Audi...
def split_file(fname): curr_file = AudioSegment.from_file(fname) low_seg = scipy_effects.low_pass_filter(curr_file, settings.LOW_FREQUENCY_LIM).export(fname + '_low.wav', 'wav') mid_seg = scipy_effects.band_pass_filter(curr_file, settings.LOW_FREQUENCY_LIM, settings.HIGH_FREQUENCY_LIM).export(fname + '_mid....
output = acc.append(nsamp, crossfade=CROSSFADE_DUR) return output # split an audio file into low, mid, high bands
random_line_split
models.py
from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.core.management import call_command from django.db import models, connections, transaction from django.urls import reverse from django_tenants.clone import CloneSchema from .postgresql_backend.base import _check_sc...
@classmethod def deactivate(cls): """ Syntax sugar, return to public schema Usage: test_tenant.deactivate() # or simpler Tenant.deactivate() """ connection = connections[get_tenant_database_alias()] connection.set_schema_to_p...
""" Syntax sugar that helps at django shell with fast tenant changing Usage: Tenant.objects.get(schema_name='test').activate() """ connection = connections[get_tenant_database_alias()] connection.set_tenant(self)
identifier_body
models.py
from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.core.management import call_command from django.db import models, connections, transaction from django.urls import reverse from django_tenants.clone import CloneSchema from .postgresql_backend.base import _check_sc...
def save(self, verbosity=1, *args, **kwargs): connection = connections[get_tenant_database_alias()] is_new = self.pk is None has_schema = hasattr(connection, 'schema_name') if has_schema and is_new and connection.schema_name != get_public_schema_name(): raise Exception("...
connection.set_schema_to_public()
random_line_split
models.py
from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.core.management import call_command from django.db import models, connections, transaction from django.urls import reverse from django_tenants.clone import CloneSchema from .postgresql_backend.base import _check_sc...
else: # create the schema cursor.execute('CREATE SCHEMA "%s"' % self.schema_name) call_command('migrate_schemas', tenant=True, schema_name=self.schema_name, interactive=Fal...
base_schema = get_tenant_base_schema() clone_schema = CloneSchema() clone_schema.clone_schema(base_schema, self.schema_name) call_command('migrate_schemas', tenant=True, fake=True, sch...
conditional_block
models.py
from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.core.management import call_command from django.db import models, connections, transaction from django.urls import reverse from django_tenants.clone import CloneSchema from .postgresql_backend.base import _check_sc...
(self, force_drop=False): """ Drops the schema""" connection = connections[get_tenant_database_alias()] has_schema = hasattr(connection, 'schema_name') if has_schema and connection.schema_name not in (self.schema_name, get_public_schema_name()): raise Exception("Can't delete ...
_drop_schema
identifier_name
test_request.py
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Description: File system resilience testing application # Author: Hubert Kario <hubert@kario.pl> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Copyright (c) 2015 Hubert Kario. All rights reserved. # # This ...
def test_send_read(self): raw_sock = mock.MagicMock() raw_sock.sendall.return_value = None cmd = NBDRequest(0, 0x134, 0, 0x4000) sock = NBDRequestSocket(raw_sock) sock.send(cmd) raw_sock.sendall.assert_called_once_with(compat_str(bytearray( b'\x25\x60\x...
sock.recv()
random_line_split
test_request.py
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Description: File system resilience testing application # Author: Hubert Kario <hubert@kario.pl> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Copyright (c) 2015 Hubert Kario. All rights reserved. # # This ...
(self): raw_sock = mock.MagicMock() raw_sock.sendall.return_value = None cmd = NBDRequest(0, 0x134, 0, 0x4000) sock = NBDRequestSocket(raw_sock) sock.send(cmd) raw_sock.sendall.assert_called_once_with(compat_str(bytearray( b'\x25\x60\x95\x13' b'\...
test_send_read
identifier_name
test_request.py
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Description: File system resilience testing application # Author: Hubert Kario <hubert@kario.pl> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Copyright (c) 2015 Hubert Kario. All rights reserved. # # This ...
@mock.patch('fsresck.nbd.request.recvexactly') def test_recv_write(self, mock_mthd): mock_mthd.side_effect = (bytearray( b'\x25\x60\x95\x13' # magic value b'\x00\x00\x00\x01' # command type - write b'\x50\xe4\x93\x01\x00\x88\xff\xff' # handle ...
mock_mthd.return_value = bytearray( b'\x25\x60\x95\x13' # magic value b'\x00\x00\x00\x00' # command type - read b'\x50\xe4\x93\x01\x00\x88\xff\xff' # handle b'\x00\x00\x00\x00\x00\x00\x00\x00' # offset b'\x00\x00\x40\x00' # length ...
identifier_body
checkwholepdb.py
# Test which PDB entries error on PDB/mmCIF parsers # Writes output to a file labelled with the week import os from datetime import datetime from math import ceil from Bio.PDB import PDBList from Bio.PDB.PDBParser import PDBParser from Bio.PDB.MMCIFParser import MMCIFParser start = datetime.now() basedir = "."
outstrs = ["Checking all PDB entries at {}".format(start.isoformat()), "Checking {} entries".format(len(pdblist))] pdb_parser = PDBParser() mmcif_parser = MMCIFParser() for pu in sorted(pdblist): p = pu.lower() try: pdbl.retrieve_pdb_file(p, pdir=basedir, file_format="pdb") except: ...
pdbl = PDBList() pdblist = pdbl.get_all_entries()
random_line_split
checkwholepdb.py
# Test which PDB entries error on PDB/mmCIF parsers # Writes output to a file labelled with the week import os from datetime import datetime from math import ceil from Bio.PDB import PDBList from Bio.PDB.PDBParser import PDBParser from Bio.PDB.MMCIFParser import MMCIFParser start = datetime.now() basedir = "." pdbl =...
if len(outstrs) == 2: outstrs.append("All entries read fine") end = datetime.now() outstrs.append("Time taken - {} minute(s)".format(int(ceil((end - start).seconds / 60)))) datestr = str(end.date()).replace("-", "") # This overwrites any existing file with open("{}/wholepdb_py_{}.txt".format(basedir, datestr), ...
try: s = mmcif_parser.get_structure("", "{}/{}.cif".format(basedir, p)) except: outstrs.append("{} - mmCIF parsing error".format(pu)) os.remove("{}/{}.cif".format(basedir, p))
conditional_block
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages classifiers = [ # Get more strings from # http://pypi.python.org/pypi?%3Aaction=list_classifiers "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Programmi...
description="Use your Arduino board with Python", license="MIT", author="Andrea Stagi", author_email="stagi.andrea@gmail.com", url="http://github.com/nanpy/nanpy", packages = find_packages(), keywords= "arduino library prototype", install_requires=[ "pyserial", ...
random_line_split
test_utils.py
# -*- coding: utf-8 -*- """swiftsc.utils unit tests.""" import unittest from swiftsc import utils as u from swiftsc.tests import test_vars as v class UtilsTests(unittest.TestCase): """Unit test of utils.py""" def test_check_mimetype(self):
def test_check_mimetype_buffer(self): """test checking mimetype of buffer""" fileobj = open(v.TEST_FILE, 'rb') self.assertEqual(v.TEST_FILE_MIMETYPE, u.check_mimetype_buffer(fileobj)) fileobj.close() def test_retrieve_info_from_buffer(self): ""...
"""test checking mimetype""" self.assertEqual(v.TEST_FILE_MIMETYPE, u.check_mimetype(v.TEST_FILE))
identifier_body
test_utils.py
# -*- coding: utf-8 -*- """swiftsc.utils unit tests.""" import unittest from swiftsc import utils as u from swiftsc.tests import test_vars as v
class UtilsTests(unittest.TestCase): """Unit test of utils.py""" def test_check_mimetype(self): """test checking mimetype""" self.assertEqual(v.TEST_FILE_MIMETYPE, u.check_mimetype(v.TEST_FILE)) def test_check_mimetype_buffer(self): """test checking mimet...
random_line_split
test_utils.py
# -*- coding: utf-8 -*- """swiftsc.utils unit tests.""" import unittest from swiftsc import utils as u from swiftsc.tests import test_vars as v class UtilsTests(unittest.TestCase): """Unit test of utils.py""" def test_check_mimetype(self): """test checking mimetype""" self.assertEqual(v.TEST...
(self): """test checking mimetype of buffer""" fileobj = open(v.TEST_FILE, 'rb') self.assertEqual(v.TEST_FILE_MIMETYPE, u.check_mimetype_buffer(fileobj)) fileobj.close() def test_retrieve_info_from_buffer(self): """test retriving info from buffer""" ...
test_check_mimetype_buffer
identifier_name
play_game.rs
use ai2048_lib::game_logic::Grid; use ai2048_lib::searcher::{self, SearchResult}; use criterion::Criterion; use criterion::{criterion_group, criterion_main}; use lazy_static::lazy_static; const MIN_PROBABILITY: f32 = 0.0001;
fn calc_move(start: Grid) -> SearchResult { searcher::search(start, MIN_PROBABILITY) } lazy_static! { static ref GRID_DEFAULT: Grid = Grid::default().add_random_tile(); static ref GRID_DEPTH_8: Grid = { let grid = Grid::from_human([ [8, 2, 4, 2], [32, 32, 4, 2], ...
random_line_split
play_game.rs
use ai2048_lib::game_logic::Grid; use ai2048_lib::searcher::{self, SearchResult}; use criterion::Criterion; use criterion::{criterion_group, criterion_main}; use lazy_static::lazy_static; const MIN_PROBABILITY: f32 = 0.0001; fn calc_move(start: Grid) -> SearchResult { searcher::search(start, MIN_PROBABILITY) } l...
(c: &mut Criterion) { c.bench_function("depth 8 move", move |b| b.iter(|| calc_move(*GRID_DEPTH_8))); } criterion_group! { name = large_sample; config = Criterion::default().sample_size(10); targets = single_moves } criterion_main!(large_sample);
single_moves
identifier_name
play_game.rs
use ai2048_lib::game_logic::Grid; use ai2048_lib::searcher::{self, SearchResult}; use criterion::Criterion; use criterion::{criterion_group, criterion_main}; use lazy_static::lazy_static; const MIN_PROBABILITY: f32 = 0.0001; fn calc_move(start: Grid) -> SearchResult
lazy_static! { static ref GRID_DEFAULT: Grid = Grid::default().add_random_tile(); static ref GRID_DEPTH_8: Grid = { let grid = Grid::from_human([ [8, 2, 4, 2], [32, 32, 4, 2], [512, 128, 64, 2], [1024, 256, 16, 0], ]) .expect("couldn't pa...
{ searcher::search(start, MIN_PROBABILITY) }
identifier_body
PortraitScriptLine.ts
/* * Copyright (C) 2016 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ /** * A portrait animation script line. */ export class PortraitScriptLine { /** The delay in time units. */ private readonly delay: number; /** The index of the animation update to apply. */ private ...
/** * Returns the index of the animation update to apply. * * @return The animation update index. */ public getUpdate(): number { return this.update; } }
{ return this.delay; }
identifier_body
PortraitScriptLine.ts
/* * Copyright (C) 2016 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ /** * A portrait animation script line. */ export class PortraitScriptLine { /** The delay in time units. */ private readonly delay: number; /** The index of the animation update to apply. */ private ...
(delay: number, update: number) { this.delay = delay; this.update = update; } /** * Returns the delay in time units. It is unknown how long a time unit really is in the game but a good * approximation is 50 milliseconds. * * @return The delay in time units. */ publi...
constructor
identifier_name
PortraitScriptLine.ts
/* * Copyright (C) 2016 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ /** * A portrait animation script line. */ export class PortraitScriptLine { /** The delay in time units. */ private readonly delay: number; /** The index of the animation update to apply. */ private ...
* @param update The index of the animation update to apply. */ public constructor(delay: number, update: number) { this.delay = delay; this.update = update; } /** * Returns the delay in time units. It is unknown how long a time unit really is in the game but a good * ap...
* * @param delay The delay in time units.
random_line_split
accretion.py
#!/usr/bin/env python # ----------------------------------------------------------------------------- # VORONOI.ACCRETION # Laura L Watkins [lauralwatkins@gmail.com] # - converted from IDL code by Michele Cappellari (bin2d_accretion) # ----------------------------------------------------------------------------- from ...
currentbin = nextbin # update the centroid of the current bin xbar = x[currentbin].mean() ybar = y[currentbin].mean() # get the centroid of all the binned pixels binned = where(clas != 0)[0] unbinned = where(clas == 0)[0] ...
random_line_split
accretion.py
#!/usr/bin/env python # ----------------------------------------------------------------------------- # VORONOI.ACCRETION # Laura L Watkins [lauralwatkins@gmail.com] # - converted from IDL code by Michele Cappellari (bin2d_accretion) # ----------------------------------------------------------------------------- from ...
(x, y, signal, noise, targetsn, pixelsize=False, quiet=False): """ Initial binning -- steps i-v of eq 5.1 of Cappellari & Copin (2003) INPUTS: x : x coordinates of pixels to bin y : y coordinates of pixels to bin signal : signal associated with each pixel no...
accretion
identifier_name
accretion.py
#!/usr/bin/env python # ----------------------------------------------------------------------------- # VORONOI.ACCRETION # Laura L Watkins [lauralwatkins@gmail.com] # - converted from IDL code by Michele Cappellari (bin2d_accretion) # ----------------------------------------------------------------------------- from ...
# for each point, find distance to all other points and select minimum # (robust but slow way of determining the pixel size of unbinned data) if not pixelsize: dx = 1.e30 for j in range(x.size-1): d = (x[j] - x[j+1:])**2 + (y[j] - y[j+1:])**2 dx = min(d.min(), dx) ...
""" Initial binning -- steps i-v of eq 5.1 of Cappellari & Copin (2003) INPUTS: x : x coordinates of pixels to bin y : y coordinates of pixels to bin signal : signal associated with each pixel noise : noise (1-sigma error) associated with each pixel targetsn...
identifier_body
accretion.py
#!/usr/bin/env python # ----------------------------------------------------------------------------- # VORONOI.ACCRETION # Laura L Watkins [lauralwatkins@gmail.com] # - converted from IDL code by Michele Cappellari (bin2d_accretion) # ----------------------------------------------------------------------------- from ...
# find unbinned pixel closest to centroid of current bin dist = (x[unbinned]-xbar)**2 + (y[unbinned]-ybar)**2 mindist = dist.min() k = dist.argmin() # find the distance from the closest pixel to the current bin mindist = ...
break
conditional_block
create_init_file.py
## Package for various utility functions to execute build and shell commands # # @copyright (c) 2007 CSIRO # Australia Telescope National Facility (ATNF) # Commonwealth Scientific and Industrial Research Organisation (CSIRO) # PO Box 76, Epping NSW 1710, Australia # atnf-enquiries@csiro.au # # This file is part of the ...
if not v: continue if k == "LD_LIBRARY_PATH": k = env.ld_prefix+k v = v.replace(aroot, '${ASKAP_ROOT}') initfile.write(vartxt % { 'key': k, 'value': v } )
conditional_block
create_init_file.py
## Package for various utility functions to execute build and shell commands # # @copyright (c) 2007 CSIRO # Australia Telescope National Facility (ATNF) # Commonwealth Scientific and Industrial Research Organisation (CSIRO) # PO Box 76, Epping NSW 1710, Australia # atnf-enquiries@csiro.au # # This file is part of the ...
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along ...
# published by the Free Software Foundation; either version 2 of the License # or (at your option) any later version. #
random_line_split
create_init_file.py
## Package for various utility functions to execute build and shell commands # # @copyright (c) 2007 CSIRO # Australia Telescope National Facility (ATNF) # Commonwealth Scientific and Industrial Research Organisation (CSIRO) # PO Box 76, Epping NSW 1710, Australia # atnf-enquiries@csiro.au # # This file is part of the ...
(name, env): ''' Create package initialization file. e.g. init_package_env.sh :param name: file name to be created. :type name: string :param env: the environment object. :type env: :class:`.Environment` :return: None ''' aroot = os.environ["ASKAP_ROOT"] inittxt= """# # ASKAP au...
create_init_file
identifier_name
create_init_file.py
## Package for various utility functions to execute build and shell commands # # @copyright (c) 2007 CSIRO # Australia Telescope National Facility (ATNF) # Commonwealth Scientific and Industrial Research Organisation (CSIRO) # PO Box 76, Epping NSW 1710, Australia # atnf-enquiries@csiro.au # # This file is part of the ...
else %(key)s=%(value)s fi export %(key)s """ with open(name, 'w') as initfile: initfile.write(inittxt) for k, v in env.items(): if not v: continue if k == "LD_LIBRARY_PATH": k = env.ld_prefix+k v = v.replace(aroot, '${ASKAP_ROO...
''' Create package initialization file. e.g. init_package_env.sh :param name: file name to be created. :type name: string :param env: the environment object. :type env: :class:`.Environment` :return: None ''' aroot = os.environ["ASKAP_ROOT"] inittxt= """# # ASKAP auto-generated file...
identifier_body
62-flag-narrowing.ts
/*@ predicate non_zero(b) = (b /= lit "#x00000000" (BitVec (Size32))) */ /*@ predicate mask_symbolflags_transient(v) = (non_zero(bvand v (lit "#x02000000" (BitVec (Size32))))) */ type ISymbol = Symbol<Immutable> type ISymbolLinks = SymbolLinks<Immutable>
} export interface Symbol<M extends ReadOnly> { /*@ (Immutable) flags: { v: bitvector32 | mask_symbolflags_transient v <=> extends_interface this "TransientSymbol" } */ flags: SymbolFlags; } export interface SymbolLinks<M extends ReadOnly> { } export interface TransientSymbol<M extends ReadOnly> extends Sy...
export enum SymbolFlags { Transient = 0x02000000
random_line_split
62-flag-narrowing.ts
/*@ predicate non_zero(b) = (b /= lit "#x00000000" (BitVec (Size32))) */ /*@ predicate mask_symbolflags_transient(v) = (non_zero(bvand v (lit "#x02000000" (BitVec (Size32))))) */ type ISymbol = Symbol<Immutable> type ISymbolLinks = SymbolLinks<Immutable> export enum SymbolFlags { Transient = 0x02000000 } e...
throw new Error("") }
{ return <TransientSymbol<Immutable>>symbol; }
conditional_block
example.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Example = mongoose.model('Example'), _ = require('lodash'), upload = require('./upload'); /** * Find example by id
if (!example) return next(new Error('Failed to load example ' + id)); req.example = example; next(); }); }; /** * Create a example */ exports.create = function(req, res) { var example = new Example(req.body); example.user = req.user; example.save(function(err) { if ...
*/ exports.example = function(req, res, next, id) { Example.load(id, function(err, example) { if (err) return next(err);
random_line_split
example.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Example = mongoose.model('Example'), _ = require('lodash'), upload = require('./upload'); /** * Find example by id */ exports.example = function(req, res, next, id) { Example.load(id, function(err, example) { ...
else { res.jsonp(example); } }); }; /** * Show an example */ exports.show = function(req, res) { res.jsonp(req.example); }; /** * List of Examples */ exports.all = function(req, res) { Example.find().sort('-created').populate('user', 'name username').exec(function(err, examples) ...
{ return res.send('/login', { errors: err.errors, example: example }); }
conditional_block
use-selected-site-selector.ts
import { useSelector } from 'react-redux'; import { getSelectedSiteId } from 'calypso/state/ui/selectors'; import type { AppState } from 'calypso/types'; export type SelectedSiteSelector< Params extends any[], Result > = ( state: AppState, siteId: ReturnType< typeof getSelectedSiteId >, ...args: Params ) => Result;...
< Params extends any[], Result >( selector: SelectedSiteSelector< Params, Result >, ...args: Params ): Result { return useSelector( ( state ) => selector( state, getSelectedSiteId( state ), ...args ) ); }
useSelectedSiteSelector
identifier_name
use-selected-site-selector.ts
import { useSelector } from 'react-redux'; import { getSelectedSiteId } from 'calypso/state/ui/selectors'; import type { AppState } from 'calypso/types'; export type SelectedSiteSelector< Params extends any[], Result > = ( state: AppState, siteId: ReturnType< typeof getSelectedSiteId >, ...args: Params ) => Result;...
{ return useSelector( ( state ) => selector( state, getSelectedSiteId( state ), ...args ) ); }
identifier_body
use-selected-site-selector.ts
import { useSelector } from 'react-redux'; import { getSelectedSiteId } from 'calypso/state/ui/selectors'; import type { AppState } from 'calypso/types'; export type SelectedSiteSelector< Params extends any[], Result > = ( state: AppState, siteId: ReturnType< typeof getSelectedSiteId >, ...args: Params ) => Result;...
* Wraps useSelector and closes over the getSelectedSiteId step when using selected site selectors. * * Usage: * * useSelectedSiteSelector( isJetpackSite ); * useSelectedSiteSelector( hasAvailableSiteFeature, FEATURE_WP_SUBDOMAIN ); * * @param selector A selector that takes state, a site id and any additiona...
/**
random_line_split
refextract_cli.py
defined here to begin the extraction of references """ __revision__ = "$Id$" import traceback import optparse import sys from invenio.docextract_record import print_records from invenio.docextract_utils import write_message, setup_loggers from invenio.bibtask import task_update_progress from invenio.refextract...
if len(subfield.value) > 2048: subfield.value = subfield.value[:2048]
conditional_block
refextract_cli.py
2 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have re...
# Help message, used by bibtask's 'task_init()' and 'usage()' HELP_MESSAGE = """ --kb-journals Manually specify the location of a journal title knowledge-base file. --kb-journals-re Manually specify the location of a journal title regexps knowledge-base file...
DESCRIPTION = ""
random_line_split
refextract_cli.py
2 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have re...
def begin_extraction(config, files): """Starts the core extraction procedure. [Entry point from main] Only refextract_daemon calls this directly, from _task_run_core() @param daemon_cli_options: contains the pre-assembled list of cli flags and values processed by the Refextract Daemon. This...
"""Extract references from one file""" # If necessary, locate the reference section: if config.treat_as_reference_section: docbody = open(pdf_path).read().decode('utf-8') record = extract_references_from_string(docbody) else: write_message("* processing pdffile: %s" % pdf_path, verbo...
identifier_body
refextract_cli.py
2 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have re...
(wmsg=None, err_code=0): """Display a usage message for refextract on the standard error stream and then exit. @param wmsg: (string) some kind of brief warning message for the user. @param err_code: (integer) an error code to be passed to halt, which is called after the usage message ha...
usage
identifier_name
app.ts
import {Router, RouterConfiguration} from 'aurelia-router'; import { PLATFORM } from 'aurelia-pal'; export class App { constructor(private router: Router) { } configureRouter(config: RouterConfiguration, router: Router) { config.title = 'Aurelia'; config.options.pushState = true; ...
this.router = router; } }
{ route: ['posts'], name: 'posts', moduleId: PLATFORM.moduleName('./posts'), title: 'Posts' } ]);
random_line_split
app.ts
import {Router, RouterConfiguration} from 'aurelia-router'; import { PLATFORM } from 'aurelia-pal'; export class App { constructor(private router: Router) { } configureRouter(config: RouterConfiguration, router: Router)
}
{ config.title = 'Aurelia'; config.options.pushState = true; config.map([ { route: [''], name: 'homepage', moduleId: PLATFORM.moduleName('./homepage'), title:'Homepage' }, { route: ['page/:id'], name: 'page', moduleId: PLATFORM.moduleName('./page'), title: 'Page' }, ...
identifier_body
app.ts
import {Router, RouterConfiguration} from 'aurelia-router'; import { PLATFORM } from 'aurelia-pal'; export class
{ constructor(private router: Router) { } configureRouter(config: RouterConfiguration, router: Router) { config.title = 'Aurelia'; config.options.pushState = true; config.map([ { route: [''], name: 'homepage', moduleId: PLATFORM.moduleName('./homepage'), title:'Homepa...
App
identifier_name
sctc.py
import pyglet import tkinter WINDOW_WIDTH = 800 # x WINDOW_HEIGHT = 600 # y LEVEL = 6 # original was 4 X_SIZE = 2 * LEVEL Y_SIZE = 3 * LEVEL def get_resolution(): root = tkinter.Tk() return root.winfo_screenwidth(), root.winfo_screenheight() def get_position(x, y): return ((x // X_SIZE) * X_SIZE, ...
if abs(dy) > 0: self.y = self.y + dy replot = True if replot: self.cursor.vertices = cursor(get_position(self.x, self.y)) def on_mouse_release(self, x, y, button, modifiers): if button == pyglet.window.mouse.LEFT: Rail(self.batch, get_positio...
random_line_split
sctc.py
import pyglet import tkinter WINDOW_WIDTH = 800 # x WINDOW_HEIGHT = 600 # y LEVEL = 6 # original was 4 X_SIZE = 2 * LEVEL Y_SIZE = 3 * LEVEL def get_resolution(): root = tkinter.Tk() return root.winfo_screenwidth(), root.winfo_screenheight() def get_position(x, y): return ((x // X_SIZE) * X_SIZE, ...
def on_mouse_motion(self, x, y, dx, dy): replot = False if self.x == -1 and self.y == -1: pos = get_position(x, y) self.cursor = self.batch.add(8, pyglet.gl.GL_LINES, None, ('v2f', cursor(pos)), ...
def __init__(self, **kwargs): kwargs.update(dict( caption='SimCTC', )) super(AppWin, self).__init__(**kwargs) self.batch = pyglet.graphics.Batch() self.x = -1 self.y = -1 for m in range(0, WINDOW_WIDTH+1, X_SIZE): for n in range(0, WINDO...
identifier_body
sctc.py
import pyglet import tkinter WINDOW_WIDTH = 800 # x WINDOW_HEIGHT = 600 # y LEVEL = 6 # original was 4 X_SIZE = 2 * LEVEL Y_SIZE = 3 * LEVEL def get_resolution(): root = tkinter.Tk() return root.winfo_screenwidth(), root.winfo_screenheight() def get_position(x, y): return ((x // X_SIZE) * X_SIZE, ...
def on_mouse_release(self, x, y, button, modifiers): if button == pyglet.window.mouse.LEFT: Rail(self.batch, get_position(self.x, self.y)) if __name__ == '__main__': window = AppWin(width=WINDOW_WIDTH, height=WINDOW_HEIGHT) window.set_exclusive_mouse(True) window.set_mouse_visible...
self.cursor.vertices = cursor(get_position(self.x, self.y))
conditional_block
sctc.py
import pyglet import tkinter WINDOW_WIDTH = 800 # x WINDOW_HEIGHT = 600 # y LEVEL = 6 # original was 4 X_SIZE = 2 * LEVEL Y_SIZE = 3 * LEVEL def get_resolution(): root = tkinter.Tk() return root.winfo_screenwidth(), root.winfo_screenheight() def get_position(x, y): return ((x // X_SIZE) * X_SIZE, ...
(self, batch, pos): x1 = pos[0] x2 = x1 + X_SIZE y1 = pos[1] + Y_SIZE / 2 batch.add(6, pyglet.gl.GL_LINES, None, ('v2f', [x1, y1-1, x2, y1-1, x1, y1, x2, y1, x1, y1+1, x2, y1+1]), ('c3B', (177, 57...
__init__
identifier_name
lib.dom.iterable.d.ts
/*! ***************************************************************************** Copyright (c) Microsoft Corporation. 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...
/// <reference no-default-lib="true"/> /// <reference path="lib.dom.d.ts" /> interface DOMTokenList { [Symbol.iterator](): IterableIterator<string>; } interface Headers { [Symbol.iterator](): IterableIterator<[string, string]>; /** * Returns an iterator allowing to go through all key/value pairs ...
and limitations under the License. ***************************************************************************** */
random_line_split
properties_65.js
var searchData= [ ['endinghash',['endingHash',['../interface_model.html#a3a3aa4972b9e878cf839228535944a82',1,'Model']]],
['endpoint',['endPoint',['../interface_causal_link_view.html#a8182eda9bbf2964ae5df72b56cabffb0',1,'CausalLinkView::endPoint()'],['../interface_new_causal_link.html#a8182eda9bbf2964ae5df72b56cabffb0',1,'NewCausalLink::endPoint()']]], ['events',['events',['../interface_event_logger.html#a67a1a529ac51538c28ff99617238e...
random_line_split
vector.rs
/// A trait for describing vector operations used by vectorized searchers. /// /// The trait is highly constrained to low level vector operations needed. In /// general, it was invented mostly to be generic over x86's __m128i and /// __m256i types. It's likely that once std::simd becomes a thing, we can /// migrate to ...
#[inline(always)] unsafe fn load_unaligned(data: *const u8) -> __m128i { _mm_loadu_si128(data as *const __m128i) } #[inline(always)] unsafe fn movemask(self) -> u32 { _mm_movemask_epi8(self) as u32 } #[inline(always)] unsafe fn ...
{ _mm_set1_epi8(byte as i8) }
identifier_body
vector.rs
/// A trait for describing vector operations used by vectorized searchers. /// /// The trait is highly constrained to low level vector operations needed. In /// general, it was invented mostly to be generic over x86's __m128i and /// __m256i types. It's likely that once std::simd becomes a thing, we can /// migrate to ...
#[inline(always)] unsafe fn and(self, vector2: Self) -> __m256i { _mm256_and_si256(self, vector2) } } }
random_line_split
vector.rs
/// A trait for describing vector operations used by vectorized searchers. /// /// The trait is highly constrained to low level vector operations needed. In /// general, it was invented mostly to be generic over x86's __m128i and /// __m256i types. It's likely that once std::simd becomes a thing, we can /// migrate to ...
(self, vector2: Self) -> __m128i { _mm_and_si128(self, vector2) } } } #[cfg(all(feature = "std", target_arch = "x86_64"))] mod x86avx { use super::Vector; use core::arch::x86_64::*; impl Vector for __m256i { #[inline(always)] unsafe fn splat(byte: u8) -> __m256i { ...
and
identifier_name
out_parameters.rs
use crate::{ analysis::{ self, conversion_type::ConversionType, function_parameters::CParameter, functions::is_carray_with_direct_elements, imports::Imports, return_value, rust_type::RustType, }, config::{self, parameter_matchable::ParameterMatchable}, env::Env, library::{ ...
.find(|c_par| c_par.name == lib_par.name) { out.lib_par.typ = c_par.typ; out.lib_par.nullable = c_par.nullable; } info.params.push(out); } else { unsupported_outs = true; } } if info.params.is_empty...
random_line_split
out_parameters.rs
use crate::{ analysis::{ self, conversion_type::ConversionType, function_parameters::CParameter, functions::is_carray_with_direct_elements, imports::Imports, return_value, rust_type::RustType, }, config::{self, parameter_matchable::ParameterMatchable}, env::Env, library::{ ...
( env: &Env, ret: &return_value::Info, func_name: &str, configured_functions: &[&config::functions::Function], ) -> bool { let typ = ret .parameter .as_ref() .map(|par| par.lib_par.typ) .unwrap_or_default(); use_function_return_for_result(env, typ, func_name, conf...
use_return_value_for_result
identifier_name
integer-tests.ts
import Integer = require("integer"); let num0: Integer.IntClass = Integer(0); num0 = num0.add(10); num0 = num0.add("10"); num0 = num0.add(num0); let num1: Integer.IntClass = Integer.fromBits(0xff); num1.compare(num0); const num2: Integer.IntClass = Integer.fromBits(0xff, 0xff); num1 = num1.shl(32); const num3: Integer...
const num6: Integer.IntClass = Integer.fromString("ff", 16); let num7: Integer.IntClass = Integer.fromString("ff", 16, "255"); num7 = Integer.fromString("ff", 16, num5); Integer(Integer(123));
random_line_split
s3-cnpm.js
/** @license MIT License (c) copyright 2014 original authors */ /** @author Karolis Narkevicius */ var path = require('path'); var knox = require('knox-s3'); var when = require('when'); var thunkify = require('thunkify'); var cp = require('fs-cp'); module.exports = function (config) { return new S3(config); }; /**...
(config) { this.config = config; this.client = knox.createClient(this.config); this.client.getFile = thunkify(this.client.getFile); this.client.deleteFile = thunkify(this.client.deleteFile); } /** * Upload a package from filepath to S3. * * @param {String} filepath the path of the file to upload * @param {...
S3
identifier_name
s3-cnpm.js
/** @license MIT License (c) copyright 2014 original authors */ /** @author Karolis Narkevicius */ var path = require('path'); var knox = require('knox-s3'); var when = require('when'); var thunkify = require('thunkify'); var cp = require('fs-cp'); module.exports = function (config) { return new S3(config); }; /**...
var filepath = this.getPath(options.key); var headers = { 'Content-Type': 'application/x-gzip' }; yield when.promise(function (resolve, reject) { client.putBuffer(content, filepath, headers, function(err, res) { if (err) return reject(err); if (res.statusCode !== 200) return reject(new Erro...
* @api public */ S3.prototype.uploadBuffer = function* (content, options) { var client = this.client;
random_line_split
s3-cnpm.js
/** @license MIT License (c) copyright 2014 original authors */ /** @author Karolis Narkevicius */ var path = require('path'); var knox = require('knox-s3'); var when = require('when'); var thunkify = require('thunkify'); var cp = require('fs-cp'); module.exports = function (config) { return new S3(config); }; /**...
/** * Upload a package from filepath to S3. * * @param {String} filepath the path of the file to upload * @param {Object} options with key and size * @return {Object} an object with the key * @api public */ S3.prototype.upload = function* (filepath, options) { var s3Config = this.config; var client = this...
{ this.config = config; this.client = knox.createClient(this.config); this.client.getFile = thunkify(this.client.getFile); this.client.deleteFile = thunkify(this.client.deleteFile); }
identifier_body
tables.py
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # 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 requir...
class DomainsTable(tables.DataTable): name = tables.Column('name', verbose_name=_('Name')) description = tables.Column(lambda obj: getattr(obj, 'description', None), verbose_name=_('Description')) id = tables.Column('id', verbose_name=_('Domain ID')) enabled = tables.C...
request.session.pop("domain_context") request.session.pop("domain_context_name") messages.success(request, _('Domain Context cleared.'))
conditional_block
tables.py
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # 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 requir...
: name = "domains" verbose_name = _("Domains") row_actions = (SetDomainContext, ViewGroupsLink, EditDomainLink, DeleteDomainsAction) table_actions = (DomainFilterAction, CreateDomainLink, DeleteDomainsAction, UnsetDomainContext)
Meta
identifier_name
tables.py
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # 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 requir...
class DomainsTable(tables.DataTable): name = tables.Column('name', verbose_name=_('Name')) description = tables.Column(lambda obj: getattr(obj, 'description', None), verbose_name=_('Description')) id = tables.Column('id', verbose_name=_('Domain ID')) enabled = tables.Col...
messages.success(request, _('Domain Context cleared.'))
random_line_split
tables.py
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # 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 requir...
class CreateDomainLink(tables.LinkAction): name = "create" verbose_name = _("Create Domain") url = constants.DOMAINS_CREATE_URL classes = ("ajax-modal",) icon = "plus" policy_rules = (('identity', 'identity:create_domain'),) def allowed(self, request, domain): return api.keystone...
name = "groups" verbose_name = _("Modify Groups") url = "horizon:admin:domains:update" classes = ("ajax-modal",) icon = "pencil" def get_link_url(self, domain): step = 'update_group_members' base_url = reverse(self.url, args=[domain.id]) param = urlencode({"step": step}) ...
identifier_body
docente-model.js
define(['backbone', 'underscore'], function (Backbone, _) {
defaults: { persona: { personaPnombre: '', personaSnombre: '', personaApaterno: '', personaAmaterno: '', dni: '' } }, validate: function (attrs, options) { console.log('persona', attrs.persona); if (_.isUndefined(attrs.persona)) { return { field: 'persona', error: 'De...
return Backbone.Model.extend({ idAttribute: 'username',
random_line_split
docente-model.js
define(['backbone', 'underscore'], function (Backbone, _) { return Backbone.Model.extend({ idAttribute: 'username', defaults: { persona: { personaPnombre: '', personaSnombre: '', personaApaterno: '', personaAmaterno: '', dni: '' } }, validate: function (attrs, options) { console.lo...
if (_.isUndefined(attrs.persona.personaAmaterno) || _.isEmpty(attrs.persona.personaAmaterno.trim())) { return { field: 'persona-personaAmaterno', error: 'El apellido materno es un campo obligatorio.' }; } } }); });
{ return { field: 'persona-personaApaterno', error: 'El apellido paterno es un campo obligatorio.' }; }
conditional_block
connection.rs
// Distributed under the OSI-approved BSD 3-Clause License. // See accompanying LICENSE file for details. use crates::dbus_bytestream::connection; use error::*; use message::{Message, MessageType}; use value::{BasicValue, Value}; bitflags! { /// Flags for use when requesting a name on the bus from the bus. p...
} } else { bail!(ErrorKind::InvalidReply("ReleaseName: no response".to_string())); } } /// Requests the server to route messages to this connection. /// /// By default, the server will not deliver any messages to this connection. In order to /// receive messa...
random_line_split
connection.rs
// Distributed under the OSI-approved BSD 3-Clause License. // See accompanying LICENSE file for details. use crates::dbus_bytestream::connection; use error::*; use message::{Message, MessageType}; use value::{BasicValue, Value}; bitflags! { /// Flags for use when requesting a name on the bus from the bus. p...
() -> Result<Self> { Ok(Connection { conn: connection::Connection::connect_system()?, }) } /// Request a name on the bus. /// /// By default, the name to address this connection directly is assigned by the daemon managing /// the bus, but a name for the application may b...
system_new
identifier_name
connection.rs
// Distributed under the OSI-approved BSD 3-Clause License. // See accompanying LICENSE file for details. use crates::dbus_bytestream::connection; use error::*; use message::{Message, MessageType}; use value::{BasicValue, Value}; bitflags! { /// Flags for use when requesting a name on the bus from the bus. p...
} else { bail!(ErrorKind::InvalidReply("RequestName: no response".to_string())); } } /// Release a name on the bus. pub fn release_name(&self, name: &str) -> Result<ReleaseNameReply> { // TODO: Use an actual struct with an API for this. let msg = Message::new_me...
{ bail!(ErrorKind::InvalidReply("RequestName: invalid response".to_string())); }
conditional_block
part2.rs
// adventofcode - day 16 // part 2 use std::io::prelude::*; use std::fs::File; use std::str::FromStr; struct Aunt { id: i32, children: i32, cats: i32, samoyeds: i32, pomeranians: i32, akitas: i32, vizslas: i32, goldfish: i32, trees: i32, cars: i32, perfumes: i32, } impl Au...
() -> String { let mut file = match File::open("../../inputs/16.txt") { Ok(f) => f, Err(e) => panic!("file error: {}", e), }; let mut data = String::new(); match file.read_to_string(&mut data){ Ok(_) => {}, Err(e) => panic!("file error: {}", e), }; data }
import_data
identifier_name
part2.rs
// adventofcode - day 16 // part 2 use std::io::prelude::*; use std::fs::File; use std::str::FromStr; struct Aunt { id: i32, children: i32, cats: i32, samoyeds: i32, pomeranians: i32, akitas: i32, vizslas: i32, goldfish: i32, trees: i32, cars: i32, perfumes: i32, } impl Au...
}; let mut linecount = 1i32; for mut line in data.lines(){ let aunt = parse_line(&mut line, linecount); if aunt.matches(&giver) { aunts.push( aunt ); } linecount += 1; } let matches = aunts.len(); for aunt in aunts { aunt.print(); } ...
{ println!("Advent of Code - day 16 | part 2"); // import data let data = import_data(); let mut aunts = Vec::new(); let giver = Aunt{ id: 0, children: 3, cats: 7, samoyeds: 2, pomeranians: 3, akitas: 0, vizslas: 0, goldfish: 5, ...
identifier_body
part2.rs
// adventofcode - day 16 // part 2 use std::io::prelude::*; use std::fs::File; use std::str::FromStr; struct Aunt { id: i32, children: i32, cats: i32, samoyeds: i32, pomeranians: i32, akitas: i32, vizslas: i32, goldfish: i32, trees: i32, cars: i32, perfumes: i32, } impl Au...
false } fn print(&self) { print!("Sue {}: ", self.id); print!("{} children, ", self.children); print!("{} cats, ", self.cats); print!("{} samoyeds, ", self.samoyeds); print!("{} pomeranians, ", self.pomeranians); print!("{} akitas, ", self.akitas); ...
{ return true; }
conditional_block
part2.rs
// adventofcode - day 16 // part 2 use std::io::prelude::*; use std::fs::File; use std::str::FromStr; struct Aunt { id: i32, children: i32, cats: i32, samoyeds: i32, pomeranians: i32, akitas: i32, vizslas: i32, goldfish: i32, trees: i32, cars: i32, perfumes: i32, } impl Au...
false } fn print(&self) { print!("Sue {}: ", self.id); print!("{} children, ", self.children); print!("{} cats, ", self.cats); print!("{} samoyeds, ", self.samoyeds); print!("{} pomeranians, ", self.pomeranians); print!("{} akitas, ", self.akitas); ...
&& (self.perfumes == -1 || self.perfumes == other.perfumes) { return true; }
random_line_split
StatefulSeries.js
//>>built define("dojox/mvc/StatefulSeries",["dojo/_base/array","dojo/_base/declare","dojo/_base/lang","dojox/mvc/at"],function(_1,_2,_3,at){ return _2("dojox.mvc.StatefulSeries",null,{constructor:function(_4){ var _5=this; function _6(){ if(_5.series){ _5.series.chart.updateSeries(_5.series.name,_5); _5.series....
var _b=_7.converter,_c=(_b||{}).format&&_3.hitch({target:_9,source:this},_b.format); this._handles.push(_9.watch(_a,function(_d,_e,_f){ _5.data[_8]=_c?_c(_f):_f; _6(); })); } return !_a?_9:_3.isFunction(_9.get)?_9.get(_a):_9[_a]; }else{ return _7; } },this); _6(); },destroy:function(){ for(var h=null;h=thi...
} if(_7.bindDirection&&!(_7.bindDirection&at.from)){ console.warn("Data binding bindDirection option is ignored in dojox/mvc/StatefulSeries."); } if(_a&&_3.isFunction(_9.set)&&_3.isFunction(_9.watch)){
random_line_split
StatefulSeries.js
//>>built define("dojox/mvc/StatefulSeries",["dojo/_base/array","dojo/_base/declare","dojo/_base/lang","dojox/mvc/at"],function(_1,_2,_3,at){ return _2("dojox.mvc.StatefulSeries",null,{constructor:function(_4){ var _5=this; function _6()
; this._handles=[]; this.data=_1.map(_4,function(_7,_8){ if((_7||{}).atsignature=="dojox.mvc.at"){ var _9=_7.target,_a=_7.targetProp; if(_3.isString(_9)){ throw new Error("Literal-based dojox/mvc/at is not supported in dojox/mvc/StatefulSeries."); } if(_7.bindDirection&&!(_7.bindDirection&at.from)){ console.wa...
{ if(_5.series){ _5.series.chart.updateSeries(_5.series.name,_5); _5.series.chart.delayedRender(); } }
identifier_body
StatefulSeries.js
//>>built define("dojox/mvc/StatefulSeries",["dojo/_base/array","dojo/_base/declare","dojo/_base/lang","dojox/mvc/at"],function(_1,_2,_3,at){ return _2("dojox.mvc.StatefulSeries",null,{constructor:function(_4){ var _5=this; function
(){ if(_5.series){ _5.series.chart.updateSeries(_5.series.name,_5); _5.series.chart.delayedRender(); } }; this._handles=[]; this.data=_1.map(_4,function(_7,_8){ if((_7||{}).atsignature=="dojox.mvc.at"){ var _9=_7.target,_a=_7.targetProp; if(_3.isString(_9)){ throw new Error("Literal-based dojox/mvc/at is not...
_6
identifier_name
StatefulSeries.js
//>>built define("dojox/mvc/StatefulSeries",["dojo/_base/array","dojo/_base/declare","dojo/_base/lang","dojox/mvc/at"],function(_1,_2,_3,at){ return _2("dojox.mvc.StatefulSeries",null,{constructor:function(_4){ var _5=this; function _6(){ if(_5.series){ _5.series.chart.updateSeries(_5.series.name,_5); _5.series....
if(_a&&_3.isFunction(_9.set)&&_3.isFunction(_9.watch)){ var _b=_7.converter,_c=(_b||{}).format&&_3.hitch({target:_9,source:this},_b.format); this._handles.push(_9.watch(_a,function(_d,_e,_f){ _5.data[_8]=_c?_c(_f):_f; _6(); })); } return !_a?_9:_3.isFunction(_9.get)?_9.get(_a):_9[_a]; }else{ return _7; } }...
{ console.warn("Data binding bindDirection option is ignored in dojox/mvc/StatefulSeries."); }
conditional_block
mod.rs
msg_name: &mut address as *const _ as *const c_void, msg_namelen: mem::size_of::<sockaddr_storage>() as socklen_t, msg_iov: iov.as_ptr() as *const IoVec<&[u8]>, // safe cast to add const-ness msg_iovlen: iov.len() as size_t, msg_control: msg_control as *const c_void, msg_...
pub trait GetSockOpt : Copy {
random_line_split
mod.rs
types may /// be added to this enum; do not exhaustively pattern-match it. /// [Further reading](http://man7.org/linux/man-pages/man3/cmsg.3.html) pub enum ControlMessage<'a> { /// A message of type SCM_RIGHTS, containing an array of file /// descriptors passed between processes. See the description in the ...
bind
identifier_name
mod.rs
0 { return Err(Error::Sys(Errno::last())); } if !feat_atomic { if flags.contains(SOCK_CLOEXEC) { try!(fcntl(res, F_SETFD(FD_CLOEXEC))); } if flags.contains(SOCK_NONBLOCK) { try!(fcntl(res, F_SETFL(O_NONBLOCK))); } } Ok(res) } /// Creat...
{ unsafe { let addr: sockaddr_storage = mem::uninitialized(); let mut len = mem::size_of::<sockaddr_storage>() as socklen_t; let ret = ffi::getpeername(fd, mem::transmute(&addr), &mut len); if ret < 0 { return Err(Error::last()); } sockaddr_storage_to_a...
identifier_body