code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def deliver_all_runfolders_for_project(self, project_name, mode): <NEW_LINE> <INDENT> projects = list(self.runfolder_service.find_runfolders_for_project(project_name)) <NEW_LINE> if len(projects) < 1: <NEW_LINE> <INDENT> raise ProjectNotFoundException("Could not find any Project " "folders for project name: {}".format(... | This method will attempt to deliver all runfolders for the specified project.
Since the process is somewhat involved, here's a explanation of what's going on and why.
First, there are three modes of delivery which needs to be handled. CLEAN, which denotes
that this project is not allowed to be delivered previously. B... | 625941e2009cb60464c6376a |
def __del__(self): <NEW_LINE> <INDENT> print('Done Printing') | (Plotter) -> stdout
Called when the client no longer uses the plotter object.
The interpreter calls this method, also known as destructor,
when the object is no longer bound to a reference with in the
executing program.
Among other times, this happens when the program’s execution
terminates. | 625941e2f7d966606f6aa3c4 |
def test_npm_install_with_unexpected_subprocess_error(self): <NEW_LINE> <INDENT> with patch('subprocess.Popen') as _mock_popen: <NEW_LINE> <INDENT> _mock_popen.side_effect = unexpected_fail_on_npm_install <NEW_LINE> with self.assertRaises(BuildFailure): <NEW_LINE> <INDENT> pavelib.prereqs.node_prereqs_installation() <N... | If there's some other error, only call npm install once, and raise a failure | 625941e216aa5153ce362833 |
def srandmember(self, key): <NEW_LINE> <INDENT> return self.execute_command("SRANDMEMBER", key) | Return a random member of the Set value at key | 625941e25fdd1c0f98dc05f0 |
def clean_extra_data(self): <NEW_LINE> <INDENT> extra_data = self.cleaned_data['extra_data'] or {} <NEW_LINE> if not isinstance(extra_data, dict): <NEW_LINE> <INDENT> raise ValidationError(ugettext( 'This must be a JSON object/dictionary.')) <NEW_LINE> <DEDENT> return extra_data | Clean the extra_data field.
This will ensure that the field is always a dictionary.
Returns:
dict:
The extra_data dictionary.
Raises:
django.core.exceptions.ValidationError:
The value was not a dictionary. | 625941e297e22403b379d356 |
def p_basic_statement(self, p): <NEW_LINE> <INDENT> p[0] = p[1] <NEW_LINE> p.set_lineno(0, p.lineno(1)) | basic_statement : if_statement
| case_statement
| casex_statement
| for_statement
| while_statement
| event_statement
| wait_statement
| forever_statement
| block
| namedblock
| parallelblock
| blocking_substitution
| nonblocking_substitution
| single_statement | 625941e201c39578d7e751f6 |
def test_update_auto_order(self): <NEW_LINE> <INDENT> pass | Test case for update_auto_order
Update an auto order | 625941e263d6d428bbe448ab |
def __setitem__(self,ndxTuple, life): <NEW_LINE> <INDENT> row = ndxTuple[0] <NEW_LINE> col = ndxTuple[1] <NEW_LINE> if life == True and self.isLiveCell(row,col)==False: <NEW_LINE> <INDENT> test = GoLMatrixElement(row,col) <NEW_LINE> self._cells.append(test) <NEW_LINE> <DEDENT> elif life == False and self.isLiveCell(row... | The possible values are only true or false:
True says alive, False for dead.
Also, check to see if this cell is outside of the maximum row and/or
column. If it is, modify the maximum row and/or maximum column. | 625941e2d8ef3951e32438f9 |
def load_plugin(self, plugin_name): <NEW_LINE> <INDENT> LOG.debug("loading application plugin '%s'" % plugin_name) <NEW_LINE> for load_dir in self.load_dirs: <NEW_LINE> <INDENT> load_dir = abspath(load_dir) <NEW_LINE> if self._load_plugin_from_dir(plugin_name, load_dir): <NEW_LINE> <INDENT> self._loaded_plugins.append(... | Load a plugin whose name is 'plugin_name'. First attempt to load
from a plugin directory (plugin_dir), secondly attempt to load from a
bootstrap module (plugin_bootstrap) determined by
self.app._meta.plugin_bootstrap.
Upon successful loading of a plugin, the plugin name is appended to
the self._loaded_plugins list.
... | 625941e238b623060ff0b1a8 |
def get_model(self): <NEW_LINE> <INDENT> pessimistic = 1.00 <NEW_LINE> max_accuracy = -inf <NEW_LINE> tuning_epoch = 10 <NEW_LINE> step_size = 0.01 <NEW_LINE> for i in range(self.k): <NEW_LINE> <INDENT> print('Tuning model #%d of %d ...' % (i + 1, tuning_epoch)) <NEW_LINE> accuracy = 0 <NEW_LINE> for train, validation ... | Get a tuned decision tree model
:return: DecisionTree | 625941e20c0af96317bb85a3 |
def test_uploading(self): <NEW_LINE> <INDENT> test_site = Site.objects.all()[0] <NEW_LINE> test_site_ct = ContentType.objects.get_for_model(test_site) <NEW_LINE> test_site_id = test_site.id <NEW_LINE> self.assertEqual( Image.objects.all().count(), 0 ) <NEW_LINE> first = Image( content_type = test_site_ct, object_id ... | Test that uploading an image works | 625941e231939e2706e4d21f |
def OnBackgroundImageLayoutChanged(self, *args): <NEW_LINE> <INDENT> pass | OnBackgroundImageLayoutChanged(self: Form, e: EventArgs)
Raises the System.Windows.Forms.Control.BackgroundImageLayoutChanged event.
e: An System.EventArgs that contains the event data. | 625941e26fb2d068a760f45e |
def modify_effect(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.modify_effect_with_http_info(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.modify_effect_with_http_info(**kwargs) <NEW_LINE> return... | Stop effect
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.modify_effect(callback=callback_function)
:param ... | 625941e21b99ca400220ae6e |
def p_expression_div(t): <NEW_LINE> <INDENT> t[0] = t[3] // t[5] | expression : INT_TYPE DIV term ',' term | 625941e29f2886367277ac46 |
def get_order_history_for_a_user(self, user_id): <NEW_LINE> <INDENT> query = "SELECT orderid,meal_name,quantity,status,order_date FROM orders WHERE user_id='{}'".format( user_id) <NEW_LINE> self.real_dic_cursor(query) <NEW_LINE> user_orders = self.cur.fetchall() <NEW_LINE> if user_orders: <NEW_LINE> <INDENT> return {'o... | Get order history of a specific user | 625941e2be8e80087fb20ff8 |
def update_editor ( self ): <NEW_LINE> <INDENT> value = self.value <NEW_LINE> for image_control in self.image_controls: <NEW_LINE> <INDENT> image_control.selected = (value == image_control._value) | Updates the editor when the object facet changes externally to the
editor. | 625941e230c21e258bdfa85b |
def check_time(self): <NEW_LINE> <INDENT> if self.type != "timer": <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> current = time.localtime() <NEW_LINE> current = current.tm_hour * 60 + current.tm_min <NEW_LINE> if self.time_off >= self.time_on: <NEW_LINE> <INDENT> if current in range(self.time_on, self.time_off): <NE... | проверка времени. Если исполнитель в это время должен быть выключен,
возвращает 0, если включен - FF | 625941e24d74a7450ccd457f |
def find_nearest(pt, pts): <NEW_LINE> <INDENT> idx = (np.linalg.norm(pts - pt, axis=1)).argmin() <NEW_LINE> return pts[idx], idx | Find points in pts that's nearest to pt (return first closest)
Args:
pt: 1xN np.array as point to be searched against
pts: MxN np.array as list of points to be searched against
Returns:
The row index of the nearest point, as well as the coordinates of the
nearest point. | 625941e29c8ee82313fbbb31 |
def init_libvirt_state(self): <NEW_LINE> <INDENT> if self.__initialized: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> initialize_failed = False <NEW_LINE> try: <NEW_LINE> <INDENT> if self.config.CLITestOptions.object_blacklist == self._name: <NEW_LINE> <INDENT> raise RuntimeError("fake initialization error") <NEW_LIN... | Function called by vmmConnection to populate initial state when
a new object appears. | 625941e2379a373c97cfaf02 |
def __init__(self, file_route, file_cpu, file_mem, file_disk, num_target): <NEW_LINE> <INDENT> global train_index, test_index <NEW_LINE> self.file_route = file_route <NEW_LINE> self.cpu = file_cpu <NEW_LINE> self.mem = file_mem <NEW_LINE> self.disk = file_disk <NEW_LINE> sample_cpu = open(self.file_route + "\\" + self.... | 初始化一些参数
:param file_route:文件的路径
:param num_target: target的数量 | 625941e23539df3088e2e706 |
def __init__(self, config, reactor): <NEW_LINE> <INDENT> super(ClientCollector, self).__init__() <NEW_LINE> self._config = config <NEW_LINE> self._queue = [] <NEW_LINE> self._reactor = reactor <NEW_LINE> self._closing = False <NEW_LINE> self._closing_done = False <NEW_LINE> reactor.callInThread(self._queue_monitor, ran... | Creates an instance of the collector. Expects the JSON config,
an implementation of the CollectorMessage interface, and the
reactor of Twisted.
:param config: The JSON config for the collector.
:type config: dict[str]
:param reactor: Instance of the Twisted reactor
:type reactor: twisted.internet.interfaces.IReactorIn... | 625941e2ff9c53063f47c5ad |
def loss(self, input, target, mask=None): <NEW_LINE> <INDENT> batch, length, _ = input.size() <NEW_LINE> energy = self(input, mask=mask) <NEW_LINE> energy_transpose = energy.transpose(0, 1) <NEW_LINE> target_transpose = target.transpose(0, 1) <NEW_LINE> mask_transpose = None <NEW_LINE> if mask is not None: <NEW_LINE> <... | Args:
input: Tensor
the input tensor with shape = [batch, length, model_dim]
target: Tensor
the tensor of target labels with shape [batch, length]
mask:Tensor or None
the mask tensor with shape = [batch, length]
Returns: Tensor
A 1D tensor for minus log likelihood loss [batc... | 625941e2e1aae11d1e74a076 |
def new_game(self): <NEW_LINE> <INDENT> self.canvas.delete(ALL) <NEW_LINE> if self.current_message_label != None: <NEW_LINE> <INDENT> self.current_message_label.destroy() <NEW_LINE> <DEDENT> self.small_boards = [] <NEW_LINE> for card in self.cards_on_canvas: <NEW_LINE> <INDENT> card.position = None <NEW_LINE> card.corn... | # Begin an entirely new game | 625941e2be8e80087fb20ff9 |
def test_two_token1(self): <NEW_LINE> <INDENT> c = Comparitor(' ( ( a) & (b)) ') <NEW_LINE> self.assertEqual('False: (a & b)', str(c)) <NEW_LINE> self.assertFalse(c.check([])) <NEW_LINE> self.assertFalse(c.check(['b'])) <NEW_LINE> self.assertEqual('False: (a & b+)', str(c)) <NEW_LINE> self.assertFalse(c.check(... | Test that a two tokens and works | 625941e257b8e32f52483859 |
def make_payout(self, customer, group, amount_cents): <NEW_LINE> <INDENT> return uuid_factory('PODUMMY')() | Returns a transaction identifier or raises error. | 625941e2167d2b6e31218f51 |
def test_create_token_invalid_credentials(self): <NEW_LINE> <INDENT> create_user( email='user@test.com', password='qwerty' ) <NEW_LINE> payload = { 'email': 'user@test.com', 'password': 'asdfgh' } <NEW_LINE> res = self.client.post(TOKEN_URL, payload) <NEW_LINE> self.assertNotIn('token', res.data) <NEW_LINE> self.assert... | Test that token is not created if invalid credentials are given. | 625941e20383005118ecf99d |
def __getattr__(self, axis): <NEW_LINE> <INDENT> if not axis in self.getAxesNames() and (axis != 'val' and axis != 'weight'): <NEW_LINE> <INDENT> logging.error('Axis \"'+axis+'\" not found.') <NEW_LINE> <DEDENT> if axis == 'val': <NEW_LINE> <INDENT> return self.getValues(retAxesVals=False) <NEW_LINE> <DEDENT> elif axis... | links any attribute with an "axis name" to getValuesAxis("axis name")
also links val and weight to the relative arrays
Keyword arguments:
axis -- the axis name | 625941e2d268445f265b522a |
def bind_extended_member(node, chain, pair, scope_key): <NEW_LINE> <INDENT> seen = [] <NEW_LINE> target_node = node <NEW_LINE> for name in chain[:-1]: <NEW_LINE> <INDENT> seen.append(name) <NEW_LINE> alias = getattr(target_node.klass, name, None) <NEW_LINE> if not isinstance(alias, Alias): <NEW_LINE> <INDENT> raise Typ... | Bind a handler pair to an extended member.
Parameters
----------
node : DeclarativeNode
The compiler node holding the declarative class.
chain : tuple
A tuple of names for the extended binding.
pair : HandlerPair
The handler pair to add to the expression engine.
scope_key : object
The closure scope ... | 625941e2baa26c4b54cb14d8 |
def display_reset(): <NEW_LINE> <INDENT> renpy.display.interface.display_reset = True | Used internally. Causes the display to be restarted at the start of
the next interaction. | 625941e230c21e258bdfa85c |
def refresh_cache(self, force): <NEW_LINE> <INDENT> self.error(ERROR_NOT_SUPPORTED, "This function is not implemented in this backend", exit=False) | Implement the {backend}-refresh_cache functionality
Needed to be implemented in a sub class | 625941e2de87d2750b860152 |
def __init__(self, timeout): <NEW_LINE> <INDENT> self._timeout = timeout <NEW_LINE> self._started = False <NEW_LINE> self._start = 0.0 <NEW_LINE> self._end = 0.0 | Timer Constructor.
:param timeout: the number of seconds before a timeout. | 625941e256ac1b37e6264584 |
def getMessages(self): <NEW_LINE> <INDENT> return self.messages | Return any messages generated while loading us | 625941e256ac1b37e6264585 |
def theme_menu(): <NEW_LINE> <INDENT> print('Please enter the number of the theme you want.') <NEW_LINE> themes = madlibs.get_madlibs_folders('libs') <NEW_LINE> counter = 1 <NEW_LINE> for theme in themes: <NEW_LINE> <INDENT> print( '{0}) {1}'.format(counter, theme[theme.rfind('\\')+1:])) <NEW_LINE> counter += 1 <NEW_LI... | (none) -> NoneType
Preconditions: none
Displays a list of themes for the user to choose from. | 625941e2d99f1b3c44c67944 |
def populate_model(self, delta_ifc_key, delta_ifc_cfg_value): <NEW_LINE> <INDENT> DMObject.populate_model(self, delta_ifc_key, delta_ifc_cfg_value) <NEW_LINE> 'Let DNSServer share the configuration with this translator' <NEW_LINE> dns_server = self.children.values()[1] <NEW_LINE> dns_server.populate_model(delta_ifc_key... | Override the default implementation because the IFC model does not directly map to self.children of DNSServer | 625941e266673b3332b9244d |
def parse_args(): <NEW_LINE> <INDENT> p = argparse.ArgumentParser(description=__doc__) <NEW_LINE> p.add_argument('--verbose', '-v', action='count', help='be more verbose') <NEW_LINE> p.add_argument('--thresholds', '-t', nargs=2, type=float, default=(0.5, 0.1), help='thresholds for labeling as prostate, lesion') <NEW_LI... | Parse command-line arguments. | 625941e2460517430c394537 |
def _prepare_link_upload(filenames: List[str], display_name: str, message: str, session: requests.Session) -> str: <NEW_LINE> <INDENT> j = { "files": [_file_name_and_size(f) for f in filenames], "display_name": display_name, "message": message, "ui_language": "en", } <NEW_LINE> r = session.post(WETRANSFER_UPLOAD_LINK_U... | Given a list of filenames and a message prepare for the link upload.
Return the parsed JSON response. | 625941e2460517430c394538 |
def __del__(self): <NEW_LINE> <INDENT> self.terminate() | Delete thread. | 625941e2d99f1b3c44c67945 |
def assert_schema_exists( self, database: Any, caplog: LogCaptureFixture ) -> None: <NEW_LINE> <INDENT> assert True | Make sure that the repository has a valid schema. | 625941e2442bda511e8be7cf |
def get_current_card(source): <NEW_LINE> <INDENT> pcm_name = get_config().get(source) <NEW_LINE> if pcm_name == 'null': <NEW_LINE> <INDENT> logger.debug('No input selected') <NEW_LINE> return None, None <NEW_LINE> <DEDENT> cards = get_cards() <NEW_LINE> if len(cards) == 0: <NEW_LINE> <INDENT> logger.error('Could not fi... | Get a tuple describing the current card selection based on config.
Parameters
----------
source : string
one of 'pcm_input' or 'pcm_output'
Returns
-------
A tuple of (d, card) with d being the index in the list of options
from get_cards. | 625941e2236d856c2ad44b9b |
def get_default_config() -> Optional[PyrrigateConf]: <NEW_LINE> <INDENT> return get_first_config(DEFAULT_CONFIG_PATHS) | Loads the first existing configuration from the default list of possible paths.
Returns:
A PyrrigateConfig object at least one file was found, None otherwise. | 625941e2e8904600ed9f22ee |
@cart_product.route('/<int:id>', methods=['GET', 'POST']) <NEW_LINE> @login_required <NEW_LINE> def detail(id): <NEW_LINE> <INDENT> resp = TbBuy(current_app).get_json('/cart_products/{}'.format(id)) <NEW_LINE> cart_product = resp['data']['cart_product'] <NEW_LINE> resp = TbMall(current_app).get_json( '/products/{}'.for... | 购物车商品详情
| 625941e2d10714528d6000a3 |
def int_or_none(s): <NEW_LINE> <INDENT> if s: <NEW_LINE> <INDENT> return int(s) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return s | Если не нуль то преобразовать в целое число | 625941e215fb5d323cde0ed1 |
def __init__(self, world, ego_vehicles, config, randomize=False, debug_mode=False, criteria_enable=True, obstacle_type='barrier', timeout=120): <NEW_LINE> <INDENT> self._world = world <NEW_LINE> self._map = CarlaDataProvider.get_map() <NEW_LINE> self._first_vehicle_location = 50 <NEW_LINE> self._second_vehicle_location... | Setup all relevant parameters and create scenario
obstacle_type -> flag to select type of leading obstacle. Values: vehicle, barrier | 625941e2507cdc57c630709f |
def solucaoEspacoPontoX(arq,t,x): <NEW_LINE> <INDENT> parametros = open(arq,'r') <NEW_LINE> lista = [] <NEW_LINE> for linha in parametros: <NEW_LINE> <INDENT> valores = linha.split() <NEW_LINE> lista.append( valores[1] ) <NEW_LINE> <DEDENT> Ks = float(lista[0]) <NEW_LINE> Kl = float(lista[1]) <NEW_LINE> Tf = floa... | Retorna a tempetura em um instante de tempo t no ponto x | 625941e2cdde0d52a9e533f2 |
def initialise(): <NEW_LINE> <INDENT> T_r_0 = [-4.088407843090480E-03 *AU, -6.135746299499617E-03 *AU, 3.570710328903993E-03 *AU] <NEW_LINE> H_r_0 = [-9.556008109223760E-03 *AU, -6.330869216667536E-04 *AU, 1.293277241526503E-03 *AU] <NEW_LINE> T_v_0 = [2.811008677848850E-03 *AU, -1.470816650319267E-03 *AU, 4.8067292680... | Return a vector of initial values to use with the simulation | 625941e2aad79263cf390e03 |
def _find_cuda_incl_path() -> pathlib.Path: <NEW_LINE> <INDENT> cuda_path = os.getenv("CUDA_PATH") <NEW_LINE> if not cuda_path: <NEW_LINE> <INDENT> if sys.platform == 'linux': <NEW_LINE> <INDENT> cuda_path = pathlib.Path("/usr/local/cuda/include") <NEW_LINE> if not (cuda_path.exists() and cuda_path.is_dir()): <NEW_LINE... | Tries to find the CUDA include path. | 625941e207f4c71912b11841 |
def prepare_mysql_pipe(self, data_list, logger, host='', port=3306, user='', pwd='', schema=''): <NEW_LINE> <INDENT> logger.info('Connecting to database...') <NEW_LINE> self.pipe = MysqlPipeFactory(logger=logger, host=host, port=port, user=user, pwd=pwd, schema=schema) <NEW_LINE> for data in data_list: <NEW_LINE> <INDE... | Prepare MySQL pipe
:param data_list: Data list
:param logger: Logger
:param host: Host
:param port: Port, defaulted as 3306
:param user: User names
:param pwd: Password
:param schema: Schema | 625941e299cbb53fe6792fa2 |
def biggest(aDict): <NEW_LINE> <INDENT> highest = 0 <NEW_LINE> for key in aDict: <NEW_LINE> <INDENT> listLength = len (aDict [key]) <NEW_LINE> if listLength >= highest: <NEW_LINE> <INDENT> highest = listLength <NEW_LINE> largestSoFar = key <NEW_LINE> <DEDENT> <DEDENT> return largestSoFar | aDict: A dictionary, where all the values are lists.
returns: The key with the largest number of values associated with it | 625941e2627d3e7fe0d6920e |
def test_createMaximal(self): <NEW_LINE> <INDENT> datum = GAME_DATA[2] <NEW_LINE> datum['user'] = self.laura <NEW_LINE> game = Game(**datum) <NEW_LINE> self.failUnlessEqual(game.max_difficulty, 7) | Test game creation with all possible data
| 625941e2ac7a0e7691ed4482 |
def stop(): <NEW_LINE> <INDENT> global _t <NEW_LINE> if _t is not None: <NEW_LINE> <INDENT> _t.stop() | Stop tracing code coverage. | 625941e2cb5e8a47e48b7e61 |
def averageOfLevels(self, root): <NEW_LINE> <INDENT> pass | :type root: TreeNode
:rtype: List[float] | 625941e2ff9c53063f47c5ae |
def mixup_data(x, y, alpha=1.0, use_cuda=True): <NEW_LINE> <INDENT> if alpha > 0: <NEW_LINE> <INDENT> lam = np.random.beta(alpha, alpha) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lam = 1 <NEW_LINE> <DEDENT> batch_size = x.size()[0] <NEW_LINE> if use_cuda: <NEW_LINE> <INDENT> index = torch.randperm(batch_size).cuda(... | Returns mixed inputs, pairs of targets, and lambda. | 625941e2f8510a7c17cf9abb |
def xeq(x0, x1, places=15): <NEW_LINE> <INDENT> scale = max(abs(x0), abs(x1)) <NEW_LINE> epsilon = scale * 10 ** -places <NEW_LINE> return abs(x0 - x1) < epsilon | Returns true iff `x0` and `x1` are within decimal `places` of each other. | 625941e256b00c62f0f14a18 |
def test_get_subscription_owner(profile_list_entry_factory): <NEW_LINE> <INDENT> view = views.ListEntryDetailView() <NEW_LINE> request = mock.Mock(name="Mock Request") <NEW_LINE> entry = profile_list_entry_factory() <NEW_LINE> expected = entry.profile_item.topic.profile.km_user.user <NEW_LINE> assert view.get_subscript... | The subscription owner should be the user who owns the profile that
the list entry is contained in. | 625941e23346ee7daa2b312a |
def export_to_csv(self, outputfilepath, separator): <NEW_LINE> <INDENT> con = fdb.connect( database=self.db_filepath, user='sysdba', password='masterkey' ) <NEW_LINE> cur = con.cursor() <NEW_LINE> statement = "select * from FILES" <NEW_LINE> cur.execute(statement) <NEW_LINE> print(cur.fetchall()) <NEW_LINE> with open(o... | export the ENTIRE DB to a CSV formatted file | 625941e2d7e4931a7ee9e2db |
def is_valid(self, request, product=None): <NEW_LINE> <INDENT> if product is not None: <NEW_LINE> <INDENT> max_length = product.get_length() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> from lfs.cart import utils as cart_utils <NEW_LINE> cart = cart_utils.get_cart(request) <NEW_LINE> if cart is None: <NEW_LINE> <INDEN... | Returns True if the criterion is valid.
If product is given the length is taken from the product otherwise from
the cart. | 625941e28e7ae83300e4b38a |
def create_copy(self): <NEW_LINE> <INDENT> self.capsule_ensure() <NEW_LINE> t = Sky() <NEW_LINE> t.capsule = _sky_lib.create_copy(self._capsule) <NEW_LINE> return t | Creates a copy of the sky model. | 625941e250485f2cf553d157 |
def cluster_get(self, name, **kwargs): <NEW_LINE> <INDENT> path = '/api/v0/cluster/{0}'.format(name) <NEW_LINE> return self._get(path) | Attempts to get cluster information.
:param name: The name of the cluster
:type name: str
:param kwargs: Any other keyword arguments
:type kwargs: dict | 625941e221bff66bcd684d0b |
def download_installer(self, url, last_modified): <NEW_LINE> <INDENT> exe = None <NEW_LINE> modified = None <NEW_LINE> headers = None <NEW_LINE> if last_modified is not None: <NEW_LINE> <INDENT> headers = {'If-Modified-Since': last_modified} <NEW_LINE> <DEDENT> dest = os.path.join(self.dir, 'browser_install.exe') <NEW_... | Download the given installer if it is newer | 625941e2c432627299f05005 |
def prepend(self, data): <NEW_LINE> <INDENT> new_head = ListNode(data) <NEW_LINE> new_head.next = self.head <NEW_LINE> self.head = new_head | add single node at the beginning of list takes O(1) time
:param data: | 625941e25fc7496912cc3d3a |
def handler500(request): <NEW_LINE> <INDENT> logger.error('handler500: Server error') <NEW_LINE> as_string = '\n'.join(traceback.format_exception(*sys.exc_info())) <NEW_LINE> logger.error(as_string) <NEW_LINE> try: <NEW_LINE> <INDENT> request_repr = repr(request) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> request_... | Custom error handling.
Catches errors that are not handled elsewhere.
NB: This only gets used by Django if omero.web.debug False (production use)
If debug is True, Django returns it's own debug error page | 625941e2b830903b967e9cc3 |
def get_config(): <NEW_LINE> <INDENT> cfg = VersioneerConfig() <NEW_LINE> cfg.VCS = "git" <NEW_LINE> cfg.style = "pep440" <NEW_LINE> cfg.tag_prefix = "" <NEW_LINE> cfg.parentdir_prefix = "umami-" <NEW_LINE> cfg.versionfile_source = "umami/_version.py" <NEW_LINE> cfg.verbose = False <NEW_LINE> return cfg | Create, populate and return the VersioneerConfig() object. | 625941e2711fe17d8254271f |
def findRestaurant(self, list1, list2): <NEW_LINE> <INDENT> length1=len(list1) <NEW_LINE> length2=len(list2) <NEW_LINE> countDict={} <NEW_LINE> for i in xrange(length1): <NEW_LINE> <INDENT> for j in xrange(length2): <NEW_LINE> <INDENT> if list1[i]==list2[j]: <NEW_LINE> <INDENT> countDict[list1[i]]=i+j <NEW_LINE> <DEDEN... | :type list1: List[str]
:type list2: List[str]
:rtype: List[str] | 625941e250812a4eaa59c6da |
def load(path): <NEW_LINE> <INDENT> with open(path, "r") as f: <NEW_LINE> <INDENT> text = f.read() <NEW_LINE> obj = json.loads(text) <NEW_LINE> start = _parse_matrix(obj["start"]) <NEW_LINE> end = _parse_matrix(obj["end"]) <NEW_LINE> errors = validate_matrix(start, "start") + validate_matrix(end, "end") <NEW_LINE> retu... | Load a configuration from a file.
parameters:
[string] path -- The file location.
return:
[tuple] A (M1, M2) tuple containing the start and end matrix. | 625941e21f037a2d8b9465b9 |
def handle_prepare(self): <NEW_LINE> <INDENT> log.debug('prepare') <NEW_LINE> try: <NEW_LINE> <INDENT> for op in self.transaction: <NEW_LINE> <INDENT> op.prepare() <NEW_LINE> <DEDENT> result = Constants.RESP_OK <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> result = Constants.RESP_ERROR <NEW_LINE> <DEDENT> result = st... | Handles a ``prepare`` operation. See :ref:`narrative documentation
<netfs_protocol_prepare>` for details. | 625941e29f2886367277ac47 |
def testTwoTouchingCircles(self): <NEW_LINE> <INDENT> delta_x = 2.0 <NEW_LINE> adsorbed_x = array([5.0, 5.0]) <NEW_LINE> adsorbed_y = array([2.0, self.width-2.0]) <NEW_LINE> arrangement = surface.surface_arrangement() <NEW_LINE> arrangement.set_particles(adsorbed_x, adsorbed_y, self.effective_radius, self.width, self.w... | Two touching circles at the y periodic BC | 625941e2d164cc617578310b |
def _create_profile(self): <NEW_LINE> <INDENT> iY, iX = np.mgrid[self.sy, self.sx] <NEW_LINE> self.distances = np.sqrt( (iX - self.x) ** 2. + (iY - self.y) ** 2. ).flatten() <NEW_LINE> self.values = self.cutout.flatten() | Compute distances to pixels in cutout | 625941e291af0d3eaac9bdd8 |
@register.filter <NEW_LINE> def nice_username(user): <NEW_LINE> <INDENT> name = user.get_full_name() <NEW_LINE> if not name: <NEW_LINE> <INDENT> name = user.username <NEW_LINE> <DEDENT> return name | Return 'full_name' or if it doesn`t exist - 'username' | 625941e282261d6c526ab861 |
def dumps(self): <NEW_LINE> <INDENT> return cPickle.dumps(self.info) | 压缩
| 625941e2596a897236089e78 |
def onAccept(self): <NEW_LINE> <INDENT> s = QSettings() <NEW_LINE> s.setValue("quickexport/exportHiddenAttributes", self.cbExportHiddenAttributes.isChecked()) <NEW_LINE> delimiterRadioButtons = self.gbDelimiter.findChildren(QtWidgets.QRadioButton) <NEW_LINE> csvDelimiter = s.value("quickexport/csvDelimiter", 0, type=in... | Save options into QSettings when pressing OK button | 625941e28da39b475bd65334 |
def grab_parkingspace(request): <NEW_LINE> <INDENT> if request.is_ajax(): <NEW_LINE> <INDENT> if request.POST['booking_id']: <NEW_LINE> <INDENT> item = Booking.objects.filter(id=int(request.POST['booking_id'])).get() <NEW_LINE> if item.space.owner == request.user and item.taken == False: <NEW_LINE> <INDENT> item.delete... | IF chosen booking is your own, Deletes your booking, making space bookable.
Else Books parking space for you. | 625941e285dfad0860c3b218 |
def process_metadata(data: dict) -> OrderedDict: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return OrderedDict( isic_id=data["_id"], image_name=data["name"], dataset=data["dataset"]["name"], description=data["dataset"]["description"], accepted=data["notes"]["reviewed"]["accepted"], created=data["created"].split("T")[... | Processes the raw metadata of the API response into a CSV friendly format.
:return: A dictionary with all relative information on the image. | 625941e2a934411ee3751a51 |
def reserved_move(self, player, coord): <NEW_LINE> <INDENT> x, y = coord[0], coord[1] <NEW_LINE> tile = self._matrix[x][y] <NEW_LINE> if player.get_reserve() < 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.last_turn == player: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if 0 > x > 5 or 0 > y ... | Moves piece from player's reserve to coord
:param: player: player object
:param: coord: (x,y) of tile on board | 625941e2a219f33f34628d21 |
def deform_grid(self): <NEW_LINE> <INDENT> for node in self.pixel_graph.nodes_iter(): <NEW_LINE> <INDENT> self.deform_pixel(node) <NEW_LINE> <DEDENT> removals = [] <NEW_LINE> for node in self.grid_graph.nodes_iter(): <NEW_LINE> <INDENT> if node in ((0, 0), (0, self.size[1]), (self.size[0], 0), self.size): <NEW_LINE> <I... | Deform the pixel grid based on the connections between similar pixels. | 625941e20383005118ecf99e |
def static_path(path, request, **kw): <NEW_LINE> <INDENT> if not os.path.isabs(path): <NEW_LINE> <INDENT> if ':' not in path: <NEW_LINE> <INDENT> package = caller_package() <NEW_LINE> path = '%s:%s' % (package.__name__, path) <NEW_LINE> <DEDENT> <DEDENT> return request.static_path(path, **kw) | This is a backwards compatibility function. Its result is the same as
calling::
request.static_path(path, **kw)
See :meth:`pyramid.request.Request.static_path` for more information. | 625941e2596a897236089e79 |
def get_prob_based_on_criteria(self, features): <NEW_LINE> <INDENT> weights = self.criteria_weights <NEW_LINE> users_prob_criteria = [] <NEW_LINE> for item in features: <NEW_LINE> <INDENT> user_id = item[0] <NEW_LINE> list_features = item[1] <NEW_LINE> prob_spammer = 1 <NEW_LINE> prob_each_feature = array(list_features... | Calculate the probability of user to be a spammer based on the
criteria weights | 625941e25166f23b2e1a5515 |
def FILTER(_input, _as, cond): <NEW_LINE> <INDENT> return {'$filter': {'input': _input, 'as': _as, 'cond': cond}} | Selects a subset of an array to return based on the specified condition. Returns an array with only those elements that match the condition.
The returned elements are in the original order.
See https://docs.mongodb.com/manual/reference/operator/aggregation/filter/
for more details
:param _input: An expression that ... | 625941e29b70327d1c4e1193 |
def bufferIsFull(self): <NEW_LINE> <INDENT> return len(self.buffer) == self.bufferSize | Checks if the buffer is full
@return: True if the buffer is full and False if not | 625941e20fa83653e4657375 |
def test_topic_unread_list_dont_show_removed_or_no_access(self): <NEW_LINE> <INDENT> TopicUnread.objects.all().delete() <NEW_LINE> category = utils.create_category() <NEW_LINE> category_removed = utils.create_category(is_removed=True) <NEW_LINE> subcategory = utils.create_category(parent=category_removed) <NEW_LINE> su... | dont show private topics if user has no access or is removed | 625941e26fb2d068a760f45f |
def apply_master_config(overrides=None, defaults=None): <NEW_LINE> <INDENT> import salt.crypt <NEW_LINE> if defaults is None: <NEW_LINE> <INDENT> defaults = DEFAULT_MASTER_OPTS <NEW_LINE> <DEDENT> opts = defaults.copy() <NEW_LINE> opts['__role'] = 'master' <NEW_LINE> if overrides: <NEW_LINE> <INDENT> opts.update(overri... | Returns master configurations dict. | 625941e26e29344779a629cd |
def __mod__(self,other) : <NEW_LINE> <INDENT> if not other : raise ZeroDivisionError; <NEW_LINE> if not self._p : return self; <NEW_LINE> if not isinstance(other,type(self)) : <NEW_LINE> <INDENT> if isinstance(other,rationalfunction) : <NEW_LINE> <INDENT> if other._b == 1 : <NEW_LINE> <INDENT> other = other._a; <NEW_LI... | Return the remainder when dividing self by other | 625941e23cc13d1c6d3c7735 |
def set_running(self, state): <NEW_LINE> <INDENT> if state: <NEW_LINE> <INDENT> self.start() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stop() | Set the state of the tracer
:param state: Specify true to start the tracing process or False to stop tracing
:return: True if the action could be executed, else False | 625941e2287bf620b61d3e1e |
def trace2(self, devicename, variable_name, variable1 = '%', variable2 = '%', variable3 = '%', variable4 = '%'): <NEW_LINE> <INDENT> if variable_name != '': <NEW_LINE> <INDENT> value_str = f"{variable_name} = " <NEW_LINE> if variable1 != '%': value_str += f" ({variable1})" <NEW_LINE> if variable2 != '%': value_str += f... | Display a message or variable in the HA log file | 625941e2d10714528d6000a4 |
def best_neutral(game_data, distance_data, factory_id, safe_data_level): <NEW_LINE> <INDENT> if factory_id == -1: <NEW_LINE> <INDENT> return -1, 0 <NEW_LINE> <DEDENT> score = 0 <NEW_LINE> best_neutral_id = -1 <NEW_LINE> for factory in game_data[('FACTORY', 0)]: <NEW_LINE> <INDENT> dist = distance_data[(factory_id, fact... | Calculate the best neutral according to distance and production | 625941e2009cb60464c6376c |
def patch_redis(dbfile=None): <NEW_LINE> <INDENT> for patch in [patch_redis_Redis, patch_redis_StrictRedis]: <NEW_LINE> <INDENT> patch(dbfile) | Patch all the redis classes provided by redislite that have been patched.
Example:
patch_redis('/tmp/redis.db')
Notes:
If the dbfile parameter is not passed, each any instances of :class:`redis.StrictRedis()` class with no
arguments will get a unique instance of the redis server. If the dbfile paramete... | 625941e2097d151d1a223214 |
def _test_fenshi_redis(self): <NEW_LINE> <INDENT> end_day = agl.CurDay() <NEW_LINE> start_day = help.MyDate.s_Dec(end_day, -15) <NEW_LINE> code = u'600100' <NEW_LINE> df_fenshi = getFiveMinFenshiFromRedis(code) <NEW_LINE> df_fenshi_day = df_fenshi.resample('D').dropna() <NEW_LINE> self.assertEqual(len(df_fenshi_day), 5... | 取一个个股的redis, 看下日期 | 625941e292d797404e304548 |
def test_reserved_extra_keys(): <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> metrics.Event( type="event", category="category", name="metric", bugs=["http://bugzilla.mozilla.com/12345"], notification_emails=["nobody@example.com"], description="description...", expires="never", extra_keys={"gle... | Test that extra keys starting with 'glean.' are rejected for
non-internal metrics. | 625941e2f7d966606f6aa3c6 |
def exempt(self, view_func): <NEW_LINE> <INDENT> if not view_func in self._exempt: <NEW_LINE> <INDENT> self._exempt.append(view_func) | Exempt a view function from being checked permission
:param view_func: The view function exempt from checking. | 625941e282261d6c526ab862 |
def _manual_skip_date(ratings_date_to_skip, all_ratings_list): <NEW_LINE> <INDENT> logging.info("_manual_skip_date - dropping - " + str(ratings_date_to_skip)) <NEW_LINE> elements_to_drop = [] <NEW_LINE> for rating_element in range(len(all_ratings_list)): <NEW_LINE> <INDENT> if all_ratings_list[rating_element]["RATINGS_... | Manually excludes elements based on ratings_date_to_skip
Parameters
----------
ratings_date_to_skip: str
pass str in YYYY-MM-DD format
elements of all_ratings_list with RATINGS_OCCURRED_ON
equal to ratings_date_to_skip will be removed from the list
all_ratings_list : list
safe source of element struc... | 625941e216aa5153ce362835 |
def student_pdf_1d(X, phi, K, nu): <NEW_LINE> <INDENT> num = math.gamma((1. + nu) / 2.) * pow( 1. + (1. / (nu - 2)) * (1. / K * (X - phi) ** 2), -(1. + nu) / 2.) <NEW_LINE> denom = math.gamma(nu / 2.) * pow((nu - 2) * math.pi * K, 0.5) <NEW_LINE> return num / denom | Univariate student-t density:
output:
the density of the given element
input:
x = parameter scalar
mu = mean
var = scale matrix
nu = degrees of freedom | 625941e2d53ae8145f87a626 |
def __init__(self, input_features, class_embeddings, d1=1024, d2=1024): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.input_features = input_features <NEW_LINE> self.c, self.embed_fts = class_embeddings.shape <NEW_LINE> self.xc = torch.tensor(class_embeddings).float().to(DEVICE) <NEW_LINE> self.dense_img = nn.... | Constructor
Arguments:
input_features {int} -- Number of features of the input
class_embeddings {numpy array} -- Word embeddings of the classes
Keyword Arguments:
d1 {int} -- First hidden size (default: {1024})
d2 {int} -- Second hidden size (default: {1024}) | 625941e201c39578d7e751f8 |
def save(self, sess, global_step, save_mode): <NEW_LINE> <INDENT> if save_mode == "debug": <NEW_LINE> <INDENT> self.ckpt_debug_saver.save(sess, self.ckpt_debug_name, global_step=global_step) <NEW_LINE> <DEDENT> elif save_mode == "epoch": <NEW_LINE> <INDENT> self.ckpt_epoch_saver.save(sess, self.ckpt_epoch_name, global_... | save checkpoint for qanet model | 625941e2004d5f362079a6ee |
def _make_rings(self): <NEW_LINE> <INDENT> nb_rings = self.geometry.nb_rings <NEW_LINE> nb_blocks = self.nb_blocks_per_ring <NEW_LINE> gap = self.gap <NEW_LINE> ri = self.inner_radius <NEW_LINE> ro = self.outer_radius <NEW_LINE> block_size = self.block_proto.block_size <NEW_LINE> grid = self.block_proto.grid <NEW_LINE>... | Generate a list of rings in the cylindrical scanner.
Create a ring list of the cylindrical PET scanner.
Each item of the list is a block list which cocntain the blocks
contains the single ring. | 625941e20c0af96317bb85a5 |
def test_trainOn_model(self): <NEW_LINE> <INDENT> stkm = StreamingKMeans() <NEW_LINE> initCenters = [[1.0, 1.0], [-1.0, 1.0], [-1.0, -1.0], [1.0, -1.0]] <NEW_LINE> stkm.setInitialCenters( centers=initCenters, weights=[1.0, 1.0, 1.0, 1.0]) <NEW_LINE> offsets = [[0, 0.1], [0, -0.1], [0.1, 0], [-0.1, 0]] <NEW_LINE> batche... | Test the model on toy data with four clusters. | 625941e28a349b6b435e8530 |
def list_available_ssl_options( self, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = self.list_available_ssl_options.metadata['url'] <NEW_LINE> path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } <NEW_LINE> ... | Lists available Ssl options for configuring Ssl policy.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: Appli... | 625941e2c432627299f05006 |
def isExist(mat, vec): <NEW_LINE> <INDENT> if type(vec)==np.ndarray: <NEW_LINE> <INDENT> vec=np.matrix(vec).T <NEW_LINE> <DEDENT> isit=np.all(mat==vec, axis=0) <NEW_LINE> if True in isit: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Checks whether an array vec exists as a column in matrix mat | 625941e226238365f5f0f230 |
def vgg16(num_classes=1000, pretrained='imagenet'): <NEW_LINE> <INDENT> model = drop_vgg.vgg16(pretrained=False) <NEW_LINE> if pretrained is not None: <NEW_LINE> <INDENT> settings = pretrained_settings['vgg16'][pretrained] <NEW_LINE> model = load_pretrained(model, num_classes, settings) <NEW_LINE> <DEDENT> model = modi... | VGG 16-layer model (configuration "D")
| 625941e2ab23a570cc250543 |
def run(self, checked): <NEW_LINE> <INDENT> if checked: <NEW_LINE> <INDENT> pass | Run method when dock toggled | 625941e2cb5e8a47e48b7e62 |
def main(algorithm): <NEW_LINE> <INDENT> pass | key = getRSAKey()
if algorithm == "DES":
#processFileDES('fin.txt', 'fout.bin')
print("
Not implemented yet
")
elif algorithm == "AES":
processFileAES('fout.txt', 'final.txt')
print("Done AES Decryption")
#processFileHybridAES('fout.txt', 'finalText.txt', secret=b"12... | 625941e2a934411ee3751a52 |
def job_scf_opt10(sample_source, tr, te, r, J): <NEW_LINE> <INDENT> op = {'n_test_freqs': J, 'max_iter': 100, 'freqs_step_size': 5.0, 'gwidth_step_size': 0.2, 'seed': r+92856, 'tol_fun': 1e-4} <NEW_LINE> test_freqs, gwidth, info = tst.SmoothCFTest.optimize_freqs_width(tr, alpha, **op) <NEW_LINE> scf_opt = tst.SmoothCFT... | SmoothCFTest with frequencies optimized. | 625941e24d74a7450ccd4582 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.