code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def sortedListToBST(self, head): <NEW_LINE> <INDENT> if head is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if head.next is None: <NEW_LINE> <INDENT> return TreeNode(head.val) <NEW_LINE> <DEDENT> slow, fast = head, head.next.next <NEW_LINE> while fast and fast.next: <NEW_LINE> <INDENT> slow = slow.next <N... | :type head: ListNode
:rtype: TreeNode | 625941d18e05c05ec3eea507 |
def plot_calibration_curve(predicted, observed): <NEW_LINE> <INDENT> slope, intercept = np.polyfit(predicted, observed, deg=1) <NEW_LINE> plt.plot(predicted, observed, "o", color="black") <NEW_LINE> plt.plot( np.linspace(0, 1), np.linspace(0, 1) * slope + intercept, "--", label=f"Slope: {slope:.2f}, Intercept: {interce... | Plot calibration curve. | 625941d191af0d3eaac9bbab |
def warshall(adjlist): <NEW_LINE> <INDENT> nodeSize = adjlist.node_cardinality() <NEW_LINE> matrix = [[None]*nodeSize]*nodeSize <NEW_LINE> tmpMatrix = copy.deepcopy(adjlist.adjacency_matrix()) <NEW_LINE> for k in range(nodeSize): <NEW_LINE> <INDENT> for i in range(nodeSize): <NEW_LINE> <INDENT> if k == i: <NEW_LINE> <I... | Returns an NxN matrix that contains the result of running Warshall's
algorithm.
Pre: adjlist is not empty. | 625941d156b00c62f0f147eb |
def _update_attributes(self, json_dict): <NEW_LINE> <INDENT> redundancy_dicts = json_dict.pop('redundancy', []) <NEW_LINE> redundancy_list = [] <NEW_LINE> for _dict in redundancy_dicts: <NEW_LINE> <INDENT> redundancy_list.append(Redundancy(_dict)) <NEW_LINE> <DEDENT> setattr(self, 'redundancy', redundancy_list) <NEW_LI... | Construct object from API response dict. | 625941d1091ae356686670ef |
def _rename_cols(df): <NEW_LINE> <INDENT> oldcols = df.columns <NEW_LINE> newcols = [re.sub('[\[/\]]', '', item.lower()) for item in oldcols] <NEW_LINE> colname_map = {} <NEW_LINE> for oldcol, newcol in zip(oldcols, newcols): <NEW_LINE> <INDENT> colname_map[oldcol] = newcol <NEW_LINE> <DEDENT> df.rename(columns=colname... | Rename columns of dataframe for easier manipulation.
Args:
df (DataFrame): Dataframe of abundances.
Returns:
DataFrame | 625941d10fa83653e465714c |
def test_iterable(): <NEW_LINE> <INDENT> assert plist(iter("a")) == plist(iter("a")) | PLists can be created from iterables even though they can't be len()
hinted. | 625941d194891a1f4081bc3b |
@ensure_csrf_cookie <NEW_LINE> @cache_control(no_cache=True, no_store=True, must_revalidate=True) <NEW_LINE> @require_level('instructor') <NEW_LINE> @require_query_params(problem_to_reset="problem urlname to reset") <NEW_LINE> @common_exceptions_400 <NEW_LINE> def rescore_problem(request, course_id): <NEW_LINE> <INDENT... | Starts a background process a students attempts counter. Optionally deletes student state for a problem.
Limited to instructor access.
Takes either of the following query paremeters
- problem_to_reset is a urlname of a problem
- unique_student_identifier is an email or username
- all_students is a boolean
... | 625941d14a966d76dd5511a1 |
def print_status(self, op: AdminOperation, tool: RepoAdminTool, indent: int) -> None: <NEW_LINE> <INDENT> print(f"{' '*indent}{op.name}: {self.value}") | Print this status value to STDOUT in a way that can be used to
implement `AdminOperation.print_status`.
Parameters
----------
op : `AdminOperation`
Operation whose status should be checked.
tool : `RepoAdminTool`
Object managing shared state for all operations.
indent : `str`
Number of spaces to indent rep... | 625941d1adb09d7d5db6c921 |
def itkLevelSetMotionRegistrationFilterIUC2IUC2IVF22_cast(*args): <NEW_LINE> <INDENT> return _itkLevelSetMotionRegistrationFilterPython.itkLevelSetMotionRegistrationFilterIUC2IUC2IVF22_cast(*args) | itkLevelSetMotionRegistrationFilterIUC2IUC2IVF22_cast(itkLightObject obj) -> itkLevelSetMotionRegistrationFilterIUC2IUC2IVF22 | 625941d18da39b475bd65106 |
def __init__(self, realm, *, user=None, password=None, do_next=False): <NEW_LINE> <INDENT> if do_next: <NEW_LINE> <INDENT> self.name = 'basicauth-next' <NEW_LINE> <DEDENT> user_password = [] <NEW_LINE> if user: <NEW_LINE> <INDENT> user += ':' <NEW_LINE> user_password.append(user) <NEW_LINE> <DEDENT> if password: <NEW_L... | :param str realm:
:param str user:
:param str password: Password or htpasswd-like file.
:param bool do_next: Allow next rule. | 625941d1d18da76e23532669 |
def pair(arg): <NEW_LINE> <INDENT> return arg if isinstance(arg, (tuple, list)) and len(arg) == 2 else None | Check if `arg` is a pair (two elements tuple or list). | 625941d14a966d76dd5511a2 |
def test_contains(self): <NEW_LINE> <INDENT> self.assertIn(muc.STATUS_CODE.SELF_PRESENCE, self.mucStatuses) <NEW_LINE> self.assertIn(muc.STATUS_CODE.ROOM_CREATED, self.mucStatuses) <NEW_LINE> self.assertNotIn(muc.STATUS_CODE.NON_ANONYMOUS, self.mucStatuses) | The status contained are 'in' the container. | 625941d150812a4eaa59c4b3 |
def validar_mascara(mascara): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mascara = int(mascara) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> if mascara == mascara_ddn(8) or mascara == mascara_ddn(9) or mascara == mascara_ddn(10): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif mascara == mascar... | Comprueba si se ha introducido una máscara de subred válida en cualquier formato. | 625941d1d6c5a102081441dd |
def run_continue(self): <NEW_LINE> <INDENT> if self.running: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.running = True <NEW_LINE> self.bp.set() <NEW_LINE> return True | Start or continue the debuggee. | 625941d130dc7b7665901af8 |
def filter_close(h, l, middle): <NEW_LINE> <INDENT> with warnings.catch_warnings(): <NEW_LINE> <INDENT> warnings.simplefilter("ignore") <NEW_LINE> return np.where(h>middle, h, l) | 当在mid上面时用high, 下面时用low
return c 用合并后的序列作为close | 625941d1462c4b4f79d1d863 |
def create_folder(folder_name): <NEW_LINE> <INDENT> if not os.path.exists(folder_name): <NEW_LINE> <INDENT> os.makedirs(folder_name) | Create Folder if does not exists | 625941d110dbd63aa1bd2d36 |
def build_ethernet_header_swap(myethheader): <NEW_LINE> <INDENT> newethheader = ETHHEADER() <NEW_LINE> newethheader.smac0 = myethheader.dmac0 <NEW_LINE> newethheader.smac1 = myethheader.dmac1 <NEW_LINE> newethheader.smac2 = myethheader.dmac2 <NEW_LINE> newethheader.smac3 = myethheader.dmac3 <NEW_LINE> newethheader.smac... | Build Ethernet header | 625941d1d53ae8145f87a401 |
def quaternion_to_euler_zyx(q: torch.Tensor) -> torch.Tensor: <NEW_LINE> <INDENT> assert len(q.size()) == 2, "Missing batch dimension" <NEW_LINE> bank = torch.atan2(2 * (q[:,0] * q[:,1] + q[:,2] * q[:,3]), 1 - 2 * (q[:,1] ** 2 + q[:,2] ** 2)) <NEW_LINE> attitude = torch.asin(2 * (q[:,0] * q[:,2] - q[:,3] * q[:,1])) <NE... | https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles#Quaternion_to_Euler_Angles_Conversion
:param q: Quaternion | 625941d199fddb7c1c9de523 |
@tf_export('StatsAccumulatorTensorResourceHandleOp') <NEW_LINE> def stats_accumulator_tensor_resource_handle_op(container="", shared_name="", name=None): <NEW_LINE> <INDENT> if container is None: <NEW_LINE> <INDENT> container = "" <NEW_LINE> <DEDENT> container = _execute.make_str(container, "container") <NEW_LINE> if s... | Creates a handle to a StatsAccumulatorTensorResource
Args:
container: An optional `string`. Defaults to `""`.
shared_name: An optional `string`. Defaults to `""`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `resource`. | 625941d17b180e01f3dc498e |
def test_cleanup_string_removes_whitespace_before_punctuation(self): <NEW_LINE> <INDENT> s1 = "Win , for me !" <NEW_LINE> s1_expected = "Win, for me!" <NEW_LINE> s2 = "some guy @ babylon # sweet" <NEW_LINE> s2_expected = "some guy @babylon #sweet" <NEW_LINE> s3 = "http: //www.somesite.com" <NEW_LINE> s3_expected = "htt... | Does cleanup_string remove punctuation before ceratin punctuation characters
caused by tokenization? | 625941d1d10714528d5ffe76 |
def console(request): <NEW_LINE> <INDENT> if not request.user.is_authenticated(): <NEW_LINE> <INDENT> return HttpResponseRedirect(reverse('login')) <NEW_LINE> <DEDENT> if request.method == 'GET': <NEW_LINE> <INDENT> token = request.GET.get('token', '') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> temptoken = token.spli... | Console instance block | 625941d1167d2b6e31218d28 |
def _append_item(items, utt_id, start, stop, phone, prev_phone, next_phone, speaker, exclude_phones): <NEW_LINE> <INDENT> if exclude_phones is [] or all( p not in exclude_phones for p in (prev_phone, phone, next_phone)): <NEW_LINE> <INDENT> items.append(' '.join( [utt_id, start, stop, phone, prev_phone, next_phone, spe... | Append a new item to items if its phones are not excluded | 625941d191f36d47f21ac685 |
def setUp(self): <NEW_LINE> <INDENT> super(TestResConfigDocLinks, self).setUp() <NEW_LINE> self.re = re.compile("<a href=\"(\S+/documentation/\S+)\"") <NEW_LINE> self.links = set() | Set-up the test environment | 625941d1ac7a0e7691ed425d |
def gtable_add_rows(object_id, input_params={}, always_retry=True, **kwargs): <NEW_LINE> <INDENT> return DXHTTPRequest('/%s/addRows' % object_id, input_params, always_retry=always_retry, **kwargs) | Invokes the /gtable-xxxx/addRows API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/GenomicTables#API-method%3A-%2Fgtable-xxxx%2FaddRows | 625941d1be383301e01b5616 |
def test_registration_no_sites(self): <NEW_LINE> <INDENT> Site._meta.installed = False <NEW_LINE> new_user = self.backend.register(_mock_request(), username='bob', email='bob@example.com', first_name='Bob', last_name='Example', password1='secret') <NEW_LINE> self.assertEqual(new_user.username, 'bob') <NEW_LINE> self.fa... | Test that registration still functions properly when
``django.contrib.sites`` is not installed; the fallback will
be a ``RequestSite`` instance. | 625941d156b00c62f0f147ec |
def time_stats(df): <NEW_LINE> <INDENT> print("Computing Time statistics\n") <NEW_LINE> df['hour'] = df['Start Time'].dt.hour <NEW_LINE> df['Start Time'] = pd.to_datetime(df['Start Time']) <NEW_LINE> popular_hour = df['hour'].mode()[0] <NEW_LINE> print('Most Popular Start Hour:', popular_hour) <NEW_LINE> kf = pd.read_c... | Displays statistics on the most frequent times of travel. | 625941d11f5feb6acb0c4ce2 |
def test_to_knx_invert(self): <NEW_LINE> <INDENT> xknx = XKNX() <NEW_LINE> remote_value = RemoteValueUpDown(xknx, invert=True) <NEW_LINE> assert remote_value.to_knx(RemoteValueUpDown.Direction.UP) == DPTBinary(1) <NEW_LINE> assert remote_value.to_knx(RemoteValueUpDown.Direction.DOWN) == DPTBinary(0) | Test to_knx function with normal operation. | 625941d15e10d32532c5f0b9 |
def db_ea(q, dbsection='desoper', drop_dupl=None): <NEW_LINE> <INDENT> connect = ea.connect(dbsection) <NEW_LINE> cursor = connect.cursor() <NEW_LINE> outtab = connect.query_to_pandas(q) <NEW_LINE> outtab.columns = map(str.lower, outtab.columns) <NEW_LINE> if (drop_dupl is not None): <NEW_LINE> <INDENT> outtab.drop_dup... | Method co call easyaccess, lowercase column names and
remove duplicates based on a specific column | 625941d13c8af77a43ae3933 |
def get_av_filenames(self, ids=None): <NEW_LINE> <INDENT> if ids is None: <NEW_LINE> <INDENT> ids = [] <NEW_LINE> <DEDENT> sql = "select id, name, memo from source where " <NEW_LINE> sql += "(mediapath like '/audio/%' or mediapath like 'audio:%' or mediapath like '/video/%' or mediapath like 'video:%') " <NEW_LINE> if ... | Get filenames of audio video files only.
param:
ids: list of Integer ids for a restricted list of files. | 625941d1d268445f265b5000 |
def _strDescr(self): <NEW_LINE> <INDENT> return ', '.join(c._strDescr() for c in self.children) | Return a generic description of the ResultSelector. | 625941d10383005118ecf774 |
def move(self, direction): <NEW_LINE> <INDENT> for direction, band in zip(direction, self.__tapes): <NEW_LINE> <INDENT> band.move(direction) | Bewegt das Band in die angegebene Richtung. | 625941d166673b3332b92223 |
def _asciiArt(self, char1='-', show_internal=True, compact=False, attributes=None): <NEW_LINE> <INDENT> if not attributes: <NEW_LINE> <INDENT> attributes = ["name"] <NEW_LINE> <DEDENT> node_name = ', '.join(map(str, [getattr(self, v) for v in attributes if hasattr(self, v)])) <NEW_LINE> LEN = max(3, len(node_name) if n... | Returns the ASCII representation of the tree.
Code based on the PyCogent GPL project. | 625941d11d351010ab855cae |
def spectral_bipartivity(G, nodes=None, weight='weight'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import scipy.linalg <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> raise ImportError('spectral_bipartivity() requires SciPy: ', 'http://scipy.org/') <NEW_LINE> <DEDENT> nodelist = G.nodes() <NEW_LINE> A =... | Returns the spectral bipartivity.
Parameters
----------
G : NetworkX nxgraph
nodes : list or container optional(default is all nodes)
Nodes to return value of spectral bipartivity contribution.
weight : string or None optional (default = 'weight')
Edge data key to use for edge weights. If None, weights set to ... | 625941d1e76e3b2f99f3a99c |
def skip_TESTS_block(app, what, name, obj, options, docstringlines): <NEW_LINE> <INDENT> from sage.misc.sagedoc import skip_TESTS_block as sagedoc_skip_TESTS <NEW_LINE> s = sagedoc_skip_TESTS("\n".join(docstringlines)) <NEW_LINE> lines = s.split("\n") <NEW_LINE> for i in range(len(lines)): <NEW_LINE> <INDENT> docstring... | Skip blocks labeled "TESTS:".
See sage.misc.sagedoc.skip_TESTS_block for more information. | 625941d1dd821e528d63b33b |
def has_mpi(): <NEW_LINE> <INDENT> return __mpi_available | Return True if the mpi4py library is available and there are at least
2 MPI processes in the current group. Otherwise return False.
This is a "does parallel processing make sense?" check.
See has_mpi4py_library() for just checking library availability. | 625941d1f9cc0f698b14078d |
def sum_multi_gpu_blob(blob_name): <NEW_LINE> <INDENT> val = 0 <NEW_LINE> for i in range(cfg.NUM_GPUS): <NEW_LINE> <INDENT> val += float(workspace.FetchBlob('gpu_{}/{}'.format(i, blob_name))) <NEW_LINE> <DEDENT> return val | Return the sum of a scalar blob held on multiple GPUs. | 625941d12eb69b55b151ca42 |
def __init__(self, boundaries, ncolors, clip=False): <NEW_LINE> <INDENT> self.clip = clip <NEW_LINE> self.vmin = boundaries[0] <NEW_LINE> self.vmax = boundaries[-1] <NEW_LINE> self.boundaries = np.asarray(boundaries) <NEW_LINE> self.N = len(self.boundaries) <NEW_LINE> self.Ncmap = ncolors <NEW_LINE> if self.N - 1 == se... | *boundaries*
a monotonically increasing sequence
*ncolors*
number of colors in the colormap to be used
If::
b[i] <= v < b[i+1]
then v is mapped to color j;
as i varies from 0 to len(boundaries)-2,
j goes from 0 to ncolors-1.
Out-of-range values are mapped
to -1 if low and ncolors if high; these are conv... | 625941d10a50d4780f667025 |
def removeChildWithName(self, name): <NEW_LINE> <INDENT> raise AssertionError("CommonHomeExternal: not supported") | No children. | 625941d163f4b57ef00012a9 |
def inc_range(pairs, reversed=False, return_removed=False): <NEW_LINE> <INDENT> prs = PairedRegionsFromPairs(pairs) <NEW_LINE> id_to_pr = prs.byId() <NEW_LINE> cm = ConflictMatrix(prs) <NEW_LINE> range_pos_data = {} <NEW_LINE> for pr in prs: <NEW_LINE> <INDENT> rr = pr.range() <NEW_LINE> if rr not in range_pos_data: <N... | Return pseudoknot-free Pairs object
pairs -- Pairs object or list of tuples. One base can only interact
with one other base, otherwise an error will be raised.
reversed -- boolean. If reversed is True: in case of two regions
with the same range the region that starts closest to the 5' side
is added first. ... | 625941d11f037a2d8b946390 |
def __init__(self, sampling_date: datetime.datetime = None, parameter: str = None, parameter_unit: str = None, value: str = None, detection_limit: str = None, report_date: datetime.datetime = None, analysis_type: str = None): <NEW_LINE> <INDENT> super().__init__(sampling_date, parameter, parameter_unit, value) <NEW_LIN... | :param sampling_date: date when the sample have been taken
:param parameter: parameter analyzed
:param parameter_unit: unit of measurement for this parameter
:param value: obtained value
:param detection_limit: detection limit
:param report_date: date of the analysis or report date if not sure | 625941d1656771135c3eba02 |
def remove(self, key): <NEW_LINE> <INDENT> if key and key in self: <NEW_LINE> <INDENT> self.pop(key) | Removes an item if it exists. | 625941d1596a897236089c52 |
def write_analysis(analysis, prefix, patterns_names, quants, cdfs, call_only=True): <NEW_LINE> <INDENT> log_filename = prefix + '.log' <NEW_LINE> try: <NEW_LINE> <INDENT> os.remove(log_filename) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> logging.basicConfig(filename=log_filename, l... | This function orchestrates the entire analysis result dump. By default, it only writes out call pattern
analysis results and the sites file, containing information about mutated columns. Optionally, it can also
output analysis results for each of the contexts separately. | 625941d1a8370b7717052a31 |
def too_long_for_us(self): <NEW_LINE> <INDENT> if self.config.max_duration is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not self.mencoder_started: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> passed = self.num_frames_read * self.delta <NEW_LINE> if passed > self.config.max_duration: <NEW_LIN... | Returns true if max_duration is set and we passed it. | 625941d10383005118ecf775 |
def register_command(command_name, command_class): <NEW_LINE> <INDENT> assert isinstance(command_name, str) <NEW_LINE> assert isinstance(command_class, type) <NEW_LINE> if command_name not in CommandRegistry: <NEW_LINE> <INDENT> CommandRegistry[command_name] = command_class <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>... | :return: None | 625941d132920d7e50b28363 |
def cache(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper_cache(*args, **kwargs): <NEW_LINE> <INDENT> cache_key = args + tuple(kwargs.items()) <NEW_LINE> if cache_key not in wrapper_cache.cache: <NEW_LINE> <INDENT> wrapper_cache.cache[cache_key] = func(*args, **kwargs) <NEW_LINE> <DEDENT> retur... | Keeps a cache of previous function calls | 625941d1c4546d3d9de72bc7 |
def nearest_value(self,value,value_arr): <NEW_LINE> <INDENT> idx = np.searchsorted(value_arr, value, side="left") <NEW_LINE> if idx > 0 and (idx == len(value_arr) or math.fabs(value- value_arr[idx-1]) < math.fabs(value - value_arr[idx])): <NEW_LINE> <INDENT> return value_arr[idx-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> ... | Function to find the nearest value in a value array
Args:
value representing the value you wish to find (float)
value_array representing the array you wish to search through (array)
Returns:
float: nearest value to that specfied
| 625941d18e7ae83300e4b15f |
def fc_get_limits(mu_bins, x_bins, acceptance_intervals): <NEW_LINE> <INDENT> upper_limit = [] <NEW_LINE> lower_limit = [] <NEW_LINE> x_values = [] <NEW_LINE> number_mu = len(mu_bins) <NEW_LINE> number_bins_x = len(x_bins) <NEW_LINE> for mu in range(number_mu): <NEW_LINE> <INDENT> upper_limit.append(-1) <NEW_LINE> lowe... | Find lower and upper limit from acceptance intervals.
For more information see :ref:`documentation <feldman_cousins>`.
Parameters
----------
mu_bins : array-like
The bins used in mue direction.
x_bins : array-like
The bins of the x distribution
acceptance_intervals : array-like
The output of fc_construct_... | 625941d1ab23a570cc250315 |
def datasourcearcgis2dict(datasource): <NEW_LINE> <INDENT> datasourcedict = {} <NEW_LINE> keys = re.findall(r'([A-z][A-z0-9-_]+)=[\'"]?[#$^?+=!*()\'-/@%&\w\."]+[\'"]?', datasource) <NEW_LINE> for k in keys: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> datasourcedict[k] = re.findall(r'{}=[\'"]([#$:_^?+=!*()\'-/@%&\w\."]... | Read a ArcGisMapServer datasource string and put data in a python dict
:param datasource: qgis project arcgis layer datasource
:return: dict with datasource params
:rtype: dict | 625941d123849d37ff7b3222 |
def slotDocumentSaved(self): <NEW_LINE> <INDENT> self._dirty = True <NEW_LINE> self._hash = None | Called when the document is saved. Forces auto-compile once. | 625941d163b5f9789fde7278 |
def get_default_device_driver(driver_id=pycdio.DRIVER_DEVICE): <NEW_LINE> <INDENT> result = pycdio.get_default_device_driver(driver_id) <NEW_LINE> if type(result) == type([1,2]): <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> return None | get_default_device_driver(self, driver_id=pycdio.DRIVER_DEVICE)
->[device, driver]
Return a string containing the default CD device if none is
specified. if driver_id is DRIVER_UNKNOWN or DRIVER_DEVICE
then one set the default device for that.
None is returned as the device if we couldn't get a default
device. | 625941d126068e7796caee73 |
def test_reweighting(self): <NEW_LINE> <INDENT> m = IMP.kernel.Model("scoring function linkage") <NEW_LINE> ps = [IMP.kernel.Particle(m) for i in range(0, 10)] <NEW_LINE> r = IMP.kernel._ConstRestraint(1, ps) <NEW_LINE> rs = IMP.kernel.RestraintSet(m, 1.0, "rs") <NEW_LINE> rs.add_restraint(r) <NEW_LINE> rsf = rs.create... | Test scoring function reweighting | 625941d15510c4643540f575 |
def check_ftfy(self, text): <NEW_LINE> <INDENT> self.count += 1 <NEW_LINE> if not possible_encoding(text, 'ascii'): <NEW_LINE> <INDENT> fixed = fix_text_encoding(text) <NEW_LINE> if text != fixed: <NEW_LINE> <INDENT> print(u'\nText:\t{text}\nFixed:\t{fixed}\n'.format( text=text, fixed=fixed )) <NEW_LINE> self.num_fixed... | Given a single text input, check whether `ftfy.fix_text_encoding`
would change it. If so, display the change. | 625941d1f7d966606f6aa197 |
def write_pcd(points, file_name="model.pcd"): <NEW_LINE> <INDENT> if type(file_name) == str: <NEW_LINE> <INDENT> f = open(file_name, 'w') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f = file_name <NEW_LINE> <DEDENT> print('# .PCD v.7 - Point Cloud Data file format', file=f) <NEW_LINE> print('VERSION .7', file=f) <NEW... | write a pointclooud as .pcd file, in binary mode or ascii mode. (compact or readable)
points should look like this:
[
p1[x-coordinate, y-coord, z-coord, r, g, b],
p2[x-coordinate, y-coord, z-coord, r, g, b],
p3[x-c... | 625941d16aa9bd52df036f37 |
def get_page(url): <NEW_LINE> <INDENT> return get(url).text | Get the text of a page from a url
:param url: url of page
:return: text from the page | 625941d116aa5153ce36260a |
def format_tweet_date(tweet_date): <NEW_LINE> <INDENT> d = tweet_date.split(' ') <NEW_LINE> formatted_date = "%s %s %s" % (d[1], d[2], d[5]) <NEW_LINE> return datetime.datetime.strptime(formatted_date, "%b %d %Y") | Format a date in the format found in a tweet in a standard date format | 625941d155399d3f05588848 |
def write(self, fileobject): <NEW_LINE> <INDENT> raise NotImplementedError("Write access not permitted.") | Wrapper to disallow write operations to configfile. | 625941d14e696a04525c95de |
def rospack_depends_on_1(pkg): <NEW_LINE> <INDENT> return rospackexec(['depends-on1', pkg]).split() | @param pkg: package name
@type pkg: str
@return: A list of the names of the packages which depend directly on pkg
@rtype: list | 625941d192d797404e30431d |
def insert_preext(filename, sub_ext): <NEW_LINE> <INDENT> fs = filename.split('.') <NEW_LINE> fs.insert(-1, sub_ext) <NEW_LINE> fn = '.'.join(fs) <NEW_LINE> return fn | Insert a pre-extension before file extension
E.g: 'file.csv' -> 'file.xyz.csv' | 625941d107d97122c4178a20 |
def __lt__(self, other): <NEW_LINE> <INDENT> if other.type == STRICT_RULE: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> ls = len(self.antecedent) <NEW_LINE> lo = len(other.antecedent) <NEW_LINE> if ls != lo: <NEW_LINE> <INDENT> return ls < lo <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ls = len(self.vulnerabil... | self < other if self has fewer antecedents, or
fewer vulnerabilities or
if str(self) is alphabetically before str(other). | 625941d1ec188e330fd5a930 |
def p_tipo(p): <NEW_LINE> <INDENT> pass | tipo : INTEGER_ID seen_Tipo
| FLOAT_ID seen_Tipo
| STRING_ID seen_Tipo
| BOOL_ID seen_Tipo | 625941d1b57a9660fec33a18 |
def test_extend(self) -> None: <NEW_LINE> <INDENT> gnl1 = GeneralNameList() <NEW_LINE> self.assertIsNone(gnl1.extend([self.dns1])) <NEW_LINE> self.assertEqual(gnl1, GeneralNameList([self.dns1])) <NEW_LINE> gnl2 = GeneralNameList() <NEW_LINE> self.assertIsNone(gnl2.extend([dns(self.dns1)])) <NEW_LINE> self.assertEqual(g... | Test extend(). | 625941d1377c676e9127233b |
def insertPFAMInAPI(designation_pfam): <NEW_LINE> <INDENT> domain_json = DomainJson(designation=designation_pfam) <NEW_LINE> domain = domain_json.setDomain() <NEW_LINE> return domain <NEW_LINE> print(id_domain) | Insert a new domain in tha API and return it
:param designation_pfam: name of the domain
:type designation_pfam: string
:return: the domain inserted
:rtype domainJ | 625941d1627d3e7fe0d68fe3 |
def reportFindings(vY, dSigma, dLoc, dTheta): <NEW_LINE> <INDENT> iN = len(vY) <NEW_LINE> dEST = vY.mean() <NEW_LINE> dVar = variance(vY) <NEW_LINE> dSE = np.sqrt(dVar/iN) <NEW_LINE> dX = dSE/dEST <NEW_LINE> dLB = dEST - 1.96 * dSE <NEW_LINE> dUB = dEST + 1.96 * dSE <NEW_LINE> print('Distribution: log-normal') <NE... | Purpose: to compute the standard deviation for a vector of data
Input:
vY vector of Y variables (floats)
Output:
We print several results | 625941d197e22403b379d12d |
def setup(self): <NEW_LINE> <INDENT> Y = np.loadtxt(get_data_path('example2_Y')) <NEW_LINE> X = np.loadtxt(get_data_path('example2_X')).reshape(-1, 4, order='F') <NEW_LINE> self.ordination = RDA(Y, X) | Data from table 9.11 in Legendre & Legendre 1998. | 625941d1377c676e9127233c |
def simpleAlignmentEst(t_prob, e, f): <NEW_LINE> <INDENT> alignment = [] <NEW_LINE> for i in range(len(e)): <NEW_LINE> <INDENT> eword = e[i] <NEW_LINE> best_align = (-1.0, -1) <NEW_LINE> for j in range(len(f)): <NEW_LINE> <INDENT> fword = f[j] <NEW_LINE> if t_prob[eword , fword] > best_align[0]: <NEW_LINE> <INDENT> bes... | a simple, greedy alignment estimation from english to foreign sentence. A decoding method coming from hindi-english-word-alignment (http://code.google.com/p/hindi-english-word-alignment). | 625941d124f1403a92600cf8 |
@templatedoc() <NEW_LINE> def random_crop(x, shape, seed=None): <NEW_LINE> <INDENT> helper = LayerHelper("random_crop", **locals()) <NEW_LINE> dtype = helper.input_dtype() <NEW_LINE> out = helper.create_tmp_variable(dtype) <NEW_LINE> if seed is None: <NEW_LINE> <INDENT> seed = random.randint(-65536, 65535) <NEW_LINE> <... | ${comment}
Args:
x(${x_type}): ${x_comment}
shape(${shape_type}): ${shape_comment}
seed(int|${seed_type}|None): ${seed_comment} By default, the seed will
get from `random.randint(-65536, 65535)`.
Returns:
${out_comment}
Examples:
>>> img = fluid.layers.data("img", [3, 256, 256])
>>> c... | 625941d15fc7496912cc3b11 |
def __init__(__self__, *, group: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, name_prefix: Optional[pulumi.Input[str]] = None, policy: Optional[pulumi.Input[str]] = None): <NEW_LINE> <INDENT> if group is not None: <NEW_LINE> <INDENT> pulumi.set(__self__, "group", group) <NEW_LINE> <DEDE... | Input properties used for looking up and filtering GroupPolicy resources.
:param pulumi.Input[str] group: The IAM group to attach to the policy.
:param pulumi.Input[str] name: The name of the policy. If omitted, this provider will
assign a random, unique name.
:param pulumi.Input[str] name_prefix: Creates a uniq... | 625941d1de87d2750b85ff26 |
def upload_gzipped(bucket, key, fp, compressed_fp=None, content_type='text/plain'): <NEW_LINE> <INDENT> if not compressed_fp: <NEW_LINE> <INDENT> compressed_fp = BytesIO() <NEW_LINE> <DEDENT> with gzip.GzipFile(fileobj=compressed_fp, mode='wb') as gz: <NEW_LINE> <INDENT> shutil.copyfileobj(fp, gz) <NEW_LINE> <DEDENT> c... | Compress and upload the contents from fp to S3.
If compressed_fp is None, the compression is performed in memory. | 625941d1adb09d7d5db6c922 |
def ten_by_ten(): <NEW_LINE> <INDENT> pass | Prints integers 1 through 100 sequentially in a ten by ten grid. | 625941d1a4f1c619b28b01ca |
def test_word2vec_sif_embeddings_glove(self): <NEW_LINE> <INDENT> embed = self._get_module('embeddings') <NEW_LINE> test_utterances = [ 'Hi, this phrase is similar to the second phrase.' , 'Hi, that phrase is like this phrase.' , 'I have nothing to do with the others.' ] <NEW_LINE> embeddings = embed.word2vec_sif_embed... | Tests using pre-trained glove word embeddings to
create sentence embeddings with -sif weightings.
The similarity between utterances 1 and 2 should be more than
1 and 3. | 625941d1cc40096d61595ae3 |
def test_was_published_recently_with_recent_question(self): <NEW_LINE> <INDENT> time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59) <NEW_LINE> recent_question = Question(pub_date=time) <NEW_LINE> self.assertIs(recent_question.was_published_recently(), True) | was_published_recently() return True for questions whose pub_date is within the last day | 625941d13eb6a72ae02ec673 |
def createTbl( data, settings=None, _smote=False, isBin=False, bugThres=1, duplicate=False): <NEW_LINE> <INDENT> makeaModel = makeAmodel.makeAModel() <NEW_LINE> _r = [] <NEW_LINE> for t in data: <NEW_LINE> <INDENT> m = makeaModel.csv2py(t, _smote=_smote, duplicate=duplicate) <NEW_LINE> _r += m._rows <NEW_LINE> <DEDENT>... | kwargs:
_smote = True/False : SMOTE input data (or not)
_isBin = True/False : Reduce bugs to defects/no defects
_bugThres = int : Threshold for marking stuff as defective,
default = 1. Not defective => Bugs < 1 | 625941d17d43ff24873a2e34 |
def __len__(self): <NEW_LINE> <INDENT> return len(self.instances) | Find how many instances of this app there are
:return: int; The application instances. | 625941d1167d2b6e31218d29 |
@app.route('/', methods=['POST']) <NEW_LINE> def webhook(): <NEW_LINE> <INDENT> req = request.get_json(silent=True, force=True) <NEW_LINE> try: <NEW_LINE> <INDENT> action = req.get('result').get('action') <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return 'json error' <NEW_LINE> <DEDENT> if action ==... | This method handles the http requests for the Dialogflow webhook
This is meant to be used in conjunction with the Banking Dialogflow agent | 625941d11f5feb6acb0c4ce3 |
def writeRibJob( path, sceneName ): <NEW_LINE> <INDENT> filePath = '%srenderman/%s/rib/job/job.rib' %(path, sceneName) <NEW_LINE> jobRibContent = ribJob( path, sceneName ) <NEW_LINE> Forge.core.System.setFile( path=filePath, content=jobRibContent ) | write a rib job file | 625941d15510c4643540f576 |
def on_set_primary_button_clicked(self, _widget): <NEW_LINE> <INDENT> _model, paths = self.groups_tree.get_selection().get_selected_rows() <NEW_LINE> path = self.groups_sort[paths[0]].path <NEW_LINE> path = self.groups_sort.convert_path_to_child_path(path) <NEW_LINE> path = self.groups_filter.convert_path_to_child_path... | Set the group as primary. | 625941d123e79379d52ee6f6 |
def IsInt(value: str) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _ = int(value) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | Check if a string can be safely casted to an int.
Args:
value (str): The string to check.
Returns:
bool: True if the string can be casted to an int. | 625941d163b5f9789fde7279 |
def is_sorted(t): <NEW_LINE> <INDENT> for i in range(len(t)): <NEW_LINE> <INDENT> if t[i+1] > t[i]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Checks whether a list is sorted.
t: list
returns: boolean
Expected output:
>>> is_sorted([1, 2, 2])
True
>>> is_sorted(['b', 'a'])
False | 625941d1097d151d1a222fed |
def draw(self, game_state): <NEW_LINE> <INDENT> super().draw(game_state) <NEW_LINE> world_map = game_state.get_world_map() <NEW_LINE> for x in range(0, len(world_map)): <NEW_LINE> <INDENT> for y in range(0, len(world_map[x])): <NEW_LINE> <INDENT> if world_map[x][y] == 1: <NEW_LINE> <INDENT> self.__display_square(self._... | :type game_state: main.gameState.GameState | 625941d18c3a87329515854f |
def test_list(self): <NEW_LINE> <INDENT> argv = ['', 'storage', 'list'] <NEW_LINE> Command().run_from_argv(argv) <NEW_LINE> out = self.stdout.getvalue() <NEW_LINE> self.assertTrue(out, "No output.") | Get listing. | 625941d1aad79263cf390bd6 |
def apply_signing(self, plan_id, contract_code, contract_display_account, notify_url, version="1.0", clientip=None, deviceid=None, mobile=None, email=None, qq=None, request_serial=None, openid=None, creid=None, outerid=None): <NEW_LINE> <INDENT> timestamp = int(time.time()) <NEW_LINE> if request_serial is None: <NEW_LI... | 申请签约 api
https://pay.weixin.qq.com/wiki/doc/api/pap.php?chapter=18_1&index=1
:param plan_id: 模板id 协议模板id,设置路径见开发步骤。
:param contract_code: 签约协议号 商户侧的签约协议号,由商户生成
:param contract_display_account: 用户账户展示名称 签约用户的名称,用于页面展示,页面样例可见案例与规范
:param notify_url: 回调通知url 用于接收签约成功消息的回调通知地址,以http或https开头。
:param version: 版本号 固定值1.0
:pa... | 625941d1293b9510aa2c3429 |
def filter_expirations_before(self, before: DateTime) -> None: <NEW_LINE> <INDENT> filtered = list(filter(lambda exp: exp.expiration_date <= before, self.expiration_list)) <NEW_LINE> self.expiration_list = filtered | Filter out any expiration dates post the before date.
Args:
before (DateTime): datetime to filter.
Example:
|Input | Args |Output |
|---------------------------|---------------|---------|
|[01JAN19, 01FEB19, 01MAR19]|before: 15JAN19|[01JAN19]| | 625941d12c8b7c6e89b35954 |
def get_new_fact_or_rule(): <NEW_LINE> <INDENT> msg = "Please type in a new fact or rule you want to add to the KB:\n" <NEW_LINE> e = read_from_input(msg) <NEW_LINE> return parse_input(e) | Creates a new fact or rule. (instead of args, we use command line input
via the read_from_input() function)
Returns:
list: fact list or list of the left and right hand sides of a rule | 625941d19f2886367277aa20 |
@raises(TypeError) <NEW_LINE> def test_Dataset_IDs_Bad_Input_Type(): <NEW_LINE> <INDENT> t = TestType.TestType() <NEW_LINE> t.datasetIDs = 2 | Exception is raised when a non-dict is passed to datasetIDs.
| 625941d13346ee7daa2b2f00 |
def build_histogram(iterator, key): <NEW_LINE> <INDENT> buckets = collections.defaultdict(int) <NEW_LINE> values = {} <NEW_LINE> num_objects = 0 <NEW_LINE> for obj in iterator: <NEW_LINE> <INDENT> num_objects += 1 <NEW_LINE> try: <NEW_LINE> <INDENT> val = obj[key] <NEW_LINE> <DEDENT> except (KeyError, TypeError): <NEW_... | Builds a histogram of values given an iterable of mappings and a key.
For each mapping "m" with key "key" in iterator, the value m[key] is
considered.
Returns a list of tuples (hash, count, proportion, value), where
- "hash" is a sha1sum hash of the value.
- "count" is the number of occurences of values that has... | 625941d156b00c62f0f147ed |
def build_desired_context_counts(seqs): <NEW_LINE> <INDENT> desired_prefix_counts = build_desired_prefix_counts(seqs) <NEW_LINE> countinit = lambda: numpy.zeros(4) <NEW_LINE> desired = defaultdict(countinit) <NEW_LINE> for prefix, count in desired_prefix_counts.iteritems(): <NEW_LINE> <INDENT> desired[prefix[:-1]][cact... | Alternative algorithm to count symbols following each context. | 625941d1e1aae11d1e749e4b |
def test_init(self): <NEW_LINE> <INDENT> key_wrapping_specification = objects.KeyWrappingSpecification() <NEW_LINE> self.assertEqual(None, key_wrapping_specification.wrapping_method) <NEW_LINE> self.assertEqual( None, key_wrapping_specification.encryption_key_information ) <NEW_LINE> self.assertEqual( None, key_wrappin... | Test that a KeyWrappingSpecification struct can be constructed with
no arguments. | 625941d194891a1f4081bc3d |
def resnet34(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet: <NEW_LINE> <INDENT> return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress, **kwargs) | ResNet-34 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr | 625941d129b78933be1e583e |
def __LaTeX2Dvi2Gif(self): <NEW_LINE> <INDENT> tmpfp, tmpname = tempfile.mkstemp(suffix=".tex", dir=self.tmp_dir) <NEW_LINE> try: <NEW_LINE> <INDENT> with os.fdopen(tmpfp, "w", encoding="utf-8") as texfile: <NEW_LINE> <INDENT> texfile.write(self.out.getvalue()) <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <I... | Write formulae to LaTeX file, compile and extract images. | 625941d1cdde0d52a9e531c8 |
def count(self, collection_name, find_options=None): <NEW_LINE> <INDENT> if find_options: <NEW_LINE> <INDENT> assert "only" not in find_options.keys(), "count() does not support the only option" <NEW_LINE> <DEDENT> return self._select("count", collection_name, find_options) | Return the number of records in the given collection, with optional find_options | 625941d126238365f5f0f003 |
def fetch_all(self, fetch_only, airflow_date, fetch_method, days_lookback): <NEW_LINE> <INDENT> queries = self.load_queries() <NEW_LINE> for name, query in queries.items(): <NEW_LINE> <INDENT> if fetch_only and name != fetch_only: <NEW_LINE> <INDENT> self.logger.debug("'--fetch-only %s' specified. Skipping fetch of %s"... | Fetch any reports or queries, writing them out as files in the output_dir | 625941d14e4d5625662d456a |
def convert_annotation(base_dir, year, image_id): <NEW_LINE> <INDENT> in_file = open(base_dir+'VOC%s/Annotations/%s.xml'%(year, image_id)) <NEW_LINE> tree=ET.parse(in_file) <NEW_LINE> root = tree.getroot() <NEW_LINE> size = root.find('size') <NEW_LINE> w = int(size.find('width').text) <NEW_LINE> h = int(size.find('heig... | Convert annotations to text format xmin ymin xmax ymax label; xmin ymin ...... | 625941d18a349b6b435e8307 |
def calculateAngleResForces(self): <NEW_LINE> <INDENT> forces = [] <NEW_LINE> for flowline in self.flowlines: <NEW_LINE> <INDENT> Fs = 0 <NEW_LINE> startTan = vectorFromPoints(flowline.p0, flowline.p1) <NEW_LINE> deltaStart = startTan.getDirection() <NEW_LINE> ds = startTan.getMagnitude() <NEW_LINE> sVectors = [o.getSt... | Calculates the angular-resolution forces. This helps to increase angular resolution of flows at nodes.
See Section 3.1.5 of Jenny et al
:return: list of forces in the same order as self.flowlines | 625941d150812a4eaa59c4b5 |
def __init__(self,ai_settings,screen): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.image = pygame.image.load('images\ship.bmp') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.screen_rect = screen.get_rect() <NEW_LINE> self.rect.centerx = self.screen_rect.centerx ... | 初始化飞船并设置其初始位置 | 625941d176d4e153a657ecc5 |
def non_max_suppression(boxes, scores, max_output_size, iou_threshold=None, name=None): <NEW_LINE> <INDENT> result = _op_def_lib.apply_op("NonMaxSuppression", boxes=boxes, scores=scores, max_output_size=max_output_size, iou_threshold=iou_threshold, name=name) <NEW_LINE> return result | Greedily selects a subset of bounding boxes in descending order of score,
pruning away boxes that have high intersection-over-union (IOU) overlap
with previously selected boxes. Bounding boxes are supplied as
[y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any
diagonal pair of box corners and the... | 625941d1be8e80087fb20dd5 |
def clear(self) -> None: <NEW_LINE> <INDENT> self.size = 0 <NEW_LINE> super(MinHeap, self).clear() | Clears heap of all data. | 625941d16fb2d068a760f232 |
def test_cap_development_city_total_growth(self): <NEW_LINE> <INDENT> storage = StorageFactory().get_storage('dict_storage') <NEW_LINE> storage.write_table(table_name='parcels', table_data=self.parcels_data) <NEW_LINE> pcl = ParcelDataset(in_storage=storage, in_table_name='parcels') <NEW_LINE> pcl.modify_attribute("num... | Test using city and total growth for controlling the growth.
| 625941d1004d5f362079a4c6 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'snap.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 Django. Are you sure it... | Run administrative tasks. | 625941d1004d5f362079a4c7 |
def isLowSurrogate(self): <NEW_LINE> <INDENT> return bool() | bool QChar.isLowSurrogate() | 625941d14527f215b584c5ea |
@click.command() <NEW_LINE> @click.option('--smtplog', default=False, is_flag=True, help='Enables mail reporting. Make sure ' 'SMTP configs are set properly first.') <NEW_LINE> @click.option('--refinish', default=False, is_flag=True, help='Retries the annotation computation loop') <NEW_LINE> def loadneo4j(smtplog, refi... | Loads the information from external database into the main knowledge repository inside neo4j
:return: | 625941d15fdd1c0f98dc03c8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.