code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_daos_racer(self): <NEW_LINE> <INDENT> self.assertGreater( len(self.hostlist_clients), 0, "This test requires one client: {}".format(self.hostlist_clients)) <NEW_LINE> daos_racer = DaosRacerCommand(self.bin, self.hostlist_clients[0]) <NEW_LINE> daos_racer.get_params(self) <NEW_LINE> daos_racer.set_environment( ... | JIRA-3855: daos_racer/consistency checker test.
Test Description:
The daos_racer test tool generates a bunch of simultaneous,
conflicting I/O requests. After it is run it will verify that all
the replicas of a given object are consistent.
Run daos_racer for 5-10 minutes or so on 3-way replicated objec... | 625941d1097d151d1a222fe9 |
def __init__(self, nbvar): <NEW_LINE> <INDENT> if not isinstance(nbvar, int): <NEW_LINE> <INDENT> print("ERROR: Sentence Sentence() -> nbvar must be an integer") <NEW_LINE> <DEDENT> self.clauses = list() <NEW_LINE> self.nbvar = nbvar | Initializes the clauses as an empty list and sets the number of variables nbvar.
:param nbvar: Integer with the number of variables in the knowledge base.
:return: --- | 625941d1236d856c2ad4496b |
def get_Nparam_from_fname_simul(a_fname): <NEW_LINE> <INDENT> if (a_fname == '3G_Simul'): <NEW_LINE> <INDENT> return 9 <NEW_LINE> <DEDENT> elif (a_fname == '2G1Ysq_Simul'): <NEW_LINE> <INDENT> return 10 <NEW_LINE> <DEDENT> elif (a_fname == '4G_Simul'): <NEW_LINE> <INDENT> return 12 <NEW_LINE> <DEDENT> elif (a_fname =... | The function to get the #.param of various fit functions for the simultaniously fitting.
(Fit fname ==> #.param)
return: #.param
Note: The definition of the fname is noted in ./Definition_Ftype.txt | 625941d19c8ee82313fbb905 |
def __init__(self, host="localhost", ssl_keyfile=None, dbName="test", collection="test_collection", port=27017, user=None, pwd=""): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.dbName = dbName <NEW_LINE> self.collection = collection <NEW_LINE> if user is not None: <NE... | Create a connection to the MongoDB demon on the given host/port.
:param host: host name where MongoDB demon is running. Can be IP address as string.
:type host: String
:param port: MongoDB demon's port
:type port: int | 625941d1293b9510aa2c3425 |
def raw_mod(opts, name, functions): <NEW_LINE> <INDENT> load = _create_loader(opts, 'modules', 'rawmodule') <NEW_LINE> return load.gen_module(name, functions) | Returns a single module loaded raw and bypassing the __virtual__ function
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
testmod = salt.loader.raw_mod(__opts__, 'test', None)
testmod['test.ping']() | 625941d1287bf620b61d3bf2 |
def remove(self, key: str): <NEW_LINE> <INDENT> pass | delete will remove a given file from the backing storage implementation | 625941d1aad79263cf390bd1 |
def softmax(predictions): <NEW_LINE> <INDENT> predictions -= np.max(predictions) <NEW_LINE> predictions_cur = np.exp(predictions) <NEW_LINE> predictions_sum = np.sum(np.exp(predictions)) <NEW_LINE> probs = predictions_cur / predictions_sum <NEW_LINE> return probs | Computes probabilities from scores
Arguments:
predictions, np array, shape is either (N) or (batch_size, N) -
classifier output
Returns:
probs, np array of the same shape as predictions -
probability for every class, 0..1 | 625941d182261d6c526ab630 |
def _purge_label(self, label_to_purge, decrement_remaining, replacement_value=0): <NEW_LINE> <INDENT> changed_block_rois = [] <NEW_LINE> stored_block_roi_destination = [None] <NEW_LINE> self.execute(self.CleanBlocks, (), SubRegion(self.Output, (0,), (1,)), stored_block_roi_destination) <NEW_LINE> stored_block_rois = st... | Scan through all labeled pixels.
(1) Reassign all pixels of the given value (set to replacement_value)
(2) If decrement_remaining=True, decrement all labels above that
value so the set of stored labels remains consecutive.
Note that the decrement is performed AFTER replacement. | 625941d14527f215b584c5e5 |
def __init__(self, volume_list, notetime, y_res=36, spacing=12): <NEW_LINE> <INDENT> self.notes = [110. * (2 ** (n/np.float32(spacing))) for n in range(y_res)] <NEW_LINE> self.framerate = 44100 <NEW_LINE> self.notetime = notetime <NEW_LINE> self.framect = int(self.framerate*self.notetime) <NEW_LINE> self.volumes = volu... | Initializes the SoundSpace object.
Starts an object that converts all the sounds
Parameters:
------------
volume_list : Numpy 2d array in np.float32
Contains a matrix of data relating to pixel intensity
notetime : float
Basically the duration of the chord you want played (in seconds)
y_res : int
How many ... | 625941d1aad79263cf390bd2 |
def get_nom(self, etat, nombre): <NEW_LINE> <INDENT> if nombre <= 0: <NEW_LINE> <INDENT> raise ValueError("le nombre {} est négatif ou nul".format(nombre)) <NEW_LINE> <DEDENT> etat = self.etats[etat] <NEW_LINE> if nombre == 1: <NEW_LINE> <INDENT> return etat.nom_singulier <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n... | Retourne le nom singulier ou pluriel. | 625941d1c4546d3d9de72bc4 |
def extend(self, *args, **kwargs): <NEW_LINE> <INDENT> self._extend(args, kwargs, 'extend', self.add) | Extends current MultiDict with more values.
This method must be used instead of update. | 625941d11f037a2d8b94638d |
def parse_tables(self, input_ddl): <NEW_LINE> <INDENT> creating = False <NEW_LINE> buff = "" <NEW_LINE> for line in input_ddl: <NEW_LINE> <INDENT> l = self.clean_line(line) <NEW_LINE> if not creating: <NEW_LINE> <INDENT> if l.lower().find("create table") >= 0: <NEW_LINE> <INDENT> creating = True <NEW_LINE> buff = l <NE... | Parses the input DDL to convert to a database model.
:param input_ddl: The DDL to convert.
:type input_ddl: list of str | 625941d115baa723493c4106 |
def next_sunrise_timestamp_ms(self, botengine): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ephem = importlib.import_module("ephem") <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> ephem = None <NEW_LINE> <DEDENT> if self.parent.longitude is None or self.parent.latitude is None or ephem is None: <NEW_LINE>... | :param botengine: BotEngine environment
:return: The next sunrise timestamp in ms | 625941d1d18da76e23532666 |
def test_book_single_flight_for_user_no_permission(self): <NEW_LINE> <INDENT> reservation_data = self.valid_reservation_data <NEW_LINE> response = self.client.post( reverse( 'account-reservations-reservations', kwargs={ 'version': 'v1', 'pk': self.user.account.id, } ), data=reservation_data ) <NEW_LINE> self.assertFals... | Book Flight for User Account - Invalid :- No permission (not logged in maybe) | 625941d19f2886367277aa1c |
def __init__(self): <NEW_LINE> <INDENT> if 'matplotlib' in sys.modules: <NEW_LINE> <INDENT> import matplotlib <NEW_LINE> backend = matplotlib.get_backend().lower() <NEW_LINE> if 'qt' in backend: <NEW_LINE> <INDENT> from bluesky.callbacks.mpl_plotting import initialize_qt_teleporter <NEW_LINE> initialize_qt_teleporter() | Initialize backend.
Currently only the Qt backend is supported. The function is
initializing the 'teleporter' if Qt backend is used. | 625941d14c3428357757c4b7 |
def long_words(words): <NEW_LINE> <INDENT> long_words_lst = [] <NEW_LINE> for word in words: <NEW_LINE> <INDENT> if len(word) > 4: <NEW_LINE> <INDENT> long_words_lst.append(word) <NEW_LINE> <DEDENT> <DEDENT> return long_words_lst | Return words in input list that longer than 4 characters.
For example::
>>> long_words(["hello", "a", "b", "hi", "bacon", "bacon"])
['hello', 'bacon', 'bacon']
(If there are duplicates, show both --- notice "bacon" appears
twice in output)
If no words are longer than 4 characters, return an empty list::
... | 625941d191af0d3eaac9bba9 |
def set_font_sizes(fontSizes: FontSizes) -> dict: <NEW_LINE> <INDENT> return {"method": "Page.setFontSizes", "params": {"fontSizes": fontSizes.to_json()}} | Set default font sizes.
Parameters
----------
fontSizes: FontSizes
Specifies font sizes to set. If a font size is not specified, it won't be changed.
**Experimental** | 625941d14e696a04525c95db |
def __str__(self): <NEW_LINE> <INDENT> j_ifaces = " " <NEW_LINE> for i in self.ifaces: <NEW_LINE> <INDENT> j_ifaces += " {},".format(i.get_name()) <NEW_LINE> <DEDENT> j_ifaces = j_ifaces[0:-1] <NEW_LINE> if self.default: <NEW_LINE> <INDENT> funcs = self.DEFAULT_FUNC_TEMPLATE.format(ifaces = j_ifaces, tree = self.get_tr... | Print the java code of this interface. | 625941d110dbd63aa1bd2d33 |
def mm_to_px(self, intersection): <NEW_LINE> <INDENT> fast = intersection[0] / self._px_size_fast <NEW_LINE> slow = intersection[1] / self._px_size_slow <NEW_LINE> return (fast, slow) | Take an intersection in mm in the abstract coordinate frame
attached to the sensor and convert it to coordinates in units of
pixels in image space. This basic implementation assumes that the
two origins coincide, the fast axis is aligned along dir1 and
the slow axis along dir2. This does no bounds checking, it is
purel... | 625941d18da39b475bd65105 |
def pacestr2nxdecomp(self, lines, graph, name): <NEW_LINE> <INDENT> td = TreeDecomposition(graph=graph, td_name=name, temp_path=self.temp_path, plot_if_td_invalid=self.plot_if_td_invalid) <NEW_LINE> if lines == '': <NEW_LINE> <INDENT> sys.stderr.write('No input string from solver.') <NEW_LINE> return td <NEW_LINE> <DED... | :param lines:
:param graph:
:param name:
:rtype: TreeDecomposition
:return: | 625941d130dc7b7665901af6 |
def output_mutt_aliases(contacts): <NEW_LINE> <INDENT> nicks = {} <NEW_LINE> printed = set() <NEW_LINE> for contact in contacts: <NEW_LINE> <INDENT> if contact.id in printed: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if not contact.email: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for email in contact.emai... | Print all contact records as a Mutt aliases file. | 625941d1462c4b4f79d1d861 |
def sphere_natural_convection(Gr, Pr): <NEW_LINE> <INDENT> Ra = Gr * Pr <NEW_LINE> return 2 + 0.589 * Ra**0.25 / (1 + (0.469 / Pr)**(9.0/16))**(4.0/9) | natural convection for sphere. characteristic dimensoion is diameter of sphare
Pr > 0.7, Ra < 1e11
return Nu | 625941d1627d3e7fe0d68fe0 |
def unpack_variation(variation): <NEW_LINE> <INDENT> ground_variation = variation & 0b00011111 <NEW_LINE> cliff_variation = (variation & 0b11100000) >> 5 <NEW_LINE> return ground_variation, cliff_variation | 5bits ground_variation
Which variation of the texture to use (bones, holes, etc...).
This is to reduce the amount of repetition.
3bits cliff_variation
Cliff variations seem to be allowed to be between the range 0 to 7.
If the cliff variation model isn't available then
the game will take the... | 625941d124f1403a92600cf5 |
def create_barchart(self, group_df, group_name, substrate): <NEW_LINE> <INDENT> labels = ["Batch", "Wafer No.", "HM location", "Test structure"] <NEW_LINE> labels.remove(self.sort_parameter) <NEW_LINE> innermost_groups = group_df.groupby(labels) <NEW_LINE> r_mean = innermost_groups["Linewidth [um]"].mean() <NEW_LINE> '... | Calculates mean if all labels are equivalent | 625941d110dbd63aa1bd2d34 |
def unsign(self, value, max_age=None): <NEW_LINE> <INDENT> result = super().unsign(value) <NEW_LINE> value, timestamp = result.rsplit(self.sep, 1) <NEW_LINE> timestamp = Base62.decode(timestamp) <NEW_LINE> if max_age is not None: <NEW_LINE> <INDENT> if isinstance(max_age, datetime.timedelta): <NEW_LINE> <INDENT> max_ag... | Retrieve original value and check it wasn't signed more
than max_age seconds ago. | 625941d176d4e153a657ecc1 |
def extract_metadata(image): <NEW_LINE> <INDENT> size = os.path.getsize(image) <NEW_LINE> mime = magic.from_file(image, mime=True) <NEW_LINE> text = magic.from_file(image) <NEW_LINE> data = {'mime': mime, 'size': size, 'length': 0, 'width': 0} <NEW_LINE> if 'image' in mime: <NEW_LINE> <INDENT> format = mime.replace('im... | Receives a image file | 625941d1004d5f362079a4c2 |
def open(self, track): <NEW_LINE> <INDENT> self.__commands__.put(("open", (track,))) | opens the given AudioFile for playing
stops playing the current file, if any | 625941d1099cdd3c635f0deb |
def total_cost(self, generated_image): <NEW_LINE> <INDENT> s = self.content_image.shape <NEW_LINE> m = "generated_image must be a tensor of shape {}".format(s) <NEW_LINE> if not isinstance(generated_image, (tf.Tensor, tf.Variable)): <NEW_LINE> <INDENT> raise TypeError(m) <NEW_LINE> <DEDENT> if generated_image.shape != ... | :param generated_image: tf.Tensor of shape (1, nh, nw, 3)
containing the generated image
:return: J, J_content, J_style)
J is the total cost
J_content is the content cost
J_style is the style cost | 625941d1004d5f362079a4c3 |
def _translate_alias_to_requests(alias_spec): <NEW_LINE> <INDENT> pci_aliases = _get_alias_from_config() <NEW_LINE> pci_requests = [] <NEW_LINE> for name, count in [spec.split(':') for spec in alias_spec.split(',')]: <NEW_LINE> <INDENT> name = name.strip() <NEW_LINE> if name not in pci_aliases: <NEW_LINE> <INDENT> rais... | Generate complete pci requests from pci aliases in extra_spec. | 625941d14f88993c3716c1f6 |
def temp_set(self): <NEW_LINE> <INDENT> self.tmp_target["text"] = "{:.1f}".format(sd.askinteger("設定温度", "設定温度を入力")) | temp_set_button押下時に設定温度を入力するファンクション | 625941d130bbd722463cbf56 |
def PSY(y, swindow0, IC, adflag): <NEW_LINE> <INDENT> t = len(y) <NEW_LINE> if not swindow0: <NEW_LINE> <INDENT> swindow0 = int(math.floor(t * (0.01 + 1.8 / np.sqrt(t)))) <NEW_LINE> <DEDENT> bsadfs = np.zeros([t, 1]) <NEW_LINE> for r2 in range(swindow0, t + 1): <NEW_LINE> <INDENT> rwadft = np.ones([r2 - swindow0 + 1, 1... | Estimate PSY's BSADF sequence of test statistics
implements the real time bubble detection procedure of Phillips, Shi and Yu (2015a,b)
param: y: np.array of the data
param: swindow0: integer minimum window size
param: adflag: An integer, lag order when IC=0; maximum number of lags when IC>0 (default = 0).
For every p... | 625941d1cc0a2c11143dd020 |
@exp.automain <NEW_LINE> def rf_ff_experiment(data_name, exp_network, in_dim, out_dim, num_layers, start_neurons, num_neurons, batch_size, num_epochs): <NEW_LINE> <INDENT> train_set, stream_train, test_set, stream_test = ds.prepare_datastream( data_name, batch_size) <NEW_LINE> methods = ['sgd', 'momentum', 'adagrad', '... | Feedforward Experiment. | 625941d15fdd1c0f98dc03c4 |
@APP.route('/subjects') <NEW_LINE> def subjects(): <NEW_LINE> <INDENT> fetched_subjects = DB.session.query(Subject).order_by(Subject.name) <NEW_LINE> return render_template('public/subjects.html', subjects=fetched_subjects) | Страничка для отображения предметов обучения | 625941d10c0af96317bb8378 |
def log_debug(self, line): <NEW_LINE> <INDENT> logging.debug("Sondehub Uploader - %s" % line) | Helper function to log a debug message with a descriptive heading.
Args:
line (str): Message to be logged. | 625941d107f4c71912b11613 |
def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.cm.Blues): <NEW_LINE> <INDENT> if not title: <NEW_LINE> <INDENT> if normalize: <NEW_LINE> <INDENT> title = 'Normalized confusion matrix' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> title = 'Confusion matrix, without normalization... | 用于绘制混淆矩阵图
y_true: 真实预测结果 Series或者array
y_pred: 模型预测结果(非概率)Series或者array
classes: 预测类别的名称 Series或者array
normalize: 是否进行标准化 boolean
title: 图形标题 str
you can see example on https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-p... | 625941d18a349b6b435e8304 |
def display_mds(*strings): <NEW_LINE> <INDENT> for string in strings: <NEW_LINE> <INDENT> display_markdown(Markdown(data=string)) | Utility function to display several strings formatted in markdown format
:param strings: any number of strings with text in markdown format
:return: None | 625941d1167d2b6e31218d26 |
def test_python_version(): <NEW_LINE> <INDENT> assert sys.version_info[0]==3 | ----------- Problem 3 (20 points in total)--------------------- | 625941d14f88993c3716c1f7 |
@pytest.fixture <NEW_LINE> def caplog(_caplog): <NEW_LINE> <INDENT> class PropogateHandler(logging.Handler): <NEW_LINE> <INDENT> def emit(self, record): <NEW_LINE> <INDENT> logging.getLogger(record.name).handle(record) <NEW_LINE> <DEDENT> <DEDENT> logger.add(PropogateHandler(), format="{message}") <NEW_LINE> yield _cap... | Hack pytest caplog for use with Loguru. | 625941d191f36d47f21ac683 |
def __setitem__(self, index, value): <NEW_LINE> <INDENT> if index == 0: <NEW_LINE> <INDENT> self.feature = value <NEW_LINE> <DEDENT> elif index == 1: <NEW_LINE> <INDENT> self.operator = value <NEW_LINE> <DEDENT> elif index == 3: <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> elif index == 4: <NEW_LINE> <IND... | Set the literal values. | 625941d1ff9c53063f47c383 |
def test_SHAHashA2AuthInt(self): <NEW_LINE> <INDENT> self.test_MD5HashA2AuthInt('sha', sha.sha) | L{calcHA2} accepts the C{'sha'} algorithm and returns a SHA hash of
its arguments, including the entity hash for QOP of C{'auth-int'}. | 625941d1be7bc26dc91cd78f |
def impure_build(drv): <NEW_LINE> <INDENT> if not is_fixed_output(drv): <NEW_LINE> <INDENT> raise Exception <NEW_LINE> <DEDENT> output_paths = all_output_paths(drv) <NEW_LINE> if len(output_paths) != 1: <NEW_LINE> <INDENT> raise Exception("doesn't support multiple outputs") <NEW_LINE> <DEDENT> output_path = output_path... | Impurely build this derivation in the current environment and add it to the store. | 625941d19f2886367277aa1d |
def is_very_long(password): <NEW_LINE> <INDENT> return len(password) >= 13 | Return True if password is very long. | 625941d1ac7a0e7691ed425b |
def fewh(self, message, unused): <NEW_LINE> <INDENT> self._plaintext_helper(message, 'phew*') | Learn appropriate spelling. | 625941d1566aa707497f46f7 |
def root(self): <NEW_LINE> <INDENT> raise NotImplementedError('must be implemented by subclass') | Return position representing root otherwise None | 625941d1a219f33f34628af9 |
def ResidualBlock(name, input_dim, output_dim, filter_size, inputs, resample=None, he_init=True, bn=False): <NEW_LINE> <INDENT> if resample=='down': <NEW_LINE> <INDENT> conv_shortcut = MeanPoolConv <NEW_LINE> conv_1 = functools.partial(lib.ops.conv2d.Conv2D, input_dim=input_dim, output_dim=input_dim) <NEW_LINE> ... | resample: None, 'down', or 'up' | 625941d1b7558d58953c50a3 |
@deprecated <NEW_LINE> def get(uri, timeout=20, headers=None, return_headers=False, limit_bytes=None, verify_ssl=True, dont_decode=False): <NEW_LINE> <INDENT> if not uri.startswith('http'): <NEW_LINE> <INDENT> uri = "http://" + uri <NEW_LINE> <DEDENT> if headers is None: <NEW_LINE> <INDENT> headers = default_headers <N... | Execute an HTTP GET query on `uri`, and return the result. Deprecated.
`timeout` is an optional argument, which represents how much time we should
wait before throwing a timeout exception. It defaults to 20, but can be set
to higher values if you are communicating with a slow web application.
`headers` is a dict of HT... | 625941d1dd821e528d63b339 |
def create_routing_instances(self, **kwargs): <NEW_LINE> <INDENT> url = '/routing-instances' <NEW_LINE> post_body = json.dumps({'routing-instance': kwargs}) <NEW_LINE> resp, body = self.post(url, post_body) <NEW_LINE> body = json.loads(body) <NEW_LINE> return base.ResponseBody(resp, body) | :param kwargs:
:return: | 625941d185dfad0860c3afec |
def testRefreshSessionRequestBodyData(self): <NEW_LINE> <INDENT> pass | Test RefreshSessionRequestBodyData | 625941d12eb69b55b151ca40 |
def t_BOOL(t): <NEW_LINE> <INDENT> mapping = {"true": True, "false": False} <NEW_LINE> t.value = mapping[t.value] <NEW_LINE> return t | (true|false) | 625941d1a05bb46b383ec9b1 |
def runge_1(n): <NEW_LINE> <INDENT> x = np.linspace(-5, 5, n) <NEW_LINE> f = 1 / (1 + x**2) <NEW_LINE> (x1, p) = interp(x, f, points=max(2*n, 1000)) <NEW_LINE> f1 = 1/ (1 + x1**2) <NEW_LINE> plt.ylabel('y') <NEW_LINE> plt.xlabel('x') <NEW_LINE> plt.yscale('linear') <NEW_LINE> plt.plot(x1, f1, x1, p, '--') | Plots function f = 1/(1 + x**2) and its interpolant of degree n+1,
interpolated at equidistant points, on interval [-5,5] to demonstrate the
Runge phenomenon.
Paramters
---------
n: integer
Determines the number of interpolation points. | 625941d10a50d4780f667023 |
def get_norm_numbers(mu, sigma, number): <NEW_LINE> <INDENT> return np.random.normal(mu, sigma, number) | Generate a list of random numbers (of length 'number') based around a normal distribution
with params, mu and sigma. | 625941d1ff9c53063f47c384 |
def get_next_event(self): <NEW_LINE> <INDENT> logging.debug("[{}] Getting next event".format(self.__class__.__name__)) <NEW_LINE> if self.event_queue.empty(): <NEW_LINE> <INDENT> logging.debug("[{}] Failed to get new event, empty event_queue!".format(self.__class__.__name__)) <NEW_LINE> return False <NEW_LINE> <DEDENT>... | Get new event from the queue | 625941d15fc7496912cc3b0e |
def _import_module(name): <NEW_LINE> <INDENT> last_dot = name.rfind('.') <NEW_LINE> if last_dot == -1: <NEW_LINE> <INDENT> package, module = None, name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> package, module = name[:last_dot], name[last_dot:] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return importlib.import_mo... | Import and return module.
This works like importlib._import_module(), except it handles
packages without requiring an extra argument.
Examples::
_import_module('mido')
_import_module('mido.backends.portmidi') | 625941d167a9b606de4a804a |
def make_naive(value, timezone): <NEW_LINE> <INDENT> value = value.astimezone(timezone) <NEW_LINE> if hasattr(timezone, 'normalize'): <NEW_LINE> <INDENT> value = timezone.normalize(value) <NEW_LINE> <DEDENT> return value.replace(tzinfo=None) | Makes an aware datetime.datetime naive in a given time zone. | 625941d1a05bb46b383ec9b2 |
def get_u_v_summary(self, shop_id, begin_date, end_date): <NEW_LINE> <INDENT> return self.__client.call("eleme.cpc.getUVSummary", {"shopId": shop_id, "beginDate": begin_date, "endDate": end_date}) | 查询推广效果数据
:param shopId:店铺ID
:param beginDate:开始时间
:param endDate:结束时间 | 625941d1656771135c3eba00 |
def last_reading(self): <NEW_LINE> <INDENT> last_upds = self._ifdb.query('SELECT * FROM "{}" GROUP BY * ORDER BY DESC LIMIT 1'.format(settings.INFLUX_READINGS)) <NEW_LINE> try: <NEW_LINE> <INDENT> last_upd = list(last_upds.get_points(tags=dict(device_id=self.id)))[0] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <I... | Get the most recent reading from this devices data.
Returns:
last_upd: The most recent reading.
last_upd_keys: The keys assosiated with the reading. | 625941d1fbf16365ca6f6357 |
def _draw_cursor(self): <NEW_LINE> <INDENT> self.canvas.delete("cursor") <NEW_LINE> x0 = MARGIN + self.row * SIDE <NEW_LINE> y0 = MARGIN + self.col * SIDE <NEW_LINE> x1 = x0 + SIDE <NEW_LINE> y1 = y0 + SIDE <NEW_LINE> self.canvas.create_rectangle(x0, y0, x1, y1, outline='red', tags='cursor') | Highlight the cell the user clicked on. | 625941d10383005118ecf773 |
def __init__(self, username=None, mail=None, site=None, extension=None, e164_number=None, photo_base64=None, groups=None, user_principal_name=None, additional_attributes=None): <NEW_LINE> <INDENT> self._username = None <NEW_LINE> self._mail = None <NEW_LINE> self._site = None <NEW_LINE> self._extension = None <NEW_LINE... | LdapUserJson - a model defined in Swagger | 625941d14428ac0f6e5ba983 |
def download(self, **kwargs): <NEW_LINE> <INDENT> symbol = kwargs.get("symbol") <NEW_LINE> self.__download_stock(symbol) | :param symbol:type string | 625941d1c4546d3d9de72bc5 |
def standardScriptHeader(jobSpecId, wfSpecId, minDiskSize=1500000): <NEW_LINE> <INDENT> script = [] <NEW_LINE> script.append("if [ -d \"$OSG_GRID\" ]; then\n") <NEW_LINE> script.append(" source $OSG_GRID/setup.sh\n") <NEW_LINE> script.append("fi\n") <NEW_LINE> script.append("echo Starting up OSG prodAgent job\n") <NE... | _standardScriptHeader_
Standard Submission script header for OSG Jobs | 625941d176d4e153a657ecc2 |
def mimi_dp(s1, s2): <NEW_LINE> <INDENT> n1, n2 = len(s1), len(s2) <NEW_LINE> dp = [[0]*(n2+1) for _ in range(n1+1)] <NEW_LINE> dp[0][0] = 1 <NEW_LINE> for i in range(n1): <NEW_LINE> <INDENT> for j in range(n2+1): <NEW_LINE> <INDENT> dp[i+1][j] += dp[i][j] <NEW_LINE> <DEDENT> for j in range(n2): <NEW_LINE> <INDENT> if ... | references:
- https://github.com/E869120/kyopro_educational_90/blob/main/editorial/008.jpg | 625941d15510c4643540f573 |
def bagOfTokensScore(self, tokens, P): <NEW_LINE> <INDENT> tokens.sort() <NEW_LINE> n = len(tokens) <NEW_LINE> score = 0 <NEW_LINE> if not tokens: return score <NEW_LINE> l, r = 0, n-1 <NEW_LINE> while l <= r: <NEW_LINE> <INDENT> while l <= r and P >= tokens[l]: <NEW_LINE> <INDENT> print(l, r, tokens[l], P) <NEW_LINE> ... | :type tokens: List[int]
:type P: int
:rtype: int | 625941d16aa9bd52df036f35 |
def _vendor_in(self, value, index, buf=None): <NEW_LINE> <INDENT> result = self._connection.controlTransfer( self.PROLIFIC_VENDOR_IN_REQTYPE, self.PROLIFIC_VENDOR_READ_REQUEST, value, index, buf, (0 if buf is None else len(buf)), self.USB_READ_TIMEOUT_MILLIS, ) <NEW_LINE> return result | USB vendor transfer in.
Request for a control message from the device. | 625941d10a50d4780f667024 |
def convert(self, s, numRows): <NEW_LINE> <INDENT> return self.aproach1(s, numRows) | :type s: str
:type numRows: int
:rtype: str
subarray[i] - index % numrows == i or index % numrows == numrows - i
| 625941d15fcc89381b1e1850 |
def update(self, drive): <NEW_LINE> <INDENT> self.content_type = "application/json" <NEW_LINE> self.method = "PATCH" <NEW_LINE> entity = Drive(json.loads(self.send(drive).content)) <NEW_LINE> self._initialize_collection_properties(entity) <NEW_LINE> return entity | Updates the specified Drive.
Args:
drive (:class:`Drive<microsoft.msgraph.model.drive.Drive>`):
The Drive to update.
Returns:
:class:`Drive<microsoft.msgraph.model.drive.Drive>`:
The updated Drive. | 625941d192d797404e30431b |
def __init__(self, filename=None): <NEW_LINE> <INDENT> self.regexp = None <NEW_LINE> super(ImageFileParser, self).__init__(filename) | Constructor
:param filename: Name of the text file to parse. | 625941d199cbb53fe6792d77 |
def _compute_max_depth(self, pos, simulate_root): <NEW_LINE> <INDENT> depth = 0 <NEW_LINE> for ii in self.synsets(pos=pos): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> depth = max(depth, ii.max_depth()) <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> print(ii) <NEW_LINE> <DEDENT> <DEDENT> if simulate_root... | Compute the max depth for the given part of speech. This is
used by the lch similarity metric. | 625941d1bd1bec0571d907c0 |
def disconnect(self, cid): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del self.observers[cid] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass | Remove the observer with connection id *cid*. | 625941d1283ffb24f3c55a91 |
def sessionUpdate(self): <NEW_LINE> <INDENT> self._dataViewer.sessionUpdate() | Called externally to update file list. | 625941d121a7993f00bc7e82 |
def create_separator(self, separatorId, parentGroup=None, name=""): <NEW_LINE> <INDENT> if (self.idSeparator[separatorId]) is None: <NEW_LINE> <INDENT> bc = c4d.GetCustomDataTypeDefault(c4d.DTYPE_SEPARATOR) <NEW_LINE> bc[c4d.DESC_NAME] = name <NEW_LINE> bc[c4d.DESC_SHORT_NAME] = name <NEW_LINE> bc[c4d.DESC_PARENTGROUP]... | Create a separator
:param separatorId: int => ID of the created separator
:param parentGroup: int => groupID of the parent group
:param name: name but can be empty string
:return: The list of separator with the newly created one | 625941d1b57a9660fec33a15 |
def recover_local_file(self, remote_url, local_url): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> remote_pem = urlopen(remote_url) <NEW_LINE> encrypted_pem_file = open(local_url + ".encrypted", 'wb') <NEW_LINE> encrypted_pem_file.write(remote_pem.read()) <NEW_LINE> encrypted_pem_file.close() <NEW_LINE> self.decrypt(enc... | Recover the ciphertext from a server into plaintext
:param remote_url: the ciphertext file url. Example-localhost:5000/static/upload/ciphertext
:param local_url: the path where plaintext file will be stored
:return: | 625941d18e71fb1e9831d939 |
def mean_std_online(arr_or_iter, ddof=0, shape=None): <NEW_LINE> <INDENT> acc = StatisticsAccumulator(ddof=ddof, shape=shape) <NEW_LINE> acc.add_many(arr_or_iter) <NEW_LINE> if acc.mean is None: <NEW_LINE> <INDENT> mean = np.nan <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mean = acc.mean <NEW_LINE> <DEDENT> try: <NEW... | calculates the mean and the standard deviation of the given data.
If the data is an iterator, the values are calculated memory efficiently
with an online algorithm, which does not store all the intermediate data.
`ddof` is the delta degrees of freedom, which is used in the formula for
the standard deviation. | 625941d18c3a87329515854c |
def test_reshaping_between_stack_and_intensities(): <NEW_LINE> <INDENT> np.random.seed(777) <NEW_LINE> image = ImageStack.from_numpy(np.random.rand(1, 2, 3, 4, 5).astype(np.float32)) <NEW_LINE> pixel_intensities = IntensityTable.from_image_stack(image, 0, 0, 0) <NEW_LINE> image_shape = (image.shape['z'], image.shape['y... | transform an pixels of an ImageStack into an IntensityTable and back again, then verify that
the created Imagestack is the same as the original | 625941d1596a897236089c51 |
def GetRegionToProcess(self): <NEW_LINE> <INDENT> return _itkFastChamferDistanceImageFilterPython.itkFastChamferDistanceImageFilterID3ID3_GetRegionToProcess(self) | GetRegionToProcess(self) -> itkImageRegion3 | 625941d15166f23b2e1a52ea |
def glDisable(cap): <NEW_LINE> <INDENT> pass | Disable server-side GL capabilities
:param cap: Specifies a symbolic constant indicating a GL capability.
:type cap: Enumerated constant | 625941d1377c676e9127233a |
@register.filter <NEW_LINE> def urljoin(origin: str, pathname: str) -> str: <NEW_LINE> <INDENT> return join(origin, pathname) | A template filter used to join URL parts.
:param origin: The origin of the URL.
:param pathname: The pathname of the URL.
:return: The URL joined via :func:`~urllib.parse.urljoin`. | 625941d1a8ecb033257d325e |
def test_node_definitions_multiple_xml(self): <NEW_LINE> <INDENT> stack = ParentStack().add(0, Node(label=['9999'])) <NEW_LINE> winter = Node("(4) Cold and dreary mean winter.", label=['9999', '4']) <NEW_LINE> winter.tagged_text = ('(4) <E T="03">Cold</E> and ' '<E T="03">dreary</E> mean winter.') <NEW_LINE> inc, _ = T... | Find xml definitions which are separated by `and` | 625941d1cb5e8a47e48b7c3a |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SegmentsActionSend): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() | Returns true if both objects are equal | 625941d1b7558d58953c50a4 |
def read_double_aperture(filename): <NEW_LINE> <INDENT> lc = at.read(filename, delimiter=' ',data_start=1) <NEW_LINE> split_filename = filename.split("/")[-1].split('_') <NEW_LINE> logging.debug(split_filename) <NEW_LINE> epicID = split_filename[1] <NEW_LINE> time = lc["Dates"] <NEW_LINE> fluxes = np.array([lc["Flux5"]... | Read in one of AMC's K2 lc files with 2 aperture extractions.
inputs
------
filename: string
should look like EPIC_205030103_xy_ap#.#_#.#_fixbox.dat
outputs
-------
time: array
flux, unc_flux: arrays, shape=(2, n_datapoints)
A flux and uncertainty array for each aperture in the file
x_pos, y_pos, qual_flu... | 625941d115fb5d323cde0ca2 |
def p_cast_expression5(self, p): <NEW_LINE> <INDENT> p[0] = Cast(Type(p[2], dimensions=p[3]), p[5]) | cast_expression : '(' name dims ')' unary_expression_not_plus_minus | 625941d13617ad0b5ed68088 |
def get_killfeed_team_color_pos(pos_x, position, gametype, version): <NEW_LINE> <INDENT> if position == LEFT: <NEW_LINE> <INDENT> return [get_ui_variable("KILLFEED_TEAM_COLOR_POS_Y", gametype, version), pos_x + get_ui_variable("KILLFEED_TEAM_COLOR_POS_X_LEFT", gametype, version)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <I... | Get pixel position from which to get team color from killfeed
Author:
Appcell
Args:
pox_x: x-axis coordinate of killfeed avatar
position: on which side the avatar lies, LEFT or OW.RIGHT
Returns:
Pos array of this pixel | 625941d1a4f1c619b28b01c8 |
def overlaps(i0, i1): <NEW_LINE> <INDENT> return i0.end() >= i1.start() and i1.end() >= i0.start() | Returns True if `i0` and `i1` represent overlapping intervals. | 625941d1cc40096d61595ae1 |
def restrict_to_dates(feed: "Feed", dates: List[str]) -> "Feed": <NEW_LINE> <INDENT> feed = feed.copy() <NEW_LINE> try: <NEW_LINE> <INDENT> trip_ids = feed.compute_trip_activity(dates).loc[ lambda x: x[[c for c in x.columns if c != "trip_id"]].sum(axis=1) > 0, "trip_id", ] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE... | Build a new feed by restricting this one to only the stops,
trips, shapes, etc. active on at least one of the given dates
(YYYYMMDD strings).
Return the resulting feed, which will have empty non-agency tables
if no trip is active on any of the given dates. | 625941d1ad47b63b2c50a111 |
def repeatedNTimes(self, A): <NEW_LINE> <INDENT> s = set() <NEW_LINE> for n in A: <NEW_LINE> <INDENT> if n in s: <NEW_LINE> <INDENT> return n <NEW_LINE> <DEDENT> s.add(n) <NEW_LINE> <DEDENT> return -1 | :type A: List[int]
:rtype: int | 625941d17d43ff24873a2e32 |
def classify(s): <NEW_LINE> <INDENT> value = re.match(r'^ ip address ([0-9]+[.][0-9]+[.][0-9]+[.][0-9]+) ([0-9]+[.][0-9]+[.][0-9]+[.][0-9]+)', s) <NEW_LINE> if value: <NEW_LINE> <INDENT> return (ipaddress.IPv4Interface(value.group(1) + '/' + value.group(2)), 0) <NEW_LINE> <DEDENT> value = re.match(r'^ ip default-gatewa... | Take parameters from input string
:param s: input string
:return: tuple of (IPv4Interface, score) if applicable or None | 625941d107f4c71912b11614 |
def fibonacci(n): <NEW_LINE> <INDENT> if n <= 1: <NEW_LINE> <INDENT> return n <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return fibonacci(n-1) + fibonacci(n-2) | Return Fibonacci number | 625941d1ec188e330fd5a92f |
def subscribe(self, subscription=None): <NEW_LINE> <INDENT> return super().subscribe(subscription) | Subscribe to new frames as they come in. By default returns a MostRecentSubscription object, which can be awaited
to get the most recent frame, and skips missed frames.
Note that all subscribers get the same frame data numpy array,
so if you are going to modify the values of the array itself, please do so in a copy!::... | 625941d12c8b7c6e89b35951 |
def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkMeanSquaresImageToImageMetricIUS3IUS3.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj | New() -> itkMeanSquaresImageToImageMetricIUS3IUS3
Create a new object of the class itkMeanSquaresImageToImageMetricIUS3IUS3 and set the input and the parameters if some
named or non-named arguments are passed to that method.
New() tries to assign all the non named parameters to the input of the new objects - the
firs... | 625941d1187af65679ca52b0 |
def test_attempt_status_stickiness(self): <NEW_LINE> <INDENT> proctored_exam = ProctoredExam.objects.create( course_id='a/b/c', content_id='test_content', exam_name='Test Exam', external_id='123aXqe3', time_limit_mins=90 ) <NEW_LINE> attempt_data = { 'exam_id': proctored_exam.id, 'external_id': proctored_exam.external_... | Test to confirm that a status timeout error will not alter a completed state | 625941d1d4950a0f3b08c4df |
def __init__(self, directions=()): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.directions = list(set(directions)) | Creates a instance.
:param directions list of direction that form the virtual button | 625941d11d351010ab855cad |
def _size_alloc_cb(self, widget, alloc): <NEW_LINE> <INDENT> width = alloc.width <NEW_LINE> height = alloc.height <NEW_LINE> ncolors, nrows, ncolumns = self._get_palette_dimensions() <NEW_LINE> if nrows and ncolumns: <NEW_LINE> <INDENT> size = int(min(width / ncolumns, height / nrows)) <NEW_LINE> size = self._constrain... | Caches layout details after size negotiation.
| 625941d163b5f9789fde7277 |
def __init__(self): <NEW_LINE> <INDENT> self.timeSymbolTick = {} | constructor | 625941d15fdd1c0f98dc03c5 |
def myAtoi(self, s): <NEW_LINE> <INDENT> if not s: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res = "" <NEW_LINE> index = 0 <NEW_LINE> while s[index] == " ": <NEW_LINE> <INDENT> if index == len(s): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> index += 1 <NEW_LINE> if index == len(s):... | :type s: str
:rtype: int | 625941d1d486a94d0b98e2d7 |
def extract_tb(tb, limit=None): <NEW_LINE> <INDENT> return StackSummary.extract(walk_tb(tb), limit=limit) | Return a StackSummary object representing a list of
pre-processed entries from traceback.
This is useful for alternate formatting of stack traces. If
'limit' is omitted or None, all entries are extracted. A
pre-processed stack trace entry is a FrameSummary object
containing attributes filename, lineno, name, and lin... | 625941d138b623060ff0af7f |
def getAllAttachmentNames(self): <NEW_LINE> <INDENT> raise AssertionError("CommonHomeExternal: not supported") | No children. | 625941d1236d856c2ad4496d |
def to_JSON(self): <NEW_LINE> <INDENT> return json.dumps({"reference_time": self._reference_time, "location": json.loads(self._location.to_JSON()), "interval": self._interval, "value": self.du_value, "reception_time": self._reception_time, }) | Dumps object fields into a JSON formatted string
:returns: the JSON string | 625941d1293b9510aa2c3427 |
def __init__(self, parent: QWidget = None): <NEW_LINE> <INDENT> super(DeadTimeCorrectionsView, self).__init__(parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self.set_dead_time_workspace_selector_visible(False) <NEW_LINE> self.set_dead_time_other_file_visible(False) | Initializes the DeadTimeCorrectionsView. | 625941d14527f215b584c5e7 |
def twoSum(self, nums, target): <NEW_LINE> <INDENT> result = [] <NEW_LINE> dict_nums = {} <NEW_LINE> for n in range(0, len(nums)): <NEW_LINE> <INDENT> if target - nums[n] in dict_nums.keys(): <NEW_LINE> <INDENT> result.append(dict_nums.get(target-nums[n])) <NEW_LINE> result.append(n) <NEW_LINE> break <NEW_LINE> <DEDENT... | 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
:type nums: List[int]
:type target: int
:rtype: List[int] | 625941d1d4950a0f3b08c4e0 |
def test_find_next(self): <NEW_LINE> <INDENT> self.assertEqual(self.a_nested_soup.a, self.a_tag_first) <NEW_LINE> self.assertEqual(self.a_nested_soup.a.find_next(), self.a_tag_second) <NEW_LINE> self.assertEqual(self.a_nested_soup.a.find_next().find_next(), self.a_tag_third) <NEW_LINE> self.assertEqual(self.a_nested_so... | Use find_next to find the next anchor tag, until there are no more | 625941d126238365f5f0f000 |
def handle(req): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = os.environ['user'] <NEW_LINE> password = os.environ['pw'] <NEW_LINE> tenant = os.environ['tenant'] <NEW_LINE> authurl = "{}/identity/api/tokens".format(req) <NEW_LINE> payload = '{{"username":"{}","password":"{}","tenant":"{}"}}'.format( user, passwor... | Builds an authentication token for the user. Takes input of the fqdn of vRA, username,
password, and tenant | 625941d1796e427e537b0758 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.