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
account_wizard.py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) conexus.at # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public ...
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
_inherit='wizard.multi.charts.accounts' _defaults = { 'code_digits' : 0, }
identifier_body
account_wizard.py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) conexus.at # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public ...
# ############################################################################## from openerp import tools from openerp.osv import osv from openerp import addons class AccountWizard_cd(osv.osv_memory): _inherit='wizard.multi.charts.accounts' _defaults = { 'code_digits' : 0, } # vim:expandtab:smartindent:tab...
# along with this program. If not, see <http://www.gnu.org/licenses/>.
random_line_split
report_issue.py
# Copyright (c) 2012-2015 Netforce Co. Ltd. # # 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, modify, merge, publ...
def get_issue_close_chart(self, context={}): closed={} for issue in get_model("issue").search_browse([["state","=","closed"],["date_closed","!=",None]]): d=issue.date_closed[:10] closed.setdefault(d,0) closed[d]+=1 values=[] for d,n in sorted(clo...
actions=[] for issue in get_model("issue").search_browse([]): if issue.date_created: actions.append((issue.date_created,"open")) if issue.state=="closed" and issue.date_closed: actions.append((issue.date_closed,"close")) actions.sort() valu...
identifier_body
report_issue.py
# Copyright (c) 2012-2015 Netforce Co. Ltd. # # 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, modify, merge, publ...
(self, context={}): closed={} for issue in get_model("issue").search_browse([["state","=","closed"],["date_closed","!=",None]]): d=issue.date_closed[:10] closed.setdefault(d,0) closed[d]+=1 values=[] for d,n in sorted(closed.items()): value...
get_issue_close_chart
identifier_name
report_issue.py
# Copyright (c) 2012-2015 Netforce Co. Ltd. # # 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, modify, merge, publ...
elif action=="close": num_issues-=1 values.append((js_time(d), num_issues)) data = { "value": values, } return data def get_issue_close_chart(self, context={}): closed={} for issue in get_model("issue").search_browse([["s...
num_issues+=1
conditional_block
report_issue.py
# Copyright (c) 2012-2015 Netforce Co. Ltd. # # Permission is hereby granted, free of charge, to any person obtaining a copy
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial porti...
# of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights
random_line_split
transport.d.ts
/// <reference types="node" /> import { Wire, WireConstructor, READY_STATE, ExistingConnectConfig, ConnectConfig, InternalConnectConfig } from './wire'; import { Identity } from '../identity'; import { EventEmitter } from 'events'; import { Environment } from '../environment/environment'; import { RuntimeEvent } from '...
{ token: string; file: string; }
AuthorizationPayload
identifier_name
transport.d.ts
/// <reference types="node" /> import { Wire, WireConstructor, READY_STATE, ExistingConnectConfig, ConnectConfig, InternalConnectConfig } from './wire'; import { Identity } from '../identity'; import { EventEmitter } from 'events'; import { Environment } from '../environment/environment'; import { RuntimeEvent } from '...
}>; protected uncorrelatedListener: Function; me: (View | Window | Frame | {}) & Identity & EntityTypeHelpers; environment: Environment; topicRefMap: Map<string, number>; sendRaw: Wire['send']; eventAggregator: EventAggregator; protected messageHandlers: MessageHandler[]; constructor...
declare class Transport extends EventEmitter { protected wireListeners: Map<number, { resolve: Function; reject: Function;
random_line_split
injector_compatibility.ts
/** * @license * Copyright Google Inc. All Rights Reserved. *
import {stringify} from '../util'; import {InjectableDef, getInjectableDef} from './defs'; import {InjectionToken} from './injection_token'; import {Injector} from './injector'; import {Inject, Optional, Self, SkipSelf} from './metadata'; /** * Injection flags for DI. * * @publicApi */ export const enum InjectFla...
* Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Type} from '../type';
random_line_split
injector_compatibility.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Type} from '../type'; import {stringify} from '../util'; import {InjectableDef, getInjectableDef} from './d...
(injector: Injector | null | undefined): Injector|undefined|null { const former = _currentInjector; _currentInjector = injector; return former; } /** * Current implementation of inject. * * By default, it is `injectInjectorOnly`, which makes it `Injector`-only aware. It can be changed * to `directiveInject`,...
setCurrentInjector
identifier_name
injector_compatibility.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Type} from '../type'; import {stringify} from '../util'; import {InjectableDef, getInjectableDef} from './d...
let type: Type<any>|undefined = undefined; let flags: InjectFlags = InjectFlags.Default; for (let j = 0; j < arg.length; j++) { const meta = arg[j]; if (meta instanceof Optional || meta.ngMetadataName === 'Optional') { flags |= InjectFlags.Optional; } else if (meta ...
{ throw new Error('Arguments array must have arguments.'); }
conditional_block
injector_compatibility.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Type} from '../type'; import {stringify} from '../util'; import {InjectableDef, getInjectableDef} from './d...
/** * Current implementation of inject. * * By default, it is `injectInjectorOnly`, which makes it `Injector`-only aware. It can be changed * to `directiveInject`, which brings in the `NodeInjector` system of ivy. It is designed this * way for two reasons: * 1. `Injector` should not depend on ivy logic. * 2....
{ const former = _currentInjector; _currentInjector = injector; return former; }
identifier_body
__init__.py
self.sid[-33] == 'S' def is_accessed(self): """Returns True if any value of this session has been accessed.""" return self._accessed def ensure_data_loaded(self): """Fetch the session data if it hasn't been retrieved it yet.""" self._accessed = True if self.data is Non...
set_quick
identifier_name
__init__.py
b64pdump = data[:SIG_LEN], data[SIG_LEN:i], data[i:] pdump = b64decode(b64pdump) actual_sig = Session.__compute_hmac(self.base_key, sid, pdump) if sig == actual_sig: self.__set_sid(sid, False) # check for expiration and terminate the session if it has...
made (specifically, if any mutator methods like __setitem__ or the like is called). If the data is small enough it will be sent back to the user in a cookie
random_line_split
__init__.py
_key, cookie.keys()) if not self.cookie_keys: return # no session yet self.cookie_keys.sort() data = ''.join(cookie[k].value for k in self.cookie_keys) i = SIG_LEN + SID_LEN sig, sid, b64pdump = data[:SIG_LEN], data[SIG_LEN:i], data[i:] ...
else: logging.error("can't find session data in the datastore for sid=%s" % self.sid) self.terminate(False) # we lost it; just kill the session return self.data = self.__decode_data(pdump) def save(self, persist_even_if_using_cookie=False): ...
pdump = session_model_instance.pdump
conditional_block
__init__.py
class SessionModel(db.Model): """Contains session data. key_name is the session ID and pdump contains a pickled dictionary which maps session variables to their values.""" pdump = db.BlobProperty() class Session(object): """Manages loading, reading/writing key-value pairs, and saving of a session....
return k.startswith(COOKIE_NAME_PREFIX)
identifier_body
mode-swift.js
lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var SwiftHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ ...
() { return [{ token : "comment", regex : "\\/\\/(?=.)", next : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next: "start"}, {defaultToken : "comment", caseInsensitive: true...
comments
identifier_name
mode-swift.js
lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var SwiftHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ ...
}, { regex: start + (options.multiline ? "" : "|$"), token: "string.end", next: nestable ? "pop" : "start" }, { defaultToken: "string" } ].filter(Boolean); if (nestable) ...
{ var nestable = options.nestable || options.interpolation; var interpStart = options.interpolation && options.interpolation.nextState || "start"; var mainRule = { regex: start + (options.multiline ? "" : "(?=.)"), token: "string.start" }; var nextState = ...
identifier_body
mode-swift.js
lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var SwiftHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ ...
regex : /[\])}]/ } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); this.normalizeRules(); }; oop.inherits(SwiftHighlightRules, TextHighlightRules); exports.HighlightRules = SwiftHighli...
regex : /[\[({]/, next : "start" }, { token : "paren.rparen",
random_line_split
slurm_cluster_resolver.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
def num_accelerators_per_worker(self, session_config=None): del session_config # Unused, since this is set in __init__ manually. return self._gpus_per_node
random_line_split
slurm_cluster_resolver.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
(ClusterResolver): """Cluster Resolver for system with Slurm workload manager. This is an implementation of cluster resolvers for Slurm clusters. This allows the specification of jobs and task counts, number of tasks per node, number of GPUs on each node and number of GPUs for each task, It retrieves system ...
SlurmClusterResolver
identifier_name
slurm_cluster_resolver.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
else: raise RuntimeError('Neither `tasks_per_node` or ' 'SLURM_NTASKS_PER_NODE is set.') self._gpus_per_node = gpus_per_node self._gpus_per_task = gpus_per_task self._auto_set_gpu = auto_set_gpu self.task_type = None self.task_index = None self.rpc_layer = r...
self._tasks_per_node = int(os.environ['SLURM_NTASKS_PER_NODE'])
conditional_block
slurm_cluster_resolver.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
def __init__(self, jobs, port_base=8888, gpus_per_node=1, gpus_per_task=1, tasks_per_node=None, auto_set_gpu=True, rpc_layer='grpc'): """Creates a new SlurmClusterResolver object. This takes in paramete...
"""Resolve host names of nodes allocated in current jobs. Returns: A list of node names as strings. """ hostlist = (subprocess.check_output(['scontrol', 'show', 'hostname']). decode('utf-8').strip().split('\n')) return hostlist
identifier_body
test_repetition_unit.py
# This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger W...
self.assertEqual("{0}".format(RepetitionUnit.objects.get(pk=1)), 'Repetitions') class OverviewTest(WorkoutManagerAccessTestCase): ''' Tests the settings unit overview page ''' url = 'core:repetition-unit:list' anonymous_fail = True class AddTestCase(WorkoutManagerAddTestCase): ''' ...
Test that the representation of an object is correct '''
random_line_split
test_repetition_unit.py
# This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger W...
(WorkoutManagerEditTestCase): ''' Tests editing a unit ''' pk = 1 object_class = RepetitionUnit url = 'core:repetition-unit:edit' data = {'name': 'Furlongs'} user_success = 'admin', user_fail = ('general_manager1', 'general_manager2', 'member1', ...
EditTestCase
identifier_name
test_repetition_unit.py
# This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger W...
class AddTestCase(WorkoutManagerAddTestCase): ''' Tests adding a new unit ''' object_class = RepetitionUnit url = 'core:repetition-unit:add' data = {'name': 'Furlongs'} user_success = 'admin', user_fail = ('general_manager1', 'general_manager2', 'mem...
''' Tests the settings unit overview page ''' url = 'core:repetition-unit:list' anonymous_fail = True
identifier_body
test_version.py
# Copyright 2017,2018 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
def test_version(self): req = mock.Mock() ver_str = {"rc": 0, "overallRC": 0, "errmsg": "", "modID": None, "output": {"api_version": version.APIVERSION, "min_version": version.APIVERS...
pass
identifier_body
test_version.py
# Copyright 2017,2018 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
from zvmsdk import version as sdk_version class HandlersRootTest(unittest.TestCase): def setUp(self): pass def test_version(self): req = mock.Mock() ver_str = {"rc": 0, "overallRC": 0, "errmsg": "", "modID": None, ...
from zvmsdk.sdkwsgi.handlers import version
random_line_split
test_version.py
# Copyright 2017,2018 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
(self): req = mock.Mock() ver_str = {"rc": 0, "overallRC": 0, "errmsg": "", "modID": None, "output": {"api_version": version.APIVERSION, "min_version": version.APIVERSION, ...
test_version
identifier_name
body_exp_euler_integrator.rs
//! Explicit Euler integrator. use na::Transformation; use math::Scalar; use object::RigidBody; use integration::Integrator; use integration::euler; /// An explicit Euler integrator. /// /// Do not use this, prefer the `BodySmpEulerIntegrator` instead. pub struct BodyExpEulerIntegrator; impl BodyExpEulerIntegrator {...
}
{ if rb.can_move() { let (t, lv, av) = euler::explicit_integrate( dt.clone(), rb.position(), rb.center_of_mass(), &rb.lin_vel(), &rb.ang_vel(), &rb.lin_acc(), &rb.ang_acc()); ...
identifier_body
body_exp_euler_integrator.rs
//! Explicit Euler integrator. use na::Transformation; use math::Scalar; use object::RigidBody; use integration::Integrator; use integration::euler; /// An explicit Euler integrator. /// /// Do not use this, prefer the `BodySmpEulerIntegrator` instead. pub struct BodyExpEulerIntegrator; impl BodyExpEulerIntegrator {...
} }
{ let (t, lv, av) = euler::explicit_integrate( dt.clone(), rb.position(), rb.center_of_mass(), &rb.lin_vel(), &rb.ang_vel(), &rb.lin_acc(), &rb.ang_acc()); rb.append_transformation(&t...
conditional_block
body_exp_euler_integrator.rs
//! Explicit Euler integrator. use na::Transformation;
use object::RigidBody; use integration::Integrator; use integration::euler; /// An explicit Euler integrator. /// /// Do not use this, prefer the `BodySmpEulerIntegrator` instead. pub struct BodyExpEulerIntegrator; impl BodyExpEulerIntegrator { /// Creates a new `BodyExpEulerIntegrator`. #[inline] pub fn ...
use math::Scalar;
random_line_split
body_exp_euler_integrator.rs
//! Explicit Euler integrator. use na::Transformation; use math::Scalar; use object::RigidBody; use integration::Integrator; use integration::euler; /// An explicit Euler integrator. /// /// Do not use this, prefer the `BodySmpEulerIntegrator` instead. pub struct BodyExpEulerIntegrator; impl BodyExpEulerIntegrator {...
() -> BodyExpEulerIntegrator { BodyExpEulerIntegrator } } impl Integrator<RigidBody> for BodyExpEulerIntegrator { #[inline] fn update(&mut self, dt: Scalar, rb: &mut RigidBody) { if rb.can_move() { let (t, lv, av) = euler::explicit_integrate( dt.clone(), ...
new
identifier_name
iterable.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 https://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] //! Implementation of `iterable<...>` and `iterable<..., ...>` WebIDL declarations. use ...
unsafe { self.iterable .get_key_at_index(index) .to_jsval(*cx, key.handle_mut()); self.iterable .get_value_at_index(index) .to_jsval(*cx, va...
{ match self.type_ { IteratorType::Keys => { unsafe { self.iterable .get_key_at_index(index) .to_jsval(*cx, value.handle_mut()); } dict_return(cx, rval....
conditional_block
iterable.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 https://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] //! Implementation of `iterable<...>` and `iterable<..., ...>` WebIDL declarations. use ...
.to_jsval(*cx, value.handle_mut()); } dict_return(cx, rval.handle_mut(), false, value.handle()) }, IteratorType::Entries => { rooted!(in(*cx) let mut key = UndefinedValue()); unsaf...
{ let index = self.index.get(); rooted!(in(*cx) let mut value = UndefinedValue()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>()); let result = if index >= self.iterable.get_iterable_length() { dict_return(cx, rval.handle_mut(), true, value.handle()) } el...
identifier_body
iterable.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 https://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] //! Implementation of `iterable<...>` and `iterable<..., ...>` WebIDL declarations. use ...
/// The values that an iterator will iterate over. #[derive(JSTraceable, MallocSizeOf)] pub enum IteratorType { /// The keys of the iterable object. Keys, /// The values of the iterable object. Values, /// The keys and values of the iterable object combined. Entries, } /// A DOM object that ca...
use std::cell::Cell; use std::ptr; use std::ptr::NonNull;
random_line_split
iterable.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 https://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] //! Implementation of `iterable<...>` and `iterable<..., ...>` WebIDL declarations. use ...
(&self, cx: JSContext) -> Fallible<NonNull<JSObject>> { let index = self.index.get(); rooted!(in(*cx) let mut value = UndefinedValue()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>()); let result = if index >= self.iterable.get_iterable_length() { dict_return(cx,...
Next
identifier_name
distillchain_lstm_cnn_deep_combine_chain_model.py
import math import models import tensorflow as tf import numpy as np import utils from tensorflow import flags import tensorflow.contrib.slim as slim FLAGS = flags.FLAGS class DistillchainLstmCnnDeepCombineChainModel(models.BaseModel): """A softmax over a mixture of logistic models (with L2 regularization).""" de...
def get_mask(self, max_frames, num_frames): mask_array = [] for i in xrange(max_frames + 1): tmp = [0.0] * max_frames for j in xrange(i): tmp[j] = 1.0 mask_array.append(tmp) mask_array = np.array(mask_array) mask_init = tf.constant_initializer(mask_array) mask_emb = tf.g...
gating_distribution[:, :num_mixtures] * expert_distribution, 1) final_probabilities = tf.reshape(final_probabilities_by_class_and_batch, [-1, vocab_size]) return final_probabilities
random_line_split
distillchain_lstm_cnn_deep_combine_chain_model.py
import math import models import tensorflow as tf import numpy as np import utils from tensorflow import flags import tensorflow.contrib.slim as slim FLAGS = flags.FLAGS class DistillchainLstmCnnDeepCombineChainModel(models.BaseModel): """A softmax over a mixture of logistic models (with L2 regularization).""" de...
def lstmoutput(self, model_input, vocab_size, num_frames): number_of_layers = FLAGS.lstm_layers lstm_sizes = map(int, FLAGS.lstm_cells.split(",")) feature_names, feature_sizes = utils.GetListOfFeatureNamesAndSizes( FLAGS.feature_names, FLAGS.feature_sizes) sub_inputs = [tf.nn.l2_normalize...
mask_array = [] for i in xrange(max_frames + 1): tmp = [0.0] * max_frames for j in xrange(i): tmp[j] = 1.0 mask_array.append(tmp) mask_array = np.array(mask_array) mask_init = tf.constant_initializer(mask_array) mask_emb = tf.get_variable("mask_emb", shape = [max_frames + 1, m...
identifier_body
distillchain_lstm_cnn_deep_combine_chain_model.py
import math import models import tensorflow as tf import numpy as np import utils from tensorflow import flags import tensorflow.contrib.slim as slim FLAGS = flags.FLAGS class DistillchainLstmCnnDeepCombineChainModel(models.BaseModel): """A softmax over a mixture of logistic models (with L2 regularization).""" de...
(self, max_frames, num_frames): mask_array = [] for i in xrange(max_frames + 1): tmp = [0.0] * max_frames for j in xrange(i): tmp[j] = 1.0 mask_array.append(tmp) mask_array = np.array(mask_array) mask_init = tf.constant_initializer(mask_array) mask_emb = tf.get_variable("m...
get_mask
identifier_name
distillchain_lstm_cnn_deep_combine_chain_model.py
import math import models import tensorflow as tf import numpy as np import utils from tensorflow import flags import tensorflow.contrib.slim as slim FLAGS = flags.FLAGS class DistillchainLstmCnnDeepCombineChainModel(models.BaseModel): """A softmax over a mixture of logistic models (with L2 regularization).""" de...
main_predictions = self.sub_model(next_input, vocab_size, sub_scope=sub_scope+"-main") support_predictions = tf.concat(support_predictions, axis=1) return {"predictions": main_predictions, "support_predictions": support_predictions} def sub_model(self, model_input, vocab_size, num_mixtures=None, ...
sub_prediction = self.sub_model(next_input, vocab_size, sub_scope=sub_scope+"prediction-%d"%layer) support_predictions.append(sub_prediction) sub_relu = slim.fully_connected( sub_prediction, relu_cells, activation_fn=tf.nn.relu, weights_regularizer=slim.l2_regularize...
conditional_block
admin.py
from django.contrib import admin from app.models import Home, Room, Thermostat, Door, Light, Refrigerator """ Administrator interface customization This module contains customization classes to the admin interface rendered by Django. This file is interpreted at run time to serve the custom administrator actions that ...
class RefrigeratorInline(admin.StackedInline): """ StackedInline """ model = Refrigerator class RoomAdmin(admin.ModelAdmin): """ ModelAdmin """ list_display = ('name','home','room_type','pk') search_fields = ('name','home') inlines = (DoorInline, LightInline, RefrigeratorInline,)...
""" ModelAdmin """ list_display = ('name','room','fridge_set_temp','fridge_current_temp','freezer_set_temp','freezer_current_temp','pk') search_fields = ('name','room')
identifier_body
admin.py
from django.contrib import admin from app.models import Home, Room, Thermostat, Door, Light, Refrigerator """ Administrator interface customization This module contains customization classes to the admin interface rendered by Django. This file is interpreted at run time to serve the custom administrator actions that ...
search_fields = ('name','room') class LightInline(admin.StackedInline): """ StackedInline """ model = Light class RefrigeratorAdmin(admin.ModelAdmin): """ ModelAdmin """ list_display = ('name','room','fridge_set_temp','fridge_current_temp','freezer_set_temp','freezer_current_temp','pk') ...
random_line_split
admin.py
from django.contrib import admin from app.models import Home, Room, Thermostat, Door, Light, Refrigerator """ Administrator interface customization This module contains customization classes to the admin interface rendered by Django. This file is interpreted at run time to serve the custom administrator actions that ...
(admin.StackedInline): """ StackedInline """ model = Refrigerator class RoomAdmin(admin.ModelAdmin): """ ModelAdmin """ list_display = ('name','home','room_type','pk') search_fields = ('name','home') inlines = (DoorInline, LightInline, RefrigeratorInline,) class RoomInline(admin.S...
RefrigeratorInline
identifier_name
0013_auto_20160904_1252.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class
(migrations.Migration): dependencies = [ ('session', '0012_auto_20160904_1130'), ] operations = [ migrations.AlterField( model_name='serversetting', name='minorating_grade', field=models.CharField(default=b'ABCN', help_text=b"Minorating Grade required to...
Migration
identifier_name
0013_auto_20160904_1252.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('session', '0012_auto_20160904_1130'), ]
migrations.AlterField( model_name='serversetting', name='minorating_grade', field=models.CharField(default=b'ABCN', help_text=b"Minorating Grade required to join this server's sessions (driver proficiency - see http://www.minorating.com/Grades for details)", max_length=8, cho...
operations = [
random_line_split
0013_auto_20160904_1252.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('session', '0012_auto_20160904_1130'), ] operations = [ migrations.AlterField( model_name='serversetting', name='minorating_grade', field=models.CharField(default=b'ABCN', help_text=b"Minorating Grade required to join this server's sessions ...
identifier_body
client.rs
extern crate env_logger; extern crate tokio_core; extern crate futures; extern crate tokio_solicit; use std::str; use std::io::{self}; use futures::{Future, Stream}; use futures::future::{self}; use tokio_core::reactor::{Core}; use tokio_solicit::client::H2Client; // Shows the usage of `H2Client` when establishing...
println!("receiving a new chunk of size {}", chunk.body.len()); vec.extend(chunk.body.into_iter()); future::ok::<_, io::Error>(vec) }) }); // Finally, yield a future that resolves once both requests are complete (and both bodies // ar...
{ let mut core = Core::new().expect("event loop required"); let handle = core.handle(); let addr = "127.0.0.1:8080".parse().expect("valid IP address"); let future_client = H2Client::cleartext_connect("localhost", &addr, &handle); let future_response = future_client.and_then(|mut client| { ...
identifier_body
client.rs
extern crate env_logger; extern crate tokio_core; extern crate futures; extern crate tokio_solicit; use std::str; use std::io::{self}; use futures::{Future, Stream}; use futures::future::{self}; use tokio_core::reactor::{Core}; use tokio_solicit::client::H2Client; // Shows the usage of `H2Client` when establishing...
() { println!(); println!("---- streaming request example ----"); use std::iter; use tokio_solicit::client::HttpRequestBody; use futures::Sink; let mut core = Core::new().expect("event loop required"); let handle = core.handle(); let addr = "127.0.0.1:8080".parse().expect("valid IP addr...
do_streaming_request
identifier_name
client.rs
extern crate env_logger; extern crate tokio_core; extern crate futures; extern crate tokio_solicit; use std::str; use std::io::{self}; use futures::{Future, Stream}; use futures::future::{self}; use tokio_core::reactor::{Core}; use tokio_solicit::client::H2Client; // Shows the usage of `H2Client` when establishing...
let future_client = H2Client::cleartext_connect("localhost", &addr, &handle); let future_response = future_client.and_then(|mut client| { let (post, tx) = client.streaming_request(b"POST", b"/post", iter::empty()); tx .send(Ok(HttpRequestBody::new(b"HELLO ".to_vec()))) ....
let handle = core.handle(); let addr = "127.0.0.1:8080".parse().expect("valid IP address");
random_line_split
pslldq.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pslldq_1()
fn pslldq_2() { run_test(&Instruction { mnemonic: Mnemonic::PSLLDQ, operand1: Some(Direct(XMM6)), operand2: Some(Literal8(32)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 115, 254, 32], OperandSize::Qword) }
{ run_test(&Instruction { mnemonic: Mnemonic::PSLLDQ, operand1: Some(Direct(XMM4)), operand2: Some(Literal8(90)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 115, 252, 90], OperandSize::Dword) }
identifier_body
pslldq.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pslldq_1() { run_test(&Instruction { mnemonic: Mnemonic::PSLLDQ, operand1: Some(Direct(XMM4)), operand2: Some(Literal8(...
() { run_test(&Instruction { mnemonic: Mnemonic::PSLLDQ, operand1: Some(Direct(XMM6)), operand2: Some(Literal8(32)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 115, 254, 32], OperandSize::Qword) }
pslldq_2
identifier_name
pslldq.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pslldq_1() { run_test(&Instruction { mnemonic: Mnemonic::PSLLDQ, operand1: Some(Direct(XMM4)), operand2: Some(Literal8(...
run_test(&Instruction { mnemonic: Mnemonic::PSLLDQ, operand1: Some(Direct(XMM6)), operand2: Some(Literal8(32)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 115, 254, 32], OperandSize::Qword) }
} fn pslldq_2() {
random_line_split
WalkableList.ts
///<reference path='../definitions/JQuery.d.ts'/> ///<reference path='GetNextFreeId.ts'/> ///<reference path='IEntity.ts'/> ///<reference path='IWalkableList.ts'/> ///<reference path='IObservableRepository.ts'/> module VjsPluginComponents { //This Walkable list implementation includes everything stored in the unde...
} add(object: IEntity) { return this._repository.create(object); } removeCurrent() { this._repository.remove(this._objects[this._index].id) } update(object: IEntity) { this._repository.update(object); } remove(id: n...
{ this.moveNext(); }
conditional_block
WalkableList.ts
///<reference path='../definitions/JQuery.d.ts'/> ///<reference path='GetNextFreeId.ts'/> ///<reference path='IEntity.ts'/> ///<reference path='IWalkableList.ts'/> ///<reference path='IObservableRepository.ts'/> module VjsPluginComponents { //This Walkable list implementation includes everything stored in the unde...
updateLocalArray() { this._objects = jQuery.grep(this._repository.toList(),this._filterFunction).sort(this._sortFunction); } getCurrent() { return this._objects[this._index]; } moveNext() { this._index++; } hasNext() { ...
{ this._index = 0; this._objects = []; this._repository = repository; this._sortFunction = sortFunction; this._filterFunction = filterFunction; this.updateLocalArray(); this._repository.on("create", () => { this.update...
identifier_body
WalkableList.ts
///<reference path='../definitions/JQuery.d.ts'/> ///<reference path='GetNextFreeId.ts'/> ///<reference path='IEntity.ts'/> ///<reference path='IWalkableList.ts'/> ///<reference path='IObservableRepository.ts'/> module VjsPluginComponents { //This Walkable list implementation includes everything stored in the unde...
() { this._index++; } hasNext() { return (this._index < this._objects.length) } isFinished() { return (this._index >= this._objects.length) } /** * resets the list to the first point upon which the condition is met. ...
moveNext
identifier_name
WalkableList.ts
///<reference path='../definitions/JQuery.d.ts'/> ///<reference path='GetNextFreeId.ts'/> ///<reference path='IEntity.ts'/> ///<reference path='IWalkableList.ts'/> ///<reference path='IObservableRepository.ts'/> module VjsPluginComponents { //This Walkable list implementation includes everything stored in the under...
this._handlersToTrigger, (a, b) => { //A appears after B when positive if ((a.time - b.time) == 0) { return this.getBoundaryOrdering(a.boundaryType) - this.getBoundaryOrdering(b.boundaryType); } else { return a.time - b.time; ...
random_line_split
legacy.rs
// // Note that this demangler isn't quite as fancy as it could be. We have lots // of other information in our symbols like hashes, version, type information, // etc. Additionally, this doesn't handle glue symbols at all. pub fn demangle(s: &str) -> Result<(Demangle, &str), ()> { // First validate the symbol. If i...
// We're the ones printing our backtraces, so we can't rely on anything else to // demangle our symbols. It's *much* nicer to look at demangled symbols, so // this function is implemented to give us nice pretty output.
random_line_split
legacy.rs
0) { return Err(()); } let mut elements = 0; let mut chars = inner.chars(); let mut c = chars.next().ok_or(())?; while c != 'E' { // Decode an identifier element's length. if !c.is_digit(10) { return Err(()); } let mut len = 0usize; while...
let digits = &escape[1..]; let all_lower_hex = digits.chars().all(|c| match c { '0'..='9' | 'a'..='f' => true, _ => false, }); ...
{ let (escape, after_escape) = if let Some(end) = rest[1..].find('$') { (&rest[1..=end], &rest[end + 2..]) } else { break; }; // see src/librustc_codegen_utils/symbol_names/legacy.rs for thes...
conditional_block
legacy.rs
11f781011E", "alloc::allocator::Layout::for_value::h02a996811f781011" ); t!("__ZN38_$LT$core..option..Option$LT$T$GT$$GT$6unwrap18_MSG_FILE_LINE_COL17haf7cb8d5824ee659E", "<core::option::Option<T>>::unwrap::_MSG_FILE_LINE_COL::haf7cb8d5824ee659"); t!("__ZN4core5slice89_$LT$impl$u20$c...
"_ZN11issu
identifier_name
legacy.rs
"test::a::bc"); } #[test] fn demangle_dollars() { t!("_ZN4$RP$E", ")"); t!("_ZN8$RF$testE", "&test"); t!("_ZN8$BP$test4foobE", "*test::foob"); t!("_ZN9$u20$test4foobE", " test::foob"); t!("_ZN35Bar$LT$$u5b$u32$u3b$$u20$4$u5d$$GT$E", "Bar<[u32; 4]>"); } #[te...
t!( "_ZN88_$LT$core..result..Result$LT$$u21$$C$$u20$E$GT$$u20$as$u20$std..process..Termination$GT$6report17hfc41d0da4a40b3e8E", "<core::result::Result<!, E> as std::process::Termination>::report::hfc41d0da4a40b3e8" ); }
identifier_body
build.rs
extern crate rustc_version; extern crate semver; use std::fs::File; use std::io::Write; use std::{env, path}; use semver::Identifier; use rustc_version::{version_meta, Channel}; fn identifier_to_source(id: &Identifier) -> String { match *id { Identifier::Numeric(ref n) => format!("semver::Identifier::Num...
(ids: &Vec<Identifier>) -> String { let mut r = "vec![".as_bytes().to_vec(); for id in ids { write!(r, "{}, ", identifier_to_source(id)).unwrap(); } write!(r, "]").unwrap(); String::from_utf8(r).unwrap() } fn main() { let mut path = path::PathBuf::from(env::var_os("OUT_DIR").unwrap()); ...
identifiers_to_source
identifier_name
build.rs
extern crate rustc_version; extern crate semver; use std::fs::File; use std::io::Write; use std::{env, path}; use semver::Identifier; use rustc_version::{version_meta, Channel}; fn identifier_to_source(id: &Identifier) -> String
fn identifiers_to_source(ids: &Vec<Identifier>) -> String { let mut r = "vec![".as_bytes().to_vec(); for id in ids { write!(r, "{}, ", identifier_to_source(id)).unwrap(); } write!(r, "]").unwrap(); String::from_utf8(r).unwrap() } fn main() { let mut path = path::PathBuf::from(env::var...
{ match *id { Identifier::Numeric(ref n) => format!("semver::Identifier::Numeric({})", n), Identifier::AlphaNumeric(ref n) => format!("semver::Identifier::AlphaNumeric({:?}.to_owned())", n), } }
identifier_body
build.rs
extern crate rustc_version; extern crate semver; use std::fs::File; use std::io::Write; use std::{env, path}; use semver::Identifier; use rustc_version::{version_meta, Channel}; fn identifier_to_source(id: &Identifier) -> String { match *id { Identifier::Numeric(ref n) => format!("semver::Identifier::Num...
}
random_line_split
serialcli.py
into a device name""" return System.IO.Ports.SerialPort.GetPortNames()[portnum] # must invoke function with byte array, make a helper to convert strings # to byte arrays sab = System.Array[System.Byte] def as_byte_array(string): return sab([ord(x) for x in string]) # XXX will require adaption when run with ...
self._isOpen = False def makeDeviceName(self, port): try: return device(port) except TypeError, e: raise SerialException(str(e)) # - - - - - - - - - - - - - - - - - - - - - - - - def inWaiting(self): """Return the number...
try: self._port_handle.Close() except System.IO.Ports.InvalidOperationException: # ignore errors. can happen for unplugged USB serial devices pass self._port_handle = None
conditional_block
serialcli.py
into a device name""" return System.IO.Ports.SerialPort.GetPortNames()[portnum] # must invoke function with byte array, make a helper to convert strings # to byte arrays sab = System.Array[System.Byte] def as_byte_array(string): return sab([ord(x) for x in string]) # XXX will require adaption when run with ...
(self, data): """Output the given string over the serial port.""" if not self._port_handle: raise portNotOpenError if not isinstance(data, (bytes, bytearray)): raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data))) try: # must call overloaded me...
write
identifier_name
serialcli.py
if the port cannot be opened.""" if self._port is None: raise SerialException("Port must be configured before it can be used.") if self._isOpen: raise SerialException("Port is already open.") try: self._port_handle = System.IO.Ports.SerialPort(self.portstr) ...
sys.stdio.write('%s\n' % s) s = Serial() sys.stdio.write('%s\n' % s)
random_line_split
serialcli.py
# must invoke function with byte array, make a helper to convert strings # to byte arrays sab = System.Array[System.Byte] def as_byte_array(string): return sab([ord(x) for x in string]) # XXX will require adaption when run with a 3.x compatible IronPython class IronSerial(SerialBase): """Serial port implem...
"""Turn a port number into a device name""" return System.IO.Ports.SerialPort.GetPortNames()[portnum]
identifier_body
vm_config.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::on_chain_config::OnChainConfig; use anyhow::{format_err, Result}; use move_core_types::gas_schedule::{CostTable, GasConstants}; use serde::{Deserialize, Serialize}; /// Defines all the on chain configuration data needed by V...
(bytes: &[u8]) -> Result<Self> { let raw_vm_config = bcs::from_bytes::<VMConfigInner>(&bytes).map_err(|e| { format_err!( "Failed first round of deserialization for VMConfigInner: {}", e ) })?; let gas_schedule = raw_vm_config.gas_schedule.a...
deserialize_into_config
identifier_name
vm_config.rs
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0 use crate::on_chain_config::OnChainConfig; use anyhow::{format_err, Result}; use move_core_types::gas_schedule::{CostTable, GasConstants}; use serde::{Deserialize, Serialize}; /// Defines all the on chain configuration data needed by VM. #[derive(Clone, Debug, Deserialize, Parti...
random_line_split
ps.rs
extern crate arg_parser; extern crate extra; use std::env; use std::fs::File; use std::io::{stdout, stderr, copy, Write}; use std::process::exit; use arg_parser::ArgParser; use extra::option::OptionalExt; const MAN_PAGE: &'static str = /* @MANSTART{ps} */ r#" NAME ps - report a snapshot of the current processes ...
{ let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "help"]); parser.parse(env::args()); if parser.found("help") { stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&...
identifier_body
ps.rs
extern crate arg_parser; extern crate extra; use std::env; use std::fs::File; use std::io::{stdout, stderr, copy, Write}; use std::process::exit; use arg_parser::ArgParser; use extra::option::OptionalExt; const MAN_PAGE: &'static str = /* @MANSTART{ps} */ r#" NAME ps - report a snapshot of the current processes ...
() { let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "help"]); parser.parse(env::args()); if parser.found("help") { stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().tr...
main
identifier_name
ps.rs
extern crate arg_parser; extern crate extra; use std::env; use std::fs::File; use std::io::{stdout, stderr, copy, Write}; use std::process::exit; use arg_parser::ArgParser; use extra::option::OptionalExt;
SYNOPSIS ps [ -h | --help] DESCRIPTION Displays information about processes and threads that are currently active OPTIONS -h --help display this help and exit "#; /* @MANEND */ fn main() { let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let m...
const MAN_PAGE: &'static str = /* @MANSTART{ps} */ r#" NAME ps - report a snapshot of the current processes
random_line_split
ps.rs
extern crate arg_parser; extern crate extra; use std::env; use std::fs::File; use std::io::{stdout, stderr, copy, Write}; use std::process::exit; use arg_parser::ArgParser; use extra::option::OptionalExt; const MAN_PAGE: &'static str = /* @MANSTART{ps} */ r#" NAME ps - report a snapshot of the current processes ...
let mut file = File::open("sys:/context").try(&mut stderr); copy(&mut file, &mut stdout).try(&mut stderr); }
{ stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&mut stderr); exit(0); }
conditional_block
text.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/. */ //! Text layout. #![deny(unsafe_block)] use fragment::{Fragment, ScannedTextFragmentInfo, UnscannedTextFragment}...
} /// Returns the metrics of the font represented by the given `FontStyle`, respectively. /// /// `#[inline]` because often the caller only needs a few fields from the font metrics. #[inline] pub fn font_metrics_for_style(font_context: &mut FontContext, font_style: Arc<FontStyle>) -> Fo...
{ // This does nothing, but it will fail to build // when more values are added to the `text-orientation` CSS property. // This will be a reminder to update the code below. let dummy: Option<text_orientation::T> = None; match dummy { Some(text_orientation::sideways_right) | Some(tex...
identifier_body
text.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/. */ //! Text layout. #![deny(unsafe_block)] use fragment::{Fragment, ScannedTextFragmentInfo, UnscannedTextFragment}...
// First, transform/compress text of all the nodes. let mut run_text = String::new(); for in_fragment in self.clump.iter() { let in_fragment = match in_fragment.specific { UnscannedTextFragment(ref text_fragment_info) => &text_fragment_info.text, ...
white_space::normal | white_space::nowrap => CompressWhitespaceNewline, white_space::pre => CompressNone, } }
random_line_split
text.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/. */ //! Text layout. #![deny(unsafe_block)] use fragment::{Fragment, ScannedTextFragmentInfo, UnscannedTextFragment}...
(metrics: &RunMetrics, writing_mode: WritingMode) -> LogicalSize<Au> { // This does nothing, but it will fail to build // when more values are added to the `text-orientation` CSS property. // This will be a reminder to update the code below. let dummy: Option<text_orient...
bounding_box_for_run_metrics
identifier_name
Jugador.ts
class
{ private _num_intentos: number; private _puntuacion: number; private _pregunta: Pregunta; private _timer: Timer; constructor () { this._num_intentos = 10; this._puntuacion = 100; this._timer = new Timer(); } get num_intentos(): number { return this._num_i...
Jugador
identifier_name
Jugador.ts
class Jugador { private _num_intentos: number; private _puntuacion: number; private _pregunta: Pregunta; private _timer: Timer; constructor () { this._num_intentos = 10; this._puntuacion = 100; this._timer = new Timer(); } get num_intentos(): number { retur...
this._timer = timer; } public mostrar_datos_jugador(): void { div_num_intentos.innerHTML = this._num_intentos + ""; div_puntuacion.innerHTML = this._puntuacion + ""; this.timer.actualizar_contador(); } public mostrar_resultados_jugador(): void { div_resultados_i...
set timer(timer: Timer) {
random_line_split
Jugador.ts
class Jugador { private _num_intentos: number; private _puntuacion: number; private _pregunta: Pregunta; private _timer: Timer; constructor () { this._num_intentos = 10; this._puntuacion = 100; this._timer = new Timer(); } get num_intentos(): number { retur...
set timer(timer: Timer) { this._timer = timer; } public mostrar_datos_jugador(): void { div_num_intentos.innerHTML = this._num_intentos + ""; div_puntuacion.innerHTML = this._puntuacion + ""; this.timer.actualizar_contador(); } public mostrar_resultados_jugador():...
{ return this._timer; }
identifier_body
Leet201_BitwiswAndRange.py
""" Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. For example, given the range [5, 7], you should return 4. Credits: Special thanks to @amrsaqr for adding this problem and creating all test cases. """ class
(object): def rangeBitwiseAnd(self, m, n): """ :type m: int :type n: int :rtype: int """ ans = 0 gap = n-m max_i = n min_i = m bits = [0 for _ in xrange(32)] for i in xrange(32): #take the i-th pos of max and min ...
Solution
identifier_name
Leet201_BitwiswAndRange.py
""" Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. For example, given the range [5, 7], you should return 4. Credits: Special thanks to @amrsaqr for adding this problem and creating all test cases. """ class Solution(object): def rangeBitwis...
return ans
ans |= each ans<<=1
conditional_block
Leet201_BitwiswAndRange.py
""" Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. For example, given the range [5, 7], you should return 4. Credits: Special thanks to @amrsaqr for adding this problem and creating all test cases. """ class Solution(object):
if gap >>i > 0: bits[i] = 0 else: bits[i] = 1 for each in bits[::-1]: ans |= each ans<<=1 return ans
def rangeBitwiseAnd(self, m, n): """ :type m: int :type n: int :rtype: int """ ans = 0 gap = n-m max_i = n min_i = m bits = [0 for _ in xrange(32)] for i in xrange(32): #take the i-th pos of max and min a = ...
identifier_body
Leet201_BitwiswAndRange.py
""" Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. For example, given the range [5, 7], you should return 4. Credits: Special thanks to @amrsaqr for adding this problem and creating all test cases. """ class Solution(object): def rangeBitwis...
gap = n-m max_i = n min_i = m bits = [0 for _ in xrange(32)] for i in xrange(32): #take the i-th pos of max and min a = max_i & 1 b = min_i & 1 max_i >>= 1 min_i >>= 1 if a == 0 or b == 0: b...
:type m: int :type n: int :rtype: int """ ans = 0
random_line_split
interval_timer.rs
//! Timer to keep track of repeating intervals. /// This struct keeps track of passage of repeated intervals (like bars of music). pub struct IntervalTimer { every: u64, next: u64, } impl IntervalTimer { #[allow(missing_docs)] pub fn new(every: u64, next: u64) -> IntervalTimer { IntervalTimer { ever...
#[inline] /// Returns the number of intervals that have elapsed since last `update`. pub fn update(&mut self, current: u64) -> u64 { if current < self.next { 0 } else { let r = 1 + (current - self.next) / self.every; self.next += self.every * r; r } } } #[test] fn simple() {...
} }
random_line_split
interval_timer.rs
//! Timer to keep track of repeating intervals. /// This struct keeps track of passage of repeated intervals (like bars of music). pub struct IntervalTimer { every: u64, next: u64, } impl IntervalTimer { #[allow(missing_docs)] pub fn
(every: u64, next: u64) -> IntervalTimer { IntervalTimer { every: every, next: next, } } #[inline] /// Returns the number of intervals that have elapsed since last `update`. pub fn update(&mut self, current: u64) -> u64 { if current < self.next { 0 } else { let r = 1 + (...
new
identifier_name
interval_timer.rs
//! Timer to keep track of repeating intervals. /// This struct keeps track of passage of repeated intervals (like bars of music). pub struct IntervalTimer { every: u64, next: u64, } impl IntervalTimer { #[allow(missing_docs)] pub fn new(every: u64, next: u64) -> IntervalTimer { IntervalTimer { ever...
else { let r = 1 + (current - self.next) / self.every; self.next += self.every * r; r } } } #[test] fn simple() { let mut timer = IntervalTimer::new(3, 3); let mut time = 2; assert_eq!(timer.update(time), 0); time += 2; assert_eq!(timer.update(time), 1); time += 2; assert_eq!(tim...
{ 0 }
conditional_block
issue-2111.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
match (a,b) { //~^ ERROR: non-exhaustive patterns: `(None, None)` not covered (Some(a), Some(b)) if a == b => { } (Some(_), None) | (None, Some(_)) => { } } } fn main() { foo(None, None); }
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn foo(a: Option<uint>, b: Option<uint>) {
random_line_split
issue-2111.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { foo(None, None); }
main
identifier_name
issue-2111.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ foo(None, None); }
identifier_body
DeleteModal.test.js
/* * Copyright 2020 Verizon Media * * 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 *
* limitations under the License. */ import React from 'react'; import { render } from '@testing-library/react'; import DeleteModal from '../../../components/modal/DeleteModal'; describe('DeleteModal', () => { it('should render', () => { const isOpen = true; const cancel = function() {}; c...
* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and
random_line_split
omwllf.py
(filename): fh = open(filename, 'rb') while True: headerba = fh.read(16) if headerba is None or len(headerba) < 16: return None record = {} header = readHeader(headerba) record['type'] = header['type'] record['length'] = header['length'] recor...
readRecords
identifier_name
omwllf.py
return start_bs + reclen_bs + headerflags_bs + \ name_bs + calcfrom_bs + chance_bs + subrec_bs def packTES3(desc, numrecs, masters): start_bs = b'TES3' headerflags_bs = bytes(8) hedr_bs = b'HEDR' + packLong(300) version_bs = pack('<f', 1.0) # .esp == 0, .esm == 1, .ess == 32 # supris...
p = Path(outmoddir) p.mkdir(parents=True)
conditional_block
omwllf.py
type'] == 'LEVC': start_bs += b'LEVC' id_bs = 'CNAM' else: start_bs += b'LEVI' id_bs = 'INAM' headerflags_bs = bytes(8) name_bs = packStringSubRecord('NAME', rec['name']) calcfrom_bs = packIntSubRecord('DATA', rec['calcfrom']) chance_bs = packIntSubRecord('NNAM', rec...
# creature lists clist = [ parseLEV(x) for x in rlevc ] levc = mergeAllLists(clist)
random_line_split
omwllf.py
ofbytes yield record def oldGetRecords(filename, rectype): return ( r for r in readRecords(filename) if r['type'] == rectype ) def getRecords(filename, rectypes): numtypes = len(rectypes) retval = [ [] for x in range(numtypes) ] for r in readRecords(filename): if r['type'] in rectypes...
data_dirs = [] mods = [] with open(cfg, 'r') as f: for l in f.readlines(): # match of form "blah=blahblah" m = re.search(r'^(.*)=(.*)$', l) if m: varname = m.group(1).strip() # get rid of not only whitespace, but also surrounding quotes...
identifier_body
aria-reference.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** IDs are deliminated by an empty space, as per the spec. */ const ID_DELIMINATOR = ' '; /** * Adds the given ID ...
const filteredIds = ids.filter(val => val != id.trim()); el.setAttribute(attr, filteredIds.join(ID_DELIMINATOR)); } /** * Gets the list of IDs referenced by the given ARIA attribute on an element. * Used for attributes such as aria-labelledby, aria-owns, etc. */ export function getAriaReferenceIds(el: Element,...
* Removes the given ID from the specified ARIA attribute on an element. * Used for attributes such as aria-labelledby, aria-owns, etc. */ export function removeAriaReferencedId(el: Element, attr: string, id: string) { const ids = getAriaReferenceIds(el, attr);
random_line_split
aria-reference.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** IDs are deliminated by an empty space, as per the spec. */ const ID_DELIMINATOR = ' '; /** * Adds the given ID ...
(el: Element, attr: string, id: string) { const ids = getAriaReferenceIds(el, attr); if (ids.some(existingId => existingId.trim() == id.trim())) { return; } ids.push(id.trim()); el.setAttribute(attr, ids.join(ID_DELIMINATOR)); } /** * Removes the given ID from the specified ARIA attribute on an element. * U...
addAriaReferencedId
identifier_name
aria-reference.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** IDs are deliminated by an empty space, as per the spec. */ const ID_DELIMINATOR = ' '; /** * Adds the given ID ...
/** * Removes the given ID from the specified ARIA attribute on an element. * Used for attributes such as aria-labelledby, aria-owns, etc. */ export function removeAriaReferencedId(el: Element, attr: string, id: string) { const ids = getAriaReferenceIds(el, attr); const filteredIds = ids.filter(val => val != i...
{ const ids = getAriaReferenceIds(el, attr); if (ids.some(existingId => existingId.trim() == id.trim())) { return; } ids.push(id.trim()); el.setAttribute(attr, ids.join(ID_DELIMINATOR)); }
identifier_body
aria-reference.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** IDs are deliminated by an empty space, as per the spec. */ const ID_DELIMINATOR = ' '; /** * Adds the given ID ...
ids.push(id.trim()); el.setAttribute(attr, ids.join(ID_DELIMINATOR)); } /** * Removes the given ID from the specified ARIA attribute on an element. * Used for attributes such as aria-labelledby, aria-owns, etc. */ export function removeAriaReferencedId(el: Element, attr: string, id: string) { const ids = ge...
{ return; }
conditional_block
barb_demo.py
from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt # read in data. file = open('fcover.dat','r') ul=[];vl=[];pl=[] nlons=73; nlats=73 dellat = 2.5; dellon = 5. for line in file.readlines():
u = np.reshape(np.array(ul,np.float32),(nlats,nlons)) v = np.reshape(np.array(vl,np.float32),(nlats,nlons)) p = np.reshape(np.array(pl,np.float32),(nlats,nlons)) lats1 = -90.+dellat*np.arange(nlats) lons1 = -180.+dellon*np.arange(nlons) lons, lats = np.meshgrid(lons1, lats1) # convert from mps to knots. u = 1.944*u; v...
l = line.replace('\n','').split() ul.append(float(l[0])) vl.append(float(l[1])) pl.append(float(l[2]))
conditional_block