code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def preprocess(spark, slide_nums, folder="data", training=True, tile_size=1024, overlap=0, tissue_threshold=0.9, sample_size=256, grayscale=False, normalize_stains=True, num_partitions=20000): <NEW_LINE> <INDENT> slides = (spark.sparkContext .parallelize(slide_nums) .filter(lambda slide: open_slide(slide, folder, train... | Preprocess a set of whole-slide images.
Preprocess a set of whole-slide images as follows:
1. Tile the slides into tiles of size (tile_size, tile_size, 3).
2. Filter the tiles to remove unnecessary tissue.
3. Cut the remaining tiles into samples of size
(sample_size, sample_size, ch), where `ch` is 1 if `gr... | 625941b8b545ff76a8913c70 |
def ExportGetFatherComponent(self, ObjectId, FatherComponentId): <NEW_LINE> <INDENT> pass | ExportGetFatherComponent(self: DelegateFake, ObjectId: int, FatherComponentId: int) -> (int, int) | 625941b8d164cc6175782b9f |
def __connections(user, content_type_id, current_level, target_level): <NEW_LINE> <INDENT> target_position = target_level <NEW_LINE> target_company = 1 <NEW_LINE> shortlisted_profiles = UserProfile.objects.get_all_profiles_by(content_type_id, target_position) <NEW_LINE> aggregated_data = __aggregate_statistics(shortlis... | 1. identify target organization
2. identify target position
3. Identify list of ppl in target position
3.1 Gather profile data
3.1.1 Number of years work ex
3.1.2 Age
3.1.3 Highest degree
3.2 Aggregate data
4 return data | 625941b89b70327d1c4e0c25 |
def __init__(self): <NEW_LINE> <INDENT> self.identifier = 0 <NEW_LINE> self.name = '' <NEW_LINE> self.level = 10 <NEW_LINE> self.created_at = '' <NEW_LINE> self.avatar_id = '' <NEW_LINE> self.post_count = 0 <NEW_LINE> self.del_post_count = 0 <NEW_LINE> self.edit_count = 0 <NEW_LINE> self.favorite_count = 0 <NEW_LINE> s... | Initiate properties | 625941b80a366e3fb873e668 |
def update_multi_precision(self, index, weight, grad, state): <NEW_LINE> <INDENT> if self.multi_precision and weight.dtype == numpy.float16: <NEW_LINE> <INDENT> weight_master_copy = state[0] <NEW_LINE> original_state = state[1] <NEW_LINE> grad32 = grad.astype(numpy.float32) <NEW_LINE> self.update(index, weight_master_c... | Updates the given parameter using the corresponding gradient and state.
Mixed precision version.
Parameters
----------
index : int
The unique index of the parameter into the individual learning
rates and weight decays. Learning rates and weight decay
may be set via `set_lr_mult()` and `set_wd_mult()`, resp... | 625941b80fa83653e4656e0e |
def _render_grid_horlines(self, w, h, x2, y2, w2, h2, min_div_hpix=50.): <NEW_LINE> <INDENT> assert h > 1. <NEW_LINE> ch = self.channels[0] <NEW_LINE> if abs(h2) < 0.000001: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> v1 = y2 <NEW_LINE> v2 = y2 + h2 <NEW_LINE> if v2 < v1: <NEW_LINE> <INDENT> v1, v2 = v2, v1 <NEW_LI... | min_div_hpix : minimum division height (grid line distance) in pixels | 625941b899fddb7c1c9de1e4 |
def testApproachSpeedDoNotExceed(self): <NEW_LINE> <INDENT> self.controller.approachSpeed = 3.99 <NEW_LINE> self.controller._approach(0.5) <NEW_LINE> self.assertEqual(self.controller.approachSpeed,4) | Test that the incremented speed doesn't exceed approachSpeed | 625941b8e64d504609d74692 |
def __init__(self, config): <NEW_LINE> <INDENT> self.contextualStructure = config["contextualStructure"] <NEW_LINE> self.contextualDependencies = {} <NEW_LINE> self.contextualGenerationProcess = {} <NEW_LINE> if "contextualDependencies" in config: <NEW_LINE> <INDENT> self.contextualDependencies = config["contextualDepe... | config is json and must declare:
contextualStructure: iterable where each entry is a contextual variable.
entries > 0 indicate a categorical variable with that number of options.
entries = -1 indicate a continuous variable.
May also declare: contextualDependencies, contextualGenerationProcess which impact generateConte... | 625941b876d4e153a657e981 |
def flush(self): <NEW_LINE> <INDENT> if self._flush_passthru: <NEW_LINE> <INDENT> return bytearray() <NEW_LINE> <DEDENT> return self._comp.flush() | Flush the data internally if required. | 625941b87cff6e4e811177d7 |
def get_libris_edition(raw): <NEW_LINE> <INDENT> control_number = raw["controlNumber"] <NEW_LINE> if is_libris_edition_id(control_number): <NEW_LINE> <INDENT> return control_number <NEW_LINE> <DEDENT> return None | Extract old-format Libris ID.
@param raw: json object of a Libris edition
@type raw: dictionary | 625941b8046cf37aa974cb9c |
def _calculate_eac(self): <NEW_LINE> <INDENT> self.workpackage.eac = self.workpackage.etc_costs + self.workpackage.ac_costs | Calculates the EAC | 625941b8377c676e91271ffc |
def _format_data(self, data): <NEW_LINE> <INDENT> return [spectrum for spectrum in sorted(data if isinstance(data, (list, tuple)) else [data], key=lambda x: x.disp[0]) if np.any(np.isfinite(spectrum.flux))] | Sort the data in blue wavelengths to red, and ignore any spectra that
have entirely non-finite or negative fluxes. | 625941b863d6d428bbe44341 |
def updateKeyCombinations(self): <NEW_LINE> <INDENT> label = self.grabKeyLabel <NEW_LINE> label.setText('Shortcut to paste the resized image: ') <NEW_LINE> [label.setText(label.text() + k + '+') for k, v in Setup.config['keys'].items() if k != 'Extra' and v == True] <NEW_LINE> if Setup.config['keys'].get('Extra'): <NEW... | update the key combination label
in the settings window according to Setup.config | 625941b8462c4b4f79d1d522 |
def get_direction(position, next_position): <NEW_LINE> <INDENT> x, y = position <NEW_LINE> nx, ny = next_position <NEW_LINE> if x == nx: <NEW_LINE> <INDENT> if y < ny: <NEW_LINE> <INDENT> return constants.Action.Right <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return constants.Action.Left <NEW_LINE> <DEDENT> <DEDENT... | Get the direction such that position --> next_position.
We assume that they are adjacent. | 625941b8baa26c4b54cb0f75 |
def show(*args): <NEW_LINE> <INDENT> context = XSCRIPTCONTEXT.getComponentContext() <NEW_LINE> shell = context.ServiceManager.createInstanceWithContext( "com.sun.star.system.SystemShellExecute", context ) <NEW_LINE> fileAccess = context.ServiceManager.createInstance( "com.sun.star.ucb.SimpleFileAccess" ) <NEW_LINE> tem... | Показать справочное руководство. | 625941b882261d6c526ab2f5 |
def copy(self): <NEW_LINE> <INDENT> attrib = ItemAttribute() <NEW_LINE> for k, v in self._attribs(): <NEW_LINE> <INDENT> setattr(attrib, k, v.copy() if hasattr(v, 'copy') else v) <NEW_LINE> <DEDENT> return attrib | Performs a deep copy of the ItemAttribute, including all values
of any dynamically added attributes.
:return: | 625941b830c21e258bdfa2ef |
def DbGetDeviceExportedList(self, argin): <NEW_LINE> <INDENT> self.debug_stream("In " + self.get_name() + ".DbGetDeviceExportedList()") <NEW_LINE> argout = [''] <NEW_LINE> return argout | Get a list of exported devices whose names satisfy the filter (wildcard is
:param argin: filter
:type: PyTango.DevString
:return: list of exported devices
:rtype: PyTango.DevVarStringArray | 625941b8a219f33f346287c6 |
def GetOutputHistogram(self): <NEW_LINE> <INDENT> return _itkHistogramMatchingImageFilterPython.itkHistogramMatchingImageFilterID3ID3_GetOutputHistogram(self) | GetOutputHistogram(self) -> itkHistogramD | 625941b8498bea3a759b9903 |
def mta013(self): <NEW_LINE> <INDENT> fromaddr = self.testaddr <NEW_LINE> toaddr = self.pconfig.get( 'noeaito') <NEW_LINE> pmsg = self.domsg('eaisubj', From=fromaddr, To=toaddr, submit=True, eaiflag=True, getrmt=True, maxcheck=3) <NEW_LINE> if pmsg: <NEW_LINE> <INDENT> return ('Fail', "Message sent anyway") <NEW_LINE> ... | check that EAI message to non-EAI server fails
submit locally, check on home server, then check for local bounce | 625941b85f7d997b871748ed |
def negotiate_session_async( self, session_compression: str, session_encryption: str ) -> Awaitable[Session]: <NEW_LINE> <INDENT> self.ensure_state([SessionState.NEGOTIATING], True) <NEW_LINE> loop = get_running_loop() <NEW_LINE> future = loop.create_future() <NEW_LINE> self.on_session_authenticating = future.set_resul... | Handle session in negotiating state.
Args:
session_compression (str): session compression type
session_encryption (str): session encryption type
Returns:
Future: A negotiated Session | 625941b80fa83653e4656e0f |
def _calculate_bilinear_cost( op, coeff, num_alive_inputs, num_alive_outputs, batch_size): <NEW_LINE> <INDENT> if op.type == 'DepthwiseConv2dNative': <NEW_LINE> <INDENT> return batch_size * coeff * num_alive_outputs <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return batch_size * coeff * num_alive_inputs * num_alive_o... | Calculates bilinear cost for an op.
Args:
op: A tf.Operation.
coeff: A float coefficient for the bilinear function.
num_alive_inputs: Scalar Tensor indicating how many input channels are
considered alive.
num_alive_outputs: Scalar Tensor indicating how many output channels are
considered alive.
batch... | 625941b88e71fb1e9831d5ff |
def set_bit_rate(self, rate): <NEW_LINE> <INDENT> if rate == 12: <NEW_LINE> <INDENT> self.__adc1_conf = self.__adc1_conf & ~(1 << 2) & ~(1 << 3) <NEW_LINE> self.__adc2_conf = self.__adc2_conf & ~(1 << 2) & ~(1 << 3) <NEW_LINE> self.__bitrate = 12 <NEW_LINE> self.__lsb = 0.0005 <NEW_LINE> <DEDENT> elif rate == 14: <NEW_... | sample rate and resolution
12 = 12 bit (240SPS max)
14 = 14 bit (60SPS max)
16 = 16 bit (15SPS max)
18 = 18 bit (3.75SPS max) | 625941b8a8370b77170526f2 |
def diff(a, b, segmenter=None): <NEW_LINE> <INDENT> a, b = list(a), list(b) <NEW_LINE> segmenter = segmenter or SEGMENTER <NEW_LINE> a_segments = segmenter.segment(a) <NEW_LINE> b_segments = segmenter.segment(b) <NEW_LINE> return diff_segments(a_segments, b_segments) | Performs a diff comparison between two sequences of tokens (`a` and `b`)
using `segmenter` to cluster and match
:class:`deltas.MatchableSegment`.
:Example:
>>> from deltas import segment_matcher, text_split
>>>
>>> a = text_split.tokenize("This is some text. This is some other text.")
>>> b = text_spl... | 625941b8283ffb24f3c5575e |
def get_crosslingual_wordsim_scores(lang1, word2id1, embeddings1, lang2, word2id2, embeddings2, lower=True): <NEW_LINE> <INDENT> if lang1 > lang2: <NEW_LINE> <INDENT> return get_crosslingual_wordsim_scores(lang2, word2id2, embeddings2, lang1, word2id1, embeddings1, lower) <NEW_LINE> <DEDENT> dirpath = os.path.join(SEME... | Return cross-lingual word similarity scores. | 625941b88a43f66fc4b53ebb |
def check_jmespath_match(parsed_response, query, expected=None): <NEW_LINE> <INDENT> actual = jmespath.search(query, parsed_response) <NEW_LINE> msg = "JMES path '{}' not found in response".format(query) <NEW_LINE> if actual is None: <NEW_LINE> <INDENT> raise exceptions.JMESError(msg) <NEW_LINE> <DEDENT> if expected is... | Check that the JMES path given in 'query' is present in the given response
Args:
parsed_response (dict, list): Response list or dict
query (str): JMES query
expected (str, optional): Possible value to match against. If None,
'query' will just check that _something_ is present | 625941b894891a1f4081b8fa |
def email_results(message, recipients): <NEW_LINE> <INDENT> if not settings.FR_EMAIL_ENABLED: <NEW_LINE> <INDENT> print("Email not configured.") <NEW_LINE> return <NEW_LINE> <DEDENT> email_from = "FireRoad <{}>".format(settings.EMAIL_HOST_USER) <NEW_LINE> send_mail("Daily update", message, email_from, recipients) | Sends an email to the given recipients with the given message. Prints to
the console if email is not set up. | 625941b8507cdc57c6306b25 |
def gps_raw_encode(self, usec, fix_type, lat, lon, alt, eph, epv, v, hdg): <NEW_LINE> <INDENT> msg = MAVLink_gps_raw_message(usec, fix_type, lat, lon, alt, eph, epv, v, hdg) <NEW_LINE> msg.pack(self) <NEW_LINE> return msg | The global position, as returned by the Global Positioning System
(GPS). This is NOT the global position estimate of the
sytem, but rather a RAW sensor value. See message
GLOBAL_POSITION for the global position estimate.
Coordinate frame is right-handed, Z-axis up (GPS
frame)
usec : Timestamp (mic... | 625941b8656771135c3eb6c4 |
def getblockheader(self, block_hash, verbose=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> block_hash = b2lx(block_hash) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> raise TypeError('%s.getblockheader(): block_hash must be bytes; got %r instance' % (self.__class__.__name__, block_hash.__class__)) <N... | Get block header <block_hash>
verbose - If true a dict is returned with the values returned by
getblockheader that are not in the block header itself
(height, nextblockhash, etc.)
Raises IndexError if block_hash is not valid. | 625941b88e7ae83300e4ae1d |
def extend(self, *args, **kwargs): <NEW_LINE> <INDENT> if len(args) > 1: <NEW_LINE> <INDENT> raise TypeError('expected at most 1 arguments, got %d' % len(args)) <NEW_LINE> <DEDENT> iterable = args[0] if args else None <NEW_LINE> if iterable: <NEW_LINE> <INDENT> if isinstance(iterable, Mapping) or hasattr(iterable, 'ite... | Add key value pairs for an iterable. | 625941b8b5575c28eb68de4f |
def _sell_limit(self, amount, price): <NEW_LINE> <INDENT> res = self.trade_client.place_order( str(amount), str(price), 'sell', 'exchange limit', symbol=self.pair_code) <NEW_LINE> return res['order_id'] | Create a sell limit order | 625941b8d10714528d5ffb31 |
@pytest.mark.skip(reason='Test is flaky.') <NEW_LINE> @pytest.mark.jira('ASC-891') <NEW_LINE> @pytest.mark.test_id('747b5458-aafb-11e8-bfa2-0025227c8120') <NEW_LINE> def test_skip(): <NEW_LINE> <INDENT> assert True is False | Verify that a test can be skipped. | 625941b876e4537e8c3514c9 |
def get_attribute(self, attribute_name: str) -> str: <NEW_LINE> <INDENT> if hasattr(self, '__' + attribute_name): <NEW_LINE> <INDENT> return getattr(self, '__' + attribute_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | 获取属性,如ClassAsClass.get_attribute('summary') | 625941b8de87d2750b85fbe0 |
def get_invalid_double( self, custom_headers={}, raw=False, **operation_config): <NEW_LINE> <INDENT> url = '/number/invaliddouble' <NEW_LINE> query_parameters = {} <NEW_LINE> header_parameters = {} <NEW_LINE> header_parameters['Content-Type'] = 'application/json; charset=utf-8' <NEW_LINE> if custom_headers: <NEW_LINE> ... | Get invalid double Number value
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: float
:rtype: :class:`ClientRa... | 625941b8d18da76e23532324 |
def compute_numerial_gradient(cost_func, theta): <NEW_LINE> <INDENT> numgrad = np.zeros(theta.size) <NEW_LINE> perturb = np.zeros(theta.size) <NEW_LINE> e = 1e-4 <NEW_LINE> for p in range(theta.size): <NEW_LINE> <INDENT> perturb[p] = e <NEW_LINE> loss1, grad1 = cost_func(theta-perturb) <NEW_LINE> loss2, grad2 = cost_fu... | numerically compute gradients | 625941b84527f215b584c2ad |
def lemonade_change(self, bills: List[int]) -> bool: <NEW_LINE> <INDENT> five_money, ten_money = 0, 0 <NEW_LINE> for bill in bills: <NEW_LINE> <INDENT> if bill == 5: <NEW_LINE> <INDENT> five_money += 1 <NEW_LINE> <DEDENT> if bill == 10: <NEW_LINE> <INDENT> if five_money > 0: <NEW_LINE> <INDENT> five_money -= 1 <NEW_LIN... | 计算是否能够换钱
Args:
bills: 账单数据-
Returns:
布尔值 | 625941b8a17c0f6771cbdea6 |
def __init__(self, dataset: DiscreteDataset, **kwargs): <NEW_LINE> <INDENT> super(TFBind10Oracle, self).__init__( dataset, is_batched=False, internal_batch_size=1, internal_measurements=1, expect_normalized_y=False, expect_normalized_x=False, expect_logits=False, **kwargs) <NEW_LINE> self.sequence_to_score = dict() <NE... | Initialize the ground truth score function f(x) for a model-based
optimization problem, which involves loading the parameters of an
oracle model and estimating its computational cost
Arguments:
dataset: DiscreteDataset
an instance of a subclass of the DatasetBuilder class which has
a set of design values 'x' ... | 625941b8a79ad161976cbf98 |
def testCSApiResponseBoolean(self): <NEW_LINE> <INDENT> pass | Test CSApiResponseBoolean | 625941b8dd821e528d63affd |
def latestKarma(quantity=25): <NEW_LINE> <INDENT> pass | Return the latest karma actions for this person.
Return no more than the number given as quantity. | 625941b86aa9bd52df036bf4 |
def task_2(): <NEW_LINE> <INDENT> mylist_42 = [1, 2, 4, 8] <NEW_LINE> print(mylist_42) <NEW_LINE> mylist_42.append(16) <NEW_LINE> print(16) | 2) В вашем распоряжении список mylist_42, состоящий из 4-х значений: 1,2,4,8.
Выполните команду для определения списка, напечатайте его.
Напишите команду для добавления к этому списку значения 16, снова напечатайте список. | 625941b8e8904600ed9f1d7b |
def to_intel64(self): <NEW_LINE> <INDENT> intel64.check_ideep_available() <NEW_LINE> d = self.__dict__ <NEW_LINE> for name in self._params: <NEW_LINE> <INDENT> d[name].to_intel64() <NEW_LINE> <DEDENT> for name in self._persistent: <NEW_LINE> <INDENT> value = d[name] <NEW_LINE> if isinstance(value, cuda.ndarray): <NEW_L... | Copies parameter variables and persistent values to CPU. | 625941b815fb5d323cde095c |
def _stats_veloc_forward(physics): <NEW_LINE> <INDENT> return player.walker.observables.veloc_forward(physics) | Player's forward velocity. | 625941b84a966d76dd550e5e |
def __iter__(self): <NEW_LINE> <INDENT> for tag, name in self.__tags_to_names.items(): <NEW_LINE> <INDENT> yield (tag, name, self.__tags_to_types[tag], self.__flags[tag]) | Iterates over all fields. | 625941b8be8e80087fb20aa2 |
def __init__(self): <NEW_LINE> <INDENT> super(SISR, self).__init__() <NEW_LINE> self.model = nn.Sequential( nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=1), nn.ReLU(), nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=1, padding=1), nn.ReLU(), nn.Conv2d(in_channels=32, out_c... | Load the pretrained ResNet-152 and replace top fc layer. | 625941b8b830903b967e9769 |
def step_into(self): <NEW_LINE> <INDENT> self.main_window.set_debugging_status(4) <NEW_LINE> self.debugger.step_into() | Issue a step into continuation command on the debugger
This gets called when the "Step into" action button is pressed. | 625941b84c3428357757c17d |
def build_url(self): <NEW_LINE> <INDENT> if self.by == "friendly_string": <NEW_LINE> <INDENT> self.base_url = "https://api.companieshouse.gov.uk/search/companies?q=" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.base_url = "https://api.companieshouse.gov.uk/company/" <NEW_LINE> <DEDENT> self.request_url = self.bas... | Creates self.request_url and adds parameters to request_kwargs if
self.by is set to "friendly_string"
Called when parent class is instantiated | 625941b81f037a2d8b946051 |
def tradfri_get_lightbulb(hubip, apiuser, apikey, deviceid): <NEW_LINE> <INDENT> tradfriHub = 'coaps://{}:5684/15001/{}' .format(hubip, deviceid) <NEW_LINE> api = '{} -m get -u "{}" -k "{}" "{}" -B {} 2> /dev/null' .format(coap, apiuser, apikey, tradfriHub, timeout) <NEW_LINE> if os.path.exists(coap): <NEW_LINE> <INDEN... | function for getting tradfri lightbulb information | 625941b8ab23a570cc24ffd2 |
def destroy(self, request, uuid): <NEW_LINE> <INDENT> draft_repo = DraftRepo(SnapshotRepo()) <NEW_LINE> draft_repo.delete(uuid) <NEW_LINE> return super().destroy(request, uuid) | This removes any files that were staged along with the database entry. | 625941b8ff9c53063f47c050 |
def random_element(self, num_bound=None, den_bound=None, *args, **kwds): <NEW_LINE> <INDENT> global ZZ <NEW_LINE> if ZZ is None: <NEW_LINE> <INDENT> from . import integer_ring <NEW_LINE> ZZ = integer_ring.ZZ <NEW_LINE> <DEDENT> if num_bound is None: <NEW_LINE> <INDENT> num = ZZ.random_element(*args, **kwds) <NEW_LINE> ... | Return an random element of `\QQ`.
Elements are constructed by randomly choosing integers
for the numerator and denominator, not neccessarily coprime.
INPUT:
- ``num_bound`` -- a positive integer, specifying a bound
on the absolute value of the numerator.
If absent, no bound is enforced.
- ``den_bound`` -- ... | 625941b8a4f1c619b28afe94 |
def get_name() -> str: <NEW_LINE> <INDENT> global used_names <NEW_LINE> name = names.get_full_name() <NEW_LINE> while name in used_names: <NEW_LINE> <INDENT> name = names.get_full_name() <NEW_LINE> <DEDENT> used_names.append(name) <NEW_LINE> return name | Used to generate a full name that has not been previously used | 625941b8507cdc57c6306b26 |
def InstallImportant(self): <NEW_LINE> <INDENT> self.whitelist = [entry for entry in self.states if not self.states[entry]] <NEW_LINE> if not self.setup['file']: <NEW_LINE> <INDENT> if self.setup['decision'] == 'whitelist': <NEW_LINE> <INDENT> dwl = self.setup['decision_list'] <NEW_LINE> w_to_r... | Install important entries
We also process the decision mode stuff here because we want to prevent
non-whitelisted/blacklisted 'important' entries from being installed
prior to determining the decision mode on the client. | 625941b891f36d47f21ac349 |
def __init__(self, other_block=-1, other_face=-1, orientation=0, filename="udf.lua", is_wall=0, sets_conv_flux=0, sets_visc_flux=0, reorient_vector_quantities=False, Rmatrix=[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], label=""): <NEW_LINE> <INDENT> BoundaryCondition.__init__(self, type_of_BC=ADJACENT_PLUS_UDF, other... | Construct a connecting boundary condition that also has some user-defined behaviour.
:param other_block: index to an adjacent block, if any.
A value of -1 will indicate that there is no adjacent block.
:param other_face: index of the adjacent face of the other block, if any.
:param orientation: for 3D connections... | 625941b87d43ff24873a2af6 |
def calculate_best_confidence(choices, metadata): <NEW_LINE> <INDENT> best_confidence = 0 <NEW_LINE> for path, line in choices: <NEW_LINE> <INDENT> confidence = calculate_confidence(path, line, metadata) <NEW_LINE> best_confidence = max(confidence, best_confidence) <NEW_LINE> <DEDENT> return best_confidence | :type choices: tuple[tuple[str, int]]
:type metadata: Metadata
:rtype: int | 625941b8d10714528d5ffb32 |
def test_doc_equality(self): <NEW_LINE> <INDENT> text = "My name is Inigo Montoya." <NEW_LINE> doc1 = API.annotate(text) <NEW_LINE> doc2 = API.annotate(text) <NEW_LINE> self.assertEqual(doc1, doc2, "two .annotate calls on same text did not produce equivalent Documents") <NEW_LINE> self.assertEqual(doc1, Document.load_f... | Two calls to API.annotate using the same text should produce equivalent Documents | 625941b8627d3e7fe0d68ca1 |
def test_Square(self): <NEW_LINE> <INDENT> s1 = Square(1) <NEW_LINE> self.assertTrue(isinstance(s1, Base)) | Check if is instance | 625941b8baa26c4b54cb0f76 |
def define_xml_path(path, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with salt.utils.files.fopen(path, 'r') as fp_: <NEW_LINE> <INDENT> return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) <NEW_LINE> <DEDENT> <DEDENT> except (OSError, IOError): <NEW_LINE> <INDENT> return False | Define a persistent domain based on the XML-file path passed to the function
:param path: path to a file containing the libvirt XML definition of the domain
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: Fluorine
:param username: username to connect with, overriding defaults
... | 625941b87c178a314d6ef2ac |
def resetStopOnReset(self, software_reset = None): <NEW_LINE> <INDENT> logging.debug("reset stop on Reset") <NEW_LINE> self.halt() <NEW_LINE> demcr = self.readMemory(DEMCR) <NEW_LINE> self.writeMemory(DEMCR, demcr | VC_CORERESET) <NEW_LINE> self.reset(software_reset) <NEW_LINE> while (self.getState() == TARGET_RUNNING)... | perform a reset and stop the core on the reset handler | 625941b88c3a873295158211 |
def fib_gen(): <NEW_LINE> <INDENT> first_no = 0 <NEW_LINE> second_no = 1 <NEW_LINE> yield first_no <NEW_LINE> while True: <NEW_LINE> <INDENT> yield second_no <NEW_LINE> second_no, first_no = second_no + first_no, second_no | Method: Generator
Yield statement is immediately recognized by the computer
and it treats this code as a Generator. One cannot have
return and yield statements in the same function.
.next() in the for loop is another special call that the
generator recognizes
:return: | 625941b826068e7796caeb2c |
def set_thread_by_index(self, thread_id): <NEW_LINE> <INDENT> result = self.debugger.communicator.send( "-thread-select {0}".format(thread_id)).is_success() <NEW_LINE> if result: <NEW_LINE> <INDENT> self.debugger.on_thread_changed.notify( self.get_thread_info().selected_thread) <NEW_LINE> self.debugger.on_frame_changed... | @type thread_id: int
@rtype: bool | 625941b8dc8b845886cb5388 |
def serialize(self, view): <NEW_LINE> <INDENT> return collections.OrderedDict([ ('id', self.id), ('flavor_id', self.flavor_id), ('chassis_model_id', self.chassis_model_id), ('schedule_priority', self.schedule_priority), ('deleted', self.deleted) ]) | Turn a FlavorProvider into a dict. | 625941b8fff4ab517eb2f28d |
@app.get('/form') <NEW_LINE> def form(request: Request, csrf_protect:CsrfProtect = Depends()): <NEW_LINE> <INDENT> csrf_token = csrf_protect.generate_csrf() <NEW_LINE> response = templates.TemplateResponse('form.html', { 'request': request, 'csrf_token': csrf_token }) <NEW_LINE> return response | Returns form template. | 625941b8d6c5a10208143e9a |
def queryset(self, request, queryset): <NEW_LINE> <INDENT> field_key = 'class_day' <NEW_LINE> if queryset.model == Registration: <NEW_LINE> <INDENT> field_key = 'classoffer__' + field_key <NEW_LINE> <DEDENT> return queryset.filter(**{field_key: self.value()}) if self.value() else queryset | Returns the filtered queryset based on value provided in the query string, retrievable via self.value(). | 625941b8442bda511e8be279 |
def build_params_from_flags(): <NEW_LINE> <INDENT> FLAGS = flags.FLAGS <NEW_LINE> if FLAGS.task_mode == 'evals': <NEW_LINE> <INDENT> assert not FLAGS.reset_output_dir, '`eval` tasks cannot `reset_output_dir`' <NEW_LINE> <DEDENT> output_dir = FLAGS.output_dir <NEW_LINE> logging.info(f'Checkpoints are at: {output_dir}') ... | Build and return a `tf.HParams` object. | 625941b830c21e258bdfa2f0 |
def _recover_auth_meta(self, auth_id, auth_meta): <NEW_LINE> <INDENT> remove_subvolumes = [] <NEW_LINE> for subvol, subvol_data in auth_meta['subvolumes'].items(): <NEW_LINE> <INDENT> if not subvol_data['dirty']: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> (group_name, subvol_name) = subvol.split('/') <NEW_LINE> g... | Call me after locking the auth meta file. | 625941b8de87d2750b85fbe1 |
def load_pkl( file_name ) : <NEW_LINE> <INDENT> with open( file_name, "r" ) as f : <NEW_LINE> <INDENT> return pickle.load( f ) | Load a python object back from the pickle file. | 625941b80fa83653e4656e10 |
def find_kth_node_from_end(self, k): <NEW_LINE> <INDENT> node1 = self.head <NEW_LINE> node2 = self.head <NEW_LINE> i = 0 <NEW_LINE> while i < k: <NEW_LINE> <INDENT> node1 = node1.next <NEW_LINE> i += 1 <NEW_LINE> if node1.next is None: <NEW_LINE> <INDENT> print('%d is larger than length of LinkedList '%k) <NEW_LINE> br... | Given a linked list, find 'n'th node from the end for a given value of n (n > 0)
idea: make 1 pointer move k nodes and then move both 1 node
complexity is O(n) and extra space used is O(1).
http://www.ideserve.co.in/learn/find-nth-node-from-the-end-of-linked-list | 625941b899fddb7c1c9de1e6 |
def abort(self, jobid, reason, code): <NEW_LINE> <INDENT> self.execute('UPDATE jobs SET abort_code = ?, aborted_by = ?, abort_time = ? WHERE jobid = ?', (code, reason, _now_ts(), jobid)) | codes:
0 - error during submission
1 - error with parent
2 - got killed by SGE/job scheduler | 625941b876d4e153a657e983 |
def main(): <NEW_LINE> <INDENT> opt = docopt(__doc__, options_first=True) <NEW_LINE> if opt['--day'] is None: <NEW_LINE> <INDENT> thisday = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> thisday = int(opt['--day']) <NEW_LINE> <DEDENT> jbt.get_background(float(opt['<ra>']), float(opt['<dec>']), float(opt['<wavelengt... | Main CLI entrypoint. | 625941b8e64d504609d74694 |
def _mapped_to_this_conductor(self, node_uuid, driver): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ring = self.ring_manager[driver] <NEW_LINE> <DEDENT> except exception.DriverNotFound: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.host in ring.get_nodes( node_uuid.encode('utf-8'), replicas=CONF.has... | Check that node is mapped to this conductor.
Note that because mappings are eventually consistent, it is possible
for two conductors to simultaneously believe that a node is mapped to
them. Any operation that depends on exclusive control of a node should
take out a lock. | 625941b80c0af96317bb803d |
def Dispose(self): <NEW_LINE> <INDENT> pass | Dispose(self: FamilyTypeSetIterator,A_0: bool) | 625941b8091ae35668666db9 |
def _upsample_add(self, x, y): <NEW_LINE> <INDENT> _, _, H, W = y.size() <NEW_LINE> return F.upsample(x, size=(H, W), mode='bilinear') + y | Upsample and add two feature maps. | 625941b8796e427e537b0416 |
def clean_internal_terms(self): <NEW_LINE> <INDENT> for term in self.connection[self.numTerms:]: <NEW_LINE> <INDENT> self.disconnect(term) <NEW_LINE> <DEDENT> self.connection = self.connection[:self.numTerms] <NEW_LINE> self.localReference = 0 | Disconnect any internal terms,
Normally used before calling process_params() for a second
time or when an element is removed from circuit. | 625941b8d18da76e23532325 |
def test_get_history_dicts(self): <NEW_LINE> <INDENT> self.resource_monitor.check_resources() <NEW_LINE> cpu_dict = self.resource_monitor.get_cpu_history_dict() <NEW_LINE> self.assertIsInstance(cpu_dict, list) <NEW_LINE> memory_dict = self.resource_monitor.get_memory_history_dict() <NEW_LINE> self.assertIsInstance(memo... | Test the CPU/memory history dictionary of a resource monitor | 625941b8f548e778e58cd3cf |
def test_player_get_max_payoff(self): <NEW_LINE> <INDENT> game = gambit.read_game("test_games/payoff_game.nfg") <NEW_LINE> assert game.players[0].max_payoff == fractions.Fraction(10,1) <NEW_LINE> assert game.players["Player 1"].max_payoff == fractions.Fraction(10,1) <NEW_LINE> assert game.players[1].max_payoff == fract... | To test getting the maximum payoff for the players | 625941b8e5267d203edcdaf4 |
def __addRows( self, aValueList ): <NEW_LINE> <INDENT> for aValue in aValueList: <NEW_LINE> <INDENT> anIter = self.theListStore.append( ) <NEW_LINE> self.theListStore.set_value ( anIter, 0 , aValue[0] ) <NEW_LINE> self.theListStore.set_value ( anIter, 1 , aValue[1] ) <NEW_LINE> self.theListStore.set_value ( anIter, 2 ... | in: list of [Name, Value, Settable, Creator Flag] | 625941b8b57a9660fec336d4 |
def list_virtual_machine_scale_set_vm_network_interfaces( self, resource_group_name, virtual_machine_scale_set_name, virtualmachine_index, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> def internal_paging(next_link=None, raw=False): <NEW_LINE> <INDENT> if not next_link: <NEW_LINE> <INDENT> ur... | Gets information about all network interfaces in a virtual machine in a
virtual machine scale set.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param virtual_machine_scale_set_name: The name of the virtual machine
scale set.
:type virtual_machine_scale_set_name: str
:par... | 625941b85166f23b2e1a4fad |
def add_tweet_enqueue_reply(output_obj, parent): <NEW_LINE> <INDENT> reply_queue = dataqueue.DataQueue('tweet-reply') <NEW_LINE> link = settings.WEB_LINK + '/?lat=%s&lng=%s&o=t' % ( output_obj['lat'], output_obj['lon'] ) <NEW_LINE> reply_data = { 'in_reply_to_status_id': output_obj['id'], 'screen_name': output_obj['scr... | Enqueue the reply now we've worked out where it's for. | 625941b8b7558d58953c4d6f |
def _execute_single_test(self, config, failure_handler, naarad_obj, test): <NEW_LINE> <INDENT> if not failure_handler.get_abort_status(): <NEW_LINE> <INDENT> test.result = constants.SKIPPED <NEW_LINE> test.message += error_messages.TEST_ABORT <NEW_LINE> logger.debug("Skipping" + test.name + "due to too many setup/teard... | Evaluates a single test
:param config:
:param failure_handler:
:param naarad_obj:
:param test:
:return: | 625941b863d6d428bbe44343 |
def main(): <NEW_LINE> <INDENT> new_products_inventory_df = run_site_crawl(BRANDS_PAGE_LINK) <NEW_LINE> save_data_to_database(new_products_inventory_df) <NEW_LINE> print('Total run time:', datetime.now() - startTime) <NEW_LINE> return | Main Function
1. Runs site crawl
2. Saves crawled data to the database | 625941b87cff6e4e811177da |
def test_gathernd(): <NEW_LINE> <INDENT> a = np.arange(12).reshape((2,2,3)) <NEW_LINE> print(a) <NEW_LINE> indice0 = [[[1],[0]]] <NEW_LINE> indice1 = [[[0,0], [1,1]]] <NEW_LINE> indice2 = [[[0,0,0], [1,1,2]]] <NEW_LINE> v0 = tf.gather_nd(a, indice0) <NEW_LINE> v1 = tf.gather_nd(a, indice1) <NEW_LINE> v2 = tf.gather_nd(... | tf.gather_nd()函数使用indice参数的前N-1维与之前的tf.gather的意义相同,第N维上的内容即为在param数组中
的索引,如果是一个元素则由N-1维的tensor的该位置将填充param[",".join(第N维的内容)]
:return: | 625941b850812a4eaa59c179 |
def create_recurring_invoice(self, product): <NEW_LINE> <INDENT> product['is_recurring'] = True <NEW_LINE> product['client_id'] = self.client['data']['id'] <NEW_LINE> product['auto_bill'] = True <NEW_LINE> today = datetime.datetime.now().date() <NEW_LINE> product['start_date'] = today.isoformat() <NEW_LINE> if product[... | Create a recurring invoice for a client. | 625941b84428ac0f6e5ba646 |
def unload(self): <NEW_LINE> <INDENT> for action in self.actions: <NEW_LINE> <INDENT> self.iface.removePluginMenu( self.tr(u"&Jacquez's Q Visualization"), action) <NEW_LINE> self.iface.removeToolBarIcon(action) <NEW_LINE> <DEDENT> del self.toolbar | Removes the plugin menu item and icon from QGIS GUI. | 625941b897e22403b379cdec |
def _set_state(self,inport): <NEW_LINE> <INDENT> self.logger.error( "_set_state: Switch method should be replaced by subclass") <NEW_LINE> self.state = inport <NEW_LINE> return self.state | Stub for real device method | 625941b8283ffb24f3c55760 |
def _schedule_update_to_recheck_turn_off_sensor(self): <NEW_LINE> <INDENT> if not self.is_on: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not self.hass: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> @callback <NEW_LINE> def _scheduled_update(now): <NEW_LINE> <INDENT> self._check_for_off_update_listener = None <N... | Schedule an update to recheck the sensor to see if it is ready to turn off. | 625941b88a43f66fc4b53ebd |
def get_calib_data(self, channel): <NEW_LINE> <INDENT> slope = float(self.send_message( "?AI{{{0}}}:SLOPE".format(channel)).split('=')[1]) <NEW_LINE> offset = float(self.send_message( "?AI{{{0}}}:OFFSET".format(channel)).split('=')[1]) <NEW_LINE> return slope, offset | Query the calibration parameters slope and offset for a given channel.
The returned values are only valid for the currently selected
voltage range.
:param channel: the analog input channel to calibrate | 625941b897e22403b379cded |
def save_all(db: DB, settings: ty.Iterable[model.Setting]) -> None: <NEW_LINE> <INDENT> rows = [setting.to_row() for setting in settings] <NEW_LINE> with db.cursor() as cur: <NEW_LINE> <INDENT> cur.executemany( "DELETE FROM user_settings WHERE key=%s AND user_id=%s", [(setting.key, setting.user_id) for setting in setti... | Save all settings | 625941b83346ee7daa2b2bbd |
def colorize(self, deg): <NEW_LINE> <INDENT> h, l, s = self.tohls() <NEW_LINE> h = clamp(deg * HUE_SCALE, 0.0, 1.0) <NEW_LINE> self.fromhls(h, l, s) | Colorize the color with the given hue. | 625941b855399d3f05588507 |
def execute_function(self, func): <NEW_LINE> <INDENT> logging.info('Importing the function: %s' % func) <NEW_LINE> with h5py.File(self.filename, 'a') as h5_file: <NEW_LINE> <INDENT> input_cubes = [] <NEW_LINE> for input_cube_name in func.input_cube_names: <NEW_LINE> <INDENT> input_cubes.append(h5_file[input_cube_name])... | Executes a function and set the output dataset status to dirty.
| 625941b899cbb53fe6792a3b |
def collate(batch): <NEW_LINE> <INDENT> elem = batch[0] <NEW_LINE> elem_type = type(elem) <NEW_LINE> if isinstance(elem, torch.Tensor): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> out = None <NEW_LINE> if torch.utils.data.get_worker_info() is not None: <NEW_LINE> <INDENT> numel = sum([x.numel() for x in batch]) <NEW_L... | Puts each data field into a tensor with outer dimension batch size | 625941b876e4537e8c3514cb |
def setup_class(cls): <NEW_LINE> <INDENT> Data.shared = Data.testsuites[__class__.__name__]['shared_data'] <NEW_LINE> Data.cfm2utilapi.device.disconnect() <NEW_LINE> time.sleep(2) <NEW_LINE> Data.cfm2masterutilapi.zeroize_hsm(**Data.shared) <NEW_LINE> Data.cfm2masterutilapi.login_hsm_default_co(**Data.shared) <NEW_LINE... | This method sets the FIPS state of the HSM to 2.
Create and Initialize Partitions.
Create crypto_users. | 625941b8046cf37aa974cb9f |
def get_token(self): <NEW_LINE> <INDENT> url = base_url + "token/" <NEW_LINE> headers = {"Content-Type" : "application/json"} <NEW_LINE> obj = { "username" : self.username, "password" : self.password } <NEW_LINE> data = json.dumps(obj).encode("utf-8") <NEW_LINE> response = requests.post(url, data, headers=headers) <NE... | CALL /token | 625941b82c8b7c6e89b35618 |
def model_dataset(input_dataset, output_types, output_shapes, algorithm=0, cpu_budget=0, name=None): <NEW_LINE> <INDENT> _ctx = _context._context or _context.context() <NEW_LINE> tld = _ctx._thread_local_data <NEW_LINE> if tld.is_eager: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _result = pywrap_tfe.TFE_Py_FastPathEx... | Identity transformation that models performance.
Identity transformation that models performance.
Args:
input_dataset: A `Tensor` of type `variant`.
A variant tensor representing the input dataset.
output_types: A list of `tf.DTypes` that has length `>= 1`.
output_shapes: A list of shapes (each a `tf.Tensor... | 625941b8d58c6744b4257ab5 |
def getVelocity(r, Xi, ws): <NEW_LINE> <INDENT> nw = len(ws) <NEW_LINE> dr = np.zeros([3,nw], dtype=complex) <NEW_LINE> v = np.zeros([3,nw], dtype=complex) <NEW_LINE> a = np.zeros([3,nw], dtype=complex) <NEW_LINE> for i in range(nw): <NEW_LINE> <INDENT> dr[:,i] = Xi[:3,i] + SmallRotate(r, Xi[3:,i]) <NEW_LINE> v[ :,i]... | Get node complex velocity spectrum based on platform motion's and relative position from PRP | 625941b8460517430c393fe2 |
def get_initial(self): <NEW_LINE> <INDENT> initial_args = self.initial.copy() <NEW_LINE> if 'username' in self.kwargs: <NEW_LINE> <INDENT> initial_args['owed_username'] = self.kwargs.get('username') <NEW_LINE> <DEDENT> initial_args['amount'] = 1 <NEW_LINE> return initial_args | Used to get the username if the form is going to be paid | 625941b8a17c0f6771cbdea8 |
def decrypt_message(self): <NEW_LINE> <INDENT> testdict = {} <NEW_LINE> for s in range(27): <NEW_LINE> <INDENT> wordCount = 0 <NEW_LINE> decrypted = Message.apply_shift(self, s) <NEW_LINE> for word in decrypted.split(' '): <NEW_LINE> <INDENT> if is_word(self.valid_words, word): <NEW_LINE> <INDENT> wordCount += 1 <NEW_L... | Decrypt self.message_text by trying every possible shift value
and find the "best" one. We will define "best" as the shift that
creates the maximum number of real words when we use apply_shift(shift)
on the message text. If s is the original shift value used to encrypt
the message, then we would expect 26 - s to be the... | 625941b88e7ae83300e4ae20 |
def cmd_line_parse(iargs=None): <NEW_LINE> <INDENT> parser = create_parser() <NEW_LINE> inps = parser.parse_args(args=iargs) <NEW_LINE> atr1 = readfile.read_attribute(inps.dis_file) <NEW_LINE> atr2 = readfile.read_attribute(inps.geom_file) <NEW_LINE> coord1 = 'geo' if 'Y_FIRST' in atr1.keys() else 'radar' <NEW_LINE> co... | Command line parser. | 625941b860cbc95b062c639d |
def info(self, task): <NEW_LINE> <INDENT> self.print_log('_______________dataX_______________') <NEW_LINE> self.print_log('dataX Shape: %s' % str(self.dataX.shape)) <NEW_LINE> self.print_log('_______________dataY_______________') <NEW_LINE> self.print_log('dataY Shape: %s' % str(self.dataY.shape)) <NEW_LINE> self.print... | Print the status, dataX.shape, dataY.shape.
:param task: task name.
:return: | 625941b8ec188e330fd5a5fa |
def is_validated_english_sentence(user_input): <NEW_LINE> <INDENT> result = True <NEW_LINE> if re.search("[0-9]+", user_input) is not None: <NEW_LINE> <INDENT> result = False <NEW_LINE> <DEDENT> elif re.search(r"[^a-zA-Z|\s|\.|,|\?|!]", user_input) is not None: <NEW_LINE> <INDENT> result = False <NEW_LINE> <DEDENT> eli... | Input:
- user_input : 문자열값으로 사용자가 입력하는 문자
Output:
- 입력한 값이 아래에 해당될 경우 False, 그렇지 않으면 True
1) 숫자가 포함되어 있거나,
2) _@#$%^&*()-+=[]{}"';:\|`~ 와 같은 특수문자가 포함되어 있거나
3) 문장부호(.,!?)를 제외하면 입력값이 없거나 빈칸만 입력했을 경우
Examples:
>>> import morsecode as mc
>>> mc.is_validated_english_sentence("Hello 123")
... | 625941b826238365f5f0ecbe |
def compute_title(src, sdate, edate): <NEW_LINE> <INDENT> if src in ["mrms", "ifc"]: <NEW_LINE> <INDENT> if sdate == edate: <NEW_LINE> <INDENT> title = sdate.strftime("%-d %B %Y") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> title = f"{sdate:%-d %b} to {edate:%-d %b %Y} (inclusive)" <NEW_LINE> <DEDENT> <DEDENT> else: ... | Figure out how to label this fun. | 625941b845492302aab5e114 |
def send_artifact(artifact, destination=None): <NEW_LINE> <INDENT> return get_experiment().log_artifact(artifact, destination) | Save an artifact (file) in experiment storage.
Alias for :meth:`~neptune.experiments.Experiment.log_artifact` | 625941b86aa9bd52df036bf7 |
def download_program(self): <NEW_LINE> <INDENT> self.request = requests.get(self.download_url) <NEW_LINE> self.request_content = self.request.content <NEW_LINE> self.file = open(self.file_name, mode="wb") <NEW_LINE> self.file.write(self.request_content) <NEW_LINE> self.file.close() | Downloads actual program executable | 625941b892d797404e303fde |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.