code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def rewrite_cl(src: str, id: str='anon', use_shim: bool=True, timeout: int=60) -> str: <NEW_LINE> <INDENT> with NamedTemporaryFile('w', suffix='.cl') as tmp: <NEW_LINE> <INDENT> tmp.write(src) <NEW_LINE> tmp.flush() <NEW_LINE> cmd = (["timeout", "-s9", str(timeout), native.CLGEN_REWRITER, tmp.name] + ['-extra-arg=' + x...
Rewrite OpenCL sources. Renames all functions and variables with short, unique names. Parameters ---------- src : str OpenCL source. id : str, optional OpenCL source name. use_shim : bool, optional Inject shim header. Returns ------- str Rewritten OpenCL source. Raises ------ RewriterException I...
625941cf63d6d428bbe44640
def zmq_sub(bind, tables, forwarder=False, green=False): <NEW_LINE> <INDENT> logger = logging.getLogger("meepo.sub.zmq_sub") <NEW_LINE> if not isinstance(tables, (list, set)): <NEW_LINE> <INDENT> raise ValueError("tables should be list or set") <NEW_LINE> <DEDENT> if not green: <NEW_LINE> <INDENT> import zmq <NEW_LINE>...
0mq fanout sub. This sub will use zeromq to fanout the events. :param bind: the zmq pub socket or zmq device socket. :param tables: the events of tables to follow. :param forwarder: set to True if zmq pub to a forwarder device. :param green: weather to use a greenlet compat zmq
625941cf9c8ee82313fbb8c7
def SetBackgroundValue(self, *args): <NEW_LINE> <INDENT> return _itkBinaryProjectionImageFilterPython.itkBinaryProjectionImageFilterIUS2IUS2_SetBackgroundValue(self, *args)
SetBackgroundValue(self, unsigned short _arg)
625941cfa17c0f6771cbe1a1
def sampleone(hull,hx,hpx,domain,isDomainFinite,maxn,nupdates,hxparams): <NEW_LINE> <INDENT> thishull= hull <NEW_LINE> noSampleYet= True <NEW_LINE> while noSampleYet: <NEW_LINE> <INDENT> candidate= sample_hull(thishull,domain,isDomainFinite) <NEW_LINE> thishux, thishlx= evaluate_hull(candidate,thishull) <NEW_LINE> u= s...
sampleone: sample one point by ars Input: hull - the hull (see doc of setup_hull for definition) hx - function that evaluates h(x) hpx - function that evaluates hp(x) domain - [.,.] upper and lower limit to the domain isDomainFinite - [.,.] is there a lower/...
625941cfe8904600ed9f207f
def castle_shaped_plate_cutout(self, centered=True): <NEW_LINE> <INDENT> half_size = Keyboard.SWITCH_CASE_SIZE / 2 <NEW_LINE> if centered: <NEW_LINE> <INDENT> self.moveTo(-half_size, -half_size) <NEW_LINE> <DEDENT> btn_half_side = [0.98, 90, 0.81, -90, 3.5, -90, 0.81, 90, 2.505] <NEW_LINE> btn_full_side = [*btn_half_si...
This cutout shaped like a castle enables switch modding and rotation. More information (type 4) on https://geekhack.org/index.php?topic=59837.0
625941cfd4950a0f3b08c4a0
def find_loc(forest, char): <NEW_LINE> <INDENT> num_of_rows = len(forest) <NEW_LINE> num_of_cols = len(forest[0]) <NEW_LINE> for i in range(num_of_rows): <NEW_LINE> <INDENT> for j in range(num_of_cols): <NEW_LINE> <INDENT> if forest[i][j] == char: <NEW_LINE> <INDENT> return (i, j) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> ...
find location of char in the forest
625941cf7d43ff24873a2df2
def os_bisect(): <NEW_LINE> <INDENT> nonlocal k <NEW_LINE> if k <= 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> k = log(k) <NEW_LINE> prefix = [0] <NEW_LINE> for x in nums: <NEW_LINE> <INDENT> prefix.append(prefix[-1] + log(x)) <NEW_LINE> <DEDENT> ans = 0 <NEW_LINE> for i, x in enumerate(prefix): <NEW_LINE> <IND...
Runtime: 1352 ms, faster than 9.28% of Python3 online submissions for Subarray Product Less Than K. log(a*b*c*d) = log(a)+log(b)+log(c)+log(d) Money exchange (Coinbase: Dijkstra, Bellman-Ford)
625941cf796e427e537b0718
def self_play(engines): <NEW_LINE> <INDENT> global games_played <NEW_LINE> games_played += 1 <NEW_LINE> index = 0 <NEW_LINE> moves = 0 <NEW_LINE> board = Board() <NEW_LINE> seenBoards = set({board_to_fen(board)}) <NEW_LINE> r = Engine(random, 1, 0.99) <NEW_LINE> while (evaluate(board) is None) and (not board.is_insuffi...
engines is a list of engines and engines[0] moves first
625941cf01c39578d7e74f8d
def present(name, bare=True, runas=None, user=None, force=False): <NEW_LINE> <INDENT> name = os.path.expanduser(name) <NEW_LINE> ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} <NEW_LINE> salt.utils.warn_until( 'Lithium', 'Please remove \'runas\' support at this stage. \'user\' support was ' 'added i...
Make sure the repository is present in the given directory name Name of the directory where the repository is about to be created bare Create a bare repository (Default: True) runas Name of the user performing repository management operations .. deprecated:: 0.17.0 user Name of the user perform...
625941cf3d592f4c4ed1d1be
def autosave(self): <NEW_LINE> <INDENT> self.autosaved = [self.straditizer.to_dataset().copy(True)] + self.autosaved[:4]
Autosave the current straditizer
625941cffbf16365ca6f6317
def update(self,time,mposition): <NEW_LINE> <INDENT> max_speed=100 <NEW_LINE> self.circlePos += self.circleVel * time <NEW_LINE> if mposition!=None: <NEW_LINE> <INDENT> mouseDir = mposition - self.circlePos <NEW_LINE> self.circleVel += mouseDir.normalized() * 80 * time <NEW_LINE> t=self.circleVel.magnitude() <NEW_LINE>...
This function is the move method for a single boid. It includes a terminal velocity denoted by maz_vel. This function primarily updates the boids position bu adding multiple accelerations that influence the velocity.
625941cf44b2445a339321e7
def test_home_route_has_three_sliding_puzzles(testapp): <NEW_LINE> <INDENT> response = testapp.get("/") <NEW_LINE> assert len(response.html.find_all('div', 'puzzle-container')) == 3
Test that the home route has three sliding puzzles.
625941cf627d3e7fe0d68fa1
def lba_ao(S, event_sig, burst_sig, burn, n_eta, n_cells, lag=6): <NEW_LINE> <INDENT> dt = params['dt'] <NEW_LINE> scale_bs = params2['scale_bs'] <NEW_LINE> E_ps = params2['E_ps'] <NEW_LINE> fs = params2['fs'] <NEW_LINE> nps = params2['nps'] <NEW_LINE> nov = params2['nov'] <NEW_LINE> FREQ_MAX_e = params2['FREQ_MAX_e'] ...
lower bound analysis activity only. Calculates lower bound from spiking data :param S: :param burst_sig: :param event_sig :param burn: :param n_eta: :param n_cells: :param lag: :return:
625941cf004d5f362079a484
def test_bed_for_macs2_with_2010_20131216(self): <NEW_LINE> <INDENT> macsxls = MacsXLS(fp=io.StringIO(MACS2010_20131216_data)) <NEW_LINE> bed = bed_for_macs2(macsxls) <NEW_LINE> self.assertEqual(bed.header(),['chr', 'abs_summit-100', 'abs_summit+100']) <NEW_LINE> self.assertEqual(bed[0]['chr'],'chr1') <NEW_LINE> self.a...
Generate BED for MACS2.0.10.20131216 data
625941cf462c4b4f79d1d822
def log_standard_gaussian(x): <NEW_LINE> <INDENT> return torch.sum(-0.5 * math.log(2 * math.pi) - x ** 2 / 2, dim=-1)
Evaluates the log pdf of a standard normal distribution at x. :param x: point to evaluate :return: log N(x|0,I)
625941cfcdde0d52a9e53185
def membership_cancel(organization_id): <NEW_LINE> <INDENT> context = {'model': model, 'session': model.Session, 'user': g.user or g.author} <NEW_LINE> try: <NEW_LINE> <INDENT> get_action('member_request_membership_cancel')(context, {"organization_id": organization_id}) <NEW_LINE> h.redirect_to('organizations_index') <...
cancel membership (not request).
625941cf63d6d428bbe44641
def generate_ability_scores(method=None): <NEW_LINE> <INDENT> switcher = { 'classic': classic_ability_gen, 'heroic': heroic_ability_gen, 'standard': standard_ability_gen, } <NEW_LINE> func = switcher.get(method, standard_ability_gen) <NEW_LINE> return func()
Generate character ability scores based on given method.
625941cf293b9510aa2c33e7
def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None: <NEW_LINE> <INDENT> if isinstance(module, (nn.Linear, nn.Conv2d)): <NEW_LINE> <INDENT> module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) <NEW_LINE> if module.bias is not None: <NEW_LINE> <INDENT> module.bias.data.z...
Initialize the weights
625941cf66673b3332b921e3
def test_SummitConstraints(self, conn, Summit, setup_tables): <NEW_LINE> <INDENT> skip_pg12_sa1217(conn) <NEW_LINE> inspector = get_inspector(conn) <NEW_LINE> constraints = inspector.get_check_constraints( Summit.__tablename__, schema='gis') <NEW_LINE> assert len(constraints) == 3 <NEW_LINE> constraint_names = {c['name...
Make sure the geometry column of table Summit is created with `use_typmod=False` (explicit constraints are created).
625941cf656771135c3eb9c1
def customized_request(method, url, **kwargs): <NEW_LINE> <INDENT> if method.upper() == 'GET': <NEW_LINE> <INDENT> if url == sync_check_url: <NEW_LINE> <INDENT> kwargs['timeout'] = sync_check_timeout <NEW_LINE> <DEDENT> <DEDENT> elif method.upper() == 'POST': <NEW_LINE> <INDENT> if url == webwx_sync_url: <NEW_LINE> <IN...
根据 请求方法 和 url 灵活调整各种参数
625941cf4e4d5625662d4529
def write_fully(fd, buf): <NEW_LINE> <INDENT> bytes_written = 0 <NEW_LINE> if len(buf) == 0: <NEW_LINE> <INDENT> return 0, 0 <NEW_LINE> <DEDENT> if not isinstance(buf, bytes): <NEW_LINE> <INDENT> buf = bytes(buf, 'utf-8') <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> retval = os.write(fd,...
Returns an (error, bytes_written) tuple where 'error' is 0 on success, otherwise a positive errno value, and 'bytes_written' is the number of bytes that were written before the error occurred. 'error' is 0 if and only if 'bytes_written' is len(buf).
625941cfac7a0e7691ed421d
def default_image_name(role): <NEW_LINE> <INDENT> return 'testimage.{role}'.format(role=role)
Image name used by rbd and iscsi
625941cf925a0f43d2549fc9
def sumRange(self, i, j): <NEW_LINE> <INDENT> return self.nums[j]-[self.nums[i-1],0][i==0]
:type i: int :type j: int :rtype: int
625941cf5fcc89381b1e1811
def test_users_get_natural(self): <NEW_LINE> <INDENT> pass
Test case for users_get_natural View a Natural User
625941cf8e7ae83300e4b11e
def verticalOrder(self, root): <NEW_LINE> <INDENT> l = self.leftmost(root, 0) <NEW_LINE> r = self.rightmost(root, 0) <NEW_LINE> ret = [[] for _ in xrange(r-l-1)] <NEW_LINE> self.bfs(root, -l-1, ret) <NEW_LINE> return ret
O(N) :type root: TreeNode :rtype: List[List[int]]
625941cf004d5f362079a485
def weights_to_cpu(self, state_dict): <NEW_LINE> <INDENT> state_dict_cpu = OrderedDict() <NEW_LINE> for key, val in state_dict.items(): <NEW_LINE> <INDENT> state_dict_cpu[key] = val.cpu() <NEW_LINE> <DEDENT> return state_dict_cpu
Copy a model state_dict to cpu. Args: state_dict (OrderedDict): Model weights on GPU. Returns: OrderedDict: Model weights on GPU.
625941cf8c0ade5d55d3eb0d
def get_plane_above_atoms(self, d, verbose=False, return_object=None, replica=None, resample=None, from_below=False): <NEW_LINE> <INDENT> iplane = self.get_index_above_atoms(d, from_below, verbose=verbose) <NEW_LINE> return self.get_plane('z', iplane, return_object=return_object, replica=replica, resample=resample)
Returns plane given by z=d above topmost atom d should be given in Angstroms.
625941cf167d2b6e31218ce8
def QueryAvailableDisksForVmfs(self, datastore=None): <NEW_LINE> <INDENT> return self.delegate("QueryAvailableDisksForVmfs")(datastore)
Query to list disks that can be used to contain VMFS datastore extents. If the optional parameter name is supplied, queries for disks that can be used to contain extents for a VMFS datastore identified by the supplied name. Otherwise, the method retrieves disks that can be used to contain new VMFS datastores.Query to l...
625941cfe1aae11d1e749e09
def write_template(output_path, template_path: str, **kwargs): <NEW_LINE> <INDENT> logging.info(f'Write command {output_path} using template {basename(template_path)}') <NEW_LINE> try: <NEW_LINE> <INDENT> makedirs(dirname(output_path), exist_ok=True) <NEW_LINE> with open(template_path, 'r') as template_fd, open(output_...
Write an executable output file using Jinja template.
625941cff9cc0f698b14074d
def testDocStringExamples(self): <NEW_LINE> <INDENT> with self.test_session(): <NEW_LINE> <INDENT> rt1 = ragged.range([3, 5, 2]).eval().tolist() <NEW_LINE> self.assertEqual(rt1, [[0, 1, 2], [0, 1, 2, 3, 4], [0, 1]]) <NEW_LINE> rt2 = ragged.range([0, 5, 8], [3, 3, 12]).eval().tolist() <NEW_LINE> self.assertEqual(rt2, [[...
Examples from ragged_range.__doc__.
625941cfd486a94d0b98e298
def __init__(self, field, vid, name, label=None): <NEW_LINE> <INDENT> super(FieldValue, self).__init__() <NEW_LINE> self.field = field <NEW_LINE> self.vid = vid <NEW_LINE> self.name = name <NEW_LINE> self.label = label
Creates a field. field is the parent field vid is the field values's unique ID number (within a containing field) name is the values's name. label is the value's shorthand label (optional for holds).
625941cfa8370b77170529f1
def test_add(self): <NEW_LINE> <INDENT> self.sysconfig['file'] = os.path.join(os.path.dirname(__file__), 'test_sieve_files/test_add.sieve') <NEW_LINE> event1 = EXAMPLE_INPUT.copy() <NEW_LINE> self.input_message = event1 <NEW_LINE> self.run_bot() <NEW_LINE> self.assertMessageEqual(0, event1) <NEW_LINE> event1['comment']...
Test adding key/value pairs
625941cf3317a56b86939da9
def set_header_vlan(self, vlan_id=1, **kwargs): <NEW_LINE> <INDENT> import scapy.layers.inet as inet <NEW_LINE> self.packet_data['vlan'] = [ inet.Dot1Q(vlan=vlan_id, **kwargs), inet.Dot1Q(vlan=vlan_id, **kwargs)]
Build a Dot1Q scapy object inside instance packet_data structure :param vlan_id: The VLAN ID :param kwargs: Extra params per scapy usage :return: None
625941cf23849d37ff7b31e1
def min_function(context, nodeset): <NEW_LINE> <INDENT> nodeset = nodeset.evaluate_as_nodeset(context) <NEW_LINE> numbers = itertools.imap(datatypes.number, nodeset) <NEW_LINE> try: <NEW_LINE> <INDENT> minimum = numbers.next() <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> return datatypes.NOT_A_NUMBER <...
The math:min function returns the minimum value of the nodes passed as the argument.
625941cf94891a1f4081bbfc
def replace(self, priority, key): <NEW_LINE> <INDENT> result_priority, result_key = self.__heap[0] <NEW_LINE> del self.__position[result_key] <NEW_LINE> self.__heap[0] = [priority, key] <NEW_LINE> self.__position[key] = 0 <NEW_LINE> self.__bubble_down(0) <NEW_LINE> return result_priority, result_key
Same as pop() followed by push(), just more efficient. Args: priority: Priority. key: Item key, must be unique and hashable. Returns: Minimum item as (priority, key) tuple.
625941cf0383005118ecf734
def parse_log( record ): <NEW_LINE> <INDENT> fields = record.split('|') <NEW_LINE> fullts = fields[1] + ' ' + fields[2] <NEW_LINE> ts = datetime.datetime.strptime(fullts,'%d/%b/%Y %H:%M:%S') - datetime.timedelta(hours=4) <NEW_LINE> fepoch = time.mktime(ts.timetuple()) <NEW_LINE> fday = time.mktime( ts.date().timetuple(...
Parse a Movistar TV log line. Return a list of fields
625941cf462c4b4f79d1d823
def update_buf_sweep(self, buf_npts, buf_start=None, buf_stop=None): <NEW_LINE> <INDENT> demod_length = self._instrument._demod_length <NEW_LINE> self._buf_npts = buf_npts <NEW_LINE> if demod_length > 1: <NEW_LINE> <INDENT> self.shapes = ((demod_length, self._buf_npts, self._rec_npts), (demod_length, self._buf_npts, se...
Function which updates the shape of the parameter (and it's setpoints when this is fixed) Args: buf_npts: number of buffers returned buf_start (optional): start value of buffers returned buf_stop (optional): stop value of records returned
625941cf92d797404e3042dc
def get_scheduler(*, optimizer): <NEW_LINE> <INDENT> schdlr_dict = config[constants.SCHEDULER] <NEW_LINE> step, gamma = 5, 0.001 <NEW_LINE> if len(schdlr_dict.keys()) > 0: <NEW_LINE> <INDENT> if constants.SCHEDULER_TYPE in schdlr_dict.keys(): <NEW_LINE> <INDENT> scheduler = schdlr_dict[constants.SCHEDULER_TYPE] <NEW_LI...
Gets the scheduler type and other parameters from config and returns the corresponding scheduler :param optimizer: the optimizer on which scheduler will run :return: scheduler, type either torch.optim.lr_scheduler or None in case no values are given in config
625941cf460517430c3942d6
def simGetImages(self, requests, vehicle_name = '', external = False): <NEW_LINE> <INDENT> responses_raw = self.client.call('simGetImages', requests, vehicle_name, external) <NEW_LINE> return [ImageResponse.from_msgpack(response_raw) for response_raw in responses_raw]
Get multiple images See https://microsoft.github.io/AirSim/image_apis/ for details and examples Args: requests (list[ImageRequest]): Images required vehicle_name (str, optional): Name of vehicle associated with the camera external (bool, optional): Whether the camera is an External Camera Returns: li...
625941cfadb09d7d5db6c8e1
def wrap_colored_text(text, colors, W, tabsize=4): <NEW_LINE> <INDENT> new_text, new_colors = [], [] <NEW_LINE> for char, color in zip(text, colors): <NEW_LINE> <INDENT> if char == '\t': <NEW_LINE> <INDENT> for i in range(tabsize): <NEW_LINE> <INDENT> new_text.append(' ') <NEW_LINE> new_colors.append(color) <NEW_LINE> ...
Wrap text with hidden units to certain width
625941cf8e71fb1e9831d8fb
def draw_shape(self, image, shape, dims, color): <NEW_LINE> <INDENT> x, y, s = dims <NEW_LINE> if shape == "circle": <NEW_LINE> <INDENT> cv2.circle(image, (x, y), s, color, 2) <NEW_LINE> <DEDENT> return image
Draws a shape from the given specs.
625941cffff4ab517eb2f58e
def levelOrder(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> cur, res = [root], [] <NEW_LINE> while cur: <NEW_LINE> <INDENT> next, val = [], [] <NEW_LINE> for node in cur: <NEW_LINE> <INDENT> val.append(node.val) <NEW_LINE> if node.left: <NEW_LINE> <INDENT> next.append(...
:type root: TreeNode :rtype: List[List[int]]
625941cf3317a56b86939daa
def patch(): <NEW_LINE> <INDENT> if getattr(flask, "_datadog_patch", False): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> setattr(flask, "_datadog_patch", True) <NEW_LINE> Pin().onto(flask.Flask) <NEW_LINE> _w("flask", "Flask.wsgi_app", traced_wsgi_app) <NEW_LINE> _w("flask", "Flask.dispatch_request", request_tracer(...
Patch `flask` module for tracing
625941cf6fb2d068a760f1f0
def findlabels(code): <NEW_LINE> <INDENT> labels = [] <NEW_LINE> n = len(code) <NEW_LINE> i = 0 <NEW_LINE> while i < n: <NEW_LINE> <INDENT> op = byte_from_code(code, i) <NEW_LINE> i = i+1 <NEW_LINE> if op >= HAVE_ARGUMENT: <NEW_LINE> <INDENT> oparg = byte_from_code(code, i) + byte_from_code(code, i+1)*256 <NEW_LINE> i ...
Detect all offsets in a bytecode which are jump targets. Return the list of offsets.
625941cfb7558d58953c5066
def test_choices_sanity_check_4(self): <NEW_LINE> <INDENT> with self.assertRaises(Exception): <NEW_LINE> <INDENT> Node( id="1", text=DOG_TO_STR, choices=[Choice("1", DOG_TO_STR, [NodeLink("1", 1)]), Choice("1", DOG_TO_STR, [NodeLink("1", 1)])], effect=lambda account, dog: None ).choices_sanity_check()
Test with choices = two same choice ids :return:
625941cf956e5f7376d70fbf
def apply(self, func, new_field_name=None, **kwargs): <NEW_LINE> <INDENT> assert callable(func), "The func you provide is not callable." <NEW_LINE> assert len(self) != 0, "Null DataSet cannot use apply()." <NEW_LINE> idx = -1 <NEW_LINE> try: <NEW_LINE> <INDENT> results = [] <NEW_LINE> for idx, ins in enumerate(self._in...
将DataSet中每个instance传入到func中,并获取它的返回值. :param callable func: 参数是 ``DataSet`` 中的 ``Instance`` :param None,str new_field_name: 将func返回的内容放入到 `new_field_name` 这个field中,如果名称与已有的field相同,则覆 盖之前的field。如果为None则不创建新的field。 :param optional kwargs: 支持输入is_input,is_target,ignore_type 1. is_input: bool, 如果为True则将 `new_fiel...
625941cf091ae356686670b0
def update_aws_cloud_account_with_http_info(self, id, body, **kwargs): <NEW_LINE> <INDENT> all_params = ['id', 'body', 'api_version'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_t...
Update AWS cloud account # noqa: E501 Update AWS cloud account # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_aws_cloud_account_with_http_info(id, body, async_req=True) >>> result = thread.get() :param as...
625941cf5fcc89381b1e1812
def pprint_coef(self): <NEW_LINE> <INDENT> print(self._model_json["output"]["coefficients_table"])
Pretty print the coefficents table (includes normalized coefficients).
625941cf23849d37ff7b31e2
def main(): <NEW_LINE> <INDENT> print(equal_slices(11, 5, 2)) <NEW_LINE> print(equal_slices(11, 5, 3)) <NEW_LINE> print(equal_slices(8, 3, 2)) <NEW_LINE> print(equal_slices(8, 3, 3)) <NEW_LINE> print(equal_slices(24, 12, 2))
Run equal_slices with samples.
625941cf38b623060ff0af40
def test_ngram_case_insensitive_n_token(): <NEW_LINE> <INDENT> c = load_from_file(fixture_location('long.conll')) <NEW_LINE> s, i, tokens = next( find_ngrams(c, 'l\' orgaNisaTion pour La sécurité et la'.split(), case_sensitive=False)) <NEW_LINE> actual_token_ids = list(map(lambda token: token.id, tokens)) <NEW_LINE> ex...
Test that the case sensitivity function works, when it is the nth token.
625941cf82261d6c526ab5f2
def execute(self, args): <NEW_LINE> <INDENT> if not set([a for a in args]).issuperset(['stored_id','name','id']): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.content_handler.client.add_to_playlist(args['id'], args['stored_id']) <NEW_LINE> return ('Feedback', {'message': 'Added to playlist {0}'.format(args['name...
Asks the Content Manager to find a playlist
625941cf8c0ade5d55d3eb0e
@pytest.mark.parametrize( "desc", [ dict(type="uniform", low=0.0, high=1.0), dict(type="categorical", choices=[1, 2, 3]), dict(type="log_uniform", low=1e-3, high=1e3), dict(type="discrete_uniform", low=1, high=9, step=2), dict(type="int_uniform", low=1, high=9, step=2), dict(type="int_uniform", low=1, high=9), dict(typ...
Test that the distribution can be constructed
625941cf26238365f5f0efc1
def get_sequence_length(n_stages, n_layers_per_stage): <NEW_LINE> <INDENT> sequence_length = 2**n_layers_per_stage * 2 * n_stages <NEW_LINE> return sequence_length
Summary Parameters ---------- n_stages : TYPE Description n_layers_per_stage : TYPE Description Returns ------- TYPE Description
625941cf99fddb7c1c9de4e3
def _get_container_env(self): <NEW_LINE> <INDENT> env_path = '/proc/{}/environ'.format(self._extract_var('Leader')) <NEW_LINE> env_str = self._exec_command('cat ' + env_path)[2] <NEW_LINE> proc_envs = env_str.split('\0') <NEW_LINE> proc_envs = dict([x.split('=') for x in proc_envs if x]) <NEW_LINE> return proc_envs
return container env dict
625941cffb3f5b602dac37e6
@db.test_schema <NEW_LINE> def test_update_product_by_id_invalid_data(): <NEW_LINE> <INDENT> expected_response = "Invalid data sent for update product." <NEW_LINE> data = {} <NEW_LINE> response = product.update_product_by_id(data) <NEW_LINE> assert not response <NEW_LINE> assert response.errors['message'] == expected_r...
Test update product for blanck data.
625941cfbde94217f3682f43
def datastreams(data): <NEW_LINE> <INDENT> l = [] <NEW_LINE> if 'datastreams' in data: <NEW_LINE> <INDENT> for datastream in data['datastreams']: <NEW_LINE> <INDENT> datastream = OrderedDict([('id' , datastream['id']), ('label' , datastream.get('unit', {}).get('label','')), ('symbol' , datastream.get('unit', {}).get('s...
Returns a table of datastreams extracted from the given data.
625941cf4e696a04525c959e
def kill(self, id): <NEW_LINE> <INDENT> if id not in self.chain: <NEW_LINE> <INDENT> raise ChainException('Unknown ID: ' + str(id)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> del self.chain[id]
Kills a node from chain without caring to what it is connected.
625941cf8a43f66fc4b541b7
def deaths_vs_pop(state, date, output_filename): <NEW_LINE> <INDENT> STATECOL = 5 <NEW_LINE> census_name = 'co-est2019-alldata.csv' <NEW_LINE> query_column = STATECOL <NEW_LINE> query_value = state <NEW_LINE> results_columns = [6, 7] <NEW_LINE> county_pops = mu.get_columns(census_name, query_column, query_value, result...
Prepares txt file containing pop and total death count in each county of a state on a given date Parameters ---------- state: string Name of state date: str Date of deaths Prints/Returns -------- county_names: str list Name of the county case_rates: float list Percap rate for that day ...
625941cfab23a570cc2502d5
def set_tags(tags, name=None, group_id=None, vpc_name=None, vpc_id=None, region=None, key=None, keyid=None, profile=None): <NEW_LINE> <INDENT> conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) <NEW_LINE> secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name, group_id=group_id, regio...
sets tags on a security group .. versionadded:: Boron tags a dict of key:value pair of tags to set on the security group name the name of the security gruop group_id the group id of the security group (in lie of a name/vpc combo) vpc_name the name of the vpc to search the named group for vpc_id ...
625941cf91af0d3eaac9bb6c
def __init__(self, iteration_count: int, state_size: int, num_players: int, brain: ValueNetworkBrain = None, reuse_tree: bool = True, k: float = 0.2, gamma: float = 0.99): <NEW_LINE> <INDENT> super(MOIMCTSMixin, self).__init__(k) <NEW_LINE> self.iteration_count = iteration_count <NEW_LINE> self.reuse_tree = reuse_tree ...
Initializer for `MOISMCTSWithValueNetworkAgent` :param iteration_count: ??? :param state_size: ??? :param num_players: The number of players :param brain: ??? :param reuse_tree: If we should reuse the tree or not :param k: ??? :param gamma: ???
625941cf16aa5153ce3625cb
def get_bucket_logging(self): <NEW_LINE> <INDENT> resp = self.__do_bucket('GET', params={Bucket.LOGGING: ''}) <NEW_LINE> return self._parse_result(resp, xml_utils.parse_get_bucket_logging, GetBucketLoggingResult)
获取Bucket的访问日志功能配置。 :return: :class:`GetBucketLoggingResult <oss2.models.GetBucketLoggingResult>`
625941cf91f36d47f21ac646
def setUp(self): <NEW_LINE> <INDENT> self.app = create_app(TestConfig) <NEW_LINE> self.app_context = self.app.app_context() <NEW_LINE> self.app_context.push() <NEW_LINE> db.create_all()
Set up unit tests
625941cf63f4b57ef000126b
def lenet300_classic(): <NEW_LINE> <INDENT> return LeNet300(dropout=False, nonlinearity=nn.Tanh)
Creates classical version of LeNet300, the one having tanh activation functions and no dropouts
625941cf56b00c62f0f147ac
def fetch_and_decode(self): <NEW_LINE> <INDENT> raise NotImplementedError()
Fetch instruction and addresses.
625941cf21a7993f00bc7e43
def train(input_tensor, target_tensor, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=MAX_LENGTH): <NEW_LINE> <INDENT> encoder_hidden = encoder.initHidden() <NEW_LINE> encoder_optimizer.zero_grad() <NEW_LINE> decoder_optimizer.zero_grad() <NEW_LINE> input_length = input_tensor.size(0) <NE...
:param input_tensor: :param target_tensor: :param encoder: :param decoder: :param encoder_optimizer: :param decoder_optimizer: :param criterion: :param max_length: :return:
625941cf8e05c05ec3eea4c8
def lca(A, x, y): <NEW_LINE> <INDENT> if not A: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> assert x != y <NEW_LINE> def inner(n): <NEW_LINE> <INDENT> if not n: <NEW_LINE> <INDENT> return (None, False) <NEW_LINE> <DEDENT> val1, done1 = inner(n.left) <NEW_LINE> val2, done2 = inner(n.right) <NEW_LINE> if done1: <...
least common ancestor
625941cf07d97122c41789df
def test_High_search(self): <NEW_LINE> <INDENT> homepage = HomePage(self.driver) <NEW_LINE> driver = self.driver <NEW_LINE> old_name = driver.find_element_by_xpath('//*[@id="table"]/tbody/tr[1]/td[3]').text <NEW_LINE> cp_name = driver.find_element_by_xpath('//*[@id="table"]/tbody/tr[1]/td[4]').text <NEW_LINE> class_A =...
高级搜索
625941cf66673b3332b921e4
def evaluate_random_function(f, x, y): <NEW_LINE> <INDENT> if f[0] == "prod": <NEW_LINE> <INDENT> return evaluate_random_function(f[1], x, y)*evaluate_random_function(f[2], x, y) <NEW_LINE> <DEDENT> elif f[0] == "avg": <NEW_LINE> <INDENT> return (evaluate_random_function(f[1], x, y) + evaluate_random_function(f[2], x, ...
Evaluate the random function f with inputs x,y Representation of the function f is defined in the assignment writeup f: the function to evaluate x: the value of x to be used to evaluate the function y: the value of y to be used to evaluate the function returns: the function value >>> evaluate_random_function(["x"],-0...
625941cf090684286d50ee39
def load_layout_file(self, layout_file): <NEW_LINE> <INDENT> for line in malt.load(layout_file, MALT_SYNTAX): <NEW_LINE> <INDENT> if line.head == 'split': <NEW_LINE> <INDENT> if line.direction.lower() in "nsew": <NEW_LINE> <INDENT> log("Adding new split on {}.".format(line.direction), level='LAYOUT') <NEW_LINE> log("Ta...
Configures this interface to the layout specified in the given file. Used internally. Filename is passed from the constructor.
625941cfe8904600ed9f2080
def get(self): <NEW_LINE> <INDENT> self.clear_cookie(constants.TESTAPI_ID) <NEW_LINE> logout_url = self.cas_client.get_logout_url(redirect_url=CONF.ui_url) <NEW_LINE> self.redirect(url=logout_url)
Handle signout request.
625941cfc4546d3d9de72b88
def find_similar_search_comb(self): <NEW_LINE> <INDENT> word_list = text_process(self.corrected_query, stem_flag=1) <NEW_LINE> word_list = sorted(set(word_list), key=word_list.index) <NEW_LINE> block_list = list() <NEW_LINE> try: <NEW_LINE> <INDENT> for word in word_list: <NEW_LINE> <INDENT> res = self.glove_model.most...
:return: such as ['chinese products', 'taiwanese', 'food']
625941cf50812a4eaa59c474
def checkProxyDetil(selfip, proxy, isHttp = True): <NEW_LINE> <INDENT> types = -1 <NEW_LINE> speed = -1 <NEW_LINE> if isHttp: <NEW_LINE> <INDENT> test_url = spiderConfig.TEST_HTTP_HEADER <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> test_url = spiderConfig.TEST_HTTPS_HEADER <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> ...
判断代理IP的有效性及相关参数: 有效性:使用requests.get()请求连接,如果超时,则认为是无效IP 协议:分别用http| https组成url进行requests.get(),根据请求结果判断代理所使用的协议 speed:根据开始请求的时间及请求结束的时间判断代理的连接速度 type:超代 high anonymous(level 0):x_forwarded_for & x_real_ip都不显示,服务器察觉不到你 在使用代理 匿名 anonymous(level 1):x_forwarded_for & x_real_ip中为代理服...
625941cfbaa26c4b54cb1272
def _gradient_finite_difference(self, inputs, targets, errorfunc = None): <NEW_LINE> <INDENT> if errorfunc is None: <NEW_LINE> <INDENT> errorfunc = self.get_base_error_func() <NEW_LINE> <DEDENT> delta = 1e-6 <NEW_LINE> error_func = errorfunc[0] <NEW_LINE> res = [] <NEW_LINE> for w in self...
Gives the same result as the gradient method. But this is an in- efficient implementation, and should not be used in practice. It is mostly included for testing reasons, and for curious people:) This method calculates the derivative of the error function with respect to each weight numerically, by using the Newton's d...
625941cf283ffb24f3c55a54
def check_flashes(lockup: dict, leds_number: int) -> str: <NEW_LINE> <INDENT> flashes, error = check_existance(lockup, 'flashes') <NEW_LINE> if error: <NEW_LINE> <INDENT> return error <NEW_LINE> <DEDENT> error = check_keys(flashes, lockup_flashes_keys) <NEW_LINE> error += check_color(flashes) <NEW_LINE> error += check_...
checks flashes settings for lockup parameter :param data: dict with settings :param leds_number: number of leds :return: error or empty message
625941cf4527f215b584c5a9
def feature_eng(df): <NEW_LINE> <INDENT> for col in df.columns: <NEW_LINE> <INDENT> if col.startswith('dat'): <NEW_LINE> <INDENT> df.ix[:, col] = pd.to_datetime(df.ix[:, col], format='%Y-%m-%d %H:%M:%S') <NEW_LINE> <DEDENT> <DEDENT> df.libjob = df.libjob.astype(str) <NEW_LINE> df = df.ix[~(df.codeClosing == 'EM') & ~(d...
A function to wrap up and combine the first feature engineering stage.
625941cf10dbd63aa1bd2cf7
def correct_misspelling_ngram(token, levenshtein_treshold=3): <NEW_LINE> <INDENT> if in_dictionary(token): <NEW_LINE> <INDENT> return token <NEW_LINE> <DEDENT> suggested_words = suggest_words(token) <NEW_LINE> jaccard_coefficients = [] <NEW_LINE> best_suggested_words = [] <NEW_LINE> if suggested_words is not None: <NEW...
corrects token by suggesting words and filtering them using the levenhstein distance. Then it takes all filtered words and chooses the one with the highest jaccard coefficient calculated using bigrams. args: token: string levenshtein threshold: int returns: token: string
625941cf60cbc95b062c6697
def getaccountaddress(self, account=None): <NEW_LINE> <INDENT> r = self._call('getaccountaddress', account) <NEW_LINE> return CBitcoinAddress.from_str(r)
Return the current Bitcoin address for receiving payments to this account.
625941cfbde94217f3682f44
def main(session): <NEW_LINE> <INDENT> global e <NEW_LINE> e = "" <NEW_LINE> done = False <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> os.system("clear") <NEW_LINE> if done: <NEW_LINE> <INDENT> print(e + "\nNow press enter to return to the menu.\n") <NEW_LINE> input() <NEW_LINE> return True <NEW_...
Try to sign in with your session.
625941cfdc8b845886cb5688
def process_permission_roles(perm, v): <NEW_LINE> <INDENT> if isinstance(v, (tuple, list)): <NEW_LINE> <INDENT> roles = v <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> roles = [v] <NEW_LINE> <DEDENT> for r in roles: <NEW_LINE> <INDENT> if isinstance(r, (tuple, list)): <NEW_LINE> <INDENT> role_name, role_props = r <NEW_...
v is roles
625941cf82261d6c526ab5f3
def mpi_submit(nworker, nserver, pass_envs): <NEW_LINE> <INDENT> def run(prog): <NEW_LINE> <INDENT> subprocess.check_call(prog, shell = True) <NEW_LINE> <DEDENT> cmd = '' <NEW_LINE> if args.hostfile is not None: <NEW_LINE> <INDENT> cmd = '--hostfile %s' % (args.hostfile) <NEW_LINE> <DEDENT> cmd += ' ' + ' '.join(args.c...
customized submit script, that submit nslave jobs, each must contain args as parameter note this can be a lambda function containing additional parameters in input Parameters nworker number of slave process to start up nserver number of server nodes to start up pass_envs enviroment variables to be added to the...
625941cfa17c0f6771cbe1a3
def add_dialogue_entry(self, dialogue_len): <NEW_LINE> <INDENT> self.dialogue_entries.append(dialogue_len)
add a new dialogue piece to the end of the dialogue
625941cf5f7d997b87174beb
@command.register(admin=True) <NEW_LINE> def addplugin(bot, event, plugin, *args): <NEW_LINE> <INDENT> config_plugins = bot.config.get_by_path(["plugins"]) or False <NEW_LINE> if not isinstance(config_plugins, list): <NEW_LINE> <INDENT> yield from bot.coro_send_message( event.conv_id, "this command only works with manu...
loads a plugin on the bot and adds it to the config, does not require plugins. prefix
625941cf7d43ff24873a2df4
def refinement_module(incoming_f, incoming_m, w_init, num_feat_out, size_out=None, a=tf.nn.elu, name='refinement'): <NEW_LINE> <INDENT> layers = list() <NEW_LINE> f_shape = incoming_f.get_output_shape() <NEW_LINE> m_shape = incoming_m.get_output_shape() <NEW_LINE> if f_shape[-1] < m_shape[-1]: <NEW_LINE> <INDENT> raise...
Refinement module as proposed in https://arxiv.org/abs/1603.08695 (refactored version) This function builds and returns a refinement module taking an input incoming_f and incoming_m with incoming_f >= incoming_m in terms of features. Parameters ------- incoming_f : Layer Input layer to refinement module with larg...
625941cf3c8af77a43ae38f4
def test_step_basic(ctx): <NEW_LINE> <INDENT> result = ctx.step(SampleStep).execute(2, 4, operation=lambda x, y: x * y) <NEW_LINE> assert result == 8
Verify a basic step operation
625941cf15baa723493c40c9
def minCostClimbingStairs(self, cost): <NEW_LINE> <INDENT> prev, current = cost[0], cost[1] <NEW_LINE> for i in range(2, len(cost)): <NEW_LINE> <INDENT> prev, current = current, min(prev, current) + cost[i] <NEW_LINE> <DEDENT> return min(prev, current)
:type cost: List[int] :rtype: int
625941cf0c0af96317bb833b
def setZeroes(self, matrix: List[List[int]]) -> None: <NEW_LINE> <INDENT> x = [] <NEW_LINE> y = [] <NEW_LINE> for i in range(len(matrix)): <NEW_LINE> <INDENT> for j in range(len(matrix[0])): <NEW_LINE> <INDENT> if matrix[i][j] == 0: <NEW_LINE> <INDENT> if j not in x: x.append(j) <NEW_LINE> if i not in y: y.append(i) <N...
Do not return anything, modify matrix in-place instead.
625941cf627d3e7fe0d68fa3
def set_ID(self, value): <NEW_LINE> <INDENT> super(UnlikePostInputSet, self)._set_input('ID', value)
Set the value of the ID input for this Choreo. ((required, integer) The ID of the post you want to unlike.)
625941cf004d5f362079a486
def GetGroups(self, id, userid=None, group=None): <NEW_LINE> <INDENT> parameter = {} <NEW_LINE> if id is not None: <NEW_LINE> <INDENT> parameter["id"] = id <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("id must not be none") <NEW_LINE> <DEDENT> if userid: <NEW_LINE> <INDENT> parameter["userid"] = userid...
Get local group assignment for userid. `id` can be a single value or a tuple. If its a tuple the groups for all matching ids are returned. returns a group assignment list [["userid", "groupid", "id"], ...]
625941cf498bea3a759b9c02
def eventFilter(self, watched, event): <NEW_LINE> <INDENT> if event.type() == QEvent.KeyPress: <NEW_LINE> <INDENT> self.keyPressEvent(event) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False
Event Filter handling
625941cf5166f23b2e1a52ad
def next(self): <NEW_LINE> <INDENT> return self._model.space.next()
seeks the next coordinate in the space and returns it
625941cf0a366e3fb873e96e
@session(name="docs-build", python="3.10") <NEW_LINE> def docs_build(session: Session) -> None: <NEW_LINE> <INDENT> args = session.posargs or ["docs", "docs/_build"] <NEW_LINE> if not session.posargs and "FORCE_COLOR" in os.environ: <NEW_LINE> <INDENT> args.insert(0, "--color") <NEW_LINE> <DEDENT> session.install(".") ...
Build the documentation.
625941cfad47b63b2c50a0d3
def t_NUMBER_INTEGER(self, t): <NEW_LINE> <INDENT> t.value = t.value[1:len(t.value)] <NEW_LINE> while t.value[0] == '0' and len(t.value) != 1: <NEW_LINE> <INDENT> t.value = t.value[1:len(t.value)] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> t.value = int(t.value) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDE...
\#[\+-]?[0-9]+
625941cf63d6d428bbe44643
def is_official_target(target_name, version): <NEW_LINE> <INDENT> result = True <NEW_LINE> reason = None <NEW_LINE> target = TARGET_MAP[target_name] <NEW_LINE> if hasattr(target, 'release_versions') and version in target.release_versions: <NEW_LINE> <INDENT> if version == '2': <NEW_LINE> <INDENT> required_toolcha...
Returns True, None if a target is part of the official release for the given version. Return False, 'reason' if a target is not part of the official release for the given version. Positional arguments: target_name - Name if the target (ex. 'K64F') version - The release version string. Should be a string contained with...
625941cf71ff763f4b5497df
def writeparams(self,chainnum): <NEW_LINE> <INDENT> defaultparamsfile = open('../' + self.paramfile) <NEW_LINE> defaultparams = defaultparamsfile.read() <NEW_LINE> defaultparamsfile.close() <NEW_LINE> output= [] <NEW_LINE> output.append('chain root = ' + 'hps' + str(self.hpsid) + '_' + str(chainnum)) <NEW_LINE> output....
this writes out the params file chainnum is an int that is the number of the chain
625941cf8e05c05ec3eea4c9
def image_channel(I, channel): <NEW_LINE> <INDENT> return I[:, channel, :, :]
Extracts the specified channel(s) from the input Neural Renderer image Parameters ---------- I : Tensor the Neural Renderer image channel : int or list of ints the channel(s) to extract Returns ------- Tensor the selected channel(s)
625941cf8c3a87329515850f
def perform_centering(self): <NEW_LINE> <INDENT> centered_data = self.data - np.repeat(self.mean_data[:, np.newaxis], self.data.shape[1], axis=1) + self.weight <NEW_LINE> return centered_data
The centering is done by directly average the shifted and weighted data. :return: (ndarray), the centered data.
625941cf7b180e01f3dc4950
def valid_port(string): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = int(string) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise argparse.ArgumentTypeError("port must be an integer") <NEW_LINE> <DEDENT> if value < 1 or value > 65535: <NEW_LINE> <INDENT> raise argparse.ArgumentTypeError("port mu...
argparse type which parses a port number.
625941cffb3f5b602dac37e7
def __init__(self, ID, parameter_decorator_class=_parameter_decorator, return_decorator_class=_return_decorator): <NEW_LINE> <INDENT> if isinstance(ID, uuid.UUID): <NEW_LINE> <INDENT> self._ID = ID <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._ID = uuid.UUID(ID) <NEW_LINE> <DEDENT> self.parameter_decorator_class ...
:param ID: This is your project's UUID. The easiest way to generate this is to use the `uuid <http://docs.python.org/3/library/uuid.html`_ module, and then store the ID somewhere convenient. :type ID: ``str`` that can be used to initialize a `UUID <http://docs.python.org/3/library/uuid.html#uuid.UUID`_...
625941cf627d3e7fe0d68fa4
def stopProducing(self): <NEW_LINE> <INDENT> self.producing = False
IPushProducer interface.
625941cf377c676e912722fc
def post_flag(self, **params): <NEW_LINE> <INDENT> all_args = ['seen', 'answered', 'flagged', 'deleted', 'draft'] <NEW_LINE> params = Resource.sanitize_params(params, all_args) <NEW_LINE> data = self._request_uri('flags', method='POST', params=params) <NEW_LINE> status = bool(data['success']) <NEW_LINE> if status: <NEW...
Set message flags for a given email. Also, populates/updates self.flags with the new data. Optional Arguments: seen: integer - Message has been read. Set this parameter to 1 to set the flag, 0 to unset it. answered: integer - Message has been answered. Set this parameter to 1 to set the flag, ...
625941cf45492302aab5e417