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
020_stack_action.py
# not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # ...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
random_line_split
create_snapshot.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c)2012 Rackspace US, Inc.
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
# All Rights Reserved.
random_line_split
taskrefresh.py
"""AWS ECS: Update cluster service to utilize a cloned task definition. Clone latest task and register it in order to update the image used on tasks in the service. It will take a while because it needs to drain connections and some other stuff. """ import sys import os import subprocess import json # we don't wan...
], )
random_line_split
taskrefresh.py
"""AWS ECS: Update cluster service to utilize a cloned task definition. Clone latest task and register it in order to update the image used on tasks in the service. It will take a while because it needs to drain connections and some other stuff. """ import sys import os import subprocess import json # we don't wan...
# Now let's get the JSON for the latest task we found task_definition_output = subprocess.check_output( [ 'aws', 'ecs', 'describe-task-definition', '--task-definition', task_definition_arn, ], ) latest_task_definition = json.loads(task_definition_output.decode('UTF-8'))...
raise Exception("Task definition not found...")
conditional_block
bfs.rs
use std::collections::VecDeque; pub fn
<F, GT: ::graph::GraphTraversal>(g: &GT, s: usize, mapped_function: &mut Box<F> ,marker: &mut ::mark::Marker) where F: FnMut(usize) { let mut q: VecDeque<usize> = VecDeque::new(); q.push_back(s); marker.mark(s); loop { if let Some(u) = q.pop_front() { mapped_function(u); ...
bfs
identifier_name
bfs.rs
use std::collections::VecDeque; pub fn bfs<F, GT: ::graph::GraphTraversal>(g: &GT, s: usize, mapped_function: &mut Box<F> ,marker: &mut ::mark::Marker) where F: FnMut(usize) { let mut q: VecDeque<usize> = VecDeque::new(); q.push_back(s); marker.mark(s); loop { if let Some(u) = q.pop_front() { ...
{ for v in g.sources() { bfs(g, v, mapped_function, marker); } }
identifier_body
bfs.rs
use std::collections::VecDeque; pub fn bfs<F, GT: ::graph::GraphTraversal>(g: &GT, s: usize, mapped_function: &mut Box<F> ,marker: &mut ::mark::Marker) where F: FnMut(usize) { let mut q: VecDeque<usize> = VecDeque::new(); q.push_back(s); marker.mark(s); loop { if let Some(u) = q.pop_front() { ...
bfs(g, v, mapped_function, marker); } }
random_line_split
bfs.rs
use std::collections::VecDeque; pub fn bfs<F, GT: ::graph::GraphTraversal>(g: &GT, s: usize, mapped_function: &mut Box<F> ,marker: &mut ::mark::Marker) where F: FnMut(usize) { let mut q: VecDeque<usize> = VecDeque::new(); q.push_back(s); marker.mark(s); loop { if let Some(u) = q.pop_front() { ...
})); } else { break; } } } pub fn full_bfs<F, GT: ::graph::GraphTraversal>(g: &GT, mapped_function: &mut Box<F>, marker: &mut ::mark::Marker) where F: FnMut(usize) { for v in g.sources() { bfs(g, v, mapped_function, marker); } }
{ None }
conditional_block
test_propagation.py
import numpy as np from dipy.data import default_sphere from dipy.tracking.propspeed import ndarray_offset, eudx_both_directions from numpy.testing import (assert_array_almost_equal, assert_equal, assert_raises, run_module_suite) def stepped_1d(arr_1d): # Make a version of `arr_1d` wh...
def test_eudx_both_directions_errors(): # Test error conditions for both directions function sphere = default_sphere seed = np.zeros(3, np.float64) qa = np.zeros((4, 5, 6, 7), np.float64) ind = qa.copy() # All of seed, qa, ind, odf_vertices must be C-contiguous. Check by # passing in ver...
for dt in (np.int32, np.float64): index = np.array([1, 1], dtype=np.intp) A = np.array([[1, 0, 0], [0, 2, 0], [0, 0, 3]], dtype=dt) strides = np.array(A.strides, np.intp) i_size = A.dtype.itemsize assert_equal(ndarray_offset(index, strides, 2, i_size), 4) assert_equal(A.r...
identifier_body
test_propagation.py
import numpy as np from dipy.data import default_sphere from dipy.tracking.propspeed import ndarray_offset, eudx_both_directions from numpy.testing import (assert_array_almost_equal, assert_equal, assert_raises, run_module_suite) def stepped_1d(arr_1d): # Make a version of `arr_1d` wh...
1., 1., 2) if __name__ == '__main__': run_module_suite()
assert_raises(ValueError, eudx_both_directions, seed, 0, qa, ind, sphere.vertices[::2], 0.5, 0.1,
random_line_split
test_propagation.py
import numpy as np from dipy.data import default_sphere from dipy.tracking.propspeed import ndarray_offset, eudx_both_directions from numpy.testing import (assert_array_almost_equal, assert_equal, assert_raises, run_module_suite) def stepped_1d(arr_1d): # Make a version of `arr_1d` wh...
def test_eudx_both_directions_errors(): # Test error conditions for both directions function sphere = default_sphere seed = np.zeros(3, np.float64) qa = np.zeros((4, 5, 6, 7), np.float64) ind = qa.copy() # All of seed, qa, ind, odf_vertices must be C-contiguous. Check by # passing in ver...
index = np.array([1, 1], dtype=np.intp) A = np.array([[1, 0, 0], [0, 2, 0], [0, 0, 3]], dtype=dt) strides = np.array(A.strides, np.intp) i_size = A.dtype.itemsize assert_equal(ndarray_offset(index, strides, 2, i_size), 4) assert_equal(A.ravel()[4], A[1, 1]) # Index and st...
conditional_block
test_propagation.py
import numpy as np from dipy.data import default_sphere from dipy.tracking.propspeed import ndarray_offset, eudx_both_directions from numpy.testing import (assert_array_almost_equal, assert_equal, assert_raises, run_module_suite) def
(arr_1d): # Make a version of `arr_1d` which is not contiguous return np.vstack((arr_1d, arr_1d)).ravel(order='F')[::2] def test_offset(): # Test ndarray_offset function for dt in (np.int32, np.float64): index = np.array([1, 1], dtype=np.intp) A = np.array([[1, 0, 0], [0, 2, 0], [0, 0,...
stepped_1d
identifier_name
day_1.rs
pub use tdd_kata::map_kata::day_1::Map; describe! map_tests { before_each { let mut map = Map::new(); } it "should create a new empty map" { assert_eq!(map.size(), 0); assert!(map.is_empty());
} it "should increase size when put into map" { let old_size = map.size(); map.put(1, 1); assert_eq!(map.size(), old_size + 1); assert!(!map.is_empty()); } it "should not increase size when put the same key into the map" { map.put(1, 1); let old_size = ...
random_line_split
Agent.py
''' Created on Sep 15, 2012 Agent classes. Contains references to instances of classes containing observer handlers and code Agent Instances are created automatically. Create a named Handler instance under the Agent, as an instance of the desired handler class, by create (POST) of a JSON object containing a dicti...
(self, linkPath): return self.linkToRef(linkPath).get() def setByLink(self, linkPath, newValue): self.linkToRef(linkPath).set(newValue) class addHandler(Handler): # an example appHandler that adds two values together and stores the result # define a method for handling state changes in observ...
getByLink
identifier_name
Agent.py
''' Created on Sep 15, 2012 Agent classes. Contains references to instances of classes containing observer handlers and code Agent Instances are created automatically. Create a named Handler instance under the Agent, as an instance of the desired handler class, by create (POST) of a JSON object containing a dicti...
def get(self, Key=None): if Key != None : return self._settings[Key] else : return self._settings def set(self, newSettings): # create an instance of a handler from settings dictionary self._settings.update(newSettings) def handleNotify(self, updateRef=...
def _init(self): pass
random_line_split
Agent.py
''' Created on Sep 15, 2012 Agent classes. Contains references to instances of classes containing observer handlers and code Agent Instances are created automatically. Create a named Handler instance under the Agent, as an instance of the desired handler class, by create (POST) of a JSON object containing a dicti...
return None # new create takes dictionary built from JSON object POSTed to parent resource def create(self, resourceDescriptor): resourceName = resourceDescriptor['resourceName'] resourceClass = resourceDescriptor['resourceClass'] # import the module if it's specified in th...
if self._handlers.has_key(handlerName) : return self._handlers[handlerName] # to get reference to handler resources by handler name
conditional_block
Agent.py
''' Created on Sep 15, 2012 Agent classes. Contains references to instances of classes containing observer handlers and code Agent Instances are created automatically. Create a named Handler instance under the Agent, as an instance of the desired handler class, by create (POST) of a JSON object containing a dicti...
class Agent(RESTfulResource): # Agent is a container for Handlers and daemons, instantiated as a resource of a SmartObject def __init__(self, parentObject=None, resourceDescriptor = {}): RESTfulResource.__init__(self, parentObject, resourceDescriptor) self._handlers = {} def get...
def _handleNotify(self, resource = None ): subprocess.call([("/usr/local/bin/gatttool"),\ ("--device="+self._settings['MACaddress']),\ ("--addr-type="+self._settings['MACtype']),\ ("--char-write"),\ ("--handle="+...
identifier_body
room.ts
import { Room, Message } from '../src'; import { MessageSocket } from './message'; import {IRoom} from "../src/interface/room/iroom"; import {RoomDomain} from "../src/domain/room-domain"; export class
{ nsp: any; name: string; data: any; socket: any; rooms: Room[] = []; messageSockets: MessageSocket[] = []; constructor(private io: any) { this.nsp = this.io.of('/room'); this.nsp.on('connection', (socket: any) => { console.log("conectado a sala"); this.socket = socket; this.up...
RoomSocket
identifier_name
room.ts
import { Room, Message } from '../src'; import { MessageSocket } from './message'; import {IRoom} from "../src/interface/room/iroom"; import {RoomDomain} from "../src/domain/room-domain"; export class RoomSocket { nsp: any; name: string; data: any; socket: any; rooms: Room[] = []; messageSockets: MessageSo...
const messageSocket = this.messageSockets[index]; if (!validRooms[messageSocket.room.name]) { this.messageSockets.splice(parseInt(index, 10), 1); } } } }
// Destroy sockets for removed rooms for (const index in this.messageSockets) {
random_line_split
room.ts
import { Room, Message } from '../src'; import { MessageSocket } from './message'; import {IRoom} from "../src/interface/room/iroom"; import {RoomDomain} from "../src/domain/room-domain"; export class RoomSocket { nsp: any; name: string; data: any; socket: any; rooms: Room[] = []; messageSockets: MessageSo...
} // Destroy sockets for removed rooms for (const index in this.messageSockets) { const messageSocket = this.messageSockets[index]; if (!validRooms[messageSocket.room.name]) { this.messageSockets.splice(parseInt(index, 10), 1); } } } }
{ console.log('inserindo no socket', room.name); this.messageSockets.push(new MessageSocket(this.io, room)); }
conditional_block
room.ts
import { Room, Message } from '../src'; import { MessageSocket } from './message'; import {IRoom} from "../src/interface/room/iroom"; import {RoomDomain} from "../src/domain/room-domain"; export class RoomSocket { nsp: any; name: string; data: any; socket: any; rooms: Room[] = []; messageSockets: MessageSo...
// List all rooms private findOne(room: RoomDomain): void { Room.findOne(room).subscribe(rooms => { this.rooms = rooms; this.updateMessageSockets(); this.nsp.emit('item', rooms); }); } // Update message sockets private updateMessageSockets(): void { // Add message sockets fo...
{ console.log('Client disconnected'); }
identifier_body
hops.py
#!/usr/bin/env python # # Wrapper script for Java Conda packages that ensures that the java runtime # is invoked with the right options. Adapted from the bash script (http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128). # # # Program Parameters # import os import...
(mem_opts, prop_opts, pass_args) = jvm_opts(sys.argv[1:]) if pass_args != [] and pass_args[0].startswith('eu'): jar_arg = '-cp' else: jar_arg = '-jar' jar_path = os.path.join(jar_dir, jar_file) java_args = [java]+ mem_opts + prop_opts + [jar_arg] + [jar_path] + pass_args if '...
def main(): java = java_executable() jar_dir = real_dirname(sys.argv[0])
random_line_split
hops.py
#!/usr/bin/env python # # Wrapper script for Java Conda packages that ensures that the java runtime # is invoked with the right options. Adapted from the bash script (http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128). # # # Program Parameters # import os import...
def jvm_opts(argv): """Construct list of Java arguments based on our argument list. The argument list passed in argv must not include the script name. The return value is a 3-tuple lists of strings of the form: (memory_options, prop_options, passthrough_options) """ mem_opts = [] prop_...
"""Return the executable name of the Java interpreter.""" java_home = getenv('JAVA_HOME') java_bin = os.path.join('bin', 'java') if java_home and access(os.path.join(java_home, java_bin), X_OK): return os.path.join(java_home, java_bin) else: return 'java'
identifier_body
hops.py
#!/usr/bin/env python # # Wrapper script for Java Conda packages that ensures that the java runtime # is invoked with the right options. Adapted from the bash script (http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128). # # # Program Parameters # import os import...
elif arg.startswith('-XX'): prop_opts.append(arg) elif arg.startswith('-Xm'): mem_opts.append(arg) else: pass_args.append(arg) # In the original shell script the test coded below read: # if [ "$jvm_mem_opts" == "" ] && [ -z ${_JAVA_OPTIONS+x} ] ...
prop_opts.append(arg)
conditional_block
hops.py
#!/usr/bin/env python # # Wrapper script for Java Conda packages that ensures that the java runtime # is invoked with the right options. Adapted from the bash script (http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128). # # # Program Parameters # import os import...
(): java = java_executable() jar_dir = real_dirname(sys.argv[0]) (mem_opts, prop_opts, pass_args) = jvm_opts(sys.argv[1:]) if pass_args != [] and pass_args[0].startswith('eu'): jar_arg = '-cp' else: jar_arg = '-jar' jar_path = os.path.join(jar_dir, jar_file) java_args = [j...
main
identifier_name
packageResource.spec.js
require( "../setup" ); var packageResource = require( "../../resource/package/resource.js" );
describe( "when getting new package callback", function() { describe( "with matching package", function() { var config, serverMock, result; before( function() { config = { package: { project: "imatch" } }; serverMock = sinon.mock( server ); serverMock.expects( "checkForNew" ).on...
describe( "Package Resource", function() { var server = { checkForNew: _.noop };
random_line_split
jsExpected.js
//mongo localhost:27017/sli --eval 'var tenant="MegatronIL";' jsExpected.js var criteria = {}; if( typeof tenant != 'undefined' && tenant != null && tenant.length > 0) criteria['metaData.tenantId']=tenant; var entities ={ 'assessment':4, 'attendance':16, ...
'studentSectionAssociation':32, 'studentTranscriptAssociation':32, 'teacherSchoolAssociation':16, 'teacherSectionAssociation':64, }; for(var entity in entities){ var expectedCount = entities[entity]; var mongoCount = db[entity].find(criteria).count(); ...
'studentDisciplineIncidentAssociation':16, 'studentGradebookEntry':2, 'studentParentAssociation':25, 'studentProgramAssociation':14, 'studentSchoolAssociation':16,
random_line_split
error.js
'use strict'; /** * @ngdoc function * @name openshiftConsole.controller:ErrorController * @description * # ErrorController * Controller of the openshiftConsole */ angular.module('openshiftConsole') .controller('ErrorController', function ($scope, $window) { var params = URI(window.location.href).query(true...
$scope.reloadConsole = function() { $window.location.href = "/"; }; });
{ $scope.errorDetails = params.error_description; }
conditional_block
error.js
'use strict'; /** * @ngdoc function * @name openshiftConsole.controller:ErrorController * @description * # ErrorController * Controller of the openshiftConsole */ angular.module('openshiftConsole') .controller('ErrorController', function ($scope, $window) { var params = URI(window.location.href).query(true...
$scope.errorMessage = "An error has occurred"; } if (params.error_description) { $scope.errorDetails = params.error_description; } $scope.reloadConsole = function() { $window.location.href = "/"; }; });
$scope.errorMessage = "Invalid request"; break; default:
random_line_split
cli_test.py
#!/usr/bin/env python # # Copyright 2015 BMC Software, Inc. # # 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 applicab...
(cli, args): output = None try: command = CLITest.get_cli_name_from_class(cli) args.insert(0, command) output = subprocess.check_output(args=args) except subprocess.CalledProcessError as e: sys.stderr.write("{0}: {1}\n".format(e.output, e.returncod...
get_cli_output
identifier_name
cli_test.py
#!/usr/bin/env python # # Copyright 2015 BMC Software, Inc. # # 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 applicab...
try: int(s) return True except ValueError: return False
identifier_body
cli_test.py
#!/usr/bin/env python # # Copyright 2015 BMC Software, Inc. # # 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 applicab...
def check_curl(test_case, cli, output): parameters = CLITestParameters() p = re.compile(r'-u ".*?"\s') a = p.findall(output) output = output.replace(a[0], '') test_case.assertEqual(parameters.get_value(cli.__class__.__name__, 'curl').encode('utf-8'), output.encode('utf-8')) ...
parameters = CLITestParameters() test_case.assertEqual(parameters.get_value(cli.__class__.__name__, 'description'), cli.get_description()) @staticmethod
random_line_split
plot_Div_spec.py
import os, sys import myfun import numpy as np import matplotlib as mpl mpl.use('ps') import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy import interpolate import lagrangian_stats import scipy.fftpack ## READ archive (too many points... somehow) # args: name, dayi, dayf, days #label ...
plt.yticks(fontsize=18) plt.xticks(fontsize=18) plt.xlim([1/2000.,1/10.]) plt.savefig('./plot/'+label+'/Divergence_'+str(z)+'_CG_'+label+'_'+tlabel+'_spec.eps',bbox_inches='tight') print './plot/'+label+'/Divergence_'+str(z)+'_CG_'+label+'_'+tlabel+'_spec.eps' plt.close() # v = np.linspace(0, 10, ...
plt.ylabel(r'PSD',fontsize=20)
random_line_split
plot_Div_spec.py
import os, sys import myfun import numpy as np import matplotlib as mpl mpl.use('ps') import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy import interpolate import lagrangian_stats import scipy.fftpack ## READ archive (too many points... somehow) # args: name, dayi, dayf, days #label ...
w = scipy.fftpack.fftfreq(xn, dx[1]) # w = scipy.fftpack.fftshift(w) FTp = np.mean(FT,1)/xn fig = plt.figure(figsize=(10,8)) p25, = plt.loglog(w[w>0], FTp[w>0],'r',linewidth=2) plt.plot([5*10**-3, 5*10**-2],[5*10**3 , 5*10**-( -3+5/3.)],'k',linewidth=1.5) plt.plot([5*10**-3, 5*10**-2],[5*10**3 , 5*10**...
tempfft = scipy.fftpack.fft(Div[:,j]**2,xn) FT[:,j] = abs(tempfft)**2
conditional_block
JobStatusUpdater.js
'use strict'; var _ = require('underscore'); var inspect = require(global.OSYNC_UTILS + 'inspect'); var logUtil = require(global.OSYNC_UTILS + 'log'); var JdsClient = require(global.OSYNC_SUBSYSTEMS + 'jds/jds-client'); function JobStatusUpdater(setLog, setConfig, jdsClient) { if (!(this instanceof JobStatusUpda...
var self = this; job.status = 'completed'; self.log.debug('JobStatusUpdater.completeJobStatus: Saving job: %s', inspect(job)); this.writeStatus(job, callback); }; module.exports = JobStatusUpdater; JobStatusUpdater._tests = { '_writeStatus': JobStatusUpdater.prototype.writeStatus, '_errorJobSta...
JobStatusUpdater.prototype.completeJobStatus = function(job, callback) {
random_line_split
JobStatusUpdater.js
'use strict'; var _ = require('underscore'); var inspect = require(global.OSYNC_UTILS + 'inspect'); var logUtil = require(global.OSYNC_UTILS + 'log'); var JdsClient = require(global.OSYNC_SUBSYSTEMS + 'jds/jds-client'); function
(setLog, setConfig, jdsClient) { if (!(this instanceof JobStatusUpdater)) { return new JobStatusUpdater(setLog, setConfig, jdsClient); } this.jdsClient = jdsClient || new JdsClient(setLog, setConfig); this.log = logUtil.getAsChild('JobStatusUpdater', setLog); // this.log = require('bunyan')...
JobStatusUpdater
identifier_name
JobStatusUpdater.js
'use strict'; var _ = require('underscore'); var inspect = require(global.OSYNC_UTILS + 'inspect'); var logUtil = require(global.OSYNC_UTILS + 'log'); var JdsClient = require(global.OSYNC_SUBSYSTEMS + 'jds/jds-client'); function JobStatusUpdater(setLog, setConfig, jdsClient) { if (!(this instanceof JobStatusUpda...
return callback(); //self.jdsClient.saveJobState(jobState, function(error, response, result) { // self.log.debug('JobStatusUpdater.writeStatus: Response from saveJobState: error: %s, response: %j, result: %j', error, response, result); // if (error) { // self.log.debug('JobStatusUpdat...
{ self.log.debug('JobStatusUpdater.writeStatus: Job has a record, covered by metastamp, don\'t record job state'); return callback(null, 'record job'); }
conditional_block
JobStatusUpdater.js
'use strict'; var _ = require('underscore'); var inspect = require(global.OSYNC_UTILS + 'inspect'); var logUtil = require(global.OSYNC_UTILS + 'log'); var JdsClient = require(global.OSYNC_SUBSYSTEMS + 'jds/jds-client'); function JobStatusUpdater(setLog, setConfig, jdsClient)
JobStatusUpdater.prototype.writeStatus = function(jobState, callback) { var self = this; jobState.timestamp = Date.now().toString(); if (_.isUndefined(jobState.rootJobId)) { jobState.rootJobId = jobState.jobId; } if (_.isUndefined(jobState.jpid) || _.isUndefined(jobState.rootJobId)) { ...
{ if (!(this instanceof JobStatusUpdater)) { return new JobStatusUpdater(setLog, setConfig, jdsClient); } this.jdsClient = jdsClient || new JdsClient(setLog, setConfig); this.log = logUtil.getAsChild('JobStatusUpdater', setLog); // this.log = require('bunyan').createLogger({ // name...
identifier_body
wizard.rs
use std::io::Result as IoResult; use std::process::{Command, Stdio, ChildStdin}; use std::path::Path; use std::iter::Iterator; use libudev::{Result as UdevResult, Context, Enumerator}; use common::config::{Config, SetupConfig, PciId}; use common::pci_device::PciDevice; use driver; use ask; use iommu; use usb; use vf...
{ Wizard.run(cfg, target, workdir, datadir); }
identifier_body
wizard.rs
use std::io::Result as IoResult; use std::process::{Command, Stdio, ChildStdin}; use std::path::Path; use std::iter::Iterator; use libudev::{Result as UdevResult, Context, Enumerator}; use common::config::{Config, SetupConfig, PciId}; use common::pci_device::PciDevice; use driver; use ask; use iommu; use usb; use vf...
() -> UdevResult<Vec<PciId>> { let udev = Context::new().expect("Failed to create udev context"); let mut iter = Enumerator::new(&udev)?; iter.match_property("DRIVER", "vfio-pci")?; Ok(iter.scan_devices()?.map(PciDevice::new).map(|x| x.id).collect()) } pub fn sudo_write_file<P: AsRef<Path>, F: FnOnce...
get_passthrough_devs
identifier_name
wizard.rs
use std::io::Result as IoResult; use std::process::{Command, Stdio, ChildStdin}; use std::path::Path; use std::iter::Iterator; use libudev::{Result as UdevResult, Context, Enumerator}; use common::config::{Config, SetupConfig, PciId}; use common::pci_device::PciDevice; use driver; use ask; use iommu; use usb; use vf...
config.save(cfg_path); if !vfio::setup(&mut config.machine) { return; } config.save(cfg_path); let passthrough_devs = get_passthrough_devs().expect("Failed to check gpu passthrough with udev"); if passthrough_devs.is_empty() { if !initramfs::reb...
{ return; }
conditional_block
wizard.rs
use std::io::Result as IoResult; use std::process::{Command, Stdio, ChildStdin}; use std::path::Path; use std::iter::Iterator; use libudev::{Result as UdevResult, Context, Enumerator}; use common::config::{Config, SetupConfig, PciId}; use common::pci_device::PciDevice; use driver; use ask; use iommu; use usb; use vf...
println!("Your VM is going to boot now."); println!("Just install Windows and shut it down cleanly as soon as that's done so we can continue."); println!(); println!("Note: Windows probably won't pick up the virtio-scsi storage device right away. You can load the drivers...
config.save(cfg_path);
random_line_split
libarchive2.py
for reading. You must call close() when done to free up resources and avoid leaks. Or use instead the Archive class as a context manager with `with`. """ # first close any existing opened struct for this file self.close() self.archive_struct = archive_reader() if...
class Entry(object): """ Represent an Archive Entry, typically a file or a directory. The attribute names are loosely based on the stdlib tarfile module Tarfile attributes.Some attributes are not handled on purpose because they are never used: things such as modes/perms/users/groups are never res...
return self.iter()
identifier_body
libarchive2.py
for reading. You must call close() when done to free up resources and avoid leaks. Or use instead the Archive class as a context manager with `with`. """ # first close any existing opened struct for this file self.close() self.archive_struct = archive_reader() if...
e = Entry(self, entry_struct) except ArchiveWarning, aw: if aw.msg and aw.msg not in e.warnings: e.warnings.append(aw.msg) yield e finally: if entry_struct: free_entry(entry_struct) ...
return
conditional_block
libarchive2.py
chunk_size = 1 while chunk_size: chunk_size = read_entry_data(self.archive.archive_struct, sbuffer, chunk_len) data = sbuffer.raw[0:chunk_size] target.write(data) os.u...
next_entry = libarchive.archive_read_next_header2 next_entry.argtypes = [c_void_p, c_void_p] next_entry.restype = c_int next_entry.errcheck = errcheck
random_line_split
libarchive2.py
for reading. You must call close() when done to free up resources and avoid leaks. Or use instead the Archive class as a context manager with `with`. """ # first close any existing opened struct for this file self.close() self.archive_struct = archive_reader() if...
(ArchiveException): pass ################################## # C ctypes interface to libarchive ################################## def errcheck(rc, archive_func, args, null=False): """ ctypes error check handler for functions returning int or or null if null is True. """ if null: if rc...
ArchiveErrorIllegalOperationOnClosedArchive
identifier_name
manager.py
import os import hashlib import flask from sparkpost import SparkPost from infosystem.common import exception from infosystem.common.subsystem import manager from infosystem.common.subsystem import operation _HTML_EMAIL_TEMPLATE = """ <div style="width: 100%; text-align: center"> <h1>{app_name}</h1> ...
para confirmar esse email e criar uma senha.</p> <div style="width: 100%; text-align: center"> <a href="{reset_url}">Clique aqui para CONFIRMAR o email e CRIAR uma senha.</a> </div> """ def send_email(token_id, user, domain): try: sparkpost = SparkPost() defau...
<p>Para ter acesso ao sistema você deve clicar no link abaixo
random_line_split
manager.py
import os import hashlib import flask from sparkpost import SparkPost from infosystem.common import exception from infosystem.common.subsystem import manager from infosystem.common.subsystem import operation _HTML_EMAIL_TEMPLATE = """ <div style="width: 100%; text-align: center"> <h1>{app_name}</h1> ...
self.user = users[0] return True def do(self, session, **kwargs): token = self.manager.api.tokens.create(user=self.user) send_email(token.id, self.user, self.domain) class Reset(operation.Operation): def pre(self, **kwargs): self.token = flask.request.headers.get('t...
f pre(self, **kwargs): email = kwargs.get('email', None) domain_name = kwargs.get('domain_name', None) infosystem_reset_url = os.environ.get( 'INFOSYSTEM_RESET_URL', 'http://objetorelacional.com.br/#/reset/') self.reset_url = kwargs.get('reset_url', infosystem_reset_url) ...
identifier_body
manager.py
import os import hashlib import flask from sparkpost import SparkPost from infosystem.common import exception from infosystem.common.subsystem import manager from infosystem.common.subsystem import operation _HTML_EMAIL_TEMPLATE = """ <div style="width: 100%; text-align: center"> <h1>{app_name}</h1> ...
elf, session, **kwargs): self.entity = super().do(session, **kwargs) self.token = self.manager.api.tokens.create( session=session, user=self.entity) self.domain = self.manager.api.domains.get(id=self.entity.domain_id) if not self.domain: raise exception.Operatio...
(s
identifier_name
manager.py
import os import hashlib import flask from sparkpost import SparkPost from infosystem.common import exception from infosystem.common.subsystem import manager from infosystem.common.subsystem import operation _HTML_EMAIL_TEMPLATE = """ <div style="width: 100%; text-align: center"> <h1>{app_name}</h1> ...
domains = self.manager.api.domains.list(name=domain_name) if not domains: raise exception.OperationBadRequest() self.domain = domains[0] users = self.manager.api.users.list( email=email, domain_id=self.domain.id) if not users: raise exception...
ise exception.OperationBadRequest()
conditional_block
test_molecule.py
# -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2015 The HORTON Development Team # # This file is part of HORTON. # # HORTON is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by th...
(): fn_fchk = context.get_fn('test/water_sto3g_hf_g03.fchk') fn_log = context.get_fn('test/water_sto3g_hf_g03.log') mol1 = IOData.from_file(fn_fchk, fn_log) mol2 = mol1.copy() assert mol1 != mol2 vars1 = vars(mol1) vars2 = vars(mol2) assert len(vars1) == len(vars2) for key1, value1 i...
test_copy
identifier_name
test_molecule.py
# -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2015 The HORTON Development Team # # This file is part of HORTON. # # HORTON is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by th...
def test_dm_ch3_rohf_g03(): fn_fchk = context.get_fn('test/ch3_rohf_sto3g_g03.fchk') mol = IOData.from_file(fn_fchk) olp = mol.obasis.compute_overlap(mol.lf) dm = mol.get_dm_full() assert abs(olp.contract_two('ab,ab', dm) - 9) < 1e-6 dm = mol.get_dm_spin() assert abs(olp.contract_two('ab...
fn_fchk = context.get_fn('test/li_h_3-21G_hf_g09.fchk') mol = IOData.from_file(fn_fchk) dm = mol.get_dm_full() assert abs(dm.get_element(0, 0) - 1.96589709) < 1e-7 assert abs(dm.get_element(0, 1) - 0.122114249) < 1e-7 assert abs(dm.get_element(1, 1) - 0.0133112081) < 1e-7 assert abs(dm.get_elem...
identifier_body
test_molecule.py
# -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2015 The HORTON Development Team # # This file is part of HORTON. # # HORTON is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by th...
def test_dm_water_sto3g_hf(): fn_fchk = context.get_fn('test/water_sto3g_hf_g03.fchk') mol = IOData.from_file(fn_fchk) dm = mol.get_dm_full() assert abs(dm.get_element(0, 0) - 2.10503807) < 1e-7 assert abs(dm.get_element(0, 1) - -0.439115917) < 1e-7 assert abs(dm.get_element(1, 1) - 1.9331206...
assert value1 is vars2[key1]
conditional_block
test_molecule.py
# -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2015 The HORTON Development Team # # This file is part of HORTON. # # HORTON is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by th...
# #-- #pylint: skip-file import numpy as np from nose.tools import assert_raises from horton import * def test_typecheck(): m = IOData(coordinates=np.array([[1, 2, 3], [2, 3, 1]])) assert issubclass(m.coordinates.dtype.type, float) assert not hasattr(m, 'numbers') m = IOData(numbers=np.array([2, 3]...
random_line_split
urls.py
"""django_todo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Clas...
Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r...
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
random_line_split
photo.service.ts
import { Injectable } from '@angular/core'; import { Http, Response, Headers } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Observable } from 'rxjs'; import 'rxjs/Rx'; import { environment } from '../../environments/environment'; @Injectable() export class PhotoService { private results: Obs...
(error: Response | any) { let errMsg: string; if (error instanceof Response) { errMsg = `${error.status} - ${error.statusText || ''}`; } else { errMsg = error.message ? error.message : error.toString(); } console.error(errMsg); return Observable.throw(errMsg); } }
handleError
identifier_name
photo.service.ts
import { Injectable } from '@angular/core'; import { Http, Response, Headers } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Observable } from 'rxjs'; import 'rxjs/Rx'; import { environment } from '../../environments/environment'; @Injectable() export class PhotoService { private results: Obs...
}
{ let errMsg: string; if (error instanceof Response) { errMsg = `${error.status} - ${error.statusText || ''}`; } else { errMsg = error.message ? error.message : error.toString(); } console.error(errMsg); return Observable.throw(errMsg); }
identifier_body
photo.service.ts
import { Injectable } from '@angular/core'; import { Http, Response, Headers } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Observable } from 'rxjs'; import 'rxjs/Rx'; import { environment } from '../../environments/environment'; @Injectable() export class PhotoService { private results: Obs...
} }
random_line_split
photo.service.ts
import { Injectable } from '@angular/core'; import { Http, Response, Headers } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Observable } from 'rxjs'; import 'rxjs/Rx'; import { environment } from '../../environments/environment'; @Injectable() export class PhotoService { private results: Obs...
console.error(errMsg); return Observable.throw(errMsg); } }
{ errMsg = error.message ? error.message : error.toString(); }
conditional_block
score.py
# Copyright (C) 2013-2014 Fox Wilson, Peter Foley, Srijay Kasturi, Samuel Damashek, James Forcier and Reed Koser # # 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 2 # of the Licen...
(s, n): if n == 1: return s else: return s + 's' @Command('score', ['config', 'db', 'botnick']) def cmd(send, msg, args): """Gets scores. Syntax: {command} <--high|--low|nick> """ if not args['config']['feature'].getboolean('hooks'): send("Hooks are disabled, and this c...
pluralize
identifier_name
score.py
# Copyright (C) 2013-2014 Fox Wilson, Peter Foley, Srijay Kasturi, Samuel Damashek, James Forcier and Reed Koser # # 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 2 # of the Licen...
@Command('score', ['config', 'db', 'botnick']) def cmd(send, msg, args): """Gets scores. Syntax: {command} <--high|--low|nick> """ if not args['config']['feature'].getboolean('hooks'): send("Hooks are disabled, and this command depends on hooks. Please contact the bot admin(s).") retu...
if n == 1: return s else: return s + 's'
identifier_body
score.py
# Copyright (C) 2013-2014 Fox Wilson, Peter Foley, Srijay Kasturi, Samuel Damashek, James Forcier and Reed Koser # # 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 2 # of the Licen...
else: count = session.query(Scores).count() if count == 0: send("Nobody cares about anything =(") else: randid = randint(1, count) query = session.query(Scores).get(randid) send("%s has %i %s!" % (query.nick, query.score, pluralize('point', qu...
send("Invalid nick")
conditional_block
score.py
# Copyright (C) 2013-2014 Fox Wilson, Peter Foley, Srijay Kasturi, Samuel Damashek, James Forcier and Reed Koser # # 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 2 # of the Licen...
if name == 'c': send("We all know you love C better than anything else, so why rub it in?") return score = session.query(Scores).filter(Scores.nick == name).scalar() if score is not None: if name == args['botnick'].lower(): ...
random_line_split
value.rs
//! Deserialization of a `Value<T>` type which tracks where it was deserialized //! from. //! //! Often Cargo wants to report semantic error information or other sorts of //! error information about configuration keys but it also may wish to indicate //! as an error context where the key was defined as well (to help us...
} impl<'de> de::Deserialize<'de> for Definition { fn deserialize<D>(deserializer: D) -> Result<Definition, D::Error> where D: de::Deserializer<'de>, { let (discr, value) = <(u32, String)>::deserialize(deserializer)?; match discr { 0 => Ok(Definition::Path(value.into()))...
{ deserializer.deserialize_identifier(FieldVisitor { expected: DEFINITION_FIELD, })?; Ok(DefinitionKey) }
identifier_body
value.rs
//! Deserialization of a `Value<T>` type which tracks where it was deserialized //! from. //! //! Often Cargo wants to report semantic error information or other sorts of //! error information about configuration keys but it also may wish to indicate //! as an error context where the key was defined as well (to help us...
D: de::Deserializer<'de>, { deserializer.deserialize_identifier(FieldVisitor { expected: VALUE_FIELD, })?; Ok(ValueKey) } } struct DefinitionKey; impl<'de> de::Deserialize<'de> for DefinitionKey { fn deserialize<D>(deserializer: D) -> Result<DefinitionKey, D::Er...
fn deserialize<D>(deserializer: D) -> Result<ValueKey, D::Error> where
random_line_split
value.rs
//! Deserialization of a `Value<T>` type which tracks where it was deserialized //! from. //! //! Often Cargo wants to report semantic error information or other sorts of //! error information about configuration keys but it also may wish to indicate //! as an error context where the key was defined as well (to help us...
(&self, other: &Definition) -> bool { match (self, other) { (Definition::Cli, Definition::Environment(_)) => true, (Definition::Cli, Definition::Path(_)) => true, (Definition::Environment(_), Definition::Path(_)) => true, _ => false, } } } impl Partia...
is_higher_priority
identifier_name
app.py
is the position of the applicant?', [rating_validator], choices=[('100', 'Pick one..'), ('0', 'Undergrad'), ('1', 'M.Sc./Ph.D. student or health pro.'), ('2', 'Postdoc, Associate Prof. or M.D.'), ('3', 'Principal Investigator')]) inst = SelectField('How do you rate the institution?', [rating_validator]...
(exception): db = getattr(g, 'db', None) if db is not None: db.close() def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if not 'user' in session: return redirect(url_for('login')) return f(*args, **kwargs) return decorated_function ######...
teardown_request
identifier_name
app.py
think is the position of the applicant?', [rating_validator], choices=[('100', 'Pick one..'), ('0', 'Undergrad'), ('1', 'M.Sc./Ph.D. student or health pro.'), ('2', 'Postdoc, Associate Prof. or M.D.'), ('3', 'Principal Investigator')]) inst = SelectField('How do you rate the institution?', [rating_vali...
g.db.execute(insert_abstract_rating, (session['a'][0], session['user'], form.abstract.data, form.english.data)) g.db.commit() session['rated'] += 1 return redirect(url_for('added', type='abstract')) return render_template('abstracts.html', form=form, a=session['a'], ...
random_line_split
app.py
is the position of the applicant?', [rating_validator], choices=[('100', 'Pick one..'), ('0', 'Undergrad'), ('1', 'M.Sc./Ph.D. student or health pro.'), ('2', 'Postdoc, Associate Prof. or M.D.'), ('3', 'Principal Investigator')]) inst = SelectField('How do you rate the institution?', [rating_validator]...
@app.route('/results') @login_required def results(): persons = pd.read_sql("select * from persons", g.db) ratings = pd.read_sql(average_ratings, g.db) abstracts = pd.read_sql(average_abstracts, g.db) persons = pd.merge(persons, ratings, on='pid', how='left') persons = pd.merge(persons, abstracts,...
return render_template('added.html', rated=session['rated'], user=session['user'], role=session['role'], type=type)
identifier_body
app.py
How do you rate the institution?', [rating_validator], choices=[('100', 'Pick one..'), ('0', 'dubious'), ('1', 'average'), ('2', 'national leader'), ('3', 'international leader')]) dist = SelectField('How do you rate the travel distance?', [rating_validator], choices=[('100', 'Pick one..'), ('0', 'local...
raise ValueError("Wrong numbers of columns in talk data!")
conditional_block
0011_auto_20200728_2316.py
# Generated by Django 2.2.13 on 2020-07-28 23:16 from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('linked_domain', '0010_auto_20200622_0156'), ] operations = [ migrations.AlterField( model_name='domainlinkhistory', name='model', field=models.CharField(choices=[('app', 'Application'), ('custom_user_data', 'Custom User Data Fields'), ('cus...
identifier_body
0011_auto_20200728_2316.py
# Generated by Django 2.2.13 on 2020-07-28 23:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('linked_domain', '0010_auto_20200622_0156'), ] operations = [ migrations.AlterField(
), ]
model_name='domainlinkhistory', name='model', field=models.CharField(choices=[('app', 'Application'), ('custom_user_data', 'Custom User Data Fields'), ('custom_product_data', 'Custom Product Data Fields'), ('custom_location_data', 'Custom Location Data Fields'), ('roles', 'User Roles...
random_line_split
0011_auto_20200728_2316.py
# Generated by Django 2.2.13 on 2020-07-28 23:16 from django.db import migrations, models class
(migrations.Migration): dependencies = [ ('linked_domain', '0010_auto_20200622_0156'), ] operations = [ migrations.AlterField( model_name='domainlinkhistory', name='model', field=models.CharField(choices=[('app', 'Application'), ('custom_user_data', 'Cus...
Migration
identifier_name
plane.rs
extern crate tray_rust; extern crate rand; extern crate image; use std::sync::Arc; use rand::StdRng; use tray_rust::linalg::{AnimatedTransform, Transform, Point, Vector}; use tray_rust::film::{Colorf, RenderTarget, Camera, ImageSample}; use tray_rust::film::filter::MitchellNetravali; use tray_rust::geometry::{Rectang...
() { let width = 800usize; let height = 600usize; let filter = Box::new(MitchellNetravali::new(2.0, 2.0, 0.333333333333333333, 0.333333333333333333)); let rt = RenderTarget::new((width, height), (20, 20), filter); let transform = AnimatedTransform::unanimated(&Transform::look_at(&Poi...
main
identifier_name
plane.rs
extern crate tray_rust; extern crate rand; extern crate image; use std::sync::Arc; use rand::StdRng; use tray_rust::linalg::{AnimatedTransform, Transform, Point, Vector}; use tray_rust::film::{Colorf, RenderTarget, Camera, ImageSample}; use tray_rust::film::filter::MitchellNetravali; use tray_rust::geometry::{Rectang...
let dim = rt.dimensions(); // A block queue is how work is distributed among threads, it's a list of tiles // of the image that have yet to be rendered. Each thread will pull a block from // this queue and render it. let block_queue = BlockQueue::new((dim.0 as u32, dim.1 as u32), (8, 8), (0, 0)); ...
random_line_split
plane.rs
extern crate tray_rust; extern crate rand; extern crate image; use std::sync::Arc; use rand::StdRng; use tray_rust::linalg::{AnimatedTransform, Transform, Point, Vector}; use tray_rust::film::{Colorf, RenderTarget, Camera, ImageSample}; use tray_rust::film::filter::MitchellNetravali; use tray_rust::geometry::{Rectang...
AnimatedTransform::unanimated(&Transform::translate(&Vector::new(0.0, 2.0, 0.0))); let instance = Instance::receiver(geometry_lock, material_lock, position_transform, "single_plane".to_string())...
{ let width = 800usize; let height = 600usize; let filter = Box::new(MitchellNetravali::new(2.0, 2.0, 0.333333333333333333, 0.333333333333333333)); let rt = RenderTarget::new((width, height), (20, 20), filter); let transform = AnimatedTransform::unanimated(&Transform::look_at(&Point:...
identifier_body
conf.py
-*- coding: utf-8 -*- # # pyramid_sms documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 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. # ...
htmlhelp_basename = 'pyramid_smsdoc' # -- Options for LaTeX output ------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for t...
# Output file base name for HTML help builder.
random_line_split
api_handler.rs
use typeable::Typeable; use traitobject; use std::any::TypeId; use std::mem; use backend; use super::{CallInfo}; use json::{JsonValue}; pub trait ApiHandler: Typeable { fn api_call<'a, 'b>(&'a self, &str, &mut JsonValue, &'b mut (backend::Request + 'b), &mut CallInfo<'a>) -> backend::HandleResult<backend::Respons...
pub type ApiHandlers = Vec<Box<ApiHandler + Send + Sync>>;
random_line_split
api_handler.rs
use typeable::Typeable; use traitobject; use std::any::TypeId; use std::mem; use backend; use super::{CallInfo}; use json::{JsonValue}; pub trait ApiHandler: Typeable { fn api_call<'a, 'b>(&'a self, &str, &mut JsonValue, &'b mut (backend::Request + 'b), &mut CallInfo<'a>) -> backend::HandleResult<backend::Respons...
} pub type ApiHandlers = Vec<Box<ApiHandler + Send + Sync>>;
{ mem::transmute(traitobject::data(self)) }
identifier_body
api_handler.rs
use typeable::Typeable; use traitobject; use std::any::TypeId; use std::mem; use backend; use super::{CallInfo}; use json::{JsonValue}; pub trait ApiHandler: Typeable { fn api_call<'a, 'b>(&'a self, &str, &mut JsonValue, &'b mut (backend::Request + 'b), &mut CallInfo<'a>) -> backend::HandleResult<backend::Respons...
<T: ApiHandler>(&mut self) -> Option<&mut T> { if self.is::<T>() { unsafe { Some(self.downcast_mut_unchecked()) } } else { None } } /// Returns a mutable reference to the boxed value, blindly assuming it to be of type `T`. /// If y...
downcast_mut
identifier_name
api_handler.rs
use typeable::Typeable; use traitobject; use std::any::TypeId; use std::mem; use backend; use super::{CallInfo}; use json::{JsonValue}; pub trait ApiHandler: Typeable { fn api_call<'a, 'b>(&'a self, &str, &mut JsonValue, &'b mut (backend::Request + 'b), &mut CallInfo<'a>) -> backend::HandleResult<backend::Respons...
} /// Returns a mutable reference to the boxed value, blindly assuming it to be of type `T`. /// If you are not *absolutely certain* of `T`, you *must not* call this. #[inline] pub unsafe fn downcast_mut_unchecked<T: ApiHandler> (&mut self) -> &mut T { ...
{ None }
conditional_block
mass_hash_request.py
import tarfile from datetime import datetime from mass_api_client import ConnectionManager from mass_api_client.resources import Sample, FileSample, IPSample, URISample, DomainSample PROGRAM_NAME = "MASS Hash Request" PROGRAM_VERSION = "0.1" PROGRAM_DESCRIPTION = "This tool queries a MASS server for multiple hash s...
for h, result in query_results.items(): path = base_dir + '/' + h touch_path(path) if result: generate_file_dirs(path, result) else: generate_no_file_found_file(path) if options.print_missing: print(h) def make_archive(path): ...
def generate_file_structure(base_dir, query_results, options): if not os.path.exists(base_dir): os.mkdir(base_dir)
random_line_split
mass_hash_request.py
import tarfile from datetime import datetime from mass_api_client import ConnectionManager from mass_api_client.resources import Sample, FileSample, IPSample, URISample, DomainSample PROGRAM_NAME = "MASS Hash Request" PROGRAM_VERSION = "0.1" PROGRAM_DESCRIPTION = "This tool queries a MASS server for multiple hash s...
def save_configuration(config, config_path): with open(config_path, "w") as fp: json.dump(config, fp, indent=4, sort_keys=True) def update_config_from_options(config, options): if options.hash_type: if options.hash_type in config['hashes']: config['hash'] = options.hash_type ...
config = dict() config['base_url'] = 'http://localhost:5000/api/' config['api_key'] = '' config['hash'] = 'md5' config['hashes'] = ['md5', 'sha1', 'sha256', 'sha512'] config['directory'] = 'mhr_result' return config
identifier_body
mass_hash_request.py
import tarfile from datetime import datetime from mass_api_client import ConnectionManager from mass_api_client.resources import Sample, FileSample, IPSample, URISample, DomainSample PROGRAM_NAME = "MASS Hash Request" PROGRAM_VERSION = "0.1" PROGRAM_DESCRIPTION = "This tool queries a MASS server for multiple hash s...
else: generate_no_file_found_file(path) if options.print_missing: print(h) def make_archive(path): with tarfile.open('result_archive.tar.gz', 'w:gz') as tar: tar.add(path) if __name__ == '__main__': args = _setup_argparser() _setup_logging(args) ...
generate_file_dirs(path, result)
conditional_block
mass_hash_request.py
import tarfile from datetime import datetime from mass_api_client import ConnectionManager from mass_api_client.resources import Sample, FileSample, IPSample, URISample, DomainSample PROGRAM_NAME = "MASS Hash Request" PROGRAM_VERSION = "0.1" PROGRAM_DESCRIPTION = "This tool queries a MASS server for multiple hash s...
(config_path): if not os.path.exists(config_path): print("configuration file not found.\ncreating config: config.json ") config = create_config() save_configuration(config, config_path) else: with open(config_path, "r") as fp: config = json.load(fp) return config ...
load_configuration
identifier_name
setup_payload.py
# # Copyright (c) 2021 Project CHIP Authors # # 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 applica...
def AddVendorAttribute(tag, value): self.vendor_attributes[tag] = value.decode() self.attribute_visitor = SetupPayload.AttributeVisitor(AddAttribute) self.vendor_attribute_visitor = SetupPayload.VendorAttributeVisitor( AddVendorAttribute) def ParseQrCode(self, qrC...
self.attributes[name.decode()] = value.decode()
identifier_body
setup_payload.py
# # Copyright (c) 2021 Project CHIP Authors # # 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 applica...
self.__InitNativeFunctions(self.chipLib) self.attributes = {} self.vendor_attributes = {} def AddAttribute(name, value): self.attributes[name.decode()] = value.decode() def AddVendorAttribute(tag, value): self.vendor_attributes[tag] = value.decode() ...
self.chipLib = GetLibraryHandle()
random_line_split
setup_payload.py
# # Copyright (c) 2021 Project CHIP Authors # # 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 applica...
(self, manualPairingCode: str): self.Clear() err = self.chipLib.pychip_SetupPayload_ParseManualPairingCode(manualPairingCode.encode(), self.attribute_visitor, self....
ParseManualPairingCode
identifier_name
setup_payload.py
# # Copyright (c) 2021 Project CHIP Authors # # 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 applica...
def Print(self): for name, value in self.attributes.items(): decorated_value = self.__DecorateValue(name, value) decorated_value = f" [{decorated_value}]" if decorated_value else "" print(f"{name}: {value}{decorated_value}") for tag in self.vendor_attributes: ...
raise ChipStackError(err)
conditional_block
0002_comment.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class
(migrations.Migration): dependencies = [ ('blogg', '0001_initial'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), (...
Migration
identifier_name
0002_comment.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
}, bases=(models.Model,), ), ]
dependencies = [ ('blogg', '0001_initial'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('content', models.TextField(m...
identifier_body
0002_comment.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('blogg', '0001_initial'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ...
'ordering': ['-created'], }, bases=(models.Model,), ), ]
('post', models.ForeignKey(related_name='comments', to='blogg.Post')), ], options={
random_line_split
foo.rs
Ints(isize, isize), Floats(f64, f64), Strings(&'a str, &'a str, &'a str), MyTypes(MyType, MyType), } #[derive(Copy, Clone)] enum SomeOtherEnum { SomeConst1, SomeConst2, SomeConst3, } enum SomeStructEnum { EnumStruct { a: isize, b: isize }, EnumStruct2 { f1: MyType, f2: MyType }, ...
ls6
identifier_name
foo.rs
, x: u32) -> u32 { println(&x.to_string()); 42 } fn provided_method(&self) -> u32 { 42 } } trait SubTrait: SomeTrait { fn stat2(x: &Self) -> u32 { 32 } } trait SizedTrait: Sized {} fn error(s: &SizedTrait) { let foo = 42; println!("Hello world! {}", foo); }...
r
identifier_body
foo.rs
UT_BITS: usize = 3; pub struct HuffmanTable { ac_lut: Option<[(i16, u8); 1 << LUT_BITS]>, } struct TupStruct(isize, isize, Box<str>); fn test_tup_struct(x: TupStruct) -> isize { x.1 } fn println(s: &str) { std::io::stdout().write_all(s.as_bytes()); } mod sub { pub mod sub2 { use std::io::Wri...
#[path = "SameDir3.rs"] pub mod SameDir2; struct nofields; #[derive(Clone)] struct some_fields { field1: u32, } type SF = some_fields; trait SuperTrait { fn qux(&self) { panic!(); } } trait SomeTrait: SuperTrait { fn Method(&self, x: u32) -> u32; fn prov(&self, x: u32) -> u32 { ...
} } pub mod SameDir; pub mod SubDir;
random_line_split
contact-form.js
/** * Contact Form */ jQuery(document).ready(function ($) { var showErrors = true; //show text errors? var sendingMessage = 'Sending...'; var debug = false; //show system errors var $f = $('.contactForm'); var $submit = $f.find('input[type="submit"]'); $f.submit(function () { ...
$submit.attr('data-value', $submit.val()).val(sendingMessage).addClass('disabled'); $.ajax({ url: $f.attr('action'), method: 'post', data: $f.serialize(), dataType: 'json', success: function (data) { $('input.error', ...
{ return false; }
conditional_block
contact-form.js
/** * Contact Form */ jQuery(document).ready(function ($) { var showErrors = true; //show text errors? var sendingMessage = 'Sending...'; var debug = false; //show system errors var $f = $('.contactForm'); var $submit = $f.find('input[type="submit"]'); $f.submit(function () { ...
alert(data.responseText); } $submit.val($submit.attr('data-value')).removeClass('disabled'); } }); return false; }); });
$submit.val($submit.attr('data-value')).removeClass('disabled'); }, error: function (data) { if (debug) {
random_line_split
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # 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 ...
def load(info): # Augment the collection creation and edit routes to accept a terms field events.bind('rest.post.collection.after', 'terms', afterPostPutCollection) events.bind('rest.put.collection/:id.after', 'terms', afterPostPutCollection) for handler in [ Collection.createCollection, ...
extraParams = event.info['params'] if 'terms' in extraParams: collectionResponse = event.info['returnVal'] collectionId = collectionResponse['_id'] terms = extraParams['terms'] ModelImporter.model('collection').update( {'_id': collectionId}, {'$set': {'terms'...
identifier_body
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # 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 ...
# Expose the terms field on all collections ModelImporter.model('collection').exposeFields(level=AccessType.READ, fields={'terms'}) # Add endpoint for registered users to accept terms info['apiRoot'].collection.route('POST', (':id', 'acceptTerms'), acceptCollectionTerms) # Expose the terms field...
handler.description.param('terms', 'The Terms of Use for the collection.', required=False)
conditional_block
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # 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 ...
# 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