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 |
|---|---|---|---|---|
nodeHealthReport.js | /*
* 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 may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | () {
super();
}
/**
* Defines the metadata of NodeHealthReport
*
* @returns {object} metadata of NodeHealthReport
*
*/
mapper() {
return {
required: false,
serializedName: 'NodeHealthReport',
type: {
name: 'Composite',
className: 'NodeHealthReport',
... | constructor | identifier_name |
nodeHealthReport.js | /*
* 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 may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... |
/**
* Defines the metadata of NodeHealthReport
*
* @returns {object} metadata of NodeHealthReport
*
*/
mapper() {
return {
required: false,
serializedName: 'NodeHealthReport',
type: {
name: 'Composite',
className: 'NodeHealthReport',
modelProperties: {
... | {
super();
} | identifier_body |
nodeHealthReport.js | /*
* 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 may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | }
},
sequenceNumber: {
required: false,
serializedName: 'SequenceNumber',
type: {
name: 'String'
}
},
removeWhenExpired: {
required: false,
serializedName: 'RemoveWhenExpired',
... | random_line_split | |
beta_decrease.py | from .naive import StratNaive
import random
import numpy as np
| StratNaive.__init__(self,vu_cfg=vu_cfg, **strat_cfg2)
self.time_scale = time_scale
def update_speaker(self, ms, w, mh, voc, mem, bool_succ, context=[]):
self.voc_update.beta = max(0,self.voc_update.beta - 1./self.time_scale)
return self.voc_update.update_speaker(ms, w, mh, voc, mem, bool_succ, context)
def ... | class BetaDecreaseStrat(StratNaive):
def __init__(self, vu_cfg, time_scale=0.9, **strat_cfg2): | random_line_split |
beta_decrease.py |
from .naive import StratNaive
import random
import numpy as np
class BetaDecreaseStrat(StratNaive):
def __init__(self, vu_cfg, time_scale=0.9, **strat_cfg2):
StratNaive.__init__(self,vu_cfg=vu_cfg, **strat_cfg2)
self.time_scale = time_scale
def update_speaker(self, ms, w, mh, voc, mem, bool_succ, context=[]):
... |
def update_hearer(self, ms, w, mh, voc, mem, bool_succ, context=[]):
self.voc_update.beta = max(0,self.voc_update.beta - 1./self.time_scale)
return self.voc_update.update_hearer(ms, w, mh, voc, mem, bool_succ, context)
| self.voc_update.beta = max(0,self.voc_update.beta - 1./self.time_scale)
return self.voc_update.update_speaker(ms, w, mh, voc, mem, bool_succ, context) | identifier_body |
beta_decrease.py |
from .naive import StratNaive
import random
import numpy as np
class BetaDecreaseStrat(StratNaive):
def __init__(self, vu_cfg, time_scale=0.9, **strat_cfg2):
StratNaive.__init__(self,vu_cfg=vu_cfg, **strat_cfg2)
self.time_scale = time_scale
def | (self, ms, w, mh, voc, mem, bool_succ, context=[]):
self.voc_update.beta = max(0,self.voc_update.beta - 1./self.time_scale)
return self.voc_update.update_speaker(ms, w, mh, voc, mem, bool_succ, context)
def update_hearer(self, ms, w, mh, voc, mem, bool_succ, context=[]):
self.voc_update.beta = max(0,self.voc_up... | update_speaker | identifier_name |
views.py | from rest_framework.decorators import api_view
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework import status
from .models import Person
from .serializers import PersonSerializer
@api_view(['GET', 'DELETE', 'PUT'])
def get_delete_update_person(request, fs... | return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | if request.method == 'GET':
people = Person.objects.all()
serializer = PersonSerializer(people, many=True)
return Response(serializer.data)
# insert a new record for a person
elif request.method == 'POST':
data = {
'firstname': request.data.get('firstname'),
... | identifier_body |
views.py | from rest_framework.decorators import api_view
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework import status
from .models import Person
from .serializers import PersonSerializer
@api_view(['GET', 'DELETE', 'PUT'])
def get_delete_update_person(request, fs... |
@api_view(['GET', 'POST'])
def get_post_people(request):
# get all people
if request.method == 'GET':
people = Person.objects.all()
serializer = PersonSerializer(people, many=True)
return Response(serializer.data)
# insert a new record for a person
elif request.method == 'POST... | serializer = PersonSerializer(person, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_204_NO_CONTENT)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | conditional_block |
views.py | from rest_framework.decorators import api_view
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework import status
from .models import Person
from .serializers import PersonSerializer
@api_view(['GET', 'DELETE', 'PUT'])
def get_delete_update_person(request, fs... | (request):
# get all people
if request.method == 'GET':
people = Person.objects.all()
serializer = PersonSerializer(people, many=True)
return Response(serializer.data)
# insert a new record for a person
elif request.method == 'POST':
data = {
'firstname': requ... | get_post_people | identifier_name |
views.py | from rest_framework.decorators import api_view
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework import status
from .models import Person
from .serializers import PersonSerializer
@api_view(['GET', 'DELETE', 'PUT'])
def get_delete_update_person(request, fs... | person.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
# update details of a single person
elif request.method == 'PUT':
serializer = PersonSerializer(person, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serial... | # delete a single person
elif request.method == 'DELETE': | random_line_split |
webdav.py | , exc:
raise dputhelper.DputUploadFatalException("Unknown key (%s) in incoming templates '%s'" % (exc, incoming))
trace("Resolved incoming to `%(url)s' params=%(params)r", url=url, params=url_params)
return url, url_params
def _url_connection(url, method, skip_host=False, skip_accept_encoding=False):... | if not overwrite and changes_file:
try:
_check_url(_file_url(changes_file, incoming), [404])
except urllib2.HTTPError, exc:
raise dputhelper.DputUploadFatalException("Overwriting existing changes at '%s' not allowed: %s" % (
... | conditional_block | |
webdav.py | , realm, authuri):
"""Prompt for a password once and remember it, unless already provided in the configuration."""
authuri = self.reduce_uri(authuri)[0]
authinfo = urllib2.HTTPPasswordMgr.find_user_password(self, realm, authuri)
if authinfo == (None, None):
credentials = sel... | if changes.startswith("-----BEGIN PGP SIGNED MESSAGE-----"):
# Let someone else check this, we don't care a bit; gimme the data already
trace("Extracting package metadata from PGP signed message...")
changes = changes.split("-----BEGIN PGP")[1].replace('\r', '').split('\n\n',... | with closing(open(changes, "r")) as handle:
changes = handle.read()
else:
changes = changes.read() # pylint: disable=maybe-no-member
| random_line_split |
webdav.py | result = os.path.abspath(os.path.expanduser(result.split(':', 1)[1]))
with closing(open(result, "r")) as handle:
result = handle.read().strip()
try:
user, pwd = result.split(':', 1)
except ValueError:
user, pwd = result, ""
trace("Res... | """Look up special forms of credential references."""
result = login
if "$" in result:
result = os.path.expandvars(result)
if result.startswith("netrc:"):
result = result.split(':', 1)[1]
if result:
result = os.path.abspath(os.path.expanduser(result))
accounts = ... | identifier_body | |
webdav.py | (msg, **kwargs):
"""Emit log traces in debug mode."""
if trace.debug:
print("D: webdav: " + (msg % kwargs))
trace.debug = False
def log(msg, **kwargs):
"""Emit log message to stderr."""
sys.stdout.flush()
sys.stderr.write("webdav: " + (msg % kwargs) + "\n")
sys.stderr.flush()
def _re... | trace | identifier_name | |
agent.py | #-*- coding: utf-8 -*-
'''
Created on 24 дек. 20%0
@author: ivan
'''
import random
all_agents = """
Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3
Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)
Mozilla/5.0 (Windows; U; Win... | Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; InfoPath.2)
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30729)
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Win64; x6... | Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.1 (KHTML, like Gecko) Chrome/4.0.219.6 Safari/532.1 | random_line_split |
agent.py | #-*- coding: utf-8 -*-
'''
Created on 24 дек. 20%0
@author: ivan
'''
import random
all_agents = """
Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3
Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)
Mozilla/5.0 (Windows; U; Win... | return agents.splitlines()[random.randint(1, 10)]
| nts = all_agents.replace(str(i), str(random.randint(0, 10)))
| conditional_block |
agent.py | #-*- coding: utf-8 -*-
'''
Created on 24 дек. 20%0
@author: ivan
'''
import random
all_agents = """
Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3
Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)
Mozilla/5.0 (Windows; U; Win... | nts = None
for i in xrange(10):
agents = all_agents.replace(str(i), str(random.randint(0, 10)))
return agents.splitlines()[random.randint(1, 10)]
| identifier_body | |
agent.py | #-*- coding: utf-8 -*-
'''
Created on 24 дек. 20%0
@author: ivan
'''
import random
all_agents = """
Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3
Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)
Mozilla/5.0 (Windows; U; Win... |
agents = None
for i in xrange(10):
agents = all_agents.replace(str(i), str(random.randint(0, 10)))
return agents.splitlines()[random.randint(1, 10)]
| _ranmom_agent(): | identifier_name |
__init__.py | # The MIT License (MIT)
#
# Copyright (c) 2013 Numenta, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, mod... | from version import version as __version__ | random_line_split | |
socketio-jwt-tests.ts | import * as fs from 'fs';
import * as http from 'http';
import * as SocketIo from 'socket.io';
import { authorize, JwtSecretFuncCallback } from 'socketio-jwt';
const app = http.createServer((req: any, rsp: any) => {
fs.readFile(__dirname + '/index.html',
(err: Error | null, data: any) => {
if (... |
rsp.writeHead(200);
rsp.end(data);
});
});
const io = SocketIo(app);
// This example test code is using the Node Http Server
io.on('connection', authorize({
secret: 'Your Secret Here'
}));
io.on('authenticated', (socket: SocketIo.Socket) => {
console.log('Authenticated!');
... | {
rsp.writeHead(500);
return rsp.end('Error loading index.html');
} | conditional_block |
socketio-jwt-tests.ts | import * as fs from 'fs';
import * as http from 'http';
import * as SocketIo from 'socket.io';
import { authorize, JwtSecretFuncCallback } from 'socketio-jwt';
const app = http.createServer((req: any, rsp: any) => {
fs.readFile(__dirname + '/index.html',
(err: Error | null, data: any) => {
if (... | (request: any, payload: any, callback: JwtSecretFuncCallback): void {
callback(null, secrets[payload.userId]);
}
// This example test code provides a callback function to get the secret
io.on('connection', authorize({
secret: secretFunc
}));
| secretFunc | identifier_name |
socketio-jwt-tests.ts | import * as fs from 'fs';
import * as http from 'http';
import * as SocketIo from 'socket.io';
import { authorize, JwtSecretFuncCallback } from 'socketio-jwt';
const app = http.createServer((req: any, rsp: any) => {
fs.readFile(__dirname + '/index.html',
(err: Error | null, data: any) => {
if (... |
// This example test code provides a callback function to get the secret
io.on('connection', authorize({
secret: secretFunc
}));
| {
callback(null, secrets[payload.userId]);
} | identifier_body |
socketio-jwt-tests.ts | import * as fs from 'fs';
import * as http from 'http';
import * as SocketIo from 'socket.io';
import { authorize, JwtSecretFuncCallback } from 'socketio-jwt';
const app = http.createServer((req: any, rsp: any) => {
fs.readFile(__dirname + '/index.html',
(err: Error | null, data: any) => {
if (... | console.log(JSON.stringify((socket as any).decoded_token));
});
const secrets: any = {
user1: 'secret 1',
user2: 'secret 2'
};
// Assume a claim name of userId
function secretFunc(request: any, payload: any, callback: JwtSecretFuncCallback): void {
callback(null, secrets[payload.userId]);
}
// This e... | io.on('authenticated', (socket: SocketIo.Socket) => {
console.log('Authenticated!'); | random_line_split |
region_IE.py | """Auto-generated file, do not edit by hand. IE metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
| toll_free=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
premium_rate=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
emergency=PhoneNumberDesc(national_number_pattern='112|999', possible_number_pattern='\\d{3}', example_number='112'),
short_cod... | PHONE_METADATA_IE = PhoneMetadata(id='IE', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='[159]\\d{2,4}', possible_number_pattern='\\d{3,5}'), | random_line_split |
rolling-array-test.js | import { isArray } from '@ember/array';
import { module, test } from 'qunit';
import RollingArray from 'nomad-ui/utils/classes/rolling-array';
module('Unit | Util | RollingArray', function() { | assert.deepEqual(
array,
['a', 'b', 'c'],
'additional arguments to the constructor become elements'
);
});
test('push works like Array#push', function(assert) {
const array = RollingArray(10);
const pushReturn = array.push('a');
assert.equal(
pushReturn,
array.leng... | test('has a maxLength property that gets set in the constructor', function(assert) {
const array = RollingArray(10, 'a', 'b', 'c');
assert.equal(array.maxLength, 10, 'maxLength is set in the constructor'); | random_line_split |
vrp_tokens.py | #!/usr/bin/env python3
# Copyright 2010-2021 Google LLC
# 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 ... | (from_index, to_index):
"""Returns the distance between the two nodes."""
del from_index
del to_index
return 10
transit_callback_index = routing.RegisterTransitCallback(distance_callback)
routing.AddDimension(
transit_callback_index,
0, # null slack
300... | distance_callback | identifier_name |
vrp_tokens.py | #!/usr/bin/env python3
# Copyright 2010-2021 Google LLC
# 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 ... | print(plan_output)
print('Total distance of all routes: {}m'.format(total_distance))
print('Total token of all routes: {}'.format(total_token))
def main():
"""Solve the CVRP problem."""
# Instantiate the data problem.
data = create_data_model()
# Create the routing index manager.
... | plan_output = f'Route for vehicle {vehicle_id}:\n'
index = routing.Start(vehicle_id)
total_token += solution.Value(token_dimension.CumulVar(index))
route_distance = 0
route_token = 0
while not routing.IsEnd(index):
node_index = manager.IndexToNode(index)
t... | conditional_block |
vrp_tokens.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 ... | #!/usr/bin/env python3
# Copyright 2010-2021 Google LLC
# 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 | random_line_split | |
vrp_tokens.py | #!/usr/bin/env python3
# Copyright 2010-2021 Google LLC
# 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 ... | node_index = manager.IndexToNode(index)
token_var = token_dimension.CumulVar(index)
route_token = solution.Value(token_var)
plan_output += f' {node_index} Token({route_token})\n'
plan_output += f'Distance of the route: {route_distance}m\n'
total_distance += route_distance... | """Prints solution on console."""
print(f'Objective: {solution.ObjectiveValue()}')
token_dimension = routing.GetDimensionOrDie('Token')
total_distance = 0
total_token = 0
for vehicle_id in range(manager.GetNumberOfVehicles()):
plan_output = f'Route for vehicle {vehicle_id}:\n'
index ... | identifier_body |
settings.py | """
Django settings for BenHoboCo project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
... | 'cs410.cs.ualberta.ca:41011',
]
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'crispy_forms',
'solo... |
# NOTE: Local server has to be in the first position!
ALLOWED_HOSTS = [
'127.0.0.1:8000', | random_line_split |
tree.js | // ========================================================================
// SproutCore -- JavaScript Application Framework
// Copyright ©2006-2011, Strobe Inc. and contributors.
// Portions copyright ©2008 Apple Inc. All rights reserved.
// ========================================================================
s... | */
treeItemChildrenKey: "treeItemChildren",
/**
Returns an SC.Array object that actually will represent the tree as a
flat array suitable for use by a CollectionView. Other than binding this
property as the content of a CollectionView, you generally should not
use this property directly. In... | children array for each tree node. The default is "treeItemChildren".
@property {String} | random_line_split |
tree.js | // ========================================================================
// SproutCore -- JavaScript Application Framework
// Copyright ©2006-2011, Strobe Inc. and contributors.
// Portions copyright ©2008 Apple Inc. All rights reserved.
// ========================================================================
s... | lse ret = null; // empty!
this._sctc_arrangedObjects = ret ;
return ret ;
}.property().cacheable(),
// ..........................................................
// PRIVATE
//
/**
@private
Manually invalidate the arrangedObjects cache so that we can teardown
any existing val... | ret = SC.TreeItemObserver.create({ item: content, delegate: this });
} e | conditional_block |
user.local.js | 'use strict';
const passport = require('passport');
//capitalize constructors as convention
const LocalStrategy = require('passport-local').Strategy;
const User = require('./user.model');
const SUCCESSFUL_LOGIN_MSG = 'Success!';
const INCORRECT_USERNAME_MSG = 'Incorrect Username or password';
const INCORRECT_PASSWOR... | done();
}
});
})
); | } else {
done();
}
});
} else { | random_line_split |
user.local.js | 'use strict';
const passport = require('passport');
//capitalize constructors as convention
const LocalStrategy = require('passport-local').Strategy;
const User = require('./user.model');
const SUCCESSFUL_LOGIN_MSG = 'Success!';
const INCORRECT_USERNAME_MSG = 'Incorrect Username or password';
const INCORRECT_PASSWOR... | else {
done();
}
});
} else {
done();
}
});
})
);
| {
done(null, user);
} | conditional_block |
glue.rs | ,
None => return,
};
restyle_subtree(node, raw_data);
}
#[no_mangle]
pub extern "C" fn Servo_StyleWorkerThreadCount() -> u32 {
*NUM_THREADS as u32
}
#[no_mangle]
pub extern "C" fn Servo_NodeData_Drop(data: ServoNodeDataOwned) -> () {
let _ = data.into_box::<NonOpaqueStyleData>();
}
#[no_mangl... | {
let _ = data.into_box::<PerDocumentStyleData>();
} | identifier_body | |
glue.rs | ckoNode, RecalcStyleOnly>(node, &shared_style_context,
per_doc_data.work_queue.as_mut().unwrap());
}
}
#[no_mangle]
pub extern "C" fn Servo_RestyleSubtree(node: RawGeckoNodeBorrowed,
raw_data: RawServoStyleSetBorrow... | Servo_ComputedValues_AddRef | identifier_name | |
glue.rs | sheet.clone());
data.stylesheets_changed = true;
}
#[no_mangle]
pub extern "C" fn Servo_StyleSet_RemoveStyleSheet(raw_data: RawServoStyleSetBorrowedMut,
raw_sheet: RawServoStyleSheetBorrowed) {
let data = PerDocumentStyleData::from_ffi_mut(raw_data);
let s... | pub extern "C" fn Servo_ComputeRestyleHint(element: RawGeckoElementBorrowed,
snapshot: *mut ServoElementSnapshot,
raw_data: RawServoStyleSetBorrowed) -> nsRestyleHint { | random_line_split | |
rq.py | from __future__ import absolute_import
import logging
try:
from redis import Redis
from rq import Queue
except ImportError:
Redis = None
Queue = None
from kaneda.exceptions import ImproperlyConfigured
from .base import BaseQueue
class RQQueue(BaseQueue):
"""
RQ queue
:param queue: que... |
def report(self, name, metric, value, tags, id_):
try:
return self.queue.enqueue('kaneda.tasks.rq.report', name, metric, value, tags, id_)
except Exception as e:
logger = logging.getLogger(__name__)
logger.exception(e)
| self.queue = Queue(queue_name, connection=Redis()) | conditional_block |
rq.py | from __future__ import absolute_import
import logging
try:
from redis import Redis
from rq import Queue
except ImportError:
Redis = None
Queue = None
from kaneda.exceptions import ImproperlyConfigured
from .base import BaseQueue
class RQQueue(BaseQueue):
"""
RQ queue
:param queue: que... | (self, name, metric, value, tags, id_):
try:
return self.queue.enqueue('kaneda.tasks.rq.report', name, metric, value, tags, id_)
except Exception as e:
logger = logging.getLogger(__name__)
logger.exception(e)
| report | identifier_name |
rq.py | from __future__ import absolute_import
import logging
try:
from redis import Redis
from rq import Queue
except ImportError:
Redis = None
Queue = None
from kaneda.exceptions import ImproperlyConfigured
from .base import BaseQueue
class RQQueue(BaseQueue):
"""
RQ queue
:param queue: que... | logger = logging.getLogger(__name__)
logger.exception(e) | try:
return self.queue.enqueue('kaneda.tasks.rq.report', name, metric, value, tags, id_)
except Exception as e: | random_line_split |
rq.py | from __future__ import absolute_import
import logging
try:
from redis import Redis
from rq import Queue
except ImportError:
Redis = None
Queue = None
from kaneda.exceptions import ImproperlyConfigured
from .base import BaseQueue
class RQQueue(BaseQueue):
"""
RQ queue
:param queue: que... | try:
return self.queue.enqueue('kaneda.tasks.rq.report', name, metric, value, tags, id_)
except Exception as e:
logger = logging.getLogger(__name__)
logger.exception(e) | identifier_body | |
dataset.service.ts | /toasts/toasts.service';
import { IProjectState } from '../../store/reducers';
import {
AbstractOverlayControllerDirective,
ConfirmationDialogComponent,
DataPickerService,
OverlayService,
} from 'cd-common';
import { BehaviorSubject, Observable, Subscription } from 'rxjs';
import { downloadBlobAsFile, createJso... | downloadBlobAsFile(jsonBlob, fileName);
};
duplicateDataset = async (dataset: cd.ProjectDataset) => {
const { storagePath, name } = dataset as cd.IJsonDataset;
const jsonBlob = await this.uploadService.downloadFile(storagePath);
if (!jsonBlob) return;
const fileName = this._incrementName(name);... | const jsonBlob = await this.uploadService.downloadFile(storagePath);
const fileName = utils.addJsonFileExtension(name); | random_line_split |
dataset.service.ts | /toasts/toasts.service';
import { IProjectState } from '../../store/reducers';
import {
AbstractOverlayControllerDirective,
ConfirmationDialogComponent,
DataPickerService,
OverlayService,
} from 'cd-common';
import { BehaviorSubject, Observable, Subscription } from 'rxjs';
import { downloadBlobAsFile, createJso... | extends AbstractOverlayControllerDirective implements OnDestroy {
private subscriptions = new Subscription();
private confirmSubscription = Subscription.EMPTY;
private _datasets: cd.ProjectDataset[] = [];
public openAddDatasetMenuTrigger$ = new BehaviorSubject(false);
public datasets$: Observable<cd.Project... | DatasetService | identifier_name |
dataset.service.ts | asts/toasts.service';
import { IProjectState } from '../../store/reducers';
import {
AbstractOverlayControllerDirective,
ConfirmationDialogComponent,
DataPickerService,
OverlayService,
} from 'cd-common';
import { BehaviorSubject, Observable, Subscription } from 'rxjs';
import { downloadBlobAsFile, createJsonFi... |
private _getBaseStoredDatasetValues = (providedFileName = ''): BaseDatasetValues => {
const projId = this.propertiesService.getProjectId();
const dataId = createId();
const jsonFileId = createId();
const fileName = providedFileName || this.getIncrementedDefaultDatasetName();
const uploadPath = s... | {
const fileName = `sheets-${tabId}`;
const [projId, dataId, _, uploadPath] = this._getBaseStoredDatasetValues(fileName);
if (!projId) return;
const dataset = utils.createSheetsDataset(dataId, projId, fileName, uploadPath, sheetId, tabId);
this._afterStoredDatasetCreated(dataId, fileName, dataset, d... | identifier_body |
async-data.js | import { resolverForGivenFunction, dataObjBuilder, metaFunctionBuilder } from './core.js'
import { dataDefaults } from './defaults.js'
export default function AsyncDataMixinBuilder(dataGlobalDefaults, meta) {
const metaRefresh = metaFunctionBuilder('refresh', meta)
const metaLoading = metaFunctionBuilder('loading', ... |
// for all non lazy properties, call refresh methods
beforeMount() {
const properties = this.$options.asyncData || {}
for (const [propName, prop] of Object.entries(properties)) {
const opt = dataDefaults(prop, dataGlobalDefaults)
if (!opt.lazy) {
this[metaRefresh(propName)]()
}
}
},
data() {
... | if (opt.more) {
methods[metaMore(propName)] = resolverForGivenFunction.call(this, propName, metas, opt.more.get, opt.default, opt.transform, opt.error, opt.more.concat)
}
}
}, | random_line_split |
async-data.js | import { resolverForGivenFunction, dataObjBuilder, metaFunctionBuilder } from './core.js'
import { dataDefaults } from './defaults.js'
export default function AsyncDataMixinBuilder(dataGlobalDefaults, meta) {
const metaRefresh = metaFunctionBuilder('refresh', meta)
const metaLoading = metaFunctionBuilder('loading', ... | ,
// for all non lazy properties, call refresh methods
beforeMount() {
const properties = this.$options.asyncData || {}
for (const [propName, prop] of Object.entries(properties)) {
const opt = dataDefaults(prop, dataGlobalDefaults)
if (!opt.lazy) {
this[metaRefresh(propName)]()
}
}
},
data() ... | {
let properties = this.$options.asyncData || {}
let methods = this.$options.methods = this.$options.methods || {}
for (const [propName, prop] of Object.entries(properties)) {
const opt = dataDefaults(prop, dataGlobalDefaults)
if (!opt.get)
throw `An asyncData was created without a get method: ${opt}... | identifier_body |
async-data.js | import { resolverForGivenFunction, dataObjBuilder, metaFunctionBuilder } from './core.js'
import { dataDefaults } from './defaults.js'
export default function AsyncDataMixinBuilder(dataGlobalDefaults, meta) {
const metaRefresh = metaFunctionBuilder('refresh', meta)
const metaLoading = metaFunctionBuilder('loading', ... | () {
return dataObjBuilder(this.$options.asyncData, metas, false)
}
}}
| data | identifier_name |
__openerp__.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2012 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the G... | """,
'data': [
'security/lunch_security.xml',
'lunch_view.xml',
'wizard/lunch_order_view.xml',
'wizard/lunch_validation_view.xml',
'wizard/lunch_cancel_view.xml',
'lunch_report.xml',
'report/report_lunch_order_view.xml',
'security/ir.model.access.c... |
In addition to a full meal and supplier management, this module offers the possibility to display warning and provides quick order selection based on employee’s preferences.
If you want to save your employees' time and avoid them to always have coins in their pockets, this module is essential. | random_line_split |
lib.rs | //! println!("Controller port 1: {:?}", controllers[0]);
//! }
//! }
//! ```
extern crate libusb;
use libusb::{Context, Device, DeviceHandle};
use std::error::Error as StdError;
use std::fmt::Error as FmtError;
use std::fmt::{Display, Formatter};
use std::time::Duration;
const VENDOR_ID: u16 = 0x057e;
co... | right: data[1] & (1 << 5) != 0,
down: data[1] & (1 << 6) != 0,
up: data[1] & (1 << 7) != 0,
start: data[2] & (1 << 0) != 0,
z: data[2] & (1 << 1) != 0,
r: data[2] & (1 << 2) != 0,
l: data[2] & (1 << 3) != 0,
| a: data[1] & (1 << 0) != 0,
b: data[1] & (1 << 1) != 0,
x: data[1] & (1 << 2) != 0,
y: data[1] & (1 << 3) != 0,
left: data[1] & (1 << 4) != 0, | random_line_split |
lib.rs | //! println!("Controller port 1: {:?}", controllers[0]);
//! }
//! }
//! ```
extern crate libusb;
use libusb::{Context, Device, DeviceHandle};
use std::error::Error as StdError;
use std::fmt::Error as FmtError;
use std::fmt::{Display, Formatter};
use std::time::Duration;
const VENDOR_ID: u16 = 0x057e;
co... | <'a> {
handle: DeviceHandle<'a>,
buffer: [u8; 37],
has_kernel_driver: bool,
interface: u8,
endpoint_in: u8,
}
impl<'a> Listener<'a> {
/// Reads a data packet and returns the states for each of the four possibly connected
/// controllers.
///
/// If reading a single packet takes over... | Listener | identifier_name |
lib.rs | //! println!("Controller port 1: {:?}", controllers[0]);
//! }
//! }
//! ```
extern crate libusb;
use libusb::{Context, Device, DeviceHandle};
use std::error::Error as StdError;
use std::fmt::Error as FmtError;
use std::fmt::{Display, Formatter};
use std::time::Duration;
const VENDOR_ID: u16 = 0x057e;
co... |
/// Returns the first adapter found, or `None` if no adapter was found.
pub fn find_adapter<'a>(&'a mut self) -> Result<Option<Adapter<'a>>, Error> {
for mut device in try!(self.context.devices()).iter() {
let desc = try!(device.device_descriptor());
if desc.vendor_id() == VEN... | {
Ok(Scanner { context: try!(Context::new()) })
} | identifier_body |
extern-generic.rs | // Copyright 2016 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 ... |
mod mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn extern_generic::mod1[0]::user[0] @@ extern_generic-mod1[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
mod mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn extern_generic::mod1[0]::mod1[0]::user[0]... | {
let _ = cgu_generic_function::foo("abc");
} | identifier_body |
extern-generic.rs | // Copyright 2016 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 ... |
mod mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn extern_generic::mod1[0]::mod1[0]::user[0] @@ extern_generic-mod1-mod1[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
}
}
mod mod2 {
use cgu_generic_function;
//~ MONO_ITEM fn extern_g... | random_line_split | |
extern-generic.rs | // Copyright 2016 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 _ = cgu_generic_function::foo("abc");
}
}
mod mod3 {
//~ MONO_ITEM fn extern_generic::mod3[0]::non_user[0] @@ extern_generic-mod3[Internal]
fn non_user() {}
}
// Make sure the two generic functions from the extern crate get instantiated
// once for the current crate
//~ MONO_ITEM fn cgu_g... | user | identifier_name |
functions_74.js | var searchData=
[ | ['teststruct',['testStruct',['../classurl_validator.html#a337a9edaa44e76bda5a7ed3a345b0b78',1,'urlValidator']]],
['testurls',['testUrls',['../classparseur_fic.html#ad2c99c1283f03ac105a2927aa9826021',1,'parseurFic']]],
['testvie',['testVie',['../classurl_validator.html#a9993e82ddcaf00c655e3ad9221a10232',1,'urlVali... | ['tester',['tester',['../classcontrol_vue.html#a92d898224293b741e5c6d3a3576a2193',1,'controlVue']]],
['testerappuyer',['testerAppuyer',['../class_vue.html#a7fb0d20950a6596a3eef78e244628682',1,'Vue']]],
['testerdossier',['testerDossier',['../classcontrol_vue.html#a630d60f73a0cdb77d2f7f92050983da7',1,'controlVue']]... | random_line_split |
htmlstyleelement.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 cssparser::Parser as CssParser;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTM... |
pub fn parse_own_css(&self) {
let node = self.upcast::<Node>();
let element = self.upcast::<Element>();
assert!(node.is_in_doc());
let win = window_from_node(node);
let url = win.get_url();
let mq_attribute = element.get_attribute(&ns!(), &atom!("media"));
... | {
Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document),
document,
HTMLStyleElementBinding::Wrap)
} | identifier_body |
htmlstyleelement.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 cssparser::Parser as CssParser;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTM... |
}
}
| {
self.parse_own_css();
} | conditional_block |
htmlstyleelement.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 cssparser::Parser as CssParser;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTM... | if let Some(ref s) = self.super_type() {
s.children_changed(mutation);
}
if self.upcast::<Node>().is_in_doc() {
self.parse_own_css();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tr... | Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn children_changed(&self, mutation: &ChildrenMutation) { | random_line_split |
htmlstyleelement.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 cssparser::Parser as CssParser;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTM... | (local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLStyleElement {
HTMLStyleElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
stylesheet: DOMRefCell::new(None),
}
}
#[allow(unr... | new_inherited | identifier_name |
constref.rs | // Copyright 2017 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 ... | {
assert!(const_ref());
assert!(associated_const_ref());
} | identifier_body | |
constref.rs | // Copyright 2017 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 ... | () {
assert!(const_ref());
assert!(associated_const_ref());
}
| main | identifier_name |
constref.rs | // Copyright 2017 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 main() {
assert!(const_ref());
assert!(associated_const_ref());
} | random_line_split | |
case_info_grammar.py | from parsimonious import Grammar
from parsimonious import NodeVisitor
from grammar_dev.grammars.CustomNodeVisitorFactory import CustomVisitorFactory
grammars = [
r"""
# Nonterminals
case_info = (new_line? assigned_filed_initiated the_rest) /
(new_line? line assigned_filed_initiated the_rest) /
... | ection_text):
grammar = Grammar(grammars[0])
custom_visitor = CustomVisitorFactory(terminals, nonterminals, dict()).create_instance()
root = grammar.parse(section_text)
# print("Parse tree:")
# print(root.prettily())
xml = custom_visitor.visit(root)
# print(xml)
return xml
| rse(s | identifier_name |
case_info_grammar.py | from parsimonious import Grammar
from parsimonious import NodeVisitor
from grammar_dev.grammars.CustomNodeVisitorFactory import CustomVisitorFactory
grammars = [
r"""
# Nonterminals
case_info = (new_line? assigned_filed_initiated the_rest) /
(new_line? line assigned_filed_initiated the_rest) /
... | ammar = Grammar(grammars[0])
custom_visitor = CustomVisitorFactory(terminals, nonterminals, dict()).create_instance()
root = grammar.parse(section_text)
# print("Parse tree:")
# print(root.prettily())
xml = custom_visitor.visit(root)
# print(xml)
return xml
| identifier_body | |
case_info_grammar.py | from parsimonious import Grammar
from parsimonious import NodeVisitor
from grammar_dev.grammars.CustomNodeVisitorFactory import CustomVisitorFactory
grammars = [
r"""
# Nonterminals
case_info = (new_line? assigned_filed_initiated the_rest) /
(new_line? line assigned_filed_initiated the_rest) /
... |
date_initiated = date_initiated_label ws date_initiated_date #"Initiation Date: 01/03/2011"
date_initiated_date = date &new_line
the_rest = line*
# Silent helper nonterminals (don't include in list of terminals)
line = single_content_char* new_line?
date = number forward_slash number forward_slash number
# Sile... | judge_assigned = judge_assigned_label ws judge_assigned_name?
judge_assigned_name = (single_content_char !(ws ws))+ single_content_char
date_filed = date_filed_label ws date_filed_date #"Date Filed: 01/03/2011"
date_filed_date = date &ws | random_line_split |
imgt2fasta.py | #! /usr/bin/env python
# Copyright 2014 Uri Laserson
#
# 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 o... | print >>outhandle, ">%s\n%s" % (chain.id,chain.seq) | random_line_split | |
imgt2fasta.py | #! /usr/bin/env python
# Copyright 2014 Uri Laserson
#
# 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 o... |
else:
raise Exception, "Wrong number of arguments."
for chain in vdj.parse_imgt(inhandle):
# print >>outhandle, chain.format('fasta') # causes chain.description output instead of chain.id
print >>outhandle, ">%s\n%s" % (chain.id,chain.seq)
| inhandle = sys.stdin
outhandle = sys.stdout | conditional_block |
query16.rs | use timely::dataflow::*;
// use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
// use differential_dataflow::AsCollection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use ::Collections;
// -- $ID$
// -- TPC-H/TPC-R Parts/Suppli... |
)
.semijoin_u(&parts)
.count()
.probe()
} | { None } | conditional_block |
query16.rs | use timely::dataflow::*;
// use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
// use differential_dataflow::AsCollection;
use differential_dataflow::operators::*; | use differential_dataflow::lattice::Lattice;
use ::Collections;
// -- $ID$
// -- TPC-H/TPC-R Parts/Supplier Relationship Query (Q16)
// -- Functional Query Definition
// -- Approved February 1998
// :x
// :o
// select
// p_brand,
// p_type,
// p_size,
// count(distinct ps_suppkey) as supplier_cnt
// f... | random_line_split | |
query16.rs | use timely::dataflow::*;
// use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
// use differential_dataflow::AsCollection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use ::Collections;
// -- $ID$
// -- TPC-H/TPC-R Parts/Suppli... |
collections
.parts()
.flat_map(|p|
if !starts_with(&p.brand, b"Brand45") && !starts_with(&p.typ.as_bytes(), b"MEDIUM POLISHED") && [49, 14, 23, 45, 19, 3, 36, 9].contains(&p.size) {
Some((p.part_key, (p.brand, p.typ.to_string(), p.size)))
}
else ... | {
println!("TODO: query 16 could use a count_u if it joins after to re-collect its attributes");
let suppliers =
collections
.suppliers()
.flat_map(|s|
if substring2(s.comment.as_bytes(), b"Customer", b"Complaints") {
Some((s.supp_key))
}
... | identifier_body |
query16.rs | use timely::dataflow::*;
// use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
// use differential_dataflow::AsCollection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use ::Collections;
// -- $ID$
// -- TPC-H/TPC-R Parts/Suppli... | <G: Scope>(collections: &mut Collections<G>) -> ProbeHandle<G::Timestamp>
where G::Timestamp: Lattice+Ord {
println!("TODO: query 16 could use a count_u if it joins after to re-collect its attributes");
let suppliers =
collections
.suppliers()
.flat_map(|s|
if substring2(s.co... | query | identifier_name |
capstone.rs | #[$func_attr:meta] )*
=> $($visibility:ident)*, $fn_name:ident,
$opt_type:ident, $param_name:ident : $param_type:ident ;
$cs_base_type:ident
) => {
$( #[$func_attr] )*
$($visibility)* fn $fn_name(&mut self, $param_name: $param_type) -> CsResult<()> {
let old_... | <T: Iterator<Item = ExtraMode>>(&mut self, extra_mode: T) -> CsResult<()> {
let old_val = self.extra_mode;
self.extra_mode = Self::extra_mode_value(extra_mode);
let old_mode = self.raw_mode;
let new_mode = self.update_raw_mode();
let result = self._set_cs_option(cs_opt_type::CS... | set_extra_mode | identifier_name |
capstone.rs | -> CsResult<()> {
let old_val = self.$param_name;
self.$param_name = $cs_base_type::from($param_name);
let old_raw_mode = self.raw_mode;
let new_raw_mode = self.update_raw_mode();
let result = self._set_cs_option(
cs_opt_type::$opt_type,
... | {
let err = unsafe { cs_option(self.csh(), option_type, option_value) };
if cs_err::CS_ERR_OK == err {
Ok(())
} else {
Err(err.into())
}
} | identifier_body | |
capstone.rs | #[$func_attr:meta] )*
=> $($visibility:ident)*, $fn_name:ident,
$opt_type:ident, $param_name:ident : $param_type:ident ;
$cs_base_type:ident
) => {
$( #[$func_attr] )*
$($visibility)* fn $fn_name(&mut self, $param_name: $param_type) -> CsResult<()> {
let old_... | /// assert!(cs.is_ok());
/// ```
pub fn new_raw<T: Iterator<Item = ExtraMode>>(
arch: Arch,
mode: Mode,
extra_mode: T,
endian: Option<Endian>,
) -> CsResult<Capstone> {
let mut handle: csh = 0;
let csarch: cs_arch = arch.into();
let csmode: cs_mode... | /// ```
/// use capstone::{Arch, Capstone, NO_EXTRA_MODE, Mode};
/// let cs = Capstone::new_raw(Arch::X86, Mode::Mode64, NO_EXTRA_MODE, None); | random_line_split |
inputs.py | import numpy as np
import tensorflow as tf
import os
def get_inputs(split, config):
split_dir = config['split_dir']
data_dir = config['data_dir']
dataset = config['dataset']
split_file = os.path.join(split_dir, dataset, split + '.lst')
filename_queue = get_filename_queue(split_file, os.path.join(d... |
else:
image = get_inputs_image(filename_queue, config)
image_batch = create_batch([image], config['batch_size'])
return image_batch
def get_inputs_image(filename_queue, config):
output_size = config['output_size']
image_size = config['image_size']
c_dim = config['c_dim']
# Read ... | image = get_inputs_cifar10(filename_queue, config)
config['output_size'] = 32
config['c_dim'] = 3 | conditional_block |
inputs.py | import numpy as np
import tensorflow as tf
import os
def get_inputs(split, config):
| return image_batch
def get_inputs_image(filename_queue, config):
output_size = config['output_size']
image_size = config['image_size']
c_dim = config['c_dim']
# Read a record, getting filenames from the filename_queue.
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)... | split_dir = config['split_dir']
data_dir = config['data_dir']
dataset = config['dataset']
split_file = os.path.join(split_dir, dataset, split + '.lst')
filename_queue = get_filename_queue(split_file, os.path.join(data_dir, dataset))
if dataset == 'mnist':
image = get_inputs_mnist(filename_... | identifier_body |
inputs.py | import numpy as np
import tensorflow as tf
import os
def get_inputs(split, config):
split_dir = config['split_dir']
data_dir = config['data_dir']
dataset = config['dataset']
split_file = os.path.join(split_dir, dataset, split + '.lst')
filename_queue = get_filename_queue(split_file, os.path.join(d... | (filename_queue, config):
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
# Defaults are not specified since all keys are required.
features={
'height': tf.FixedLenFeature([], tf.int6... | get_inputs_mnist | identifier_name |
inputs.py | import numpy as np
import tensorflow as tf
import os
def get_inputs(split, config):
split_dir = config['split_dir']
data_dir = config['data_dir']
dataset = config['dataset']
split_file = os.path.join(split_dir, dataset, split + '.lst')
filename_queue = get_filename_queue(split_file, os.path.join(d... | image = tf.decode_raw(features['image_raw'], tf.uint8)
image.set_shape([784])
image = tf.reshape(image, [28, 28, 1])
image = tf.cast(image, tf.float32) / 255.
# Convert label from a scalar uint8 tensor to an int32 scalar.
label = tf.cast(features['label'], tf.int32)
binary_image = (tf.rand... | 'label': tf.FixedLenFeature([], tf.int64),
'image_raw': tf.FixedLenFeature([], tf.string),
})
| random_line_split |
View.js | "use strict";
var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDes... | if (args.components) {
this.addComponents(args.components);
}
_get(Object.getPrototypeOf(View.prototype), "constructor", this).call(this, { name: args.name + "View" });
}
_inherits(View, Module);
_prototypeProperties(View, null, {
render: {
// ## re... | this.components = []; | random_line_split |
View.js | "use strict";
var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDes... | (args) {
_classCallCheck(this, View);
this.template = args.template || function () {
return "";
};
this.components = [];
if (args.components) {
this.addComponents(args.components);
}
_get(Object.getPrototypeOf(View.prototype), "constructor... | View | identifier_name |
View.js | "use strict";
var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDes... | };
var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subC... | { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } | conditional_block |
View.js | "use strict";
var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDes... |
_inherits(View, Module);
_prototypeProperties(View, null, {
render: {
// ## render method
// The render method passes any data avaialbe to a template and returns the rendered string
// Takes two arguments
// - err - an error that occured in the parent ... | {
_classCallCheck(this, View);
this.template = args.template || function () {
return "";
};
this.components = [];
if (args.components) {
this.addComponents(args.components);
}
_get(Object.getPrototypeOf(View.prototype), "constructor", this... | identifier_body |
query-builder.js | 'use strict';
var resourceManager = require('./resource-manager');
var debog = require('./debog');
var relLog = debog('relationships');
var queryLog = debog('query');
/**
* @name query-builder
* @module query-builder
* @description
* build and return query object
*
* @param {object} struct - structure
*... | else { // create new groups for each layer
subDebug = subDebug.nest(item.root.name);
}
subDebug.stash(item.resource.name);
}
// END Debug Code
// path completed
// convert to flat array and return true for sucessfull
if (item.resource.name === b.name) {
reducePath(path.ch... | { // root
relLog.stash('Pathway that was used in attempt to find '+relLog.chalk.magenta(b.name)+' resource')
subDebug = relLog.nest(item.root.name);
} | conditional_block |
query-builder.js | var debog = require('./debog');
var relLog = debog('relationships');
var queryLog = debog('query');
/**
* @name query-builder
* @module query-builder
* @description
* build and return query object
*
* @param {object} struct - structure
* @param {array} ids - array of ids for calling specific peices fo da... | 'use strict';
var resourceManager = require('./resource-manager'); | random_line_split | |
query-builder.js | 'use strict';
var resourceManager = require('./resource-manager');
var debog = require('./debog');
var relLog = debog('relationships');
var queryLog = debog('query');
/**
* @name query-builder
* @module query-builder
* @description
* build and return query object
*
* @param {object} struct - structure
*... | // END Debug Code
// path completed
// convert to flat array and return true for sucessfull
if (item.resource.name === b.name) {
reducePath(path.children[item.resource.name], arr);
return true;
}
// continue finding on paths that have not been explored yet
if (path.added.indexO... | {
return (a.relationships || []).some(function (item) {
path.children[item.resource.name] = {
added: path.added,
parent: path,
item: item,
children: {}
};
// NOTE debug code
var subDebug = debug;
if (subDebug && relLog.active) {
if (subDebug === true) { // root
... | identifier_body |
query-builder.js | 'use strict';
var resourceManager = require('./resource-manager');
var debog = require('./debog');
var relLog = debog('relationships');
var queryLog = debog('query');
/**
* @name query-builder
* @module query-builder
* @description
* build and return query object
*
* @param {object} struct - structure
*... | (resource, parentResource) {
var arr = [];
if (relLog.active) { debugRelations(resource, parentResource); }
// top down
var found = pathFinder(parentResource, resource, {
added: [],
parent: parentResource,
children: {}
}, arr);
if (found) {
arr = arr.reverse();
return arr;
}
// bott... | findRelations | identifier_name |
pact.ts | import * as q from 'q';
import * as path from 'path';
import serverFactory, { Server, ServerOptions } from './server';
import stubFactory, { Stub, StubOptions } from './stub';
import verifierFactory, { VerifierOptions } from './verifier';
import messageFactory, { MessageOptions } from './message';
import publisherFacto... |
// Listen to stub delete events, to remove from stub list
stub.once(AbstractService.Events.DELETE_EVENT, (s: Stub) => {
logger.info(
`Deleting Pact Stub with options: \n${JSON.stringify(stub.options)}`,
);
this.__stubs = _.without(this.__stubs, s);
});
return stub;
}
// Return arrays of all st... | ); | random_line_split |
pact.ts | import * as q from 'q';
import * as path from 'path';
import serverFactory, { Server, ServerOptions } from './server';
import stubFactory, { Stub, StubOptions } from './stub';
import verifierFactory, { VerifierOptions } from './verifier';
import messageFactory, { MessageOptions } from './message';
import publisherFacto... |
logger.info('Removing all Pact stubs.');
return q.all<Stub>(
_.map(this.__stubs, (stub: Stub) => stub.delete() as PromiseLike<Stub>),
);
}
// Remove all the servers and stubs
public removeAll(): q.Promise<AbstractService[]> {
return q.all<AbstractService>(
_.flatten([this.removeAllStubs(), this.remo... | {
return q(this.__stubs);
} | conditional_block |
pact.ts | import * as q from 'q';
import * as path from 'path';
import serverFactory, { Server, ServerOptions } from './server';
import stubFactory, { Stub, StubOptions } from './stub';
import verifierFactory, { VerifierOptions } from './verifier';
import messageFactory, { MessageOptions } from './message';
import publisherFacto... | (level?: LogLevels | number): number | void {
return setLogLevel(level);
}
// Creates server with specified options
public createServer(options: ServerOptions = {}): Server {
if (
options &&
options.port &&
_.some(this.__servers, (s: Server) => s.options.port === options.port)
) {
let msg = `Port ... | logLevel | identifier_name |
pact.ts | import * as q from 'q';
import * as path from 'path';
import serverFactory, { Server, ServerOptions } from './server';
import stubFactory, { Stub, StubOptions } from './stub';
import verifierFactory, { VerifierOptions } from './verifier';
import messageFactory, { MessageOptions } from './message';
import publisherFacto... |
// Creates server with specified options
public createServer(options: ServerOptions = {}): Server {
if (
options &&
options.port &&
_.some(this.__servers, (s: Server) => s.options.port === options.port)
) {
let msg = `Port '${options.port}' is already in use by another process.`;
logger.error(msg... | {
return setLogLevel(level);
} | identifier_body |
common.js | // shared config (dev and prod)
const {resolve} = require('path');
const {CheckerPlugin} = require('awesome-typescript-loader');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
},
context: resolve(__dirname, '../../src'),
m... | }; | hints: false,
}, | random_line_split |
dbd_parsers.py | #!/usr/bin/env python
"""
@package glider_utils
@file glider_utils.py
@author Stuart Pearce & Chris Wingard
@brief Module containing glider utiliities
"""
__author__ = 'Stuart Pearce & Chris Wingard'
__license__ = 'Apache 2.0'
import numpy as np
import warnings
#import pdb
import re
#import pygsw.vectors as gsw
class... |
self.data_keys = column_labels
class DataVizDataParser(DbaDataParser):
"""
A class that parses a glider data file and holds it in dictionaries.
GliderParsedData parses a Slocum Electric Glider data file that has
been converted to ASCII from binary, and holds the self describing
header d... | min_d100, deg = np.modf(data_col/100.)
deg_col = deg + (min_d100*100.)/60.
self.data_dict[column_labels[ii]]['Data_deg'] = deg_col | conditional_block |
dbd_parsers.py | #!/usr/bin/env python
"""
@package glider_utils
@file glider_utils.py
@author Stuart Pearce & Chris Wingard
@brief Module containing glider utiliities
"""
__author__ = 'Stuart Pearce & Chris Wingard'
__license__ = 'Apache 2.0'
import numpy as np
import warnings
#import pdb
import re
#import pygsw.vectors as gsw
class... | (DbaDataParser):
"""
A class that parses a glider data file and holds it in dictionaries.
GliderParsedData parses a Slocum Electric Glider data file that has
been converted to ASCII from binary, and holds the self describing
header data in a header dictionary and the data in a data dictionary
u... | DataVizDataParser | identifier_name |
dbd_parsers.py | #!/usr/bin/env python
"""
@package glider_utils
@file glider_utils.py
@author Stuart Pearce & Chris Wingard
@brief Module containing glider utiliities
"""
__author__ = 'Stuart Pearce & Chris Wingard'
__license__ = 'Apache 2.0'
import numpy as np
import warnings
#import pdb
import re
#import pygsw.vectors as gsw
class... |
def _read_data(self):
"""
Read in the column labels, data type, number of bytes of each
data type, and the data from an ASCII glider data file.
"""
column_labels = self._fid.readline().split()
column_type = self._fid.readline().split()
column_num_bytes = self... | hdr_line += 1 | random_line_split |
dbd_parsers.py | #!/usr/bin/env python
"""
@package glider_utils
@file glider_utils.py
@author Stuart Pearce & Chris Wingard
@brief Module containing glider utiliities
"""
__author__ = 'Stuart Pearce & Chris Wingard'
__license__ = 'Apache 2.0'
import numpy as np
import warnings
#import pdb
import re
#import pygsw.vectors as gsw
class... | dict.__init__ | identifier_body | |
main.rs | mod sqrl_s4;
mod sqrl_crypto;
use sqrl_s4::SqrlS4Identity;
use sqrl_crypto::en_scrypt;
fn main() | {
//let identity = SqrlS4Identity{type1_length: 34, ..Default::default()};
//let mut identity = SqrlS4Identity::default();
let sqrlbinary = b"sqrldata}\x00\x01\x00-\x00\"wQ\x122\x0e\xb5\x891\xfep\x97\xef\xf2e]\xf6\x0fg\x07\x8c_\xda\xd4\xe0Z\xe0\xb8\t\x96\x00\x00\x00\xf3\x01\x04\x05\x0f\x00\x023\x88\xcd\xa0\... | identifier_body | |
main.rs | mod sqrl_s4;
mod sqrl_crypto;
use sqrl_s4::SqrlS4Identity;
use sqrl_crypto::en_scrypt;
fn main() {
//let identity = SqrlS4Identity{type1_length: 34, ..Default::default()};
//let mut identity = SqrlS4Identity::default();
let sqrlbinary = b"sqrldata}\x00\x01\x00-\x00\"wQ\x122\x0e\xb5\x891\xfep\x97\xef\xf2e]... | println!("identity debug\n{:?}", identity);
println!("identity print\n{}", identity);
identity.type1_length = 125;
println!("identity.type1_length {}", identity.type1_length);
println!("{:?}", en_scrypt(b"", b"", 64, 1));
} | let mut identity = SqrlS4Identity::from_binary(sqrlbinary); | random_line_split |
main.rs | mod sqrl_s4;
mod sqrl_crypto;
use sqrl_s4::SqrlS4Identity;
use sqrl_crypto::en_scrypt;
fn | () {
//let identity = SqrlS4Identity{type1_length: 34, ..Default::default()};
//let mut identity = SqrlS4Identity::default();
let sqrlbinary = b"sqrldata}\x00\x01\x00-\x00\"wQ\x122\x0e\xb5\x891\xfep\x97\xef\xf2e]\xf6\x0fg\x07\x8c_\xda\xd4\xe0Z\xe0\xb8\t\x96\x00\x00\x00\xf3\x01\x04\x05\x0f\x00\x023\x88\xcd\x... | main | identifier_name |
test_ivim.py | in `IvimFit` class gives the correct output.
"""
assert_array_equal(ivim_fit_single.shape, ())
ivim_fit_multi = ivim_model_trr.fit(data_multi)
assert_array_equal(ivim_fit_multi.shape, (2, 2, 1))
def test_multiple_b0():
# Generate a signal with multiple b0
# This gives an isotropic signal.
... | run_module_suite() | conditional_block | |
test_ivim.py | 0., 160., 180., 200., 300.,
400., 500., 600., 700., 800., 900.,
1000.])
bvecs_with_multiple_b0 = generate_bvecs(N)
gtab_with_multiple_b0 = gradient_table(bvals_with_multiple_b0,
bvecs_with_m... | def single_exponential(S0, D, bvals):
return S0 * np.exp(-bvals * D)
def test_single_voxel_fit():
"""
Test the implementation of the fitting for a single voxel.
Here, we will use the multi_tensor function to generate a
bi-exponential signal. The multi_tensor generates a multi
tensor signal an... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.