code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_post_bookmark_with_invalid_data(self): <NEW_LINE> <INDENT> response = self.send_post( client=self.client, url=reverse('bookmarks'), data={'usage_id': 'invalid'}, expected_status=400 ) <NEW_LINE> self.assertEqual(response.data['user_message'], u'An error has occurred. Please try again.') <NEW_LINE> response = s... | Test that posting a bookmark for a block with invalid usage id returns a 400.
Scenarios:
1) Invalid usage id.
2) Without usage id.
3) With empty request.data | 625941c155399d3f0558862b |
def register_extensions(app): <NEW_LINE> <INDENT> db.init_app(app) <NEW_LINE> db.create_all(app=app) <NEW_LINE> provider.init_app(app) <NEW_LINE> provider._validator = RequestValidator() | Registers application extensions. | 625941c199cbb53fe6792b5f |
@sdc_min_version('3.19.0') <NEW_LINE> @database('oracle') <NEW_LINE> @pytest.mark.parametrize('buffer_locally', [True, False]) <NEW_LINE> @pytest.mark.parametrize('dictionary_source', ['DICT_FROM_REDO_LOGS', 'DICT_FROM_ONLINE_CATALOG']) <NEW_LINE> def test_disable_continuous_mine(sdc_builder, sdc_executor, database, ke... | Simple test to check "Disable Continuous Mine" stage option.
The test just inserts a few records in the test table and check they are successfully consumed by Oracle
CDC. This is tested with different configurations which affect how LogMiner sessions are set.
Pipeline: oracle_cdc >> wiretap | 625941c13317a56b86939bd6 |
def enable_callback_tracebacks(flag): <NEW_LINE> <INDENT> pass | By default you will not get any tracebacks in user-defined functions,
aggregates, converters, authorizer callbacks etc.
:type flag: bool
:rtype: None | 625941c1a8ecb033257d3046 |
def get_account_ids_from_match(*matches: dict): <NEW_LINE> <INDENT> account_ids = [] <NEW_LINE> for match in matches: <NEW_LINE> <INDENT> for participant in match['participantIdentities']: <NEW_LINE> <INDENT> account_ids.append(participant['player']['accountId']) <NEW_LINE> <DEDENT> <DEDENT> return list(set(account_ids... | From an initial list of matches, find all account ids. | 625941c1dc8b845886cb54ac |
def predict_class_local(self, X): <NEW_LINE> <INDENT> result = callBigDlFunc(self.bigdl_type, "predictLocalClass", self.value, self._to_jtensors(X)) <NEW_LINE> return np.stack(result) | :param X: X can be a ndarray or list of ndarray if the model has multiple inputs.
The first dimension of X should be batch.
:return: a ndarray as the prediction result. | 625941c17b25080760e393d2 |
def backupToZip(folder): <NEW_LINE> <INDENT> folder = os.path.abspath(folder) <NEW_LINE> number = 1 <NEW_LINE> while True: <NEW_LINE> <INDENT> zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip' <NEW_LINE> if not os.path.exists(zipFilename): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> number += 1 <NEW... | создает резервную копию всего содержимого папки folder | 625941c1e76e3b2f99f3a788 |
def cmyk(c, m, y, k): <NEW_LINE> <INDENT> rgb_scale = 1.0 <NEW_LINE> cmyk_scale = 1.0 <NEW_LINE> r = rgb_scale * (1.0 - (c + k) / float(cmyk_scale)) <NEW_LINE> g = rgb_scale * (1.0 - (m + k) / float(cmyk_scale)) <NEW_LINE> b = rgb_scale * (1.0 - (y + k) / float(cmyk_scale)) <NEW_LINE> return r, g, b | this was taken from https://stackoverflow.com/questions/14088375/how-can-i-convert-rgb-to-cmyk-and-vice-versa-in-python | 625941c1d6c5a10208143fc1 |
def spawnlp(mode, file, *args): <NEW_LINE> <INDENT> return spawnvp(mode, file, args) | spawnlp(mode, file, *args) -> integer
Execute file (which is looked for along $PATH) with arguments from
args in a subprocess with the supplied environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the ... | 625941c1a8370b7717052819 |
def redondear(numero, full_scale): <NEW_LINE> <INDENT> if abs(numero) <= 0.001 * abs(full_scale): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if numero < 0: <NEW_LINE> <INDENT> negativo = True <NEW_LINE> numero = numero * (-1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> negativo = False <NEW_LINE> <DEDENT> numer... | Función para redondear el valor pasado por argumento | 625941c10a366e3fb873e791 |
def update_state(tenant, state_code, state_name): <NEW_LINE> <INDENT> with DBConnection(tenant) as connection: <NEW_LINE> <INDENT> dim_inst_hier = connection.get_table("dim_inst_hier") <NEW_LINE> fact_asmt = connection.get_table("fact_asmt_outcome") <NEW_LINE> fact_asmt_vw = connection.get_table("fact_asmt_outcome_vw")... | Update state_code in all the tables for a tenant | 625941c1a934411ee375160b |
def get_nonlocal_ip(host, subnet=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ailist = socket.getaddrinfo(host, None) <NEW_LINE> <DEDENT> except socket.gaierror: <NEW_LINE> <INDENT> raise exc.UnableToResolveError(host) <NEW_LINE> <DEDENT> for ai in ailist: <NEW_LINE> <INDENT> ip = ai[4][0] <NEW_LINE> if subnet a... | Search result of getaddrinfo() for a non-localhost-net address | 625941c1711fe17d825422e8 |
def get_course_run_detail(site, course_run_key): <NEW_LINE> <INDENT> resource = "course_runs" <NEW_LINE> cache_key = get_cache_key( site_domain=site.domain, resource="{}-{}".format(resource, course_run_key) ) <NEW_LINE> return _get_discovery_response(site, cache_key, resource, course_run_key) | Return the course run information of given course_run_key from Discovery Service and cache.
Arguments:
site (Site): Site object containing Site Configuration data
course_run_key (str): Course run key
Returns:
dict: CourseRun information received from Discovery API | 625941c11b99ca400220aa2a |
def display_genre(self): <NEW_LINE> <INDENT> return ', '.join(genre.name for genre in self.genre.all()[:3]) | Create a string for the genre
:return: | 625941c173bcbd0ca4b2bfef |
def _register_controllers(self, ext): <NEW_LINE> <INDENT> handler = ext.obj <NEW_LINE> LOG.debug("Running _register_controllers on %s", ext.obj) <NEW_LINE> for extension in handler.get_controller_extensions(): <NEW_LINE> <INDENT> ext_name = extension.extension.name <NEW_LINE> collection = extension.collection <NEW_LINE... | Register controllers defined by the extensions
Extensions define what resources they want to add through
a get_controller_extensions function | 625941c14e696a04525c93c5 |
def shortStr(self): <NEW_LINE> <INDENT> return "%s %s '%s'" % (self.startDateTime.strftime("%Y-%m-%d %a"), self.startDateTime.time(), self.summary) | Return a short string to identify the meeting uniquely | 625941c1091ae35668666edb |
def apply_recommendation(self, customer_id, operations, partial_failure=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): <NEW_LINE> <INDENT> if 'apply_recommendation' not in self._inner_api_calls: <NEW_LINE> <INDENT> self._inner_api_calls[ 'apply_reco... | Applies given recommendations with corresponding apply parameters.
Args:
customer_id (str): The ID of the customer with the recommendation.
operations (list[Union[dict, ~google.ads.googleads_v1.types.ApplyRecommendationOperation]]): The list of operations to apply recommendations. If
partial\_failure=f... | 625941c107d97122c41787ff |
def insert_target(self): <NEW_LINE> <INDENT> if self.target['row'] is not None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> columns = self.target['connection'].get_mandatory_columns(self.database['table']) <NEW_LINE> columns.append(self.database['column']) <NEW_LINE> columns = set(columns) <NEW_LINE> values = [] <NE... | insert as little data as possible into the target database, if nothing
exists there already. This allows us to reselect and continue as normal | 625941c124f1403a92600ae1 |
@bind_hass <NEW_LINE> def execute(hass, filename, source, data=None): <NEW_LINE> <INDENT> compiled = compile_restricted_exec(source, filename=filename) <NEW_LINE> if compiled.errors: <NEW_LINE> <INDENT> _LOGGER.error( "Error loading script %s: %s", filename, ", ".join(compiled.errors) ) <NEW_LINE> return <NEW_LINE> <DE... | Execute Python source. | 625941c14e4d5625662d4353 |
def increment_values(self): <NEW_LINE> <INDENT> self.__current[:] = self.__future[:] | Increment field values | 625941c1442bda511e8be394 |
def active(self): <NEW_LINE> <INDENT> today = datetime.date.today() <NEW_LINE> return self.get_query_set().filter(Q(expiration_date__isnull=True) | Q(expiration_date__gte=today), publish_date__lte=today, is_active=True,) | Retrieves all active ads which have been published and have not yet expired. | 625941c1d53ae8145f87a1ec |
def __del__(self): <NEW_LINE> <INDENT> Rectangle.number_of_instances -= 1 <NEW_LINE> print('Bye rectangle...') | Privated instance method to delete | 625941c1e5267d203edcdc18 |
def print_sorted(self): <NEW_LINE> <INDENT> print(sorted(self)) | Fucntion that prints a sorted list | 625941c16fb2d068a760f014 |
def _read_quadrangle_annotations(csv_reader, classes, detect_text=False): <NEW_LINE> <INDENT> result = OrderedDict() <NEW_LINE> for line, row in enumerate(csv_reader, 1): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> img_file, x1, y1, x2, y2, x3, y3, x4, y4, class_name = row[:10] <NEW_LINE> if img_file not in result: <N... | Read annotations from the csv_reader.
Args:
csv_reader: csv reader of args.annotations_path
classes: list[str] all the class names read from args.classes_path
Returns:
result: dict, dict is like {image_path: [{'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2,
'x3': x3, 'y3': y3, 'x4'... | 625941c1377c676e91272122 |
def _ImageDimensions(images, dynamic_shape=False): <NEW_LINE> <INDENT> if dynamic_shape: <NEW_LINE> <INDENT> return array_ops.unpack(array_ops.shape(images)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return images.get_shape().as_list() | Returns the dimensions of an image tensor.
Args:
images: 4-D Tensor of shape [batch, height, width, channels]
dynamic_shape: Whether the input image has undertermined shape. If set to
`True`, shape information will be retrieved at run time. Default to
`False`.
Returns:
list of integers [batch, height, wi... | 625941c194891a1f4081ba21 |
def plot_inv_act_para(fo, ts, para, low_limit=1e-5, save=False, sfile=""): <NEW_LINE> <INDENT> act_grid = np.zeros((113,173)) <NEW_LINE> for nuc in fo.timestep_data[ts-1].inventory: <NEW_LINE> <INDENT> if float(nuc[para]) > 0: <NEW_LINE> <INDENT> if nuc[0][-1] == "n": <NEW_LINE> <INDENT> nuc[0] = nuc[0][:-1] <NEW_LINE>... | plots parameter as table of nuclides form for a timestep
this is for active parameters | 625941c15fdd1c0f98dc01ab |
def nmt(src_input, tgt_input, tgt_output, nmt_colocation, unroll=True, **kwargs): <NEW_LINE> <INDENT> hparams = create_nmt_hparams(**kwargs) <NEW_LINE> return NMT(hparams, nmt_colocation, unroll).build_graph( src_input, tgt_input, tgt_output) | Returns a NMT network. | 625941c18a349b6b435e80ec |
def temperature_linearterms(system): <NEW_LINE> <INDENT> from ...component.temperature import temperature <NEW_LINE> dT = np.zeros_like(system.Temperature) <NEW_LINE> f_m, f_p = system.b_Temperature <NEW_LINE> assert not temperature(system.nz, system.nn, dT, system.Temperature, system.dz, system.npa[0,:], f_p, f_m) <NE... | Operate the derivative of temperature linear term computer. | 625941c12ae34c7f2600d0aa |
def get_data(db_session): <NEW_LINE> <INDENT> return db_session.query(Request).all() | Equivalent function to get_data_from, but returns all data.
:param db_session: session for the database
:return list of all requests in the Request table | 625941c1956e5f7376d70de7 |
def run(self): <NEW_LINE> <INDENT> error, show = Show.pause(self.indexerid, self.pause) <NEW_LINE> if error: <NEW_LINE> <INDENT> return _responds(RESULT_FAILURE, msg=error) <NEW_LINE> <DEDENT> return _responds(RESULT_SUCCESS, msg='{0} has been {1}'.format(show.name, ('resumed', 'paused')[show.paused])) | Pause or un-pause a show | 625941c1aad79263cf3909b7 |
def test_3 (self): <NEW_LINE> <INDENT> res = solve ('PLAYS', 'WELL', 'BETTER') <NEW_LINE> self.assertEquals (res, [97426, 8077, 105503]) | PLAYS + WELL = BETTER | 625941c1046cf37aa974ccc3 |
def ingestion_complete(self): <NEW_LINE> <INDENT> if self.outcome is None: <NEW_LINE> <INDENT> self._ingestion_complete = True <NEW_LINE> self._perhaps_complete() | See superclass method for specification. | 625941c12ae34c7f2600d0ab |
def _dim_index_to_slice(index_list): <NEW_LINE> <INDENT> if len(index_list) == 1: <NEW_LINE> <INDENT> return index_list[0] <NEW_LINE> <DEDENT> elif len(index_list) == 2: <NEW_LINE> <INDENT> return slice(index_list[0],index_list[1]) <NEW_LINE> <DEDENT> elif len(index_list) == 3: <NEW_LINE> <INDENT> return slice(index_li... | .. function:: _dim_index_to_slice(index_list)
Convert string formatted as: dimname,start[,stop[,stride]]
to index (for the case where only 'start' is provided)
or indexing object (slice).
:param index_list: index list as passed in from
-d dimname,start,stop,stride
:returns: dict -- {dimname: index... | 625941c155399d3f0558862c |
def shuffle_blocks(vlist, bsize=-1): <NEW_LINE> <INDENT> vlen = len(vlist) <NEW_LINE> if bsize < 0 or bsize >= vlen: <NEW_LINE> <INDENT> shuffle(vlist) <NEW_LINE> return <NEW_LINE> <DEDENT> if bsize < 2: return <NEW_LINE> nblocks = vlen // bsize <NEW_LINE> nrem = vlen % bsize <NEW_LINE> boff = 0 <NEW_LINE> for ind ... | like shuffle, but in blocks of given size | 625941c17047854f462a1385 |
def _postback(self): <NEW_LINE> <INDENT> raise NotImplementedError | Perform postback to MoIP and store the response in self.response. | 625941c17d43ff24873a2c18 |
@_docstring_parameter(_csv_load_params_doc) <NEW_LINE> def baseline_newline_count(filename, *args, **kwargs): <NEW_LINE> <INDENT> params = _get_params(*args, **kwargs) <NEW_LINE> nc = pti.NewlineCounter(); <NEW_LINE> count = nc.load(filename, params) <NEW_LINE> return count | Computes the number of newline characters in the file.
Note: this is not the same as the number of lines in a file.
Parameters
----------
{0}
Returns
-------
n : int
The number of newlines in a file. | 625941c1eab8aa0e5d26dad0 |
def execute_system_command(self, command): <NEW_LINE> <INDENT> return subprocess.check_output(command, shell=True) | Execute a system command.
:param command: command that we want to execute
:type command: str
:return: resulting command
:rtype: str | 625941c199fddb7c1c9de30b |
def create_user(passwd, username='usuario', email='[email protected]'): <NEW_LINE> <INDENT> user = django.contrib.auth.get_user_model().objects.create_user( username=username, email=email, password=passwd) <NEW_LINE> return user | Creates and stores a user | 625941c11f037a2d8b946177 |
def check_and_create_dir(dir): <NEW_LINE> <INDENT> pathlib.Path(dir).mkdir(parents=True, exist_ok=True) | check_and_create_dir
Checks whether an output directory exists and creates it. | 625941c1c4546d3d9de729ab |
def test_sw1_stack_down(self): <NEW_LINE> <INDENT> dps = [valve.dp for valve in self.valves_manager.valves.values()] <NEW_LINE> for dp in dps: <NEW_LINE> <INDENT> for port in dp.ports.values(): <NEW_LINE> <INDENT> if port.lacp: <NEW_LINE> <INDENT> port.actor_up() <NEW_LINE> port.select_port() <NEW_LINE> <DEDENT> if por... | Test stack health metrics with SW1 | 625941c1de87d2750b85fd09 |
def cleanup(self): <NEW_LINE> <INDENT> super(TrafficGen, self).cleanup() <NEW_LINE> gevent.get_hub().destroy() | Shutdown gevent as it seems to be leaking some globals. | 625941c1a05bb46b383ec79d |
def toHex(self, num): <NEW_LINE> <INDENT> if num == 0: <NEW_LINE> <INDENT> return '0' <NEW_LINE> <DEDENT> if num < 0: <NEW_LINE> <INDENT> num += 2**32 <NEW_LINE> <DEDENT> result = '' <NEW_LINE> s = ['a', 'b', 'c', 'd', 'e', 'f'] <NEW_LINE> while num: <NEW_LINE> <INDENT> temp = num % 16 <NEW_LINE> if temp > 9: <NEW_LINE... | :type num: int
:rtype: str | 625941c1de87d2750b85fd0a |
def get_url(song_input, auto): <NEW_LINE> <INDENT> youtube_list = OrderedDict() <NEW_LINE> num = 0 <NEW_LINE> html = requests.get("https://www.youtube.com/results", params={'search_query': song_input}) <NEW_LINE> soup = BeautifulSoup(html.text, 'html.parser') <NEW_LINE> for i in soup.findAll('a', {'rel': YOUTUBECLASS})... | Provides user with a list of songs to choose from
returns the url of chosen song. | 625941c1b7558d58953c4e92 |
def test_adjust_context_scope(time_keyed_left, time_keyed_right): <NEW_LINE> <INDENT> @adjust_context.register(CustomAsOfJoin) <NEW_LINE> def adjust_context_custom_asof_join( op: ops.AsOfJoin, scope: Scope, timecontext: TimeContext, ) -> TimeContext: <NEW_LINE> <INDENT> assert scope is not None <NEW_LINE> return timeco... | Test that `adjust_context` has access to `scope` by default. | 625941c16fece00bbac2d6b6 |
@dispatch <NEW_LINE> @abstract() <NEW_LINE> def ones(dtype: DType, *shape: Int): <NEW_LINE> <INDENT> pass | Create a tensor of ones.
Can also give a reference tensor whose data type and shape will be used to
construct a tensor of ones.
Args:
dtype (dtype, optional): Data type. Defaults to the default data type.
*shape (shape): Shape of the tensor.
Returns:
tensor: Tensor of ones of shape `shape` and data type ... | 625941c11d351010ab855a96 |
def _load_consumer(self, consumer): <NEW_LINE> <INDENT> queue = rotate_to_first_in_deque_and_pop(self._unassigned_queues, lambda q: q.active) <NEW_LINE> if queue: <NEW_LINE> <INDENT> consumer.assign_queue(queue) <NEW_LINE> return True <NEW_LINE> <DEDENT> queue = rotate_to_first_in_deque_and_pop(self._unassigned_queues,... | Assign the first available queue to the consumer and return immediately. If no queue can be assigned to
the consumer then the youngest consumer is scheduled to stop and one of it's queues is donated to the consumer. | 625941c1e76e3b2f99f3a789 |
def overwrite_existing_file(self, context): <NEW_LINE> <INDENT> self.current = context.transport.get(self.filename) <NEW_LINE> if self.current != self.contents: <NEW_LINE> <INDENT> self.renderer.changed_file( self.filename, self.current, self.contents, self.sensitive) <NEW_LINE> if not context.simulate: <NEW_LINE> <IND... | Change the content of an existing file | 625941c126068e7796caec54 |
def setup_config(command, filename, section, vars): <NEW_LINE> <INDENT> conf = appconfig('config:' + filename) <NEW_LINE> load_environment(conf.global_conf, conf.local_conf) <NEW_LINE> from oil import db as model <NEW_LINE> answer = raw_input('Delete Current Tables If any exist [y/n]?') <NEW_LINE> if answer.lower() in ... | Place any commands to setup oil here | 625941c13cc13d1c6d3c72f4 |
def parsing_boolean(self, field, data): <NEW_LINE> <INDENT> if field in data: <NEW_LINE> <INDENT> v = data[field] <NEW_LINE> if v in ['True', '有', ]: <NEW_LINE> <INDENT> data[field] = True <NEW_LINE> <DEDENT> elif v in ['False', ]: <NEW_LINE> <INDENT> data[field] = False | 解析布尔字段 | 625941c1fbf16365ca6f6139 |
def relativeValue(self): <NEW_LINE> <INDENT> return float() | float KIntNumInput.relativeValue() | 625941c10c0af96317bb8162 |
def random_string(length): <NEW_LINE> <INDENT> s = '' <NEW_LINE> while len(s) < length: <NEW_LINE> <INDENT> s += valid_string_characters[randint(0, 84)] <NEW_LINE> <DEDENT> return s | Return a random string of given length. | 625941c1293b9510aa2c3212 |
def test2(self): <NEW_LINE> <INDENT> signal = 'onAdjournmentsList' <NEW_LINE> lines = [ 'Stored games for tester:', ' C Opponent On Type Str M ECO Date', ' 1: W TheDane N [ br 2 12] 0-0 B2 ??? Sun Nov 23, 6:14 CST 1997', ' 2: W PyChess Y [psu 2 12] 39-39 W3 C20 Sun Jan 11, 1... | Testing a double line | 625941c15fcc89381b1e1637 |
def parse(self, entry: typing.Any): <NEW_LINE> <INDENT> return self.DescriptionNode(**entry) | Parse description data. | 625941c192d797404e304103 |
def stopTrial(self): <NEW_LINE> <INDENT> self.sendMsg('stop_trial') <NEW_LINE> time.sleep(10 / 1000.0) <NEW_LINE> self.stopRecording() | Stops the eyetracker recording mode and also sends a message to the
eyelink log that the trial is stoped. The message sent is
'stop_trial'. Use this function before the trial starts.
If dummy mode, prints the message to the console.
Examples
--------
>>> tracker.stopTrial() | 625941c14f6381625f1149b5 |
def get_feedback(self): <NEW_LINE> <INDENT> return self._feedback | :rtype: list[Feedback] | 625941c1bf627c535bc13148 |
def getRowCol(self, pixelX, pixelY): <NEW_LINE> <INDENT> x0, y0 = self.rect.topleft <NEW_LINE> if self.outOfBounds(pixelX, pixelY): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> relX = pixelX - x0 <NEW_LINE> relY = pixelY - y0 <NEW_LINE> row = int(relY / self.cellHeight) <NEW_LINE> col = int(relX / self.cellWidth... | get the (row, col) coordinate for the given (x, y) location | 625941c185dfad0860c3add3 |
def main(): <NEW_LINE> <INDENT> _solution = Solution() <NEW_LINE> inp = [([1,1,1],2), ([2,3,2,3,2],5), ([28,54,7,-70,22,65,-6], 100),([0,0,0,0,0,0,0,0,0,0],0)] <NEW_LINE> for i in inp: <NEW_LINE> <INDENT> print(_solution.func(i[0], i[1])) | main function | 625941c194891a1f4081ba22 |
def __init__(self): <NEW_LINE> <INDENT> self.sections = 0 <NEW_LINE> self.close_filein = False <NEW_LINE> self.close_fileout = False <NEW_LINE> try: <NEW_LINE> <INDENT> if len(sys.argv) > 1: <NEW_LINE> <INDENT> self.filein = open(sys.argv[1], 'r') <NEW_LINE> self.close_filein = True <NEW_LINE> <DEDENT> else: <NEW_LINE>... | Initialize input and ouput file objects from command line options or
if absent from stdin/stdout | 625941c1925a0f43d2549def |
def stopEngine(self, engine_id): <NEW_LINE> <INDENT> for access_id, v in self.engine_instances.iteritems(): <NEW_LINE> <INDENT> if engine_id == v: <NEW_LINE> <INDENT> self.processManager.stopProcess(engine_id) <NEW_LINE> del self.engine_instances[access_id] <NEW_LINE> break | XXX hacky. improve next iteration.
| 625941c15166f23b2e1a50d3 |
def is_option_list(sValue, *aOptions): <NEW_LINE> <INDENT> return [is_option(sMem, *aOptions) for sMem in is_list(sValue)] | Validator function for option_list configspec type. | 625941c13cc13d1c6d3c72f5 |
def __init__(self, vec2d): <NEW_LINE> <INDENT> self.vec = vec2d <NEW_LINE> self.row = self.col = 0 | Initialize your data structure here.
:type vec2d: List[List[int]] | 625941c14527f215b584c3d3 |
def transition_import_(self): <NEW_LINE> <INDENT> Channel = Pool().get('sale.channel') <NEW_LINE> channel = Channel(Transaction().context.get('active_id')) <NEW_LINE> sales = [] <NEW_LINE> products = [] <NEW_LINE> if self.start.import_orders: <NEW_LINE> <INDENT> sales = channel.import_orders() <NEW_LINE> <DEDENT> if se... | Downstream channel implementation can customize the wizard | 625941c157b8e32f52483413 |
def pc_work_time_var(self): <NEW_LINE> <INDENT> return _lilacsat_swig.afsk1200_rx_f_sptr_pc_work_time_var(self) | pc_work_time_var(afsk1200_rx_f_sptr self) -> float | 625941c1bde94217f3682d6d |
def number(self, number): <NEW_LINE> <INDENT> s = [ord(x) for x in str(number)] + [14] <NEW_LINE> if number == int(number) and abs(number) < 65536: <NEW_LINE> <INDENT> sign = 0xFF if number < 0 else 0 <NEW_LINE> b = [0, sign] + self.numberLH(number) + [0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (C, ED, LH) = fp.i... | Returns a floating point (or integer) number for a BASIC
program. That is: It's ASCII representation followed by 5 bytes
in floating point or integer format (if number in (-65535 + 65535) | 625941c17b180e01f3dc477b |
def qrcode_image_response(data=''): <NEW_LINE> <INDENT> img = make_qr_code_image(data) <NEW_LINE> response = HttpResponse(content_type='image/png') <NEW_LINE> img.save(response, 'png') <NEW_LINE> return response | Returns a QR Code image as an HTTP response
This method is unrestricted (i.e. you wouldn't want anyone on the web generating QR codes automatically)
For restricted access, see: restricted_qrcode_image_response
TODO: Possible improvements: Cache (for a short period) requests for the same QR Code data-payload? | 625941c1d164cc6175782cc7 |
def _DoLensAlignment(future, navcam, sem_stage): <NEW_LINE> <INDENT> logging.debug("Starting lens alignment...") <NEW_LINE> try: <NEW_LINE> <INDENT> if future._lens_alignment_state == CANCELLED: <NEW_LINE> <INDENT> raise CancelledError() <NEW_LINE> <DEDENT> image = navcam.data.get(asap=False) <NEW_LINE> try: <NEW_LINE>... | Detects the objective lens with the NavCam and moves the SEM stage to center
them in the NavCam view. Returns the final SEM stage position.
future (model.ProgressiveFuture): Progressive future provided by the wrapper
navcam (model.DigitalCamera): The NavCam
sem_stage (model.Actuator): The SEM stage
returns sem_position... | 625941c130dc7b76659018e2 |
def get_text_data_list(self): <NEW_LINE> <INDENT> return [self.surname, self.prefix, self.connector, str(self.origintype)] | Return the list of all textual attributes of the object.
:returns: Returns the list of all textual attributes of the object.
:rtype: list | 625941c1f9cc0f698b140577 |
def handler(self): <NEW_LINE> <INDENT> if self.event == SUBSCRIBE: <NEW_LINE> <INDENT> return self.subscribe() <NEW_LINE> <DEDENT> elif self.event == SCAN: <NEW_LINE> <INDENT> return self.scan() <NEW_LINE> <DEDENT> elif self.event == CLICK: <NEW_LINE> <INDENT> return self.menu_click() <NEW_LINE> <DEDENT> elif self.even... | 事件处理入口
@return 符合微信要求格式的字符串。xml格式 | 625941c1d58c6744b4257bda |
def test_private(self): <NEW_LINE> <INDENT> self.assertRaises(AttributeError, getattr, self.prop, '__test__') | Test private attributes. | 625941c171ff763f4b549602 |
def get_website_config(): <NEW_LINE> <INDENT> config = {"ErrorDocument": {"Key": INDEX}, "IndexDocument": {"Suffix": ERROR}, } <NEW_LINE> return config | Gets the website config | 625941c1e8904600ed9f1ea5 |
def __init__(self, type=None, title=None, result_list=None): <NEW_LINE> <INDENT> self._type = None <NEW_LINE> self._title = None <NEW_LINE> self._result_list = None <NEW_LINE> self.discriminator = None <NEW_LINE> if type is not None: <NEW_LINE> <INDENT> self.type = type <NEW_LINE> <DEDENT> if title is not None: <NEW_LI... | DeviceSLAWidgetData - a model defined in Swagger | 625941c1e1aae11d1e749c2f |
def get_virtual_machine_scale_set_ip_configuration( self, resource_group_name, virtual_machine_scale_set_name, virtualmachine_index, network_interface_name, ip_configuration_name, expand=None, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: Res... | Get the specified network interface ip configuration in a virtual machine scale set.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param virtual_machine_scale_set_name: The name of the virtual machine scale set.
:type virtual_machine_scale_set_name: str
:param virtualmachi... | 625941c1d164cc6175782cc8 |
def calc_rh(at_date, at_val, dp_date, dp_val): <NEW_LINE> <INDENT> comp_val = 6999 <NEW_LINE> o_val = [] <NEW_LINE> index = 0 <NEW_LINE> while (index < len(at_date)): <NEW_LINE> <INDENT> rh_val = comp_val <NEW_LINE> if not(at_date[index] == dp_date[index]): <NEW_LINE> <INDENT> print_center("ERROR: dates do not match fo... | calcualtes the relative humidity
arguments:
at_date: ((datetime) list) air temerature date array
at_val: ((float) list) air temerature value array
dp_date: ((datetime) list) dew point date array
dp_val: ((float) list) dew point value array
returns:
an array of relative humiditys | 625941c1d7e4931a7ee9de97 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'google_maps_directions_proj.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import ... | Run administrative tasks. | 625941c1507cdc57c6306c50 |
def _get_sensor_col_files(self, gas, loc): <NEW_LINE> <INDENT> sub = os.path.join(self.GasNames[gas], self.Locs[loc]) <NEW_LINE> files = os.listdir(os.path.join(self.data_location, sub)) <NEW_LINE> files.sort() <NEW_LINE> return (sub, files) | lists the files in the directory corresponding to the gas and location. | 625941c1377c676e91272123 |
@pytest.mark.django_db <NEW_LINE> def test_sendmessage_command(mocker, organization, partner): <NEW_LINE> <INDENT> test_message = os.path.join(TEST_DIR, "testmessage.edi") <NEW_LINE> with pytest.raises(management.CommandError): <NEW_LINE> <INDENT> management.call_command( "sendas2message", "AS2 Server", "AS2 Client", t... | Test the command for sending an as2 message | 625941c199cbb53fe6792b61 |
@app.route("/tags/<int:tag_id>/edit", methods=["POST"]) <NEW_LINE> def edit_tag(tag_id): <NEW_LINE> <INDENT> tag_name = request.form["tag_name"] <NEW_LINE> post_ids = [int(num) for num in request.form.getlist("posts")] <NEW_LINE> posts = Post.query.filter(Post.id.in_(post_ids)).all() <NEW_LINE> tag = Tag.query.get_or_4... | This view function makes changes to an existing tag and makes sure it isaved in the blogly db | 625941c1aad79263cf3909b8 |
def img_preprocess(img): <NEW_LINE> <INDENT> out = cv2.resize(img, (112, 112)) <NEW_LINE> out = cv2.cvtColor(out, cv2.COLOR_BGR2GRAY) <NEW_LINE> mu = np.mean(out) <NEW_LINE> std = np.std(out) <NEW_LINE> out = (out - mu) / std <NEW_LINE> out = out[np.newaxis, :, :, np.newaxis] <NEW_LINE> return out | Conduct gray, resize and normalization on a face image
Args:
img: np.array, bgr color face img, [h, w, 3]
Returns: [1, 112, 112, 1] gray, normalized version | 625941c150485f2cf553cd13 |
def do_quick(self, code_line, evaluate = False): <NEW_LINE> <INDENT> self.send_debug_response("<code>do_quick</code> with <code>{}</code>".format(code_line)) <NEW_LINE> if isinstance(code_line, list): <NEW_LINE> <INDENT> for line in code_line: <NEW_LINE> <INDENT> self.child.sendline(line) <NEW_LINE> self.child.expect(S... | Quickly execute a line using the underlying REPL and, if needed,
evaluate it as Python code. | 625941c1462c4b4f79d1d64a |
def get_snp_genos(self, c, p, as_strings=True): <NEW_LINE> <INDENT> snps = [x for x in self.get_range(c,p,p,as_strings=as_strings)] <NEW_LINE> return len(snps)==1 and dict(snps[0][3]) or {} | Read a single position from a VCF file and return the genotypes
as a sample -> allele map. If there is not exactly one matching
row in the VCF file at this position (if there are none or multiple)
then we return an empty map: {}. | 625941c1cdde0d52a9e52fab |
def set_Datastreams(self, value): <NEW_LINE> <INDENT> super(CreateProductInputSet, self)._set_input('Datastreams', value) | Set the value of the Datastreams input for this Choreo. ((optional, json) Default device datastream JSON array. Every newly created device in this product will have this default datastream. Ex: [{"id":"channel1"},{"id":"demo"}]) | 625941c19f2886367277a809 |
def comment(request, template="generic/comments.html", extra_context=None): <NEW_LINE> <INDENT> response = initial_validation(request, "comment") <NEW_LINE> if isinstance(response, HttpResponse): <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> obj, post_data = response <NEW_LINE> form_class = import_dotted_path... | Handle a ``ThreadedCommentForm`` submission and redirect back to its
related object. | 625941c1e76e3b2f99f3a78a |
def __init__(self, OD): <NEW_LINE> <INDENT> self.od = OD | Class constructor.
>>> isinstance(Driver(OD(1, 2, 8, 15)), Driver)
True
>>> isinstance(Driver(1), Driver)
True
>>> isinstance(Driver(OD(1, 2, 8, 15)).od, OD)
True
The class contructor needs to be more precise about its input. | 625941c1d6c5a10208143fc3 |
def has_key(self, key): <NEW_LINE> <INDENT> return key.lower() in self.caseless_keys | Determines if the `dict` has an item with a specific `key`.
Args:
key: Key to check for presence. Key is case insensitive, so
`d.has_key('Key')` evaluates to the same value as `d.has_key('key')`.
Returns:
`True` if `dict` contains the specified `key`, else `False`. | 625941c166673b3332b9200b |
def _get_line_id(line): <NEW_LINE> <INDENT> if line.product.is_course_entitlement_product: <NEW_LINE> <INDENT> return line.product.attr.UUID <NEW_LINE> <DEDENT> return line.product.course_id | Return unique id of line
Args:
line: line in application orders
Returns:
if product is entitlement product then uuid
else course_id. | 625941c1851cf427c661a48c |
def ev_list(request, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> events = Event.objects.filter(end_date__gte=datetime.datetime.now()) <NEW_LINE> <DEDENT> except Event.DoesNotExist: <NEW_LINE> <INDENT> events = {} <NEW_LINE> <DEDENT> ret = dict(events=events) <NEW_LINE> return render(request, 'verbena... | list all events | 625941c1cad5886f8bd26f54 |
def config_api(stream, request, query): <NEW_LINE> <INDENT> mimetype = 'application/json' <NEW_LINE> indent = None <NEW_LINE> options = cgi.parse_qs(query) <NEW_LINE> if utils.intify(options.get('debug', ['0'])[0]): <NEW_LINE> <INDENT> mimetype = 'text/plain' <NEW_LINE> indent = 4 <NEW_LINE> <DEDENT> if utils.intify(op... | Implements /api/config API | 625941c19b70327d1c4e0d4f |
def db_init(): <NEW_LINE> <INDENT> db = db_open() <NEW_LINE> with app.open_resource('schema.sql', mode='r') as f: <NEW_LINE> <INDENT> db.cursor().executescript(f.read()) <NEW_LINE> <DEDENT> db.commit() | Initializes the database. | 625941c10a366e3fb873e793 |
def freq2time(spectrum, n=None): <NEW_LINE> <INDENT> return np.fft.irfft(spectrum, axis=-1, n=n) / 2 ** 0.5 | Conversion frequency to time domain
Goal: coherent normalization of the fft: np.sum(trace**2) * dt = np.sum(spectrum**2) * df
performs backward FFT with correct normalization that conserves the power
-- addional division 1/sqrt(2) to account for omitted negative frequencies when using "real fft"
Arguments
---... | 625941c1d268445f265b4de9 |
def _parcel_profile_helper(pressure, temperature, dewpoint): <NEW_LINE> <INDENT> press_lcl, temp_lcl = lcl(pressure[0], temperature, dewpoint) <NEW_LINE> press_lcl = press_lcl.to(pressure.units) <NEW_LINE> press_lower = concatenate((pressure[pressure >= press_lcl], press_lcl)) <NEW_LINE> temp_lower = dry_lapse(press_lo... | Help calculate parcel profiles.
Returns the temperature and pressure, above, below, and including the LCL. The
other calculation functions decide what to do with the pieces. | 625941c191f36d47f21ac46b |
def test_upheight(self): <NEW_LINE> <INDENT> r1 = Rectangle(2, 3, 4, 5, 6) <NEW_LINE> r1.update(85, 12, 8) <NEW_LINE> self.assertEqual(r1.width, 12) <NEW_LINE> self.assertEqual(r1.height, 8) <NEW_LINE> self.assertEqual(r1.x, 4) <NEW_LINE> self.assertEqual(r1.y, 5) <NEW_LINE> self.assertEqual(r1.id, 85) | Height Update | 625941c13539df3088e2e2c6 |
def process_property(self, resources, resource, model, prop, context, model_ids): <NEW_LINE> <INDENT> pass | Post process a property from a model.
:param resources: Resource listing object
:param resource: resource object.
:param model: Model object.
:param prop: Property object.
:type context: ParsingContext
:param context: Current context in the API. | 625941c14e696a04525c93c7 |
@onsetup <NEW_LINE> def setup_product(): <NEW_LINE> <INDENT> fiveconfigure.debug_mode = True <NEW_LINE> import plone.browserlayer <NEW_LINE> zcml.load_config('configure.zcml', plone.browserlayer) <NEW_LINE> import googlesitemap.common <NEW_LINE> zcml.load_config('configure.zcml', googlesitemap.common) <NEW_LINE> import... | Set up the package and its dependencies.
The @onsetup decorator causes the execution of this body to be
deferred until the setup of the Plone site testing layer. We could
have created our own layer, but this is the easiest way for Plone
integration tests. | 625941c15e10d32532c5eea2 |
def test_replace_namespaced_scale_scale_1(self): <NEW_LINE> <INDENT> pass | Test case for replace_namespaced_scale_scale_1
replace scale of the specified Scale | 625941c18e7ae83300e4af47 |
def DetailedStats(self, pc): <NEW_LINE> <INDENT> self.screen.clear() <NEW_LINE> L = [] <NEW_LINE> L.append(("^Y^-= %s =-" % lang.label_char_title) % (pc.name, pc.level, pc.archetype.cname)) <NEW_LINE> L.append("") <NEW_LINE> b = pc.MeleeDamageBonus() <NEW_LINE> if b >= 0: <NEW_LINE> <INDENT> b = "+%s" % b <NEW_LINE> <D... | Show a detailed player stats screen. | 625941c1656771135c3eb7e7 |
def portal_disconnect_all(self): <NEW_LINE> <INDENT> self._disconnect_all = True <NEW_LINE> for session in self.values: <NEW_LINE> <INDENT> session.disconnect() <NEW_LINE> <DEDENT> del self._disconnect_all | Called from Portal when Portal is closing down. All
Sessions should die. The Portal should not be informed. | 625941c15fdd1c0f98dc01ad |
def testRestartLastProcEmptyDb(self): <NEW_LINE> <INDENT> self.restart_with_empty_db('lastproc') | Verify we can start up in lastproc mode with an empty DB
| 625941c176e4537e8c3515eb |
def attrs(*args, **kwargs): <NEW_LINE> <INDENT> attributes = {} <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> if isinstance(arg, tuple): <NEW_LINE> <INDENT> if len(arg) == 2: <NEW_LINE> <INDENT> attributes[arg[0]] = arg[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('illegal argument') <NEW_LINE> <D... | Convert arguments into a string containing HTML attributes.
Positional arguments can be either strings or key-value tuples. Keyword
arguments map strings to values. Values may be strings, booleans, or
sequences of strings. | 625941c1f8510a7c17cf9676 |
@ffi.def_extern(name="pfx_table_callback") <NEW_LINE> def pfx_table_callback(pfx_record, object_handle): <NEW_LINE> <INDENT> callback, data = ffi.from_handle(object_handle) <NEW_LINE> callback(PFXRecord(pfx_record), data) | Wraps the pfx_table callback, used for iteration of the pfx table,
to hide cffi specifics | 625941c13eb6a72ae02ec452 |
def skipgram_batches(corpus_data, batch_size, num_skips, context_window): <NEW_LINE> <INDENT> buffer_index = 0 <NEW_LINE> assert batch_size % num_skips == 0 <NEW_LINE> assert num_skips <= 2 * context_window <NEW_LINE> input_words = np.ndarray(shape=(batch_size), dtype=np.int32) <NEW_LINE> context_words = np.ndarray(sha... | Generate training data mini-batches using the skip-gram method | 625941c1046cf37aa974ccc5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.