code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def p_binary_3(p): <NEW_LINE> <INDENT> p[0] = p[1] | binary_func : CONSTANT | 625941df76e4537e8c3519e4 |
def adjustPosition(self, eventPos): <NEW_LINE> <INDENT> prop = MaeMoneyProperties.instance() <NEW_LINE> newPos = QPoint(eventPos.x(), eventPos.y()) <NEW_LINE> if prop.isPortraitMode(): <NEW_LINE> <INDENT> offset = 50 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> offset = 72 <NEW_LINE> <DEDENT> newY = max(0, eventPos.y(... | @param eventPos - QPoint | 625941df0c0af96317bb8556 |
def count_conflicts(drones, conflict_radius,debug=False,limit=-1): <NEW_LINE> <INDENT> assert -1 <= limit <= len(drones), "Limit to number of drones should not exceed total number of drones available" <NEW_LINE> start_pre = time.time() <NEW_LINE> drones = [Drone(drone,drone_id) for drone_id,drone in enumerate(drones)] ... | Count the number of drones that are in conflict over an airspace
Logic:
1. Convert raw coordinate pairs into a list of handier Drone() objects
2. Split the big airfield into smaller overlapping sectors
3. Associate each drone with sectors it resides in
4. Examine each sector for drones within that are ... | 625941df656771135c3ebbe1 |
def _compress_data(self, in_size): <NEW_LINE> <INDENT> assert in_size <= 0xffffffff <NEW_LINE> zlengths = [] <NEW_LINE> crcval = zlib.crc32(b"") <NEW_LINE> need = in_size <NEW_LINE> while need > 0: <NEW_LINE> <INDENT> read_size = min(need, CHUNK_LENGTH) <NEW_LINE> chunk = self.input_buffer.read(read_size) <NEW_LINE> if... | Compresses the given number of input bytes to the output.
The output consists of:
1) The compressed data.
2) 4 bytes of CRC.
3) 4 bytes of file size. | 625941df711fe17d825426d2 |
def extend_markovtable(table, words): <NEW_LINE> <INDENT> word0 = word1 = word2 = START_SYMBOL <NEW_LINE> for word in itertools.ifilter(None, words + [END_SYMBOL]): <NEW_LINE> <INDENT> if not word0 in table: <NEW_LINE> <INDENT> table[word0] = {} <NEW_LINE> <DEDENT> if not word1 in table[word0]: <NEW_LINE> <INDENT> tabl... | マルコフ連鎖の辞書を拡張する。 | 625941df24f1403a92600ed2 |
def grant(self, permission, user): <NEW_LINE> <INDENT> fl = self.fl <NEW_LINE> fl.assert_('Local Rights' in fl.getBody(), 'Current page is not a rights tab.') <NEW_LINE> server_url = fl.server_url <NEW_LINE> state = fl.getLastJsfState() <NEW_LINE> fl.post(server_url + "/site/automation/UserGroup.Suggestion", Data('appl... | Grant perm to user. | 625941df9c8ee82313fbbae4 |
def binfmt_lookup(self): <NEW_LINE> <INDENT> binfmt_misc = '/proc/sys/fs/binfmt_misc' <NEW_LINE> if not isinstance(self.process, process): <NEW_LINE> <INDENT> log.debug("Not a process") <NEW_LINE> return '' <NEW_LINE> <DEDENT> if self.process._qemu: <NEW_LINE> <INDENT> return self.process._qemu <NEW_LINE> <DEDENT> if n... | Parses /proc/sys/fs/binfmt_misc to find the interpreter for a file | 625941df8a349b6b435e84e2 |
def format(self, record): <NEW_LINE> <INDENT> data = record.__dict__.copy() <NEW_LINE> if record.args: <NEW_LINE> <INDENT> record.msg = record.msg % record.args <NEW_LINE> <DEDENT> data.update( time=datetime.now(), message=record.msg, args=tuple(arg for arg in record.args) ) <NEW_LINE> if 'exc_info' in data and data['e... | 制定需要的日志信息 | 625941df3d592f4c4ed1d3d3 |
def setCallback(self, callback, current=None): <NEW_LINE> <INDENT> pass | Sets the single callback used by the ServiceFactory
to communicate with the client application. A default
callback is set by the omero::client object on
session creation which should suffice for most usage.
See the client object's documentation in each language
mapping for ways to use the callback. | 625941df07d97122c4178c02 |
def test_post_info(self): <NEW_LINE> <INDENT> url = reverse('admin_info') <NEW_LINE> data = {} <NEW_LINE> self.client.force_authenticate(user=self.admin) <NEW_LINE> response = self.client.post(url, data) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) | Tests POST request on info | 625941df50485f2cf553d10a |
def t_OP(self, t): <NEW_LINE> <INDENT> return t | =|in|like | 625941dfaad79263cf390db5 |
def test_200_barbican_identity_relation(self): <NEW_LINE> <INDENT> u.log.debug('Checking barbican to keystone identity-service ' 'relation data...') <NEW_LINE> unit = self.barbican_sentry <NEW_LINE> relation = ['identity-service', 'keystone:identity-service'] <NEW_LINE> barbican_ip = unit.relation(*relation)['private-a... | Verify the barbican to keystone identity-service relation data | 625941df3eb6a72ae02ec854 |
def ProcessMessage(self, message): <NEW_LINE> <INDENT> raise NotImplementedError() | Processes a message and returns it.
Returns None if there is no need to continue processing this message. | 625941df16aa5153ce3627e6 |
def build_tasks(self, **kwargs): <NEW_LINE> <INDENT> return list() | to implement
:param dict kwargs: tasks parameters (~=context)
:return: list of tasks
:rtype: list(kser.sequencing.task.Task) | 625941dfb57a9660fec33bf8 |
def dfs_paths(graph, start, goal): <NEW_LINE> <INDENT> stack = [(start, [start])] <NEW_LINE> while stack: <NEW_LINE> <INDENT> (vertex, path) = stack.pop() <NEW_LINE> for nxt in graph[vertex] - set(path): <NEW_LINE> <INDENT> if nxt == goal: <NEW_LINE> <INDENT> yield path + [nxt] <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND... | Depth-First Paths | 625941df67a9b606de4a8226 |
def islandPerimeter(self, grid): <NEW_LINE> <INDENT> def helper(grid, i, j): <NEW_LINE> <INDENT> res = 0 <NEW_LINE> if grid[i][j] == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if i == 0 or i - 1 >= 0 and grid[i - 1][j] == 0: <NEW_LINE> <INDENT> res += 1 <NEW_LINE> <DEDENT> if i == len(grid) - 1 or i + 1 < len(... | :type grid: List[List[int]]
:rtype: int | 625941df30dc7b7665901cd1 |
def cmd_retr(args): <NEW_LINE> <INDENT> pass | Retrieve a file.
| 625941dffb3f5b602dac3a06 |
def set_max_output_buffer(self, *args): <NEW_LINE> <INDENT> return _blocks_swig5.rms_cf_sptr_set_max_output_buffer(self, *args) | set_max_output_buffer(rms_cf_sptr self, long max_output_buffer)
set_max_output_buffer(rms_cf_sptr self, int port, long max_output_buffer) | 625941df71ff763f4b549a00 |
def setActionForIndex( self, new_action, index ): <NEW_LINE> <INDENT> self.setDirty() | Must be overridden by subclasses.
Set the action for this index to new_action, then either call this method
or call setDirty() directly to mark this file as edited.
e.g. self.actions[index] = new_action; self.setDirty() | 625941df66656f66f7cbc51b |
def loader(f: Callable[[str, dict], dict]) -> Any: <NEW_LINE> <INDENT> _loaders.insert(0, f) <NEW_LINE> return f | Register a site source content loader. | 625941df0fa83653e4657328 |
def test_expand_all_when_all_collapsed(self): <NEW_LINE> <INDENT> self.course_outline_page.visit() <NEW_LINE> self.course_outline_page.toggle_expand_collapse() <NEW_LINE> self.assertEquals(self.course_outline_page.expand_collapse_link_state, ExpandCollapseLinkState.EXPAND) <NEW_LINE> self.course_outline_page.toggle_exp... | Scenario: Expanding all sections when all sections are collapsed
Given I navigate to the outline page of a course with multiple sections
And I click the "Collapse All Sections" link
When I click the "Expand All Sections" link
Then I see the "Collapse All Sections" link
And all sections are expanded | 625941df236d856c2ad44b4d |
def watch_job(self, job_name, namespace): <NEW_LINE> <INDENT> watcher = Watch() <NEW_LINE> try: <NEW_LINE> <INDENT> for event in watcher.stream(self.batch.list_namespaced_job, namespace=namespace, label_selector=f'job-name={job_name}'): <NEW_LINE> <INDENT> succeed = event['object'].status.succeeded <NEW_LINE> active = ... | 监控job是否完成 bool | 625941dfd6c5a102081443bc |
def driveToPointGenerator(self, x, y, finalAngle=None, speed=1, robotPositionTolerance=0, robotAngleTolerance=0): <NEW_LINE> <INDENT> dist, aDiff = self._robotVectorToPoint(x, y) <NEW_LINE> for wheel in self.drive.wheels: <NEW_LINE> <INDENT> wheel.resetPosition() <NEW_LINE> <DEDENT> if dist < 0.1: <NEW_LINE> <INDENT> d... | A generator to drive to a location on the field while simultaneously
pointing the robot in a new direction. This will attempt to move the
robot so it reaches the target position at a given speed and ends by
rotating to the inputted angle.
This generator never exits, but yields ``True`` or ``False``
if the robot is clo... | 625941df099cdd3c635f0fc8 |
def merge_two_box(box_a, box_b): <NEW_LINE> <INDENT> x1_min, y1_min, x1_max, y1_max = box_a <NEW_LINE> x2_min, y2_min, x2_max, y2_max = box_b <NEW_LINE> nx_min, ny_min = min(x1_min, x2_min), min(y1_min, y2_min) <NEW_LINE> nx_max, ny_max = max(x1_max, x2_max), max(y1_max, y2_max) <NEW_LINE> tmp_box = [nx_min, ny_min, nx... | 合并两个box | 625941df097d151d1a2231c6 |
def img_disp(name,img): <NEW_LINE> <INDENT> cv2.imshow(name,img.astype(int)/255.0) <NEW_LINE> cv2.waitKey() | Displays passed image in a window with the title as passed.
Image should have pixel values within [0,255] | 625941dfcad5886f8bd27348 |
def close(self): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> for sub in list(self.subscribers) + self._hooks: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sub.setsockopt(LINGER, 1) <NEW_LINE> sub.close() <NEW_LINE> <DEDENT> except ZMQError: <NEW_LINE> <INDENT> pass | Close the subscriber: stop it and close the local subscribers.
| 625941df851cf427c661a87b |
def resolve(self, name: str, default: object = _undefined) -> Any: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.scope[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> if default == _undefined: <NEW_LINE> <INDENT> return self.env.undefined(name) <NEW_LINE> <DEDENT> return default | Return the object/value at `name` in the current scope.
This is like `get`, but does a single, top-level lookup rather than a
chained lookup from a sequence of keys. | 625941dfd8ef3951e32438ad |
def get_polrot(isys, osys, spos, site): <NEW_LINE> <INDENT> return coordinates.transform(isys, osys, spos, site=site, pol=True)[2] | Get the angle by which the polarization was rotated when going from isys to osys. | 625941df10dbd63aa1bd2f11 |
def download(url, path, overwrite=False, sizecompare=False): <NEW_LINE> <INDENT> if os.path.isfile(path) and not overwrite: <NEW_LINE> <INDENT> if (sizecompare): <NEW_LINE> <INDENT> fileSize = os.path.getsize(path) <NEW_LINE> resHead = requests.head(url) <NEW_LINE> resGet = requests.get(url,stream=True) <NEW_LINE> if '... | Downloads the file from the internet.
Set the input options correctly to overwrite or do the size comparison
Parameters
----------
url : str
Operator name, such as Convolution, Connected, etc
path : str
List of input symbols.
overwrite : dict
Dict of operator attributes
sizecompare : dict
Dict of opera... | 625941dfd486a94d0b98e4b6 |
def timer(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper_decorator(*args, **kwargs): <NEW_LINE> <INDENT> start_time = time.perf_counter() <NEW_LINE> value = func() <NEW_LINE> end_time = time.perf_counter() <NEW_LINE> run_time = end_time - start_time <NEW_LINE> print(f"Finished {func.__name__!r... | Loging function run time. | 625941df097d151d1a2231c7 |
def test_serializer(self) -> None: <NEW_LINE> <INDENT> reference = json.loads(self.json_configuration) <NEW_LINE> for key, value in self.dict_configuration.items(): <NEW_LINE> <INDENT> serialized = self.instance.serializer(value) <NEW_LINE> self.assertEqual(reference[key], serialized) | Test all :attr:`dict_configuration` values serialiazed are equal to expected values
defined in :attr:`json_configuration`. | 625941dfac7a0e7691ed4435 |
def test_cd_home_dir(): <NEW_LINE> <INDENT> homepath = "~/somepath" <NEW_LINE> with cd(homepath): <NEW_LINE> <INDENT> eq_(env.cwd, homepath) | cd() should work with home directories | 625941df3317a56b86939fc0 |
def populate_location_with_postcodes_from_people(cursor_connection): <NEW_LINE> <INDENT> cursor_connection[0].execute("SELECT postcode FROM people ") <NEW_LINE> for row in cursor_connection[0].fetchall(): <NEW_LINE> <INDENT> results = check_if_postcode_exists_in_location(row,cursor_connection) <NEW_LINE> if len(results... | This function has one argument cursor_connection and has no output. It checks if the postcodes from
people table are already in the location table and if not, it retrieves the coordinates and inserts
both into the location table. | 625941df5fc7496912cc3ced |
def click(self, locator="None", t='1.0'): <NEW_LINE> <INDENT> self.sleep(t) <NEW_LINE> el = self.__find_element(locator) <NEW_LINE> if el is not None: <NEW_LINE> <INDENT> el.click() <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | 点击元素
:param locator: 元素定位表达式
:param t: 默认点击之前等待1.0秒
:return: | 625941df6fb2d068a760f411 |
def dd_as_py(dd): <NEW_LINE> <INDENT> if not isinstance(dd, IDataDescriptor): <NEW_LINE> <INDENT> raise TypeError('expected DataDescriptor, got %r' % type(dd)) <NEW_LINE> <DEDENT> if isinstance(dd, BLZDataDescriptor): <NEW_LINE> <INDENT> return [dd_as_py(child_dd) for child_dd in dd] <NEW_LINE> <DEDENT> if dd.capabilit... | Converts the data in a data descriptor into Python
types. This uses the data_descriptor iteration methods,
so is not expected to be fast. Its main initial purpose
is to assist with writing unit tests. | 625941dfff9c53063f47c561 |
def get_cli_event_returns( self, jid, minions, timeout=None, tgt='*', tgt_type='glob', verbose=False, progress=False, show_timeout=False, show_jid=False, **kwargs): <NEW_LINE> <INDENT> log.trace('func get_cli_event_returns()') <NEW_LINE> if verbose: <NEW_LINE> <INDENT> msg = 'Executing job with jid {0}'.format(jid) <NE... | Get the returns for the command line interface via the event system | 625941df23849d37ff7b33fc |
def coalesce(*cols): <NEW_LINE> <INDENT> sc = SparkContext._active_spark_context <NEW_LINE> jc = sc._jvm.functions.coalesce(_to_seq(sc, cols, _to_java_column)) <NEW_LINE> return Column(jc) | Returns the first column that is not null.
>>> cDf = sqlContext.createDataFrame([(None, None), (1, None), (None, 2)], ("a", "b"))
>>> cDf.show()
+----+----+
| a| b|
+----+----+
|null|null|
| 1|null|
|null| 2|
+----+----+
>>> cDf.select(coalesce(cDf["a"], cDf["b"])).show()
+-------------+
|Coalesce(a,b)|
+----... | 625941dfadb09d7d5db6cafd |
def DescribePersonTrace(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("DescribePersonTrace", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.DescribePersonTraceRe... | 输出开始时间到结束时间段内的进出场数据。
:param request: Request instance for DescribePersonTrace.
:type request: :class:`tencentcloud.youmall.v20180228.models.DescribePersonTraceRequest`
:rtype: :class:`tencentcloud.youmall.v20180228.models.DescribePersonTraceResponse` | 625941df21bff66bcd684cbe |
def validateTransaction(trans): <NEW_LINE> <INDENT> errors = "" <NEW_LINE> if trans["day"]<1 or trans["day"]>31: <NEW_LINE> <INDENT> errors +="Invalid day!!! It must be an integer between 1 and 31\n" <NEW_LINE> <DEDENT> if trans["amount"]<0: <NEW_LINE> <INDENT> errors += "Invalid amount!!! It must be a positive float v... | Validates transaction, rasing errors if the user doesn't give proper parameters.
I: trans | 625941df21a7993f00bc8065 |
def invcost_factor(dep_prd, interest): <NEW_LINE> <INDENT> return ((1 + interest) ** dep_prd * interest / ((1 + interest) ** dep_prd - 1)) | Investment cost factor formula.
Evaluates the factor multiplied to the invest costs
for depreciation duration and interest rate.
Args:
dep_prd: depreciation period (years)
interest: interest rate (e.g. 0.06 means 6 %) | 625941dfd4950a0f3b08c6ba |
def __del__(self): <NEW_LINE> <INDENT> self.stopRecording() | Destructor that stops the active recording and terminates the thread. | 625941df7d847024c06be62e |
def clone(self): <NEW_LINE> <INDENT> return copy.deepcopy(self) | Clone the object. | 625941df711fe17d825426d3 |
def intersect_with(self, rect): <NEW_LINE> <INDENT> if not isinstance(rect, Rectangle): <NEW_LINE> <INDENT> raise ValueError('Cannot compute intersection if "rect" is not a Rectangle') <NEW_LINE> <DEDENT> dx = min(self.x_max, rect.x_max) - max(self.x_min, rect.x_min) <NEW_LINE> dy = min(self.y_max, rect.y_max) - max(se... | Compute the intersection between this instance and another Rectangle.
Parameters
----------
rect : Rectangle
The instance of the second Rectangle.
Returns
-------
intersection_area : float
Area of intersection between the two rectangles expressed in number of pixels. | 625941df30bbd722463cc137 |
def __init__(self, mu, sigma, validate_args=False, allow_nan_stats=True, name="Normal"): <NEW_LINE> <INDENT> parameters = locals() <NEW_LINE> parameters.pop("self") <NEW_LINE> with ops.name_scope(name, values=[mu, sigma]) as ns: <NEW_LINE> <INDENT> with ops.control_dependencies([check_ops.assert_positive(sigma)] if val... | Construct Normal distributions with mean and stddev `mu` and `sigma`.
The parameters `mu` and `sigma` must be shaped in a way that supports
broadcasting (e.g. `mu + sigma` is a valid operation).
Args:
mu: Floating point tensor, the means of the distribution(s).
sigma: Floating point tensor, the stddevs of the dis... | 625941df187af65679ca548f |
def reporTokenStatus(self, clientSign, statusInfo, failToken, getTokenSum): <NEW_LINE> <INDENT> pass | Parameters:
- clientSign
- statusInfo
- failToken
- getTokenSum | 625941df6aa9bd52df037115 |
def __init__(__self__, __name__, __opts__=None, domain_name=None, domain_name_servers=None, netbios_name_servers=None, netbios_node_type=None, ntp_servers=None, tags=None): <NEW_LINE> <INDENT> if not __name__: <NEW_LINE> <INDENT> raise TypeError('Missing resource name argument (for URN creation)') <NEW_LINE> <DEDENT> i... | Create a VpcDhcpOptions resource with the given unique name, props, and options. | 625941df8a43f66fc4b543d1 |
def downloadSongs(): <NEW_LINE> <INDENT> for index,song in enumerate(amiripper.songUrls): <NEW_LINE> <INDENT> r = requests.get(song, stream=True) <NEW_LINE> localFilename = song.split('/')[-1].replace("%20", " ") <NEW_LINE> with open(localFilename, 'wb') as f: <NEW_LINE> <INDENT> for chunk in r.iter_content(chunk_size=... | Downloads a song and saves it with the correct filename | 625941df7b25080760e397c7 |
def __virtual__(): <NEW_LINE> <INDENT> if not __opts__.get('stormpath', {}).get('apiid', None): <NEW_LINE> <INDENT> return (False, 'The stormpath execution module failed to load: requires the stormpath:apiid config option to be set.') <NEW_LINE> <DEDENT> if not __opts__.get('stormpath', {}).get('apikey', None): <NEW_LI... | Only load the module if apache is installed | 625941df3617ad0b5ed68266 |
def generate_json(sourced_id, title, description, assign_date, due_date, class_sourced_id, category, result_value_max,result_value_min): <NEW_LINE> <INDENT> if result_value_max is None: <NEW_LINE> <INDENT> result_value_max = 0.0 <NEW_LINE> <DEDENT> if result_value_min is None: <NEW_LINE> <INDENT> result_value_min = 0.0... | Generate a JSON formatted value ready to be sent to OpenLRW
:param sourced_id:
:param title:
:param description:
:param assign_date:
:param due_date:
:param class_sourced_id:
:param category:
:param result_value_max:
:param result_value_min
:return: | 625941dff548e778e58cd8ee |
def input_overload(prompt: str = None) -> str: <NEW_LINE> <INDENT> global arepl_input_iterator <NEW_LINE> if prompt is not None: <NEW_LINE> <INDENT> print(prompt) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if arepl_input_iterator is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return next(arepl_input_iterat... | AREPL requires standard_input to be hardcoded, like so: standard_input = 'hello world'; print(input()). You can also hardcode standard_input as a generator or list.
Keyword Arguments:
prompt {str} -- (default: {None})
Raises:
StopIteration -- if there is no more input | 625941dfe1aae11d1e74a02a |
def deserialize(self, data): <NEW_LINE> <INDENT> s = data.index('[') + 1 <NEW_LINE> e = data.index(']', s) <NEW_LINE> nodes = list(map(lambda x: TreeNode(int(x)) if x != 'null' else None, data[s:e].split(','))) <NEW_LINE> i, j, k = 0, 1, len(nodes) <NEW_LINE> while i < k: <NEW_LINE> <INDENT> n = nodes[i] <NEW_LINE> if ... | Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode | 625941dfa8370b7717052c0d |
def __init__(self, text, shift): <NEW_LINE> <INDENT> self.message_text = text <NEW_LINE> self.valid_words = load_words(WORDLIST_FILENAME) <NEW_LINE> self.shift = shift <NEW_LINE> self.encrypting_dict = Message.build_shift_dict(self,shift) <NEW_LINE> self.message_text_encrypted = Message.apply_shift(self,shift) | Initializes a PlaintextMessage object
text (string): the message's text
shift (integer): the shift associated with this message
A PlaintextMessage object inherits from Message and has five attributes:
self.message_text (string, determined by input text)
self.valid_words (list, determined using helper ... | 625941df32920d7e50b28542 |
def validate_and_normalize(self, obj, value): <NEW_LINE> <INDENT> return FrequencyProperty.validate_and_normalize(self, obj, FloatRegister.validate_and_normalize(self, obj, value)) | Same as FloatRegister, except the value should be positive. | 625941df167d2b6e31218f04 |
def system_slash(string): <NEW_LINE> <INDENT> if sys.platform == "win32" or sys.platform == "win64" or sys.platform == "cygwin": <NEW_LINE> <INDENT> return string.replace("/", "\\") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return string.replace("\\", "/") | Change / or \ depend on the OS | 625941df435de62698dfdfbd |
def test_faster_task_to_recv_is_cancelled_by_slower( arb_addr, start_method, ): <NEW_LINE> <INDENT> async def main(): <NEW_LINE> <INDENT> sequence = list(range(1000)) <NEW_LINE> async with open_sequence_streamer( sequence, arb_addr, start_method, ) as stream: <NEW_LINE> <INDENT> async with trio.open_nursery() as n: <NE... | Ensure that if a faster task consuming from a stream is cancelled
the slower task can continue to receive all expected values. | 625941dfac7a0e7691ed4436 |
def getopt(args: List[str], shortopts: str, longopts: Iterable[str] = []) -> Tuple[List[Tuple[str, str]], List[str]]: <NEW_LINE> <INDENT> opts = List[Tuple[str, str]]() <NEW_LINE> if isinstance(longopts, str): <NEW_LINE> <INDENT> longopts = [longopts] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> longopts = list(long... | getopt(args, options[, long_options]) -> opts, args
Parses command line options and parameter list. args is the
argument list to be parsed, without the leading reference to the
running program. Typically, this means "sys.argv[1:]". shortopts
is the string of option letters that the script wants to
recognize, with o... | 625941df96565a6dacc8fa3a |
def create_eq_filter(): <NEW_LINE> <INDENT> def eq_filter(raw_audio): <NEW_LINE> <INDENT> return signal.lfilter(FILTER_B, FILTER_A, raw_audio) <NEW_LINE> <DEDENT> return eq_filter | Return a function that applies equalization to a numpy array. | 625941dfbf627c535bc1353f |
def register_prefix(self): <NEW_LINE> <INDENT> self._register_prefix(self.filename) | Register directory prefixes where remove() is allowed | 625941df38b623060ff0b15d |
def ascend(cNode, nodeSet, rootSet): <NEW_LINE> <INDENT> for _p in cNode.oNode.is_a: <NEW_LINE> <INDENT> if str(_p).startswith('obo.BFO_0000051'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> try : <NEW_LINE> <INDENT> p = _p.value <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> p = _p <NEW_LINE> <DED... | Recursively look for the 1st ascendant node w/out parent
| 625941df99fddb7c1c9de6ff |
def test_get_flat_product_parameters_using_get(self): <NEW_LINE> <INDENT> pass | Test case for get_flat_product_parameters_using_get
Get product parameters available in given category # noqa: E501 | 625941df30c21e258bdfa80f |
def minDistance(self, word1, word2): <NEW_LINE> <INDENT> m = len(word1) + 1 <NEW_LINE> n = len(word2) + 1 <NEW_LINE> dp = [([0]*m) for _ in range(n)] <NEW_LINE> for i in range(1, n): <NEW_LINE> <INDENT> for j in range(1, m): <NEW_LINE> <INDENT> if word2[i-1] == word1[j-1]: <NEW_LINE> <INDENT> dp[i][j] = dp[i-1][j-1] + ... | :type word1: str
:type word2: str
:rtype: int | 625941dfb545ff76a8914185 |
def __call__(self, values): <NEW_LINE> <INDENT> return self.substitute(values) | An alternative way to call the substitute() method.
| 625941dfbe7bc26dc91cd969 |
def assertSuccessful(self, test, result): <NEW_LINE> <INDENT> self.assertEqual(result.successes, 1) <NEW_LINE> self.assertEqual(result.failures, []) <NEW_LINE> self.assertEqual(result.errors, []) <NEW_LINE> self.assertEqual(result.expectedFailures, []) <NEW_LINE> self.assertEqual(result.unexpectedSuccesses, []) <NEW_LI... | Utility function -- assert there is one success and the state is
plausable | 625941dfc4546d3d9de72da6 |
def mutate(x, sig, alph, lamb, n, lims): <NEW_LINE> <INDENT> tau = 1/(2*(n)**0.5)**0.5 <NEW_LINE> tau_dash = 1/(2*n)**0.5 <NEW_LINE> beta = 0.0873 <NEW_LINE> sig_mut = sig * np.exp(tau_dash*np.random.randn(lamb, 1) + tau*np.random.randn(lamb, n)) <NEW_LINE> alph_mut = alph + beta*np.random.randn(lamb, n, n) <NEW_LINE> ... | ARGUMENTS
x : generation locations
sig : generation standard deviations
alph : generation rotation angles
lamb : number of offspring created in each iteration
n : number of control variables
lims : bounds of the optimisation function in form [min, max]
OUTPUTS
x_mut : mutated gener... | 625941df63d6d428bbe44860 |
def notifications(self): <NEW_LINE> <INDENT> n = diaspy.notifications.Notifications(self.connection) <NEW_LINE> return n.last() | Return last notifications from user | 625941df60cbc95b062c68b3 |
def test_flatpage_admin_form_url_validation(self): <NEW_LINE> <INDENT> self.assertTrue(FlatpageForm(data=dict(url='/new_flatpage/', **self.form_data)).is_valid()) <NEW_LINE> self.assertTrue(FlatpageForm(data=dict(url='/some.special~chars/', **self.form_data)).is_valid()) <NEW_LINE> self.assertTrue(FlatpageForm(data=dic... | The flatpage admin form validates correctly validates urls | 625941df97e22403b379d30b |
def get_forces(system,distances,directions): <NEW_LINE> <INDENT> forcematrix = np.zeros(shape=(N_PARTICLES,2)) <NEW_LINE> for i in range(N_PARTICLES): <NEW_LINE> <INDENT> f = [0.0,0.0] <NEW_LINE> a,b,c,d = [],[],[],[] <NEW_LINE> force_self, force_boundary,force_repulsion,fselfandboundary = (f,f,f,f) <NEW_LINE> force_se... | Calculates the net force on each particle due to its self propulsion,
the boundary condition and the repulsion due to other particles | 625941dfe64d504609d74baf |
def delete_node(filter: str = None, configuration: Configuration = None, secrets: Secrets = None): <NEW_LINE> <INDENT> logger.debug( "Start delete_node: configuration='{}', filter='{}'".format( configuration, filter)) <NEW_LINE> query = node_resource_group_query(filter, configuration, secrets) <NEW_LINE> return delete_... | Delete a node at random from a managed Azure Kubernetes Service.
**Be aware**: Deleting a node is an invasive action. You will not be able
to recover the node once you deleted it.
Parameters
----------
filter : str
Filter the managed AKS. If the filter is omitted all AKS in
the subscription will be selected a... | 625941df4527f215b584c7c3 |
def execute(self, text, *multiparams, **params): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> statement = sqlalchemy.text(text).bindparams(*multiparams, **params) <NEW_LINE> result = self.engine.execute(str(statement.compile(compile_kwargs={"literal_binds": True}))) <NEW_LINE> if result.returns_rows: <NEW_LINE> <INDENT... | Execute statement | 625941df50812a4eaa59c68e |
def isvalidcolor(intcolor): <NEW_LINE> <INDENT> return isinstance(intcolor, int) and 0 <= intcolor <= 255 | Is a valid color?
Return: True if the color is an int(0,255) | 625941dfbde94217f368315d |
def init_default_thread(self): <NEW_LINE> <INDENT> tg_klass = self.get_class("java/lang/ThreadGroup") <NEW_LINE> t_klass = self.get_class("java/lang/Thread") <NEW_LINE> tg = tg_klass.get_instance(self) <NEW_LINE> t = t_klass.get_instance(self) <NEW_LINE> tg.fields["name"] = self.make_heap_string("system") <NEW_LINE> tg... | Create initial thread group and thread.
Both are java's objects | 625941df4e696a04525c97bd |
def write(self, value): <NEW_LINE> <INDENT> row, col = self._cursor_pos <NEW_LINE> if self._content[row][col] != value: <NEW_LINE> <INDENT> self._send(value, RS_DATA) <NEW_LINE> self._content[row][col] = value <NEW_LINE> unchanged = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> unchanged = True <NEW_LINE> <DEDENT... | Write a raw byte to the LCD. | 625941df15fb5d323cde0e84 |
def check_proxy(ip,port): <NEW_LINE> <INDENT> url = 'http://api.proxyipchecker.com/pchk.php' <NEW_LINE> data = "ip={}&port={}".format(ip, port).encode() <NEW_LINE> req = request.Request(url, data=data, method='POST') <NEW_LINE> try: t = request.urlopen(req).readall().decode() <NEW_LINE> except: return False <NEW_LINE> ... | Проверяет доступность прокси с помощью API сайта proxyipchecker.com.
Часто результат положительный | 625941df9f2886367277abfb |
def xuat_ten_buoc(self): <NEW_LINE> <INDENT> if self.loi_giai.lop_cuoi: <NEW_LINE> <INDENT> return 'Bài giải' <NEW_LINE> <DEDENT> if self.tien_trinh == []: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> ten_buoc = 'Bước ' <NEW_LINE> for lop in self.tien_trinh: <NEW_LINE> <INDENT> ten_buoc += str(lop + 1) + '.' <NEW_... | Xuat ten buoc hien tai
:return str: | 625941df55399d3f05588a26 |
def TransDecoderGTFToAttributes(tdir, tag): <NEW_LINE> <INDENT> gtf = reader(open("{0}/NCR.fna.transdecoder.gff3".format(tdir)), delimiter="\t") <NEW_LINE> attributes = [] <NEW_LINE> locs = [] <NEW_LINE> exon_count = 0 <NEW_LINE> contig_id = "" <NEW_LINE> gene_id = "" <NEW_LINE> annotations = "" <NEW_LINE> cregex = r"(... | Extract genomic attributes information from TransDecoder GTF file. A bit different
from our GeneMark GTF parser in that TransDecoder gene sections are seperated in
the latter GTF file by newline, which makes some things easier (and some things
harder).
Note: sometimes TransDecoder will add comment lines into a GTF fil... | 625941df3346ee7daa2b30de |
def binaryTreePaths(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> path = [] <NEW_LINE> paths = [] <NEW_LINE> self.btreeHelper(root, path, paths) <NEW_LINE> return paths | :type root: TreeNode
:rtype: List[str] | 625941df5166f23b2e1a54c9 |
def describe_city(name, country = 'america'): <NEW_LINE> <INDENT> print(name.title() + " is in " + country.title()) | Display city name and their country | 625941dfbe8e80087fb20fae |
def distinct(self, column): <NEW_LINE> <INDENT> return list(self.data[column].drop_duplicates()) | Get distinct values from column gaven
:param column: str column name
:return: list [str] | 625941df32920d7e50b28543 |
def __init__(self, fs=None, **kwargs): <NEW_LINE> <INDENT> self.st_mtime = 0 <NEW_LINE> self.st_size = 0 <NEW_LINE> for attr in STAT_ATTRS: <NEW_LINE> <INDENT> if attr in kwargs: <NEW_LINE> <INDENT> val = kwargs[attr] <NEW_LINE> setattr(self, attr, int(val)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(self, a... | Init function | 625941e026068e7796caf054 |
def _rename_schema(self, schema): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._schema_new_names[schema] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> new_name = schema <NEW_LINE> for pattern, repl in self.schema_rename.items(): <NEW_LINE> <INDENT> new_name, subs_made = re.subn(pattern, repl, sch... | Rename a schema name and return new name
Args:
schema (str): schema nae
Returns:
str | 625941e07c178a314d6ef7d5 |
def _get_sim_files(self, id_task): <NEW_LINE> <INDENT> dir_var = self._out_dir <NEW_LINE> compress = '.gz' if self._compress else '' <NEW_LINE> return { 'info_csv': os.path.join( dir_var, self._data_folder, 'info_{0}.csv{1}'.format( id_task, compress)), 'messages_mpf' : os.path.join( dir_var, self._data_folder, 'messag... | This creates sim file names for a given id_task | 625941e0b57a9660fec33bf9 |
def _organize_states_for_delete(base_mapper, states, uowtransaction): <NEW_LINE> <INDENT> for state, dict_, mapper, connection in _connections_for_states( base_mapper, uowtransaction, states): <NEW_LINE> <INDENT> mapper.dispatch.before_delete(mapper, connection, state) <NEW_LINE> if mapper.version_id_col is not None: <... | Make an initial pass across a set of states for DELETE.
This includes calling out before_delete and obtaining
key information for each state including its dictionary,
mapper, the connection to use for the execution per state. | 625941e0090684286d50f05b |
def add_client_columns(data_set): <NEW_LINE> <INDENT> client_ids = {} <NEW_LINE> for row in data_set: <NEW_LINE> <INDENT> client_ids[row[1]] = True <NEW_LINE> <DEDENT> for i in xrange(len(data_set)): <NEW_LINE> <INDENT> data_set[i] = data_set[i] + [1 if client == data_set[i][1] else 0 for client in list(client_ids)] <N... | Given a data set, add a column for each unique user and set it to 1 for that user's row(s), 0 otherwise.
particular user. | 625941e0379a373c97cfaeb7 |
@api_view(['GET']) <NEW_LINE> @throttle_classes([BurstRateThrottle, SustainedRateThrottle]) <NEW_LINE> def generate_miro_subject_id(request): <NEW_LINE> <INDENT> id_input = MiroSubjectIdInput(data=request.query_params) <NEW_LINE> if not id_input.is_valid(): <NEW_LINE> <INDENT> return Response( id_input.errors, status=s... | Generate a Miro Subject ID based on Study ID and Study Subject ID | 625941e01b99ca400220ae23 |
def admin_duid(self, client: Client) -> str: <NEW_LINE> <INDENT> return client.duid_ll or client.duid | Show the DUID as MAC address if possible
:param client: The client object
:return: The MAC address embedded in the DUID, otherwise the DUID itself | 625941e044b2445a33932404 |
def wav_to_spectro(infolder='../speech_corpora/TIMIT/', outfolder='../Spectrograms/', max_number=None): <NEW_LINE> <INDENT> infilelist = listdir(infolder) <NEW_LINE> count = 0 <NEW_LINE> for infilename in infilelist: <NEW_LINE> <INDENT> if not infilename.lower().endswith('.wav'): <NEW_LINE> <INDENT> continue <NEW_LINE>... | Takes all the .wav files in the given folder and makes files containing
spectrograms according to the parameters in Carlson et al.
Stops after max_number spectrograms if specified. | 625941e08a349b6b435e84e3 |
def un_link_users(self, group_id=None, linked_user_ids=None): <NEW_LINE> <INDENT> params = {} <NEW_LINE> if group_id is not None: params['groupID'] = group_id <NEW_LINE> if linked_user_ids is not None: params['linkedUserIDs'] = linked_user_ids <NEW_LINE> data = self.session.put(self.api_url()+'/unLinkUsers', params) | The ``unLinkUsers`` action.
:param group_id: groupID (type: ``string``)
:param linked_user_ids: linkedUserIDs (type: ``string[]``) | 625941e0d58c6744b4257fcf |
def parse(contents): <NEW_LINE> <INDENT> contents = json.loads(contents) if isinstance(contents, str) else contents <NEW_LINE> return _parse(contents) | Parse the YINsolidated model from JSON or a string. | 625941e07cff6e4e81117cf6 |
def find_all_devices(userId): <NEW_LINE> <INDENT> return 'do some magic!' | Get all user registered devices
Get all user registered devices # noqa: E501
:param userId: user id
:type userId: str
:rtype: List[DeviceArray] | 625941e03c8af77a43ae3b14 |
def __init__(self, size=None, position=None, line_width=None, colour=None, anti_aliasing=None, cross_size=None): <NEW_LINE> <INDENT> if cross_size is not None and size is None: <NEW_LINE> <INDENT> raise DeprecationWarning("Property cross_size is obsolete. Please use size") <NEW_LINE> <DEDENT> if position is None: <NEW_... | Create a fixation cross.
Parameters
----------
size : (int, int), optional
size of the cross
position : (int, int), optional
position of the stimulus
line_width : int optional
width of the lines
colour : (int, int, int), optional
colour of the cross
anti_aliasing : int, optional
anti aliasing para... | 625941e073bcbd0ca4b2c3e6 |
def get_closest_waypoint(self, pose): <NEW_LINE> <INDENT> if self.waypints_tree: <NEW_LINE> <INDENT> return self.waypoints_tree.query([x,y], 1)[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 | Identifies the closest path waypoint to the given position
https://en.wikipedia.org/wiki/Closest_pair_of_points_problem
Args:
pose (Pose): position to match a waypoint to
Returns:
int: index of the closest waypoint in self.waypoints | 625941e031939e2706e4d1d6 |
def letterCombinations(self, digits): <NEW_LINE> <INDENT> if not digits: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> type_dic = { "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz" } <NEW_LINE> res = [""] <NEW_LINE> for d in digits: <NEW_LINE> <INDENT> temp = [] <NEW_... | :type digits: str
:rtype: List[str] | 625941e063b5f9789fde7457 |
def Image(self): <NEW_LINE> <INDENT> return QUrl() | static QUrl Soprano.Vocabulary.Xesam.Image() | 625941e0507cdc57c6307053 |
def _valid_indicator(feature_grid_y, feature_grid_x, true_feature_shapes): <NEW_LINE> <INDENT> height = tf.cast(true_feature_shapes[:, :, 0:1], dtype=feature_grid_y.dtype) <NEW_LINE> width = tf.cast(true_feature_shapes[:, :, 1:2], dtype=feature_grid_x.dtype) <NEW_LINE> valid_indicator = tf.logical_and( tf.expand_dims( ... | Computes a indicator vector for valid indices.
Computes an indicator vector which is true for points on feature map and
false for points off feature map.
Args:
feature_grid_y: An int32 tensor of shape [batch, num_boxes, size_y]
containing y coordinate vector.
feature_grid_x: An int32 tensor of shape [batch, n... | 625941e0a4f1c619b28b03a2 |
def __str__(self): <NEW_LINE> <INDENT> d = {} <NEW_LINE> d["structSeqStructSimpleBool"] = self.structSeqStructSimpleBool <NEW_LINE> d["structSeqStructSimpleSeqBool"] = self.structSeqStructSimpleSeqBool <NEW_LINE> return str(d) | Return a string representation of this structure | 625941e04f88993c3716c3d5 |
def _window_name(arg=None): <NEW_LINE> <INDENT> return ['-name', str(arg)] if arg is not None else [] | Supported by some patches.
Args:
arg (str): defines window name for dmenu. Defaults to "dmenu".
Returns:
list: command line arguments to use with dmenu
Raises:
ValueError: Same as ``str(arg)`` if ``arg`` can't be casted.
Examples:
>>> _window_name()
[]
>>> _window_name('some window name')
... | 625941e0460517430c3944ed |
def main(): <NEW_LINE> <INDENT> model = moose.loadModel( os.path.join( cwd, '../genesis/reaction.g' ), '/model' ) <NEW_LINE> written = mooseWriteKkit('/model', 'testsave.g') <NEW_LINE> print( written ) | This example illustrates loading a kinetic model defined in Genesis format
into Moose using "loadModel" function and using "saveModel" function one can
save the model back to Genesis format
| 625941e03eb6a72ae02ec856 |
def start(self, output_dir, source_dir): <NEW_LINE> <INDENT> pass | Conversion is about to start.
:param output_dir: Base output directory
:type output_dir: str
:param source_dir: Content source directory
:type source_dir: str | 625941e0d486a94d0b98e4b7 |
def walkNodes(self, topDown=True, depth=0): <NEW_LINE> <INDENT> if topDown: <NEW_LINE> <INDENT> yield self, depth <NEW_LINE> <DEDENT> if hasattr(self, "passBranch"): <NEW_LINE> <INDENT> for n, d in self.passBranch.walkNodes(topDown, depth + 1): <NEW_LINE> <INDENT> yield n, d <NEW_LINE> <DEDENT> <DEDENT> if hasattr(self... | Return a generator that walks over all nodes in the tree, yielding a 2-tuple of node and depth.
:type topDown: bool
:param topDown: if ``True``, do a depth-first walk from root to leaf; if ``False``, do a depth-first walk from leaf to root
:type depth: int
:param depth: starting value for reporting depth
:rtype: gener... | 625941e0004d5f362079a6a2 |
def index(self, val): <NEW_LINE> <INDENT> return self.filters.index(val) | index - Get the index of the first match of a given filter
@param val <FilterType obj> - Filter to search for
@return <int> - First index of given filter | 625941e0b57a9660fec33bfa |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.