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
generate.py
#!/usr/bin/python """Utility to generate files to benchmark""" # Copyright Abel Sinkovics (abel@sinkovics.hu) 2016. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import argparse import os import stri...
(self, regex): """Find the first line matching regex and return the match object""" cregex = re.compile(regex) for line in self.content.splitlines(): match = cregex.match(line) if match: return match raise Exception('No "{0}" line in {1}.cpp'.forma...
_match
identifier_name
generate.py
#!/usr/bin/python """Utility to generate files to benchmark""" # Copyright Abel Sinkovics (abel@sinkovics.hu) 2016. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import argparse import os import stri...
def main(): """The main function of the script""" desc = 'Generate files to benchmark' parser = argparse.ArgumentParser(description=desc) parser.add_argument( '--src', dest='src_dir', default='src', help='The directory containing the templates' ) parser.add_arg...
"""Determine the output filename""" return '{0}_{1}_{2}.cpp'.format(template.name, n_val, mode.identifier)
identifier_body
generate.py
#!/usr/bin/python """Utility to generate files to benchmark""" # Copyright Abel Sinkovics (abel@sinkovics.hu) 2016. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import argparse import os import stri...
raise Exception('No "{0}" line in {1}.cpp'.format( regex_to_error_msg(regex), self.name )) def _get_line(self, regex): """Get a line based on a regex""" return self._match(regex).group(1) def load_file(path): """Returns the content of the file""" w...
match = cregex.match(line) if match: return match
conditional_block
generate.py
#!/usr/bin/python """Utility to generate files to benchmark"""
# Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import argparse import os import string import random import re import json import Cheetah.Template import chars def regex_to_error_msg(regex): """...
# Copyright Abel Sinkovics (abel@sinkovics.hu) 2016.
random_line_split
ValidateInstrumentDefinitionFiles.py
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + #pylint: disable=invalid-name #pylint: disabl...
direc = config['instrumentDefinition.directory'] self.xsdFile = os.path.join(direc,'Schema/IDF/1.0/','IDFSchema.xsd') if self.theFileToTest is None: files = self.__getDataFileList__() else: files = [os.path.join(direc,self.theFileToTest)] # run the tes...
myXsValidator = MyXsValidator(**kw) # parse XML input file inputTreeWrapper = myXsValidator.parse (inputFile) # validate XML input file return myXsValidator.validateXmlInputForceReadFile (inputFile, inputTreeWrapper, xsdFile)
identifier_body
ValidateInstrumentDefinitionFiles.py
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + #pylint: disable=invalid-name #pylint: disabl...
from minixsv import pyxsval # need to extend minixsv library to add method for that forces it to # validate against local schema when the xml file itself has # reference to schema online. The preference is to systemtest against # a local schema file to avoid this systemtest faili...
def runTest(self): """Main entry point for the test suite"""
random_line_split
ValidateInstrumentDefinitionFiles.py
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + #pylint: disable=invalid-name #pylint: disabl...
return files def runTest(self): """Main entry point for the test suite""" from minixsv import pyxsval # need to extend minixsv library to add method for that forces it to # validate against local schema when the xml file itself has # reference to schema online. The ...
files.append(os.path.join(direc, filename))
conditional_block
ValidateInstrumentDefinitionFiles.py
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + #pylint: disable=invalid-name #pylint: disabl...
(systemtesting.MantidSystemTest): xsdFile='' # Explicitly specify single file to test. If None, test all. theFileToTest=None #"MARI_Definition.xml" def skipTests(self): try: from genxmlif import GenXmlIfError # noqa from minixsv import pyxsval # noqa except Impo...
ValidateInstrumentDefinitionFiles
identifier_name
fromJson.js
/* Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.secure.fromJson"]){ dojo._hasResource["dojox.secure.fromJson"]=true; dojo.provide("dojox.secur...
for(var k in _17){ if(_d.call(_17,k)&&_17!==_16){ var v=_15(_17,k); if(v!==void 0){ _17[k]=v; }else{ if(!_18){ _18=[]; } _18.push(k); } } } if(_18){ for(var i=_18.length;--i>=0;){ delete _17[_18[i]]; } } } return _f.call(_16,key,_17); }; _11=_15({"":_11},""); } return _11; }; })(); }
if(_17&&typeof _17==="object"){ var _18=null;
random_line_split
fromJson.js
/* Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.secure.fromJson"]){ dojo._hasResource["dojox.secure.fromJson"]=true; dojo.provide("dojox.secur...
; var _a=new String(""); var _b="\\"; var _c={"{":Object,"[":Array}; var _d=Object.hasOwnProperty; return function(_e,_f){ var _10=_e.match(_4); var _11; var tok=_10[0]; var _12=false; if("{"===tok){ _11={}; }else{ if("["===tok){ _11=[]; }else{ _11=[]; _12=true; } } var key; var _13=[_11]; for(var i=1-_12,n=_10.length;...
{ return ch?_6[ch]:String.fromCharCode(parseInt(_9,16)); }
identifier_body
fromJson.js
/* Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.secure.fromJson"]){ dojo._hasResource["dojox.secure.fromJson"]=true; dojo.provide("dojox.secur...
(_8,ch,_9){ return ch?_6[ch]:String.fromCharCode(parseInt(_9,16)); }; var _a=new String(""); var _b="\\"; var _c={"{":Object,"[":Array}; var _d=Object.hasOwnProperty; return function(_e,_f){ var _10=_e.match(_4); var _11; var tok=_10[0]; var _12=false; if("{"===tok){ _11={}; }else{ if("["===tok){ _11=[]; }else{ _11=[];...
_7
identifier_name
fromJson.js
/* Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.secure.fromJson"]){ dojo._hasResource["dojox.secure.fromJson"]=true; dojo.provide("dojox.secur...
} return _f.call(_16,key,_17); }; _11=_15({"":_11},""); } return _11; }; })(); }
{ var _18=null; for(var k in _17){ if(_d.call(_17,k)&&_17!==_16){ var v=_15(_17,k); if(v!==void 0){ _17[k]=v; }else{ if(!_18){ _18=[]; } _18.push(k); } } } if(_18){ for(var i=_18.length;--i>=0;){ delete _17[_18[i]]; } }
conditional_block
BaseControl.ts
// NG2 import { EventEmitter } from '@angular/core'; import { Validators } from '@angular/forms'; // APP
import { NovoControlGroupAddConfig } from '../ControlGroup'; export interface NovoGroupedControlConfig { label?: string; icon?: string; add?: NovoControlGroupAddConfig; remove?: boolean; key: string; initialValue?: {}[]; } class ControlConfig { alwaysActive?: Boolean; allowInvalidDate?: boolean; app...
import { Helpers } from '../../../utils/Helpers'; import { notify } from '../../../utils/notifier/notifier.util'; import { IMaskOptions } from '../Control';
random_line_split
BaseControl.ts
// NG2 import { EventEmitter } from '@angular/core'; import { Validators } from '@angular/forms'; // APP import { Helpers } from '../../../utils/Helpers'; import { notify } from '../../../utils/notifier/notifier.util'; import { IMaskOptions } from '../Control'; import { NovoControlGroupAddConfig } from '../ControlGroup...
this.parentScrollSelector = config.parentScrollSelector; this.description = config.description; if (config.tooltip) { this.tooltip = config.tooltip; this.tooltipPosition = config.tooltipPosition; this.tooltipSize = config.tooltipSize; this.tooltipPreline = config.tooltipPreline; ...
{ notify(`'appendToBody' has been deprecated. Please remove this attribute.`); }
conditional_block
BaseControl.ts
// NG2 import { EventEmitter } from '@angular/core'; import { Validators } from '@angular/forms'; // APP import { Helpers } from '../../../utils/Helpers'; import { notify } from '../../../utils/notifier/notifier.util'; import { IMaskOptions } from '../Control'; import { NovoControlGroupAddConfig } from '../ControlGroup...
{ alwaysActive?: Boolean; allowInvalidDate?: boolean; appendToBody: boolean; // Deprecated; associatedEntity: string; asyncValidators?: Array<any>; checkboxLabel: string; closeOnSelect: boolean; config: any; controlType: string; currencyFormat: string; customControl?: any; customControlConfig?:...
ControlConfig
identifier_name
SlotMap.test.js
// @flow import * as React from 'react' import { shallow } from 'enzyme'
const wrapper = shallow(<SlotMap occupiedSlots={['1']} />) expect(wrapper.find('rect')).toHaveLength(11) }) it('component renders crash info icon when collision slots present', () => { const wrapper = shallow( <SlotMap occupiedSlots={['1']} collisionSlots={['4']} /> ) expect(wrapper.fin...
import { SlotMap } from '../SlotMap' import { Icon } from '../../icons' describe('SlotMap', () => { it('component renders 11 slots', () => {
random_line_split
menu_button.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! A widget that shows a menu when clicked on use ffi; use cast::GTK_MENUBUTTON; use ArrowT...
pub fn set_align_widget<T: ::WidgetTrait>(&self, align_widget: &T) -> () { unsafe { ffi::gtk_menu_button_set_align_widget(GTK_MENUBUTTON(self.pointer), align_widget.unwrap_widget()) } } } impl_drop!(MenuButton); impl_TraitWidget!(MenuButton); impl ::ContainerTrait for MenuButton {}...
unsafe { ffi::gtk_menu_button_get_direction(GTK_MENUBUTTON(self.pointer)) } }
identifier_body
menu_button.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! A widget that shows a menu when clicked on use ffi; use cast::GTK_MENUBUTTON; use ArrowT...
self) -> ArrowType { unsafe { ffi::gtk_menu_button_get_direction(GTK_MENUBUTTON(self.pointer)) } } pub fn set_align_widget<T: ::WidgetTrait>(&self, align_widget: &T) -> () { unsafe { ffi::gtk_menu_button_set_align_widget(GTK_MENUBUTTON(self.pointer), align_widget...
t_direction(&
identifier_name
menu_button.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! A widget that shows a menu when clicked on use ffi; use cast::GTK_MENUBUTTON; use ArrowT...
pub fn set_direction(&self, direction: ArrowType) -> () { unsafe { ffi::gtk_menu_button_set_direction(GTK_MENUBUTTON(self.pointer), direction); } } pub fn get_direction(&self) -> ArrowType { unsafe { ffi::gtk_menu_button_get_direction(GTK_MENUBUTTON(self.poi...
random_line_split
__init__.py
#!/usr/bin/python3 # Copyright 2017-2021 Joel Allen Luellwitz and Emily Frost # # 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 option) any later v...
# along with this program. If not, see <http://www.gnu.org/licenses/>. """The project test runner. To run the test suite, execute the following from the project root: CLEAR_GPG_AGENT_CACHE=true python3 -m unittest """ __author__ = 'Joel Luellwitz and Emily Frost' __version__ = '0.8' import unittest from test.gpgma...
# # You should have received a copy of the GNU General Public License
random_line_split
__init__.py
#!/usr/bin/python3 # Copyright 2017-2021 Joel Allen Luellwitz and Emily Frost # # 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 option) any later v...
unittest.main()
conditional_block
batch.py
http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permiss...
:param connection: The connection used to connect to datastore. :raises: :class:`ValueError` if either a connection or dataset ID are not set. """ self._connection = connection or _implicit_environ.CONNECTION self._dataset_id = dataset_id or _implicit_environ.DA...
random_line_split
batch.py
http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permiss...
def __exit__(self, exc_type, exc_val, exc_tb): try: if exc_type is None: self.commit() else: self.rollback() finally: _BATCHES.pop() def _assign_entity_to_mutation(mutation_pb, entity, auto_id_entities): """Copy ``entity`` i...
_BATCHES.push(self) self.begin() return self
identifier_body
batch.py
://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions ...
if not _dataset_ids_equal(self._dataset_id, key.dataset_id): raise ValueError("Key must be from same dataset as batch") key_pb = key.to_protobuf() helpers._add_keys_to_request(self.mutation.delete, [key_pb]) def begin(self): """No-op Overridden by :class:`gcl...
raise ValueError("Key must be complete")
conditional_block
batch.py
://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions ...
(self): """Getter for connection over which the batch will run. :rtype: :class:`gcloud.datastore.connection.Connection` :returns: The connection over which the batch will run. """ return self._connection @property def mutation(self): """Getter for the current mu...
connection
identifier_name
gulpfile.js
var gulp = require('gulp'), webpack = require('webpack-stream'), zip = require('gulp-zip'), del = require('del'), rename = require("gulp-rename"), webserver = require('gulp-webserver'), ghPages = require('gulp-gh-pages'); gulp.task('default', ['webpack', 'phaser']); gulp.task('watch', ['default'], function...
.pipe(zip('dist.zip')) .pipe(gulp.dest('.')); });
random_line_split
tasks.py
task execution involved a device. device_serial_number = db.StringProperty(required=False) result_metadata = db.TextProperty(required=False) worker_log = db.TextProperty(required=False) class Task(db.Model): """MrTaskman's representation of a Task. Includes metadata not needed in a Task config. """ # ...
if task.attempts != attempt: logging.info('Attempts: %d, attempt: %d', task.attempts, attempt) counter.incr('Tasks.Completed.TimedOut') if device_serial_number: counter.incr('Executors.%s.TimedOut' % device_serial_number) raise TaskTimedOutError() # Here we allow a timed out tas...
counters.incr('Executors.%s.Completed' % device_serial_number)
conditional_block
tasks.py
if task execution involved a device. device_serial_number = db.StringProperty(required=False) result_metadata = db.TextProperty(required=False) worker_log = db.TextProperty(required=False) class Task(db.Model): """MrTaskman's representation of a Task. Includes metadata not needed in a Task config. """ ...
counter.incr('Tasks.Completed.TimedOut') if device_serial_number: counter.incr('Executors.%s.TimedOut' % device_serial_number) raise TaskTimedOutError() # Here we allow a timed out task to publish results if it hasn't # been scheduled to another worker yet. if task.state not in [Ta...
logging.info('Attempts: %d, attempt: %d', task.attempts, attempt)
random_line_split
tasks.py
if task execution involved a device. device_serial_number = db.StringProperty(required=False) result_metadata = db.TextProperty(required=False) worker_log = db.TextProperty(required=False) class Task(db.Model): """MrTaskman's representation of a Task. Includes metadata not needed in a Task config. """ ...
(worker, executor_capabilities): """Looks for Tasks worker can execute, assigning one if possible. Args: worker: Name of worker as str. executor_capabilities: Capabilities as list of str. Returns: Task if a Task was assigned, None otherwise. """ assert worker assert executor_capabilities lo...
Assign
identifier_name
tasks.py
if task execution involved a device. device_serial_number = db.StringProperty(required=False) result_metadata = db.TextProperty(required=False) worker_log = db.TextProperty(required=False) class Task(db.Model): """MrTaskman's representation of a Task. Includes metadata not needed in a Task config. """ ...
def DeleteById(task_id): """Deletes Task with given integer task_id.""" task = GetById(task_id) if task is None: return False task.delete() counter.incr('Tasks.Deleted') return True def GetByExecutor(executor, limit=1000, keys_only=False): """Retrieves a list of tasks waiting for a given executor...
"""Returns list of Tasks with given name, or [].""" assert isinstance(task_name, basestring) tasks = Task.all().filter('name =', task_name).order('-scheduled_time').fetch(limit=1000) if not tasks: return [] if not isinstance(tasks, list): return [tasks] return tasks
identifier_body
route.js
import { inject as service } from '@ember/service'; import Route from '@ember/routing/route'; import { get } from '@ember/object'; export default Route.extend({ access: service(), catalog: service(), scope: service(), beforeModel() { this._super(...arguments); return get(this, 'catalog').fetchUnSc...
() { // Clear the cache when leaving the route so that it will be reloaded when you come back. this.set('cache', null); }, actions: { refresh() { // Clear the cache so it has to ask the server again this.set('cache', null); this.refresh(); }, }, queryParams: { category: ...
deactivate
identifier_name
route.js
import { inject as service } from '@ember/service'; import Route from '@ember/routing/route'; import { get } from '@ember/object'; export default Route.extend({ access: service(), catalog: service(), scope: service(), beforeModel() { this._super(...arguments); return get(this, 'catalog').fetchUnSc...
}, deactivate() { // Clear the cache when leaving the route so that it will be reloaded when you come back. this.set('cache', null); }, actions: { refresh() { // Clear the cache so it has to ask the server again this.set('cache', null); this.refresh(); }, }, queryParams...
{ controller.setProperties({ category: '', catalogId: '', projectCatalogId: '', clusterCatalogId: '', }) }
conditional_block
route.js
import { inject as service } from '@ember/service'; import Route from '@ember/routing/route'; import { get } from '@ember/object'; export default Route.extend({ access: service(), catalog: service(), scope: service(), beforeModel() { this._super(...arguments); return get(this, 'catalog').fetchUnSc...
, resetController(controller, isExiting/* , transition*/) { if (isExiting) { controller.setProperties({ category: '', catalogId: '', projectCatalogId: '', clusterCatalogId: '', }) } }, deactivate() { // Clear the cache when leaving the route...
{ return get(this, 'catalog').fetchTemplates(params) .then((res) => { res.catalogs = get(this, 'catalogs'); return res; }); }
identifier_body
route.js
import { inject as service } from '@ember/service'; import Route from '@ember/routing/route'; import { get } from '@ember/object'; export default Route.extend({ access: service(), catalog: service(), scope: service(), beforeModel() { this._super(...arguments); return get(this, 'catalog').fetchUnSc...
return res; }); }, resetController(controller, isExiting/* , transition*/) { if (isExiting) { controller.setProperties({ category: '', catalogId: '', projectCatalogId: '', clusterCatalogId: '', }) } }, deactivate() { // Clea...
return get(this, 'catalog').fetchTemplates(params) .then((res) => { res.catalogs = get(this, 'catalogs');
random_line_split
filter.spec.js
import {T} from './T' import {filter} from './filter' import {filter as filterRamda} from 'ramda'
a: 1, b: 2, c: 3, d: 4, } test('happy', () => { const isEven = n => n % 2 === 0 expect(filter(isEven, [1, 2, 3, 4])).toEqual([2, 4]) expect( filter(isEven, { a: 1, b: 2, d: 3, }) ).toEqual({b: 2}) }) test('predicate when input is object', () => { const obj = { a: 1, ...
const sampleObject = {
random_line_split
sap_hana_linked_service.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(LinkedService): """SAP HANA Linked Service. :param additional_properties: Unmatched properties from the message are deserialized this collection :type additional_properties: dict[str, object] :param connect_via: The integration runtime reference. :type connect_via: ~azure.mgmt.datafactor...
SapHanaLinkedService
identifier_name
sap_hana_linked_service.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
:param authentication_type: The authentication type to be used to connect to the SAP HANA server. Possible values include: 'Basic', 'Windows' :type authentication_type: str or ~azure.mgmt.datafactory.models.SapHanaAuthenticationType :param user_name: Username to access the SAP HANA server. Type: s...
:type server: object
random_line_split
sap_hana_linked_service.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
Expression with resultType string). :type user_name: object :param password: Password to access the SAP HANA server. :type password: ~azure.mgmt.datafactory.models.SecureString :param encrypted_credential: The encrypted credential used for authentication. Credentials are encrypted using the in...
"""SAP HANA Linked Service. :param additional_properties: Unmatched properties from the message are deserialized this collection :type additional_properties: dict[str, object] :param connect_via: The integration runtime reference. :type connect_via: ~azure.mgmt.datafactory.models.IntegrationR...
identifier_body
acceptance.py
""" This config file extends the test environment configuration so that we can run the lettuce acceptance tests. """ # We intentionally define lots of variables that aren't used, and # want to import all variables from base settings files # pylint: disable=wildcard-import, unused-wildcard-import from .test import * f...
(): return os.getppid() # Silence noisy logs LOG_OVERRIDES = [ ('track.middleware', logging.CRITICAL), ('codejail.safe_exec', logging.ERROR), ('edx.courseware', logging.ERROR), ('audit', logging.ERROR), ('instructor_task.api_helper', logging.ERROR), ] for log_name, log_level in LOG_OVERRIDES: ...
seed
identifier_name
acceptance.py
""" This config file extends the test environment configuration so that we can run the lettuce acceptance tests. """ # We intentionally define lots of variables that aren't used, and # want to import all variables from base settings files # pylint: disable=wildcard-import, unused-wildcard-import from .test import * f...
return os.getppid() # Silence noisy logs LOG_OVERRIDES = [ ('track.middleware', logging.CRITICAL), ('codejail.safe_exec', logging.ERROR), ('edx.courseware', logging.ERROR), ('audit', logging.ERROR), ('instructor_task.api_helper', logging.ERROR), ] for log_name, log_level in LOG_OVERRIDES: ...
def seed():
random_line_split
acceptance.py
""" This config file extends the test environment configuration so that we can run the lettuce acceptance tests. """ # We intentionally define lots of variables that aren't used, and # want to import all variables from base settings files # pylint: disable=wildcard-import, unused-wildcard-import from .test import * f...
# Generate a random UUID so that different runs of acceptance tests don't break each other import uuid SECRET_KEY = uuid.uuid4().hex ANONYMOUS_ID_SECRET_KEY = SECRET_KEY USERNAME_CIPHER_SECRET_KEY = SECRET_KEY ############################### PIPELINE ####################################### PIPELINE_ENABLED = False ...
SEARCH_ENGINE = "search.tests.mock_search_engine.MockSearchEngine"
conditional_block
acceptance.py
""" This config file extends the test environment configuration so that we can run the lettuce acceptance tests. """ # We intentionally define lots of variables that aren't used, and # want to import all variables from base settings files # pylint: disable=wildcard-import, unused-wildcard-import from .test import * f...
# Silence noisy logs LOG_OVERRIDES = [ ('track.middleware', logging.CRITICAL), ('codejail.safe_exec', logging.ERROR), ('edx.courseware', logging.ERROR), ('audit', logging.ERROR), ('instructor_task.api_helper', logging.ERROR), ] for log_name, log_level in LOG_OVERRIDES: logging.getLogger(log_n...
return os.getppid()
identifier_body
emitters.py
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.utils import simplejson from django.core.serializers.json import DateTimeAwareJSONEncoder from django.utils.xmlutils import SimplerXMLGenerator from django.utils.encoding import smart_unicode EMITTERS = {} def g...
xml.endElement(key) else: xml.characters(smart_unicode(data))
to_xml(xml, value)
random_line_split
emitters.py
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.utils import simplejson from django.core.serializers.json import DateTimeAwareJSONEncoder from django.utils.xmlutils import SimplerXMLGenerator from django.utils.encoding import smart_unicode EMITTERS = {} def g...
else: xml.characters(smart_unicode(data))
for key, value in data.iteritems(): xml.startElement(key, {}) to_xml(xml, value) xml.endElement(key)
conditional_block
emitters.py
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.utils import simplejson from django.core.serializers.json import DateTimeAwareJSONEncoder from django.utils.xmlutils import SimplerXMLGenerator from django.utils.encoding import smart_unicode EMITTERS = {} def g...
(xml, data): if isinstance(data, (list, tuple)): for item in data: xml.startElement('resource', {}) to_xml(xml, item) xml.endElement('resource') elif isinstance(data, dict): for key, value in data.iteritems(): xml.startElement(key, {}) ...
to_xml
identifier_name
emitters.py
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.utils import simplejson from django.core.serializers.json import DateTimeAwareJSONEncoder from django.utils.xmlutils import SimplerXMLGenerator from django.utils.encoding import smart_unicode EMITTERS = {} def g...
def to_xml(xml, data): if isinstance(data, (list, tuple)): for item in data: xml.startElement('resource', {}) to_xml(xml, item) xml.endElement('resource') elif isinstance(data, dict): for key, value in data.iteritems(): xml.startElement(key, {}) ...
stream = StringIO() xml = SimplerXMLGenerator(stream, 'utf-8') xml.startDocument() xml.startElement('response', {}) to_xml(xml, data) xml.endElement('response') xml.endDocument() return stream.getvalue()
identifier_body
index.js
/* eslint-disable flowtype/require-valid-file-annotation */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Button from 'material-ui/Button'; import Dialog, { DialogTitle, DialogContent, DialogContentText, DialogActions, } from 'material-ui/Dialog'; import Typography from '...
<Dialog open={this.state.open} onRequestClose={this.handleRequestClose}> <DialogTitle>Super Secret Password</DialogTitle> <DialogContent> <DialogContentText>1-2-3-4-5</DialogContentText> </DialogContent> <DialogActions> <Button color="primary" onCl...
render() { return ( <div className={this.props.classes.root}>
random_line_split
index.js
/* eslint-disable flowtype/require-valid-file-annotation */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Button from 'material-ui/Button'; import Dialog, { DialogTitle, DialogContent, DialogContentText, DialogActions, } from 'material-ui/Dialog'; import Typography from '...
() { return ( <div className={this.props.classes.root}> <Dialog open={this.state.open} onRequestClose={this.handleRequestClose}> <DialogTitle>Super Secret Password</DialogTitle> <DialogContent> <DialogContentText>1-2-3-4-5</DialogContentText> </DialogContent> ...
render
identifier_name
index.js
/* eslint-disable flowtype/require-valid-file-annotation */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Button from 'material-ui/Button'; import Dialog, { DialogTitle, DialogContent, DialogContentText, DialogActions, } from 'material-ui/Dialog'; import Typography from '...
<Button raised color="accent" onClick={this.handleClick}> Super Secret Password </Button> </div> ); } } Index.propTypes = { classes: PropTypes.object.isRequired, }; export default withRoot(withStyles(styles)(Index));
{ return ( <div className={this.props.classes.root}> <Dialog open={this.state.open} onRequestClose={this.handleRequestClose}> <DialogTitle>Super Secret Password</DialogTitle> <DialogContent> <DialogContentText>1-2-3-4-5</DialogContentText> </DialogContent> ...
identifier_body
htmlfieldsetelement.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/. */ use dom::bindings::utils::{DOMString, ErrorResult}; use dom::htmlcollection::HTMLCollection; use dom::htmlelement:...
}
{ }
identifier_body
htmlfieldsetelement.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/. */ use dom::bindings::utils::{DOMString, ErrorResult}; use dom::htmlcollection::HTMLCollection; use dom::htmlelement:...
} pub fn Name(&self) -> DOMString { None } pub fn SetName(&mut self, _name: &DOMString) -> ErrorResult { Ok(()) } pub fn Type(&self) -> DOMString { None } pub fn Elements(&self) -> @mut HTMLCollection { let window = self.htmlelement.element.node.owner_...
None
random_line_split
htmlfieldsetelement.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/. */ use dom::bindings::utils::{DOMString, ErrorResult}; use dom::htmlcollection::HTMLCollection; use dom::htmlelement:...
(&self) -> @mut ValidityState { let global = self.htmlelement.element.node.owner_doc().document().window; ValidityState::new(global) } pub fn ValidationMessage(&self) -> DOMString { None } pub fn CheckValidity(&self) -> bool { false } pub fn SetCustomValidity(&...
Validity
identifier_name
enum-non-c-like-repr-c-and-int.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
4 => MyEnumTag::E, _ => return Err(()), }; match dest.tag { MyEnumTag::A => { dest.payload.A.0 = read_u32_le(buf)?; } MyEnumTag::B => { dest.payload.B.x = read_u8(buf)?; dest.payload.B.y = read_u...
dest.tag = match tag { 0 => MyEnumTag::A, 1 => MyEnumTag::B, 2 => MyEnumTag::C, 3 => MyEnumTag::D,
random_line_split
enum-non-c-like-repr-c-and-int.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(Duration); fn main() { let result: Vec<Result<MyEnum, ()>> = vec![ Ok(MyEnum::A(17)), Ok(MyEnum::B { x: 206, y: 1145 }), Ok(MyEnum::C), Err(()), Ok(MyEnum::D(Some(407))), Ok(MyEnum::D(None)), Ok(MyEnum::E(Duration::from_secs(100))), Err(()), ]; ...
MyEnumVariantE
identifier_name
enum-non-c-like-repr-c-and-int.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let val = buf[0]; *buf = &buf[1..]; Ok(val) }
{ return Err(()) }
conditional_block
enum-non-c-like-repr-c-and-int.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
dest.payload.B.x = read_u8(buf)?; dest.payload.B.y = read_u16_le(buf)? as i16; } MyEnumTag::C => { /* do nothing */ } MyEnumTag::D => { let is_some = read_u8(buf)? == 0; if is_some { ...
{ unsafe { // Should be correct to do this transmute. let dest: &'a mut MyEnumRepr = mem::transmute(dest); let tag = read_u8(buf)?; dest.tag = match tag { 0 => MyEnumTag::A, 1 => MyEnumTag::B, 2 => MyEnumTag::C, 3 => MyEnumTag::D, ...
identifier_body
MushroomScene.js
var MyLayer = cc.Layer.extend({ isMouseDown:false, helloImg:null, helloLabel:null, circle:null, sprite:null, init:function () { ////////////////////////////// // 1. super init first this._super(); ///////////////////////////// // 2. add a menu item with...
this.map.initScene(this.gameLayer); this.map.syncScene(); } });
{ this.map.add(sw.MapObj.create(sw.MapObjTypes.Block)); }
conditional_block
MushroomScene.js
var MyLayer = cc.Layer.extend({ isMouseDown:false, helloImg:null, helloLabel:null, circle:null, sprite:null, init:function () { //////////////////////////////
///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // ask director the window size var size = cc.Director.getInstance().getWinSize(); // add a "close" icon to exit the progress. it's an autore...
// 1. super init first this._super();
random_line_split
id-generation.service.ts
import {Injectable} from 'angular2/core'; import {IdCode} from '../model/idCode'; import {CodeTypeEnum} from '../model/codeTypeEnum'; declare var S:any; @Injectable() export class IdGenerationService { generateRandomCodes(numberOfCodes: number, codeLength: number) { var idCodeList: IdCode[] = []; var code: an...
return idCodeList; } // Returns a random integer between min (included) and max (included) // Using Math.round() will give you a non-uniform distribution! getRandomIntInclusive(min:number, max:number) { return Math.floor(Math.random() * (max - min + 1)) + min; } }
{ console.log(i); code = this.getRandomIntInclusive(0, Math.pow(10, codeLength)); code = S(code).padLeft(codeLength, '0').s; idCodeList.push({ "applicationId": 11, "code": code, "type": CodeTypeEnum.SIMPLE, "creationDatetime": new Date() }); }
conditional_block
id-generation.service.ts
import {Injectable} from 'angular2/core'; import {IdCode} from '../model/idCode'; import {CodeTypeEnum} from '../model/codeTypeEnum'; declare var S:any; @Injectable() export class IdGenerationService { generateRandomCodes(numberOfCodes: number, codeLength: number) { var idCodeList: IdCode[] = []; var code: an...
(min:number, max:number) { return Math.floor(Math.random() * (max - min + 1)) + min; } }
getRandomIntInclusive
identifier_name
id-generation.service.ts
import {Injectable} from 'angular2/core'; import {IdCode} from '../model/idCode'; import {CodeTypeEnum} from '../model/codeTypeEnum';
@Injectable() export class IdGenerationService { generateRandomCodes(numberOfCodes: number, codeLength: number) { var idCodeList: IdCode[] = []; var code: any = null; for (var i = 0; i < numberOfCodes; i++) { console.log(i); code = this.getRandomIntInclusive(0, Math.pow(10, codeLength)); code = S(c...
declare var S:any;
random_line_split
conf.py
# -*- coding: utf-8 -*- # # pail documentation build configuration file, created by # sphinx-quickstart on Sat May 4 03:26:35 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All co...
#modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme #...
# A list of ignored prefixes for module index sorting.
random_line_split
conf.py
# -*- coding: utf-8 -*- # # pail documentation build configuration file, created by # sphinx-quickstart on Sat May 4 03:26:35 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All co...
# The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #t...
release = '%s (unreleased)' % release
conditional_block
sourceMappingVisitor.spec.ts
import { expect } from 'chai'; import { renderSync } from 'node-sass'; import * as ts from 'typescript'; import { SourceMappingVisitor } from '../../src/angular/sourceMappingVisitor'; import { getDecoratorPropertyInitializer } from '../../src/util/utils'; const getAst = (code: string, file = 'file.ts') => { return ...
const last = <T extends ts.Node>(nodes: ts.NodeArray<T>) => nodes[nodes.length - 1]; describe('SourceMappingVisitor', () => { it('should map to correct position', () => { const ast = getAst(fixture1); const classDeclaration = last(ast.statements); const styles = getDecoratorPropertyInitializer(last(clas...
export class Foo {} `;
random_line_split
simple_example.py
# coding: utf-8 # pylint: disable = invalid-name, C0111 import json import lightgbm as lgb import pandas as pd from sklearn.metrics import mean_squared_error # load or create your dataset print('Load data...') df_train = pd.read_csv('../regression/regression.train', header=None, sep='\t') df_test = pd.read_csv('../reg...
early_stopping_rounds=5) print('Save model...') # save model to file gbm.save_model('model.txt') print('Start predicting...') # predict y_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration) # eval print('The rmse of prediction is:', mean_squared_error(y_test, y_pred) ** 0.5) print('Dump mode...
random_line_split
compiler.ts
import * as debug from "debug"; import * as llvm from "llvm-node"; import * as ts from "typescript"; import {BuiltInSymbols} from "./built-in-symbols"; import {CodeGenerationDiagnostics, isCodeGenerationDiagnostic} from "./code-generation-diagnostic"; import {DefaultCodeGenerationContextFactory} from "./code-generation...
LOG("Program compiled"); return { exitStatus, diagnostics: emitResult.diagnostics }; } catch (ex) { if (isCodeGenerationDiagnostic(ex)) { return { exitStatus: ts.ExitStatus.DiagnosticsPresent_OutputsSkipped, diagnostics: [ CodeGenerationDiagnostics.toDiagnos...
{ const codeGenerationContextFactory = new DefaultCodeGenerationContextFactory(new NotYetImplementedCodeGenerator()); const codeGenerator = new PerFileCodeGenerator(compilationContext.llvmContext, codeGenerationContextFactory); const logUnknownVisitor = new LogUnknownTransformVisitor(); ...
identifier_body
compiler.ts
import * as debug from "debug"; import * as llvm from "llvm-node"; import * as ts from "typescript"; import {BuiltInSymbols} from "./built-in-symbols"; import {CodeGenerationDiagnostics, isCodeGenerationDiagnostic} from "./code-generation-diagnostic"; import {DefaultCodeGenerationContextFactory} from "./code-generation...
const LOG = debug("compiler"); /** * The main Interface for compiling a SpeedyJS Program. * The compiler creates compiles all with "use speedyjs" marked functions and rewrites the original source file * to invoke the web assembly function instead of executing the function body in the JS runtime. */ export class Co...
random_line_split
compiler.ts
import * as debug from "debug"; import * as llvm from "llvm-node"; import * as ts from "typescript"; import {BuiltInSymbols} from "./built-in-symbols"; import {CodeGenerationDiagnostics, isCodeGenerationDiagnostic} from "./code-generation-diagnostic"; import {DefaultCodeGenerationContextFactory} from "./code-generation...
const context = new llvm.LLVMContext(); const builtIns = BuiltInSymbols.create(program, this.compilerHost); const compilationContext: CompilationContext = { builtIns, compilerHost: this.compilerHost, compilerOptions: this.compilerOptions, llvmCon...
{ return { diagnostics, exitStatus: ts.ExitStatus.DiagnosticsPresent_OutputsSkipped }; }
conditional_block
compiler.ts
import * as debug from "debug"; import * as llvm from "llvm-node"; import * as ts from "typescript"; import {BuiltInSymbols} from "./built-in-symbols"; import {CodeGenerationDiagnostics, isCodeGenerationDiagnostic} from "./code-generation-diagnostic"; import {DefaultCodeGenerationContextFactory} from "./code-generation...
(rootFileNames: string[]): { exitStatus: ts.ExitStatus, diagnostics: ts.Diagnostic[] } { LOG("Start Compiling"); Compiler.initLLVM(); const program: ts.Program = ts.createProgram(rootFileNames, this.compilerOptions, this.compilerHost); const diagnostics = [ ...program.getSynt...
compile
identifier_name
test_merge_foreign_rss_stories.py
from operator import itemgetter from mediawords.db import connect_to_db from mediawords.dbi.downloads.store import store_content from mediawords.test.db.create import create_test_topic, create_test_medium, create_test_feed, create_test_story from topics_base.stories import merge_foreign_rss_stories def
(): """Test merge_foreign_rss_stories().""" db = connect_to_db() topic = create_test_topic(db, 'foo') medium = create_test_medium(db, 'norss') feed = create_test_feed(db=db, label='norss', medium=medium) num_stories = 10 stories = [ create_test_story(db=db, label=str(i), feed=feed)...
test_merge_foreign_rss_stories
identifier_name
test_merge_foreign_rss_stories.py
from operator import itemgetter from mediawords.db import connect_to_db from mediawords.dbi.downloads.store import store_content from mediawords.test.db.create import create_test_topic, create_test_medium, create_test_feed, create_test_story from topics_base.stories import merge_foreign_rss_stories
"""Test merge_foreign_rss_stories().""" db = connect_to_db() topic = create_test_topic(db, 'foo') medium = create_test_medium(db, 'norss') feed = create_test_feed(db=db, label='norss', medium=medium) num_stories = 10 stories = [ create_test_story(db=db, label=str(i), feed=feed) ...
def test_merge_foreign_rss_stories():
random_line_split
test_merge_foreign_rss_stories.py
from operator import itemgetter from mediawords.db import connect_to_db from mediawords.dbi.downloads.store import store_content from mediawords.test.db.create import create_test_topic, create_test_medium, create_test_feed, create_test_story from topics_base.stories import merge_foreign_rss_stories def test_merge_f...
# noinspection SqlInsertValues db.query( f""" insert into topic_stories (stories_id, topics_id) select s.stories_id, {int(topic['topics_id'])} from stories s """ ) assert db.query("select count(*) from topic_stories").flat()[0] == num_storie...
story = create_test_story(db=db, label=str(i), feed=rss_feed) download = db.create('downloads', { 'stories_id': story['stories_id'], 'feeds_id': rss_feed['feeds_id'], 'url': story['url'], 'host': 'foo', 'type': 'content', 'state': 'success'...
conditional_block
test_merge_foreign_rss_stories.py
from operator import itemgetter from mediawords.db import connect_to_db from mediawords.dbi.downloads.store import store_content from mediawords.test.db.create import create_test_topic, create_test_medium, create_test_feed, create_test_story from topics_base.stories import merge_foreign_rss_stories def test_merge_f...
for i in range(num_rss_stories): story = create_test_story(db=db, label=str(i), feed=rss_feed) download = db.create('downloads', { 'stories_id': story['stories_id'], 'feeds_id': rss_feed['feeds_id'], 'url': story['url'], 'host': 'foo', 'typ...
"""Test merge_foreign_rss_stories().""" db = connect_to_db() topic = create_test_topic(db, 'foo') medium = create_test_medium(db, 'norss') feed = create_test_feed(db=db, label='norss', medium=medium) num_stories = 10 stories = [ create_test_story(db=db, label=str(i), feed=feed) ...
identifier_body
aux-scanner.ts
declare const Components: any declare const Zotero: any Components.utils.import('resource://gre/modules/osfile.jsm') declare const OS: any import { sleep } from './sleep' import { KeyManager } from './key-manager' import { Translators } from './translators' import { Preferences as Prefs } from './prefs' export let A...
} }
{ const tagged: number[] = await Zotero.DB.columnQueryAsync('SELECT itemID FROM itemTags JOIN tags ON tags.tagID = itemTags.tagID WHERE LOWER(tags.name) = LOWER(?)', [tag]) // cited but not tagged let itemIDs = cited.filter(item => !tagged.includes(item)) if (itemIDs.length) { for (const item of ...
identifier_body
aux-scanner.ts
declare const Components: any declare const Zotero: any Components.utils.import('resource://gre/modules/osfile.jsm') declare const OS: any import { sleep } from './sleep' import { KeyManager } from './key-manager' import { Translators } from './translators' import { Preferences as Prefs } from './prefs' export let A...
// cited but not tagged let itemIDs = cited.filter(item => !tagged.includes(item)) if (itemIDs.length) { for (const item of await Zotero.Items.getAsync(itemIDs)) { item.addTag(tag, 1) await item.saveTx() } } // tagged but not cited itemIDs = tagged.filter(item => !ci...
} private async saveToTag(cited: number[], tag: string, libraryID: number) { const tagged: number[] = await Zotero.DB.columnQueryAsync('SELECT itemID FROM itemTags JOIN tags ON tags.tagID = itemTags.tagID WHERE LOWER(tags.name) = LOWER(?)', [tag])
random_line_split
aux-scanner.ts
declare const Components: any declare const Zotero: any Components.utils.import('resource://gre/modules/osfile.jsm') declare const OS: any import { sleep } from './sleep' import { KeyManager } from './key-manager' import { Translators } from './translators' import { Preferences as Prefs } from './prefs' export let A...
(itemIDs: number[], missing_keys: string[], target: { collection?: any, libraryID?: number, basename?: string }) { if (typeof target.libraryID === 'number') { if (target.collection) throw new Error('cannot have both collection and library target') if (!target.basename) throw new Error('Saving to library...
saveToCollection
identifier_name
upload.js
$(document).ready(function() { status('Choose a file :)'); var timerId; timerId = setInterval(function() { if($('#userPhotoInput').val() !== '') { clearInterval(timerId); $('#uploadForm').submit(); } }, 500); $('#uploadForm').submit(function() { st...
});
{ $('#status').text(message); }
identifier_body
upload.js
$(document).ready(function() { status('Choose a file :)'); var timerId; timerId = setInterval(function() { if($('#userPhotoInput').val() !== '') { clearInterval(timerId); $('#uploadForm').submit(); } }, 500); $('#uploadForm').submit(function() { st...
status('Error: ' + xhr.status); }, success: function(response) { try { response = $.parseJSON(response); } catch(e) { status('Bad response from server'); return; ...
$(this).ajaxSubmit({ dataType: 'text', error: function(xhr) {
random_line_split
upload.js
$(document).ready(function() { status('Choose a file :)'); var timerId; timerId = setInterval(function() { if($('#userPhotoInput').val() !== '') { clearInterval(timerId); $('#uploadForm').submit(); } }, 500); $('#uploadForm').submit(function() { st...
var imageUrlOnServer = response.path; status('Success, file uploaded to:' + imageUrlOnServer); } }); return false; }); function status(message) { $('#status').text(message); } });
{ status('Oops, something bad happened'); return; }
conditional_block
upload.js
$(document).ready(function() { status('Choose a file :)'); var timerId; timerId = setInterval(function() { if($('#userPhotoInput').val() !== '') { clearInterval(timerId); $('#uploadForm').submit(); } }, 500); $('#uploadForm').submit(function() { st...
(message) { $('#status').text(message); } });
status
identifier_name
axe-audit-test.js
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or a...
extends AxeAudit { static get meta() { return { id: 'fake-aria-fail', title: 'You have an aria-* issue', requiredArtifacts: ['Accessibility'], }; } } const artifacts = { Accessibility: { violations: [{ id:...
FakeA11yAudit
identifier_name
axe-audit-test.js
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
'use strict'; const AxeAudit = require('../../../audits/accessibility/axe-audit'); const assert = require('assert'); /* eslint-env jest */ describe('Accessibility: axe-audit', () => { describe('audit()', () => { it('generates audit output using subclass meta', () => { class FakeA11yAudit extends AxeAudit...
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */
random_line_split
index.d.ts
// Type definitions for react-spinkit 3.0.0 // Project: https://github.com/KyleAMathews/react-spinkit // Definitions by: Qubo <https://github.com/tkqubo>, Mleko <https://github.com/mleko>, Tom Crockett <https://github.com/pelotom>, zzanol <https://github.com/zzanol> // Definitions: https://github.com/DefinitelyTyped/De...
declare const spinner: spinner.Spinner; export = spinner;
export interface Spinner extends React.ComponentClass<SpinnerProps> { } }
random_line_split
move-into-dead-array-2.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { foo([d(), d(), d(), d()], 1); foo([d(), d(), d(), d()], 3); } fn foo(mut a: [D; 4], i: usize) { drop(a); a[i] = d(); //~ ERROR use of moved value: `a` }
main
identifier_name
move-into-dead-array-2.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Ensure that w...
random_line_split
net.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let fd = try!(cvt(libc::socket(fam, ty, 0))); Ok(Socket(FileDesc::new(fd))) } } pub fn accept(&self, storage: *mut libc::sockaddr, len: *mut libc::socklen_t) -> io::Result<Socket> { let fd = try!(cvt_r(|| unsafe { libc::accept(self.0.raw(), ...
}; unsafe {
random_line_split
net.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn cvt_gai(err: c_int) -> io::Result<()> { if err == 0 { return Ok(()) } let detail = unsafe { str::from_utf8(CStr::from_ptr(c::gai_strerror(err)).to_bytes()).unwrap() .to_string() }; Err(io::Error::new(io::ErrorKind::Other, &format!("failed to lookup ad...
{}
identifier_body
net.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(fd: c_int) -> Socket { Socket(FileDesc::new(fd)) } }
from_inner
identifier_name
bootstrap-modal.js
AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* MODAL C...
setTimeout(function () { that.$element .addClass('animated') .addClass(that.options.attentionAnimation); }, 0); } this.focus(); }, destroy: function () { var e = $.Event('destroy'); this.$element.triggerHandler(e); if (e.isDefaultPrevented()) return; this.teardown(); ...
random_line_split
ca8.py
"""Oral Argument Audio Scraper for Eighth Circuit Court of Appeals CourtID: ca8 Court Short Name: 8th Cir. Author: Brian W. Carver Date created: 2014-06-21 History: - 2014-07-22: download_url fixed by mlr """ from datetime import datetime from juriscraper.OralArgumentSite import OralArgumentSite class Site(OralArg...
(self, request_dict={}): """Go through the items and filter out ones that aren't complete. """ self.items = [] html_tree = super(Site, self)._download(request_dict=request_dict) for item in html_tree.xpath('//item'): case_name = item.xpath('./title/text()')[0].split("...
_download
identifier_name
ca8.py
"""Oral Argument Audio Scraper for Eighth Circuit Court of Appeals CourtID: ca8 Court Short Name: 8th Cir. Author: Brian W. Carver Date created: 2014-06-21 History: - 2014-07-22: download_url fixed by mlr """ from datetime import datetime from juriscraper.OralArgumentSite import OralArgumentSite class Site(OralArg...
# Set self.html to None so it can't be misused. return None def _get_download_urls(self): return [item.xpath('//enclosure/@url')[0] for item in self.items] def _get_case_names(self): case_names = [] for txt in [item.xpath('./title/text()')[0] for item in self.items]: ...
case_name = item.xpath('./title/text()')[0].split(":", 1)[1] if case_name.strip(): self.items.append(item)
conditional_block
ca8.py
"""Oral Argument Audio Scraper for Eighth Circuit Court of Appeals CourtID: ca8 Court Short Name: 8th Cir. Author: Brian W. Carver Date created: 2014-06-21 History: - 2014-07-22: download_url fixed by mlr """ from datetime import datetime from juriscraper.OralArgumentSite import OralArgumentSite class Site(OralArg...
def _get_case_names(self): case_names = [] for txt in [item.xpath('./title/text()')[0] for item in self.items]: case_name = txt.split(': ', 1)[1] case_names.append(case_name) return case_names def _get_case_dates(self): case_dates = [] for txt in...
def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.court_id = self.__module__ self.url = 'http://media-oa.ca8.uscourts.gov/circ8rss.xml' def _download(self, request_dict={}): """Go through the items and filter out ones that aren't complete. ...
identifier_body
ca8.py
"""Oral Argument Audio Scraper for Eighth Circuit Court of Appeals CourtID: ca8 Court Short Name: 8th Cir. Author: Brian W. Carver Date created: 2014-06-21 History: - 2014-07-22: download_url fixed by mlr """ from datetime import datetime from juriscraper.OralArgumentSite import OralArgumentSite class Site(OralArg...
for item in html_tree.xpath('//item'): case_name = item.xpath('./title/text()')[0].split(":", 1)[1] if case_name.strip(): self.items.append(item) # Set self.html to None so it can't be misused. return None def _get_download_urls(self): return...
""" self.items = [] html_tree = super(Site, self)._download(request_dict=request_dict)
random_line_split
train.py
# -*- coding: utf-8 -*- from transH import TransH import pickle import numpy as np import sys def main(): if len(sys.argv) != 3: print '[Usage] python train.py train_data validation_data' exit(0) train_data, valid_data = sys.argv[1:] X, E, R = loadData(train_data) V = loadData(valid_data, E=E, R=R, mode='va...
main()
conditional_block
train.py
# -*- coding: utf-8 -*- from transH import TransH import pickle import numpy as np import sys def main(): if len(sys.argv) != 3: print '[Usage] python train.py train_data validation_data' exit(0) train_data, valid_data = sys.argv[1:] X, E, R = loadData(train_data) V = loadData(valid_data, E=E, R=R, mode='va...
(file_path, E=None, R=None, mode='train'): if mode == 'train': E, R = {}, {} e_ind, r_ind = 0, 0 X = [] f = open(file_path, 'r') for line in f: h, r, t = line.strip().split('\t') if not h in E: E[h] = e_ind e_ind += 1 if not t in E: E[t] = e_ind e_ind +=1 if not r in R: R[r] =...
loadData
identifier_name
train.py
# -*- coding: utf-8 -*- from transH import TransH import pickle import numpy as np import sys def main(): if len(sys.argv) != 3: print '[Usage] python train.py train_data validation_data' exit(0)
X, E, R = loadData(train_data) V = loadData(valid_data, E=E, R=R, mode='valid') # parameters gamma = 1 k = 50 alpha = 0.1 b = 5000 c = 0.25 transH = TransH(len(E), len(R), gamma, k, alpha, b, c) transH.fit(X, validationset=V) w = open('transH.model', 'w') pickle.dump((transH, E, R), w) def loadData(f...
train_data, valid_data = sys.argv[1:]
random_line_split
train.py
# -*- coding: utf-8 -*- from transH import TransH import pickle import numpy as np import sys def main(): if len(sys.argv) != 3: print '[Usage] python train.py train_data validation_data' exit(0) train_data, valid_data = sys.argv[1:] X, E, R = loadData(train_data) V = loadData(valid_data, E=E, R=R, mode='va...
elif mode == 'valid': X = [] f = open(file_path, 'r') for line in f: h, r, t = line.strip().split('\t') X.append((E[h], R[r], E[t])) return np.array(X) if __name__ == "__main__": main()
if mode == 'train': E, R = {}, {} e_ind, r_ind = 0, 0 X = [] f = open(file_path, 'r') for line in f: h, r, t = line.strip().split('\t') if not h in E: E[h] = e_ind e_ind += 1 if not t in E: E[t] = e_ind e_ind +=1 if not r in R: R[r] = r_ind r_ind += 1 X.append((E[h], R[r...
identifier_body
yesterday_dump.py
import time from pymongo import MongoClient from datetime import datetime, timedelta import json from bson import Binary, Code from bson.json_util import dumps client = MongoClient('localhost', 27017) db = client['election-2016'] def dumpData(yesterdayStr): collectionName = 't' + yesterdayStr cursor = db[...
else: file.write('\n]') i = i + 1 print('data for ' + yesterdayStr + ' successfully dumped at ' + str(now)) # Run following code when the program starts if __name__ == '__main__': currentDate = str(datetime.now().month) + '_' + str(datetime.now().day) #get no...
file.write(',\n')
conditional_block
yesterday_dump.py
import time from pymongo import MongoClient from datetime import datetime, timedelta import json from bson import Binary, Code from bson.json_util import dumps client = MongoClient('localhost', 27017) db = client['election-2016'] def
(yesterdayStr): collectionName = 't' + yesterdayStr cursor = db[collectionName].find() count = cursor.count() print(collectionName + ' found ' + str(count) + ' tweets') # dump only if data count is greater than 0 if count > 0: file = open('out/' + yesterdayStr + '.json', 'w') ...
dumpData
identifier_name
yesterday_dump.py
import time from pymongo import MongoClient from datetime import datetime, timedelta import json from bson import Binary, Code from bson.json_util import dumps client = MongoClient('localhost', 27017) db = client['election-2016'] def dumpData(yesterdayStr):
i = i + 1 print('data for ' + yesterdayStr + ' successfully dumped at ' + str(now)) # Run following code when the program starts if __name__ == '__main__': currentDate = str(datetime.now().month) + '_' + str(datetime.now().day) #get now and yesterday strings now = datetime.now() ...
collectionName = 't' + yesterdayStr cursor = db[collectionName].find() count = cursor.count() print(collectionName + ' found ' + str(count) + ' tweets') # dump only if data count is greater than 0 if count > 0: file = open('out/' + yesterdayStr + '.json', 'w') file.write('[') ...
identifier_body