code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def unmold_detections(self, detections, original_image_shape, image_shape, window): <NEW_LINE> <INDENT> zero_ix = np.where(detections[:, 4] == 0)[0] <NEW_LINE> N = zero_ix[0] if zero_ix.shape[0] > 0 else detections.shape[0] <NEW_LINE> boxes = detections[:N, :4] <NEW_LINE> class_ids = detections[:N, 4].astype(np.int32) ... | Reformats the detections of one image from the format of the neural
network output to a format suitable for use in the rest of the
application.
detections: [N, (y1, x1, y2, x2, class_id, score)] in normalized coordinates
mrcnn_mask: [N, height, width, num_classes]
original_image_shape: [H, W, C] Original image shape b... | 625941d5d18da76e235326f2 |
def test_if_username_field_is_empty(self): <NEW_LINE> <INDENT> test_data = self.client.post( reverse('authentication:user_signup'), self.user_credentials('jake@jake.jake', '', 'HelloWorldKen12!3'), format='json' ) <NEW_LINE> self.assertEqual(test_data.data['errors']['username'][0], "Username field is required.") | Test if the username field is empty | 625941d5442bda511e8be631 |
def _update_meta_metadata(self, fields=None, section=None, keep_core_values=True, store_backup=True): <NEW_LINE> <INDENT> raise NotImplementedError('Missing implementation on this version') | Given one field definition fills up the parallel dictionary with the
needed meta-metadata, including field extensions and after decorators.
If there is some information about this field in the json structure it
will keep some core information like the source format. | 625941d585dfad0860c3b076 |
def readdir(self, path, fh): <NEW_LINE> <INDENT> return self._dir_entries | ..see:: :py:class:`fuse.Operations` | 625941d5d486a94d0b98e361 |
def add_box(fig, axes, idx1, idx2, hpad, vpad, offset=None, **kwargs): <NEW_LINE> <INDENT> if not offset: <NEW_LINE> <INDENT> offset = [0., 0., 0., 0.] <NEW_LINE> <DEDENT> offset_f = [0.]*4 <NEW_LINE> hpad_f, vpad_f = _plot_boxes.convert_pad(fig, hpad, vpad) <NEW_LINE> offset_f[:2] = _plot_boxes.convert_pad(fig, *offse... | Add box around axes.
idx1: lower left axes index in the axes
idx2: upper right axes index in the axes
hpad/vpad: horizontal and vertical padding between the axes in points
offset: additional offset [left, right, bottom, top]
kwargs transmitted to the rectangle artist
Returns xy (bottom left position) and wh (width, ... | 625941d550485f2cf553cfb6 |
def test_output_case4(self): <NEW_LINE> <INDENT> user_input = "10" <NEW_LINE> expected = "" <NEW_LINE> with patch("builtins.input", return_value=user_input) as input_call: <NEW_LINE> <INDENT> with patch("sys.stdout", new=StringIO()) as output: <NEW_LINE> <INDENT> import attempt <NEW_LINE> self.assertEqual(output.getval... | Correct output when the number is NOT a perfect square | 625941d5cc40096d61595b6b |
def start(self, shutdown_events=True, http_server=True): <NEW_LINE> <INDENT> if config["agent_manhole"]: <NEW_LINE> <INDENT> self._start_manhole(config["agent_manhole_port"], config["agent_manhole_username"], config["agent_manhole_password"]) <NEW_LINE> <DEDENT> if http_server: <NEW_LINE> <INDENT> self._start_http_api(... | Internal code which starts the agent, registers it with the master,
and performs the other steps necessary to get things running.
:param bool shutdown_events:
If True register all shutdown events so certain actions, such as
information the master we're going offline, can take place.
:param bool http_server:
... | 625941d576e4537e8c35188f |
def __init__(self, buildout, name, options): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> options['eggs'] = 'slapos.cookbook' <NEW_LINE> self.options = options <NEW_LINE> self.logger = logging.getLogger(self.name) <NEW_LINE> self.slap = slap.slap() <NEW_LINE> slap_connection = buildout['slap-connection'] <NEW_LINE> ... | Default initialisation | 625941d5dd821e528d63b3c3 |
def countUnassigned(): <NEW_LINE> <INDENT> with with_cursor() as c: <NEW_LINE> <INDENT> c.execute("SELECT COUNT(*) FROM remainplayers") <NEW_LINE> (result,) = c.fetchone() <NEW_LINE> <DEDENT> return result | Returns the number of players to be assigned to matches in the round.
| 625941d58e7ae83300e4b1e8 |
def prob6(A): <NEW_LINE> <INDENT> pass | Divide each row of 'A' by the row sum and return the resulting array.
Example:
>>> A = np.array([[1,1,0],[0,1,0],[1,1,1]])
>>> prob6(A)
array([[ 0.5 , 0.5 , 0. ],
[ 0. , 1. , 0. ],
[ 0.33333333, 0.33333333, 0.33333333]]) | 625941d596565a6dacc8f8e6 |
def OnHandleDestroyed(self,*args): <NEW_LINE> <INDENT> pass | OnHandleDestroyed(self: Label,e: EventArgs)
Raises the System.Windows.Forms.Control.HandleDestroyed event.
e: An System.EventArgs that contains the event data. | 625941d5cdde0d52a9e5324f |
def on_get(self, _req, resp): <NEW_LINE> <INDENT> msg = {'message': 'Welcome'} <NEW_LINE> resp.text = json.dumps(jsend.success(msg)) <NEW_LINE> resp.status = falcon.HTTP_200 | on get request
return Welcome message | 625941d53eb6a72ae02ec6fc |
def handle_audio_end(self, event): <NEW_LINE> <INDENT> self.loop.unmute() | Request unmute, if more sources has requested the mic to be muted
it will remain muted. | 625941d521bff66bcd684b6c |
def test_attribute_adding(self): <NEW_LINE> <INDENT> int_attr_name = "intTestAttr" <NEW_LINE> int_plug = "{}.{}".format(TEST_MESH, int_attr_name) <NEW_LINE> int_attr = self.node_mesh.add_float(int_attr_name) <NEW_LINE> self.assertIsInstance(int_attr, noca.NcNode) <NEW_LINE> self.assertEqual(int_attr.plugs[0], int_plug)... | Test convenience methods to add attributes to Maya nodes | 625941d57047854f462a1623 |
def get_valid_opts(self): <NEW_LINE> <INDENT> vopts = OPT.OptionList('uber_subject.py options') <NEW_LINE> vopts.add_opt('-help', 0, [], helpstr='show this help') <NEW_LINE> vopts.add_opt('-help_gui', 0, [], helpstr='show help for GUI') <NEW_LINE> vopts.add_opt('-help_todo', 0, [], helpstr='show todo list') <NEW_LINE> ... | return an OptionsList of valid program options | 625941d5a219f33f34628b82 |
def get_autoscale_group_configuration(self, application): <NEW_LINE> <INDENT> application_configuration = self.get_application_configuration(application) <NEW_LINE> if self.AUTOSCALE_GROUP_KEY not in application_configuration: <NEW_LINE> <INDENT> raise ForsetiConfigurationException( "Application `%s` configuration does... | Get the `application` autoscale group configuration.
Raises `ForsetiConfigurationException` if `application` is unknown or
it has no `AUTOSCALE_GROUP_KEY` defined.
:param application: Application name | 625941d50fa83653e46571d6 |
def locate_rootfs_uImage(binary): <NEW_LINE> <INDENT> l = len(binary) <NEW_LINE> i = 0 <NEW_LINE> mbytes = struct.pack(">L", uImage.UIMAGE_MAGIC) <NEW_LINE> while i <= l-len(mbytes): <NEW_LINE> <INDENT> if binary[i:i+len(mbytes)] == mbytes: <NEW_LINE> <INDENT> print("Found uImage candidate at %x" % i) <NEW_LINE> uim = ... | returns rootfs data offset | 625941d5460517430c39439d |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1UniqueVolumeName): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941d57d847024c06be4d9 |
def fetchStatus(self, current_step): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> service_name = self._service_prefix + GoalProxy.SERVICE_NAME_GET_STATUS <NEW_LINE> rhbplog.logdebug("Waiting for service %s", service_name) <NEW_LINE> rospy.wait_for_service(service_name, timeout=self.SERVICE_TIMEOUT) <NEW_LINE> self.__co... | This method fetches the status from the actual goal node via GetStatus service call
:param current_step: | 625941d521bff66bcd684b6d |
def assign_entity_view_to_public_customer_using_post(self, entity_view_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.assign_entity_view_to_public_customer_using_post_with_http_info(entity_view_id, **kwargs) <NEW_LINE> <D... | Make entity view publicly available (assignEntityViewToPublicCustomer) # noqa: E501
Entity View will be available for non-authorized (not logged-in) users. This is useful to create dashboards that you plan to share/embed on a publicly available website. However, users that are logged-in and belong to different tenant... | 625941d5d7e4931a7ee9e139 |
def __init__(self, depth: int, channels: int, samplerate: int, unsigned: bool = False): <NEW_LINE> <INDENT> self._state = None <NEW_LINE> self._depth = depth <NEW_LINE> self._rate = samplerate <NEW_LINE> self._channels = channels <NEW_LINE> self._unsigned = unsigned <NEW_LINE> self._width = depth // 8 | Convert audio data.
Resample audio data with the given values to any other type. | 625941d523849d37ff7b32aa |
def emission_matrix(tags, words, words_tags): <NEW_LINE> <INDENT> vect_words = list(set(words)) <NEW_LINE> vect_tags = list(set(tags)) <NEW_LINE> vect_words_tags = list(set(words_tags)) <NEW_LINE> n = len(vect_tags) <NEW_LINE> m = len(vect_words_tags) <NEW_LINE> b = np.zeros((n, m)) <NEW_LINE> for i in range(n): <NEW_L... | Calculate emission matrix b | 625941d57d847024c06be4da |
def test_basic(script, tmpdir): <NEW_LINE> <INDENT> expected = ('--hash=sha256:2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425' 'e73043362938b9824') <NEW_LINE> result = script.pip('hash', _hello_file(tmpdir)) <NEW_LINE> assert expected in str(result) | Run 'pip hash' through its default behavior. | 625941d5046cf37aa974cf62 |
def __copy__(self): <NEW_LINE> <INDENT> return self.copy() | Return a shallow copy of the sorted dictionary. | 625941d5d268445f265b508a |
def getSpikeBufferSize(self, lo_atom, hi_atom, no_machine_time_steps): <NEW_LINE> <INDENT> if self._record == False: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if no_machine_time_steps is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> ratefactor = 1 <NEW_LINE> OUT_SPIKE_BYTES = int(ceil((hi_atom - lo_atom... | Gets the size of the spike buffer for a range of neurons and time steps | 625941d5f8510a7c17cf9918 |
def feature_colormap( self, feature: str, cmap: str = "viridis", vmin: float = None, vmax: float = None, ) -> Dict[str, str]: <NEW_LINE> <INDENT> cmap = mp.cm.get_cmap(cmap) <NEW_LINE> if vmin is None: <NEW_LINE> <INDENT> vmin = np.nanmin([getattr(node, feature) for node in self.tree.traverse()]) <NEW_LINE> <DEDENT> if... | Generate a colormap based on a continuous tree feature.
Args:
feature: feature name (all nodes in tree attribute must have this feature)
cmap: any matplotlib color palette: https://matplotlib.org/stable/gallery/color/colormap_reference.html
vmin: minimum value for colormap (default to minimum of the featur... | 625941d5851cf427c661a729 |
def dual_vector_valued_bernstein_basis_simplex(r, vertices, n, ordering="interleaved"): <NEW_LINE> <INDENT> dual_basis = [] <NEW_LINE> m = dimension(vertices) <NEW_LINE> if ordering == "interleaved": <NEW_LINE> <INDENT> for mi in multiindex.MultiIndexIterator(m, r): <NEW_LINE> <INDENT> for i in range(n): <NEW_LINE> <IN... | Generate all dual Bernstein base functions for the space :math:`\mathcal{P}_r(T, \mathbb{R}^n)`, where T is an
m-dimensional simplex (i.e. a basis for :math:`\mathcal{P}_r(T, \mathbb{R}^n)^*`).
See :func:`dual_vector_valued_bernstein_basis_fn_simplex`.
:param int r: Degree of the polynomial space.
:param vertices: Ve... | 625941d57b180e01f3dc4a16 |
def add_service(self, service_reg_info): <NEW_LINE> <INDENT> if not isinstance(service_reg_info, (type, ServiceRegistrationInfo)): <NEW_LINE> <INDENT> raise ValueError("Expected ServiceRegistrationInfo object") <NEW_LINE> <DEDENT> with self.lock: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> service_handler = self.servi... | Adds the specified service.
:param service: The service to add.
:return: None. | 625941d555399d3f055888d0 |
def get_name(obj): <NEW_LINE> <INDENT> if hasattr(obj, "getName"): <NEW_LINE> <INDENT> return obj.getName() <NEW_LINE> <DEDENT> elif hasattr(obj, "name"): <NEW_LINE> <INDENT> return obj.name <NEW_LINE> <DEDENT> elif hasattr(obj, "value"): <NEW_LINE> <INDENT> return obj.value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT... | Retrieve the name of an OCIO object | 625941d5dd821e528d63b3c4 |
def __init__(self, datameasure, noise=np.random.normal): <NEW_LINE> <INDENT> FeaturewiseMeasure.__init__(self) <NEW_LINE> self.__datameasure = datameasure <NEW_LINE> self.__noise = noise | Parameters
----------
datameasure : `Measure`
Used to quantify the effect of noise perturbation.
noise: Callable
Used to generate noise. The noise generator has to return an 1d array
of n values when called the `size=n` keyword argument. This is the
default interface of the random number generators in NumPy's
... | 625941d5379a373c97cfad62 |
def do_pprint(self, args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = self.evaluate(args) <NEW_LINE> display.display(pprint.pformat(result)) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass | Pretty Print | 625941d59b70327d1c4e0ff1 |
def init_lattice_basis(nfermions, L): <NEW_LINE> <INDENT> sites = tuple( LatticeSite(x, y, L) for x in range(L) for y in range(L) ) <NEW_LINE> hartree_products = tuple( itertools.permutations(sites, nfermions) ) <NEW_LINE> determinants = tuple( itertools.combinations(sites, nfermions) ) <NEW_LINE> return (hartree_produ... | Construct many-fermion bases.
:param integer nfermions: number of fermions in a simulation cell.
:param integer L: dimension of 2D square simulation cell, where each lattice
site contains a single-partle basis function.
:returns: (hartree_producs, determinants) where:
hartree_products
tuple containin... | 625941d567a9b606de4a80d4 |
def get_miniconda3_setup_starter(): <NEW_LINE> <INDENT> miniconda3_setup_starter = '{0}/{1}-setup-starter.sh'.format(xlib.get_temp_dir(), xlib.get_miniconda3_name()) <NEW_LINE> return miniconda3_setup_starter | Get the Miniconda3 setup starter path in the local computer. | 625941d5c432627299f04e63 |
def phase2(Z_list, del_list = None, new_veh =[]): <NEW_LINE> <INDENT> phase1_result = phase1(['D1', 'D2']) + new_veh <NEW_LINE> for veh in phase1_result: <NEW_LINE> <INDENT> veh.phase2_dist2Z(Z_list) <NEW_LINE> <DEDENT> sorted_routes = sorted(phase1_result, key = lambda x: x.num) <NEW_LINE> if del_list: <NEW_LINE> <IND... | 第二阶段 | 625941d53eb6a72ae02ec6fd |
def guardar_cumples(cumples): <NEW_LINE> <INDENT> with open('empleados_dict.csv', mode='w') as employee_file: <NEW_LINE> <INDENT> employee_writer = csv.DictWriter(employee_file, fieldnames=['nombre', 'area', 'mes de cumpleaños']) <NEW_LINE> employee_writer.writeheader() <NEW_LINE> employee_writer.writerows(cumples) | Guarda en un archivo CSV los cumples indicados | 625941d5a79ad161976cc361 |
def _slope_intercept(Y, X): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> coefs, full_rank = linest_helper(Y, X) <NEW_LINE> <DEDENT> except AssertionError: <NEW_LINE> <INDENT> return NA_ERROR <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return VALUE_ERROR <NEW_LINE> <DEDENT> if len(coefs) != 2: <NEW_LINE> ... | Groom linest results for SLOPE(), INTERCEPT() and FORECAST() | 625941d58c3a8732951585d7 |
def main(): <NEW_LINE> <INDENT> image = Image.open("westbrook.jpg") <NEW_LINE> for y in range(0, image.size[1]): <NEW_LINE> <INDENT> for x in range(0, image.size[0]): <NEW_LINE> <INDENT> orig_px = image.getpixel((x, y)) <NEW_LINE> new_px = (int(orig_px[0] / 2), int(orig_px[1] / 2), int(orig_px[2] / 2)) <NEW_LINE> image... | Main | 625941d51f037a2d8b946419 |
def _init(msgs: deque, title: str, stages: int, maxlines: int, timer_: timer) -> None: <NEW_LINE> <INDENT> write(f'{title}\n') <NEW_LINE> if stages: <NEW_LINE> <INDENT> prog_bar = make_progress_frame(stages) <NEW_LINE> for line in prog_bar: <NEW_LINE> <INDENT> write(f'{line}\n') <NEW_LINE> <DEDENT> <DEDENT> if maxlines... | Write the initial status display. | 625941d5ac7a0e7691ed42e5 |
def next_date_monthly_sla(self, timestamp): <NEW_LINE> <INDENT> return timestamp + self.storage.stats_month_duration(timestamp) | Get the next month from a specific date
Args:
timestamp (long): a specific date
Returns:
long: The next month | 625941d5baa26c4b54cb133a |
def get_score(self): <NEW_LINE> <INDENT> return self.__score | this function return score | 625941d597e22403b379d1b7 |
def sweep(pst, **kwargs): <NEW_LINE> <INDENT> p = icp.get.params() <NEW_LINE> folder = '/'.join([p['sweep_path'], pst]) <NEW_LINE> files = glob.glob(folder + '/*sweeps*') <NEW_LINE> products = [i.split('/')[-1] for i in files] <NEW_LINE> return products | Get available sweeps files for a PST
| 625941d5377c676e912723c4 |
def range(self): <NEW_LINE> <INDENT> assert self.symmetric == 0 <NEW_LINE> assert self.keep_negative <NEW_LINE> assert self.alpha is None or self.alpha == 1.0 <NEW_LINE> x = np.asarray(range(2**self.bits), dtype=np.float32) <NEW_LINE> p_and_n = np.where(x >= 2**(self.bits - 1), (x - 2**(self.bits - 1)) - 2**(self.bits ... | Returns a list of all values that quantized_bits can represent
ordered by their binary representation ascending. | 625941d594891a1f4081bcc6 |
def memoized(obj): <NEW_LINE> <INDENT> @functools.wraps(obj) <NEW_LINE> def memoizer(*args, **kwargs): <NEW_LINE> <INDENT> if hasattr(args[0], 'cache') and args[0].cache: <NEW_LINE> <INDENT> cache = args[0].cache <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return obj(*args, **kwargs) <NEW_LINE> <DEDENT> key = str(arg... | decorate class methods with caching.
Requires the class to have a dict-like attribute used as storage | 625941d5507cdc57c6306efa |
def __init__(self, lock_url, details=None): <NEW_LINE> <INDENT> self.lock_url = lock_url <NEW_LINE> self.details = details | Create a lock result for lock with optional details about the lock. | 625941d532920d7e50b283ee |
def choropleth( data_frame=None, lat=None, lon=None, locations=None, locationmode=None, color=None, hover_name=None, hover_data=None, custom_data=None, animation_frame=None, animation_group=None, category_orders={}, labels={}, color_continuous_scale=None, range_color=None, color_continuous_midpoint=None, projection=Non... | In a choropleth map, each row of `data_frame` is represented by a
colored region mark on a map. | 625941d563b5f9789fde7301 |
def _getElementsByAttributeValue(self, doc, path, name, value): <NEW_LINE> <INDENT> elements = doc.findall(path) <NEW_LINE> return [element for element in elements if element.get(name) == value] | Return a list of elements whose named attribute matches the value.
The cElementTree implementation does not support attribute selection
(@) or conditional expressions (./PARAM[@name = 'start']).
:param doc: An ElementTree of an XML document.
:param path: A string path to match the first element.
:param name: The attr... | 625941d58a43f66fc4b5427f |
def feed_forward_attention(self, attendees): <NEW_LINE> <INDENT> attn_length = attendees.get_shape()[1].value <NEW_LINE> attn_size = attendees.get_shape()[2].value <NEW_LINE> hidden = tf.reshape(attendees, [-1, attn_length, 1, attn_size]) <NEW_LINE> k1 = tf.get_variable("W1", [1,1,attn_size,attn_size]) <NEW_LINE> k2 = ... | Sends 3D tensor through two 2D convolutions with 2 different features | 625941d5e8904600ed9f214b |
def __init__(self, *args): <NEW_LINE> <INDENT> trie = {} <NEW_LINE> for word in args: <NEW_LINE> <INDENT> if type(word) != str: <NEW_LINE> <INDENT> raise TypeError("Trie only works on str!") <NEW_LINE> <DEDENT> temp_trie = trie <NEW_LINE> for letter in word: <NEW_LINE> <INDENT> temp_trie = temp_trie.setdefault(letter, ... | Make a trie by given words. | 625941d5f9cc0f698b140816 |
def create_jam(self, draw): <NEW_LINE> <INDENT> lineNum = random.randint(self.jam_num[0], self.jam_num[1]) <NEW_LINE> for i in range(lineNum): <NEW_LINE> <INDENT> begin = (random.randint(0, self.size[0]), random.randint(0, self.size[1])) <NEW_LINE> end = (random.randint(0, self.size[0]), random.randint(0, self.size[1])... | usage: 创建干扰线
para: draw 表示画笔
return: None
for:
todo: | 625941d5c4546d3d9de72c51 |
def _preparefilter(fp, fs, s_rate): <NEW_LINE> <INDENT> fp = _np.atleast_1d(fp) <NEW_LINE> fs = _np.atleast_1d(fs) <NEW_LINE> wp = _np.sort(_convertfreq(fp, s_rate)) <NEW_LINE> ws = _np.sort(_convertfreq(fs, s_rate)) <NEW_LINE> if len(wp) == 1: <NEW_LINE> <INDENT> if ws < wp: ftype = 'highpass' <NEW_LINE> if ws > wp: f... | Convert frequencies and get type of filter | 625941d5a8ecb033257d32e8 |
def format_pagination_body(page: int, size: int, paging_token=""): <NEW_LINE> <INDENT> return { "queryTerms": {}, "sortByKey": "ACTIVE_DATE", "cultureId": "en-US", "pagingInfo": { "PageNumber": page, "PagingToken": paging_token, "RecordsPerPage": size } } | :param page:
:param size:
:param paging_token:
:return: | 625941d507f4c71912b116a0 |
def __init__(self, *args): <NEW_LINE> <INDENT> super().__init__(*args, category=CATEGORY_THERMOSTAT) <NEW_LINE> self._unit = self.hass.config.units.temperature_unit <NEW_LINE> min_temp, max_temp = self.get_temperature_range() <NEW_LINE> serv_thermostat = self.add_preload_service(SERV_THERMOSTAT) <NEW_LINE> self.char_cu... | Initialize a WaterHeater accessory object. | 625941d563b5f9789fde7302 |
def forward(self, x): <NEW_LINE> <INDENT> return np.log(np.exp(x) + 1.) + self._lower | Implementation of softplus. Overflow avoided by use of the logaddexp function.
self._lower is added before returning. | 625941d59f2886367277aaa9 |
def read_exclude_date(ex_date_list, date_list_all, print_msg=True): <NEW_LINE> <INDENT> ex_date_list = ptime.read_date_list(ex_date_list) <NEW_LINE> if ex_date_list and print_msg: <NEW_LINE> <INDENT> print(('exclude the following dates for DEM error estimation:' ' ({})\n{}').format(len(ex_date_list), ex_date_list)) <NE... | Read exclude dates info
Parameters: ex_date_list : list of string, date in YYMMDD or YYYYMMDD format,
or text file with date in it
date_list_all : list of string, date in YYYYMMDD format
Returns: drop_date : 1D array of bool in size of (num_date,) | 625941d55f7d997b87174cb5 |
def camera_image(self): <NEW_LINE> <INDENT> raise NotImplementedError() | Return bytes of camera image. | 625941d54e4d5625662d45f2 |
def __init__(self, basename, titles=[], singleFile=False): <NEW_LINE> <INDENT> self.files={} <NEW_LINE> self.lastTime="" <NEW_LINE> self.called={} <NEW_LINE> self.basename=basename <NEW_LINE> self.setTitles(titles) <NEW_LINE> self.singleFile=singleFile <NEW_LINE> self.openList=[] | :param basename: name of the base directory
:param titles: names of the data columns
:param singleFile: don't split into multiple files if more than one
datum is insert per time-step | 625941d52c8b7c6e89b359dc |
def test_magic_marker_happy_path_two_tests(two_tests_unmarked, original_behavior_config, uuid_patch, mocker): <NEW_LINE> <INDENT> mocker.patch('uuid.uuid1', return_value=uuid_patch) <NEW_LINE> runner = CliRunner() <NEW_LINE> cli_arguments = ["--config={}".format(original_behavior_config), two_tests_unmarked.path] <NEW_... | Test marking two tests in the same file | 625941d5435de62698dfde69 |
def get_token(server_id, private_key): <NEW_LINE> <INDENT> crnt_time = int(datetime.now().strftime('%s')) <NEW_LINE> exp_time = crnt_time + 3600 <NEW_LINE> claim_set = { 'iss': server_id, 'iat': crnt_time, 'exp': exp_time } <NEW_LINE> key = open(private_key).read() <NEW_LINE> lw_jwt = jwt.encode(claim_set, key, algorit... | JWT から server token の生成 | 625941d53317a56b86939e71 |
def Load(self, XMLElement): <NEW_LINE> <INDENT> super().Load(XMLElement) <NEW_LINE> self._x = float(XMLElement.find('x').text) <NEW_LINE> self._y = float(XMLElement.find('y').text) <NEW_LINE> self._z = float(XMLElement.find('z').text) <NEW_LINE> self._rotation = float(XMLElement.find('rotation').text) <NEW_LINE> self._... | This is for initialization from an XML element. Doesn't necessarily
have to be fast | 625941d54527f215b584c671 |
def __init__(self, *args, **kargs): <NEW_LINE> <INDENT> GraphicsObject.__init__(self) <NEW_LINE> self.setFlag(self.ItemHasNoContents) <NEW_LINE> self.xData = None <NEW_LINE> self.yData = None <NEW_LINE> self.xDisp = None <NEW_LINE> self.yDisp = None <NEW_LINE> self.curve = PlotCurveItem() <NEW_LINE> self.scatter = Scat... | There are many different ways to create a PlotDataItem:
Data initialization: (x,y data only)
=================================== ======================================
PlotDataItem(xValues, yValues) x and y values may be any sequence (including ndarray) of real numbers
PlotDataItem(yValues) ... | 625941d55fc7496912cc3b9a |
def get_started(self, *args): <NEW_LINE> <INDENT> url = QUrl(LINKS["get-started"]) <NEW_LINE> QDesktopServices.openUrl(url) | Show getting started documentation
| 625941d58a43f66fc4b54280 |
def __getitem__(self, key): <NEW_LINE> <INDENT> if key in (KEY_2WAY, KEY_3WAY, KEY_NWAY): <NEW_LINE> <INDENT> return self.config.get(section=SECTION_ENGINES, option=key, fallback=None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (self.config[key] if self.config.has_section(key) else None) | Return section or option value for key from configuration.
If key is one of KEY_2WAY, KEY_3WAY or KEY_NWAY, assume section is
"Engines", hence return their option values. On any other key,
return section for that key. | 625941d556ac1b37e62643ea |
def iwithini(mention, other): <NEW_LINE> <INDENT> return (mention.sentno == other.sentno and (mention.begin <= other.begin <= mention.end or mention.begin <= other.end <= mention.end or other.begin <= mention.begin <= other.end or other.begin <= mention.end <= other.end)) | Check whether spans overlap. | 625941d5596a897236089cdb |
def _handle_stream_iteration(self) -> None: <NEW_LINE> <INDENT> if not self._authenticated: <NEW_LINE> <INDENT> raise WebsocketAuthenticationError( f"Failed to authenticate against the server: {self._error}") <NEW_LINE> <DEDENT> if self._server_close_code == self._API_STATUS_JOB_DONE: <NEW_LINE> <INDENT> self._server_c... | Handle a streaming iteration. | 625941d57c178a314d6ef67e |
def _set_retriever_info( question, scored_hits, table_id, ): <NEW_LINE> <INDENT> result = _get_table_rank_and_score(scored_hits, table_id) <NEW_LINE> if result is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> rank, score = result <NEW_LINE> ext = question.Extensions[retriever_info_pb2.RetrieverInfo.question_ext]... | Sets the basic retriever info. | 625941d599fddb7c1c9de5ad |
def findMin(self, nums): <NEW_LINE> <INDENT> if len(nums) < 3: <NEW_LINE> <INDENT> return min(nums) <NEW_LINE> <DEDENT> left, right = 0, len(nums)-1 <NEW_LINE> while left <= right: <NEW_LINE> <INDENT> mid = left + (right - left) / 2 <NEW_LINE> if mid == 0: <NEW_LINE> <INDENT> if nums[mid] < nums[mid+1] and nums[mid] < ... | :type nums: List[int]
:rtype: int | 625941d5091ae35668667178 |
def test_decode_even(self): <NEW_LINE> <INDENT> bytestream = b"\x54\x00\x00\x0a\x00\x06\x31\x2e\x32\x2e\x33\x31\x00\x01" <NEW_LINE> item = SCP_SCU_RoleSelectionSubItem() <NEW_LINE> item.decode(bytestream) <NEW_LINE> assert item.item_length == 10 <NEW_LINE> assert item.uid_length == 6 <NEW_LINE> assert item.sop_class_ui... | Test decoding even-length UID | 625941d5a4f1c619b28b0252 |
def process_exception(self, request, exception): <NEW_LINE> <INDENT> record_exception(exception=exception, request=request) | Get exception and save it in database. | 625941d599fddb7c1c9de5ae |
def planck(self, T): <NEW_LINE> <INDENT> wave = self.wavelength*1e8 <NEW_LINE> conv = 2 * hplank * c_cgs**2 / wave**5 * 1e8 <NEW_LINE> denom = (np.exp(hplanck * c_cgs / (kboltz * T)) - 1) <NEW_LINE> return conv * 1 / denom | Return planck function B_lambda(cgs) for a given T
| 625941d55166f23b2e1a5376 |
@select_database("alcrni.tdb") <NEW_LINE> def test_ternary_ordered_magnetic(load_database): <NEW_LINE> <INDENT> dbf = load_database() <NEW_LINE> check_energy(Model(dbf, ['AL', 'CR', 'NI'], 'L12_FCC'), {v.T: 300, v.SiteFraction('L12_FCC', 0, 'AL'): 5.42883e-8, v.SiteFraction('L12_FCC', 0, 'CR'): 2.07934e-6, v... | Ternary ordered solution phase with IHJ magnetic model. | 625941d5009cb60464c635cd |
def __getattr__(self, name): <NEW_LINE> <INDENT> return os.environ.get(name.upper(), self.values.get(name.lower())) | Get the value from the ENV, if it's not present, get
it from the dictionary. Returns None if not found. | 625941d57b180e01f3dc4a17 |
@offline_wrapper <NEW_LINE> def time(adr, token): <NEW_LINE> <INDENT> rv = requests.post(adr + '/time', json={'token': token}).json() <NEW_LINE> return f'Server data:\t{rv["date"]}\nServer time:\t{rv["time"]}' | | get server time
:param adr: server address
:param token: user token
:return: str, server time | 625941d53cc13d1c6d3c7596 |
def load(self): <NEW_LINE> <INDENT> chain = TChain(self._tree) <NEW_LINE> for f in self._files: <NEW_LINE> <INDENT> if not isfile(f): <NEW_LINE> <INDENT> raise RuntimeError('file does not exist {0}'.format(f)) <NEW_LINE> <DEDENT> chain.Add(f) <NEW_LINE> <DEDENT> for friend in self._friends: <NEW_LINE> <INDENT> chain.Ad... | Loads the process data.
Returns:
A TChain for the process. | 625941d55f7d997b87174cb6 |
def associate_data_sheet(self): <NEW_LINE> <INDENT> path = askopenfilename(parent=root, initialdir=self.dsdir, defaultextension='.pdf', title='Associate Datasheet') <NEW_LINE> print(len(path)) <NEW_LINE> if path is not None and len(path): <NEW_LINE> <INDENT> if path.startswith(self.dsdir): <NEW_LINE> <INDENT> path = pa... | Associate a datasheet to a manufacturer part number
:return: N/A | 625941d55fcc89381b1e18dd |
def create_host_user(): <NEW_LINE> <INDENT> hosts_file = os.path.join(base_dir, 'db', 'new_host_user.yml') <NEW_LINE> f = open(hosts_file) <NEW_LINE> source = yaml.load(f) <NEW_LINE> if source: <NEW_LINE> <INDENT> for key, val in source.items(): <NEW_LINE> <INDENT> host = val.get('host') <NEW_LINE> host_ret = db_conn.s... | 创建主机用户 一台主机可以有不同权限的用户
:return: | 625941d55fc7496912cc3b9b |
def update_cluster(self, cluster): <NEW_LINE> <INDENT> if self.cluster is not None: <NEW_LINE> <INDENT> self.cluster.update_by_twh(self, factor=-1) <NEW_LINE> <DEDENT> self.cluster = cluster <NEW_LINE> if cluster is not None: <NEW_LINE> <INDENT> cluster.update_by_twh(self, factor=1) | 若原本有聚类,则将当前推特从原本的 self.cluster 中分离;
并将当前推特合并至 cluster 中(若不为None),更新 self.cluster
:param cluster: 目标聚类对象
:return: | 625941d515fb5d323cde0d2e |
def classification_accuracy(knn, k, eval_data, eval_labels): <NEW_LINE> <INDENT> predictions = [] <NEW_LINE> for i in range(len(eval_data)): <NEW_LINE> <INDENT> prediction_val = knn.query_knn(eval_data[i], k) <NEW_LINE> predictions.append(prediction_val) <NEW_LINE> <DEDENT> return accuracy_score(eval_labels, prediction... | Evaluate the classification accuracy of knn on the given 'eval_data'
using the labels | 625941d5596a897236089cdc |
def temps_restant(self): <NEW_LINE> <INDENT> return self.temps_maximum() - (time.time() - self.temps_depart) | Retourne le temps restant à l'utilisateur pour finir la partie.
:return: temps restant | 625941d56fece00bbac2d95d |
def test_get_extraneous(self): <NEW_LINE> <INDENT> cs = self.get_filelist2_cs() <NEW_LINE> assert len(cs.orphaned_backup_sets) == 1, cs.orphaned_backup_sets <NEW_LINE> assert len(cs.local_orphaned_sig_names) == 0, cs.local_orphaned_sig_names <NEW_LINE> assert len(cs.remote_orphaned_sig_names) == 1, cs.remote_orphaned_s... | Test the listing of extraneous files | 625941d58e05c05ec3eea593 |
def chunkify(string: str): <NEW_LINE> <INDENT> for i in range(0, len(string), BLOCK_SIZE): <NEW_LINE> <INDENT> yield string[i:i + BLOCK_SIZE] | Create a generator of chunks of CHUNK_SIZE length | 625941d592d797404e3043a8 |
def test_simple(self): <NEW_LINE> <INDENT> self.assertIsNotNone(self.runtime) <NEW_LINE> self.assertIsInstance(self.runtime,ELR) | Check the runtime works in a minimal case | 625941d56fb2d068a760f2bd |
def generate_inverted_index(self): <NEW_LINE> <INDENT> from baseline.word_embedding import AbbrIndex <NEW_LINE> abbr_index = AbbrIndex() <NEW_LINE> txt_post_processed = [] <NEW_LINE> global_instance_idx = 0 <NEW_LINE> for doc_idx, doc in enumerate(self.corpus): <NEW_LINE> <INDENT> doc_abbr = defaultdict(list) <NEW_LINE... | Generate abbr inverted index and remove abbr marks.
:return: | 625941d566673b3332b922af |
def has_intersection(self, obj): <NEW_LINE> <INDENT> distance = math.sqrt((obj.x_location - self.x_location) ** 2 + ( obj.y_location - self.y_location) ** 2) <NEW_LINE> if distance <= self.get_radius() + obj.get_radius(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | this function checks if an object has the same location as an asteroid
:param obj: ship or torpedo type object
:return: True if there's an intersection, False otherwise | 625941d5d268445f265b508b |
def print_card_double(fields, wipe_fields=True): <NEW_LINE> <INDENT> if wipe_fields: <NEW_LINE> <INDENT> fields = wipe_empty_fields(fields) <NEW_LINE> <DEDENT> nfields_main = len(fields) - 1 <NEW_LINE> nBDF_lines = nfields_main // 8 <NEW_LINE> if nfields_main % 8 != 0: <NEW_LINE> <INDENT> nBDF_lines += 1 <NEW_LINE> nEx... | Prints a nastran-style card with 16-character width fields.
:param fields: all the fields in the BDF card (no trailing Nones)
:param wipe_fields: some cards (e.g. PBEAM) have ending fields
that need to be there, others cannot have them.
.. note:: An internal field value of None or '' will be trea... | 625941d50a50d4780f6670b1 |
def set_arm(self, arm, timeout): <NEW_LINE> <INDENT> old_arm = self.state.armed <NEW_LINE> loop_freq = 1 <NEW_LINE> rate = rospy.Rate(loop_freq) <NEW_LINE> arm_set = False <NEW_LINE> for i in xrange(timeout * loop_freq): <NEW_LINE> <INDENT> if self.state.armed == arm: <NEW_LINE> <INDENT> arm_set = True <NEW_LINE> rospy... | arm: True to arm or False to disarm, timeout(int): seconds | 625941d5d8ef3951e324375a |
def chattitle(slack_bot, msg, args): <NEW_LINE> <INDENT> return slack_bot.bot.call_shared( 'setchattitle', args=args, platform=slack_bot.identifier, fallback=msg.channel, source=slack_bot.conversations) | update the synced chattitle for the current or specified channel
Args:
slack_bot (core.SlackRTM): the instance which received the message
msg (message.SlackMessage): the currently handled message
args (tuple[str]): additional arguments as strings
Returns:
str: command output | 625941d550485f2cf553cfb8 |
def build_dataset_hierarchy(host, secret_key, clowder_user, clowder_pass, root_space, season, experiment, root_coll_name, year='', month='', date='', leaf_ds_name=''): <NEW_LINE> <INDENT> if season: <NEW_LINE> <INDENT> season_collect = get_collection_or_create(host, secret_key, clowder_user, clowder_pass, season, paren... | This will build collections if needed in parent space.
Typical hierarchy:
MAIN LEVEL 1 DATA SPACE IN CLOWDER
- Season ("Season 6")
- Experiment ("Sorghum BAP")
- Root collection for sensor ("stereoRGB geotiffs")
- Year collection ("stereoRGB geotiffs - 2017")
- Month collection ("stereoRGB geotiffs - 2017-... | 625941d51d351010ab855d39 |
def merge_cart_cookie_to_redis(request, user, response): <NEW_LINE> <INDENT> cookie_cart = request.COOKIES.get('cart') <NEW_LINE> if not cookie_cart: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> cookie_cart_dict = pickle.loads(base64.b64decode(cookie_cart)) <NEW_LINE> if not cookie_cart_dict: <NEW_LINE> <INDENT> retu... | 合并请求用户的购物车数据,将未登录保存在cookie里的保存到redis中
遇到cookie与redis中出现相同的商品时以cookie数据为主,覆盖redis中的数据
:param request: 用户的请求对象
:return: | 625941d5aad79263cf390c61 |
def all_index(self, name): <NEW_LINE> <INDENT> self._set_ddb_index(name, LocalIndex.all) <NEW_LINE> return self | Index this field and project all attributes
Parameters
----------
name : str
The name of the index | 625941d5d18da76e235326f5 |
def test_read(self): <NEW_LINE> <INDENT> EXPECTED = {'501': ['Sheman', 'Tai', 'Wyss', 'Mallard Loop', '133', 'Whitefish', '59937', 'stumpy@lowdog.com', 'Guard Dog', 'Mom', 'Igor', '501', 'yes', 'yes', '12/10/2011', '20'], '500' :['Madison', 'Katy', 'Wyss', 'Marina Blvd', '305', 'San Leandro', '90210', 'madison@baby.com... | Read in rows of data into a dict of lists, update Spreadsheet Rolodex
to highest Rolodex. | 625941d5ff9c53063f47c410 |
def reset_course_to_version(self, course_key, version_guid, user_id): <NEW_LINE> <INDENT> draft_course_key = course_key.for_branch(ModuleStoreEnum.BranchName.draft) <NEW_LINE> version_object_id = course_key.as_object_id(version_guid) <NEW_LINE> with self.bulk_operations(draft_course_key): <NEW_LINE> <INDENT> index_entr... | Resets a course to a version specified by the string `version_guid`.
The `version_guid` refers to the Mongo-level id ("_id")
of the structure we want to revert to. It should be a 24-digit hex string. | 625941d573bcbd0ca4b2c293 |
def test_Is_Proper_Position__Improper_Length(score, max_score): <NEW_LINE> <INDENT> max_score.value += 1 <NEW_LINE> try: <NEW_LINE> <INDENT> assert not Position.is_proper_position(4, (1,)) <NEW_LINE> score.value += 1 <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass | Function is_proper_position: given position is a tuple of length different from 2. | 625941d530c21e258bdfa6bb |
def p_string(p): <NEW_LINE> <INDENT> p[0] = p[1] | string : SSTRING
| DSTRING
| USTRING | 625941d5dd821e528d63b3c5 |
def _connect(self): <NEW_LINE> <INDENT> super(Connection, self)._connect() <NEW_LINE> network_os = self._play_context.network_os <NEW_LINE> if not network_os: <NEW_LINE> <INDENT> for cls in terminal_loader.all(class_only=True): <NEW_LINE> <INDENT> network_os = cls.guess_network_os(self.ssh) <NEW_LINE> if network_os: <N... | Connections to the device and sets the terminal type | 625941d5cdde0d52a9e53251 |
def extract_csv_or_tsv(self, file): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> row = next(file) <NEW_LINE> self.amount_of_lines += 1 <NEW_LINE> return row <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> break | Extracts all rows from a csv or tsv file | 625941d5283ffb24f3c55b1d |
def add_drift_unit_vectors(inst): <NEW_LINE> <INDENT> theta = inst['mlt'] * (np.pi / 12.0) - np.pi * 0.5 <NEW_LINE> r = np.radians(90.0 - inst['mlat'].abs()) <NEW_LINE> pos_x = r * np.cos(theta) <NEW_LINE> pos_y = r * np.sin(theta) <NEW_LINE> diff_x = pos_x.diff() <NEW_LINE> diff_y = pos_y.diff() <NEW_LINE> norm = np.s... | Add unit vectors for the satellite velocity
Parameters
----------
inst : pysat.Instrument
DMSP IVM Instrument object
Note
----
Assumes that the RAM vector is pointed perfectly forward | 625941d57cff6e4e81117ba3 |
def test_odd_sum_of_js(self): <NEW_LINE> <INDENT> self.assertAlmostEqual( nf_amc.wigner_3j( 0, 2, 0, 0, 0, 0 ), 0.0 ) <NEW_LINE> self.assertAlmostEqual( nf_amc.wigner_3j( 6, 0, 0, 0, 0, 0 ), 0.0 ) | J = j1 + j2 + j3 == odd, then is zero | 625941d56fece00bbac2d95e |
def test_simple_case(self): <NEW_LINE> <INDENT> file_a = os.path.join(SIMPLE_TEST, 'a.ts') <NEW_LINE> result = get_deptree([file_a]) <NEW_LINE> expected = OrderedDict([('lib/deptree/test/data/simple/a.ts', []), ('lib/deptree/test/data/simple/b.ts', ['lib/deptree/test/data/simple/a.ts']), ('lib/deptree/test/data/simple/... | Test a very simple depedency case. | 625941d5b7558d58953c512f |
def get_set_from_curs(cur_set): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for (idx, in_cur_set) in enumerate(cur_set): <NEW_LINE> <INDENT> if in_cur_set: <NEW_LINE> <INDENT> result.append(idx) <NEW_LINE> <DEDENT> <DEDENT> return result | Get number set from boolean list
:param cur_set: list
:return: list | 625941d5090684286d50ef04 |
def evaluate(self): <NEW_LINE> <INDENT> return self._result | return contents of url or none"
| 625941d571ff763f4b5498ac |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.