code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def random_sample(mean, log_sigma_sq, is_training): <NEW_LINE> <INDENT> shape = tf.shape(log_sigma_sq) <NEW_LINE> eps = tf.random_normal(shape, dtype=tf.float32) <NEW_LINE> eps = tf.cond(is_training, lambda: eps, lambda: tf.zeros(shape)) <NEW_LINE> z = mean + tf.multiply(tf.exp(log_sigma_sq * 0.5), eps) <NEW_LINE> retu... | sample from N(mean, log_sigma_sq), if is_training | 625941dc851cf427c661a7f9 |
def commit_config(self): <NEW_LINE> <INDENT> self.device.cu.commit(ignore_warning=self.ignore_warning) <NEW_LINE> if not self.config_lock: <NEW_LINE> <INDENT> self._unlock() | Commit configuration. | 625941dc2ae34c7f2600d41d |
def test_generic_relation(self): <NEW_LINE> <INDENT> cb = CanonicalBuilding.objects.get(pk=self.cb.pk) <NEW_LINE> audit_logs = cb.audit_logs.all() <NEW_LINE> notes = cb.audit_logs.filter(audit_type=NOTE) <NEW_LINE> logs = cb.audit_logs.filter(audit_type=LOG) <NEW_LINE> self.assertEqual(audit_logs.count(), 2) <NEW_LINE>... | test CanonicalBuilding.audit_logs | 625941dccad5886f8bd272c5 |
def is_deterministic(self): <NEW_LINE> <INDENT> for map in self._transitions.values(): <NEW_LINE> <INDENT> for targets in map.values(): <NEW_LINE> <INDENT> if len(targets) > 1: return False <NEW_LINE> <DEDENT> <DEDENT> return True | Return whether this is a DFA
(every symbol leads from a state to at most one target state). | 625941dc31939e2706e4d153 |
def bit_string(text: bytes) -> str: <NEW_LINE> <INDENT> return ''.join(['{:08b}'.format(letter) for letter in text]) | :param text: text to be turned into a binary string
:return: a binary string | 625941dc004d5f362079a61e |
def format_workspaces_json(workspaces, skip=[]): <NEW_LINE> <INDENT> formatted_ws = [] <NEW_LINE> for ws in workspaces: <NEW_LINE> <INDENT> uid = ws.UID <NEW_LINE> if uid in skip: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> title = safe_unicode(ws['Title']) <NEW_LINE> formatted_ws.append({ 'id': uid, 'text': title... | Format a list of workspaces as JSON for use with pat-autosuggest
:param list workspaces: A list of brains
:param lis skip: A list of UIDs to skip
:rtype string: JSON {"ws_id1": "ws_title1", ...} | 625941dcbe8e80087fb20f2b |
def patch_mako_templates(): <NEW_LINE> <INDENT> orig_render = Template.render_unicode <NEW_LINE> def wrapped_render(*args, **kwargs): <NEW_LINE> <INDENT> django.test.signals.template_rendered.send(sender=None, template=None, context=kwargs) <NEW_LINE> return orig_render(*args, **kwargs) <NEW_LINE> <DEDENT> return mock.... | Patch mako so the django test client can access template context | 625941dc21a7993f00bc7fe1 |
def __init__(self): <NEW_LINE> <INDENT> r <NEW_LINE> raise NotImplementedError("'BasisShape' is an abstract interface.") | :raise: :py:class:`NotImplementedError` Abstract interface. | 625941dc435de62698dfdf3a |
def __init__(self, window, row, column, size, is_filled=False): <NEW_LINE> <INDENT> self.window = window <NEW_LINE> self.row = row <NEW_LINE> self.column = column <NEW_LINE> self.size = size <NEW_LINE> self.is_filled = is_filled | Building block for the gui grid. It can visualize itself, and toggle filled, not filled
:param window Tk: the Tk application object
:param row int: the row index for the cell
:param column int: the column index for the cell
:param size int: the size in px the cell should take on the screen
:param is_filled bool: whethe... | 625941dc1f037a2d8b9464ea |
def __init__(self, builder=None, newick=None, zero_based=False, taxon_labels=None, rooted=False): <NEW_LINE> <INDENT> TreeBase.__init__(self) <NEW_LINE> self.setRootedness(rooted) <NEW_LINE> if builder: <NEW_LINE> <INDENT> builder.buildTree(self) <NEW_LINE> <DEDENT> elif newick: <NEW_LINE> <INDENT> self.buildFromString... | Calls clear() to initialize data members.
If a `builder` is passed in, then the builder.buildTree() function
will be called to initialize the tree.
If no builder is passed in, but `newick` is specified then the tree
definition comes from the newick string and `zero_based` is used to
indicate whether the taxa indices ... | 625941dc099cdd3c635f0f47 |
def learn(self, experiences, gamma): <NEW_LINE> <INDENT> states, actions, rewards, next_states, dones = experiences <NEW_LINE> actions_next = self.actor_target(next_states) <NEW_LINE> Q_targets_next = self.critic_target(next_states, actions_next) <NEW_LINE> Q_targets = rewards + (gamma * Q_targets_next * (1 - dones)) <... | Update policy and value parameters using given batch of experience tuples.
Q_targets = r + γ * critic_target(next_state, actor_target(next_state))
where:
actor_target(state) -> action
critic_target(state, action) -> Q-value
Params
======
experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples... | 625941dc99cbb53fe6792ed3 |
def combine_batch_lists(processed_batch_queue: multiprocessing.Queue) -> np.array: <NEW_LINE> <INDENT> batches = list() <NEW_LINE> while not processed_batch_queue.empty(): <NEW_LINE> <INDENT> batches.append(processed_batch_queue.get()) <NEW_LINE> <DEDENT> return batches | Combines processed batches produced my the multiprocessing module into a single batch list.
Params:
- processed_batch_queue (multiprocessing.Queue): The Queue of processed batches
Returns:
- batches (list<Batch>): The combined list of batches | 625941dc3eb6a72ae02ec7d1 |
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> end = 0 <NEW_LINE> _x = self <NEW_LINE> start = end <NEW_LINE> end += 28 <NEW_LINE> (_x.id, _x.x, _x.y, _x.angle,) = _struct_i3d.unpack(str[start:end]) <NEW_LINE> return self <NEW_LINE> <DEDENT> except struct.error as e: <NEW_LINE> <I... | unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module | 625941dc24f1403a92600e51 |
def local(self): <NEW_LINE> <INDENT> logging.info(__name__ + ' : Set control to local & locked') <NEW_LINE> self.set_remote_status(0) | Set control to local & locked | 625941dc76e4537e8c351962 |
def connect_livestatus(address, port, timeout): <NEW_LINE> <INDENT> with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: <NEW_LINE> <INDENT> logging.info("Connect to Livestatus at %s:%s ...", address, port) <NEW_LINE> sock.settimeout(timeout) <NEW_LINE> try: <NEW_LINE> <INDENT> sock.conne... | Test connection to Livestatus. Return True on success, False on error. | 625941dcc4546d3d9de72d23 |
def prm19_resnet50(pretrained=False, **kwargs): <NEW_LINE> <INDENT> model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) <NEW_LINE> return model | Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet | 625941dc57b8e32f52483789 |
def answer(n): <NEW_LINE> <INDENT> return max(prime_factors(n)) | Returns the largest prime factor of n
----------
n : int
Input number
Returns
-------
max : int
Maximum prime factor
Doc Test
----------
>>> answer(13195)
29
>>> answer(600851475143)
6857 | 625941dccad5886f8bd272c6 |
def get_review_settings(): <NEW_LINE> <INDENT> return _settings.get('review', None) | Return a dict of review charts settings. | 625941dc67a9b606de4a81a4 |
def decode_packet_21(self, data): <NEW_LINE> <INDENT> return self.decode_unsigned_byte(data) | Decode Packet 21 (charging state) and return its value
Arguments:
data: The bytes to decode
Returns: A value from 0-5, that describes the charging state | 625941dc379a373c97cfae33 |
def is_status_flags_supported(self) -> bool: <NEW_LINE> <INDENT> return self.version >= (1, 4, 0) | Check whether status flags supported by the current protocol. | 625941dcf9cc0f698b1408e6 |
def extract_feat(self, img): <NEW_LINE> <INDENT> x = self.backbone(img) <NEW_LINE> if self.with_neck: <NEW_LINE> <INDENT> x = self.neck(x) <NEW_LINE> <DEDENT> return x | Extract features
Args:
img (torch.Tensor): Image tensor with shape (n, c, h ,w).
Returns:
list[torch.Tensor]: Multi-level features that may have
different resolutions. | 625941dcfff4ab517eb2f72a |
def reset_parameters(self): <NEW_LINE> <INDENT> stdv = 1.0 / math.sqrt(self.hidden_size) <NEW_LINE> for weight in self.parameters(): <NEW_LINE> <INDENT> if not weight.requires_grad: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> weight.data.uniform_(-stdv, stdv) | https://github.com/pytorch/pytorch/blob/7b6b7d4575832a9af4257ba341f3da9e7a2a2b57/torch/nn/modules/rnn.py#L115 | 625941dc0fa83653e46572a6 |
def filter_odd_numbers(arr: list): <NEW_LINE> <INDENT> pass | Filters all the odd numbers in a given array
i.e: filter_odd_numbers([1,2,3,4,5]) returns [1,3,5]
Args:
- arr: any ordinary list
Returns:
- an array only with odd numbers | 625941dc283ffb24f3c55beb |
def isValid(self, s): <NEW_LINE> <INDENT> if len(s) == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if len(s) == 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> pDict = { ')':'(', ']': '[', '}':'{' } <NEW_LINE> pStack = [s[0]] <NEW_LINE> for i in s[1:]: <NEW_LINE> <INDENT> if i not in pDict: <NEW_LINE... | :type s: str
:rtype: bool | 625941dcd18da76e235327c6 |
def test_defaultdict_with_list(self): <NEW_LINE> <INDENT> ad = DefaultAttrDict(list) <NEW_LINE> self.assertEqual(ad['x'], []) <NEW_LINE> self.assertEqual(ad['y'], []) <NEW_LINE> self.assertEqual(ad, {'x': [], 'y': []}) <NEW_LINE> self.assertFalse('z' in ad) <NEW_LINE> ad = DefaultAttrDict(list) <NEW_LINE> self.assertEq... | DefaultAttrDict as a list generator | 625941dc4428ac0f6e5baae1 |
def sparse_categorical_accuracy(y_true, y_pred): <NEW_LINE> <INDENT> return K.mean(K.equal(K.max(y_true, axis=-1), K.cast(K.argmax(y_pred, axis=-1), K.floatx()))) | Same as categorical_accuracy, but useful when the predictions are for
sparse targets | 625941dceab8aa0e5d26de46 |
def create_unbinding_reaction_rule(reactant, product1, product2, k): <NEW_LINE> <INDENT> rr = _gfrd.ReactionRule([reactant], [product1, product2]) <NEW_LINE> rr['k'] = '%.16g' % k <NEW_LINE> return rr | Example: A -> B + C.
Arguments:
- reactant
a Species.
- product1
a Species.
- product2
a Species.
- k
intrinsic reaction rate. Units: per second. (Rough order of
magnitude: 1e-2 /s to 1e2 /s).
The reactant and the products should be in/on the same
Region or Su... | 625941dc8a43f66fc4b5434f |
def input(self): <NEW_LINE> <INDENT> self.job = input("job file: ") <NEW_LINE> self.loglevel = input("Log Level: ") <NEW_LINE> self.logfile = input("logfile name: ") <NEW_LINE> self.logfile = input("logfile name: ") <NEW_LINE> self.interval = input("Interval (secodns): ") <NEW_LINE> self.keyfile = input("Key File: ") <... | Manually configures authentication | 625941dc16aa5153ce362765 |
def goto_url(self, obj): <NEW_LINE> <INDENT> if self.goto: <NEW_LINE> <INDENT> return filter_url(self.goto, obj) <NEW_LINE> <DEDENT> return None | Given an object, return its "Goto" url, or None. | 625941dc046cf37aa974d033 |
def to_dataset(container, attrs=None, coords=None, variables=None, *args, **kwargs): <NEW_LINE> <INDENT> container = _coerce_to_metacsv(container, *args, **kwargs) <NEW_LINE> _parse_args(container, attrs, coords, variables) <NEW_LINE> if len(container.shape) == 1: <NEW_LINE> <INDENT> return metacsv_series_to_dataset(co... | Convert a CSV, Series or DataFrame, DataArray, or Dataset to an
:py:class:`xarray.Dataset`
.. note ::
If a Series is passed, the variable will be named
'__xarray_data_variable__'
Parameters
----------
container : object
A pandas or metacsv Series, DataFrame, o, an xarray DataArray or
Dataset, or a ... | 625941dcd6c5a1020814433a |
def __init__(self, block, depth, num_classes, channels=3): <NEW_LINE> <INDENT> super(CifarResNet, self).__init__() <NEW_LINE> self.featureSize = 64 <NEW_LINE> assert (depth - 2) % 6 == 0, 'depth should be one of 20, 32, 44, 56, 110' <NEW_LINE> layer_blocks = (depth - 2) // 6 <NEW_LINE> self.dic = dict() <NEW_LINE> self... | Constructor
Args:
depth: number of layers.
num_classes: number of classes
base_width: base width | 625941dcbd1bec0571d9091c |
def dump(self, update=False): <NEW_LINE> <INDENT> if not update and exists(self.out_dir): <NEW_LINE> <INDENT> shutil.rmtree(self.out_dir) if isdir(self.out_dir) else os.remove(self.out_dir) <NEW_LINE> <DEDENT> elif update and isfile(self.out_dir): <NEW_LINE> <INDENT> logger.error("Output directory is not valid") <NEW_L... | Dump resources for every known application in the memory dump.
:param update: update output directory (meaning that collected pieces of information should not be recollected
using Volatility commands) | 625941dc6fece00bbac2da2f |
def __init__(self, cell, embedding, start_tokens, end_token, initial_state, beam_width, output_layer=None, length_penalty_weight=0.0): <NEW_LINE> <INDENT> if not rnn_cell_impl._like_rnncell(cell): <NEW_LINE> <INDENT> raise TypeError("cell must be an RNNCell, received: %s" % type(cell)) <NEW_LINE> <DEDENT> if (output_la... | Initialize the BeamSearchDecoder.
Args:
cell: An `RNNCell` instance.
embedding: A callable that takes a vector tensor of `ids` (argmax ids),
or the `params` argument for `embedding_lookup`.
start_tokens: `int32` vector shaped `[batch_size]`, the start tokens.
end_token: `int32` scalar, the token that marks... | 625941dc097d151d1a223145 |
def get_paper_venue_citations(self, subtract=False, mean=False): <NEW_LINE> <INDENT> venue_cit = np.array(self.get_venue_citations()) <NEW_LINE> self.logger.debug('Copying paper-venue matrix as CSR matrix') <NEW_LINE> venue_cit_m = self.paper_venue_m.tocsr().copy() <NEW_LINE> self.logger.debug('Replacing matrix data wi... | :param subtract: whether to subtract citations received by a paper
from the venue total, e.g. if paper X was published
at venue Y, the venue Y was cited 300 times in total
and the paper 45 times, then the result for the paper
will be 300-45=255
:param ... | 625941dca4f1c619b28b0320 |
def show_images(data): <NEW_LINE> <INDENT> for loop in range(2): <NEW_LINE> <INDENT> plt.title('Training Data Image') <NEW_LINE> imgplot = plt.imshow(data[loop]) <NEW_LINE> plt.show() | This function is used for plot image and save it.
Args:
data: Two images from train data with shape (2, 16, 16). The shape represents total 2
images and each image has size 16 by 16.
Returns:
Do not return any arguments, just save the images you plot for your report. | 625941dc3539df3088e2e638 |
def myadd(x, y): <NEW_LINE> <INDENT> return (x+y) | 两个数相加 | 625941dcb5575c28eb68e2f0 |
def get_datetime_calendar_wdg(): <NEW_LINE> <INDENT> date_calendar_wdg = CalendarInputWdg("datetime_calendar") <NEW_LINE> date_calendar_wdg.set_option('show_activator', 'true') <NEW_LINE> date_calendar_wdg.set_option('show_time', 'true') <NEW_LINE> date_calendar_wdg.set_option('width', '300px') <NEW_LINE> date_calendar... | Get a CalendarInputWdg that displays the time.
:return: CalendarInputWdg | 625941dc50485f2cf553d088 |
def decrypt(self, message): <NEW_LINE> <INDENT> return self.__substitute_letters(message, self.keyword_alphabet, ALPHABET) | Returns the decrypted message by substituting the letters
in the class variable <keyword_alphabet> with the letters in the
standard alphabet. | 625941dc236d856c2ad44acb |
def __init__(self, container=None): <NEW_LINE> <INDENT> if container: <NEW_LINE> <INDENT> self._pool = container | container决定是否是线程安全的。
Args:
container (list or Queue): 事件容器 | 625941dc30c21e258bdfa78c |
def generate_room(dim=(13, 13), p_change_directions=0.35, num_steps=25, num_boxes=3, tries=4): <NEW_LINE> <INDENT> room_state = np.zeros(shape=dim) <NEW_LINE> room_structure = np.zeros(shape=dim) <NEW_LINE> for t in range(tries): <NEW_LINE> <INDENT> room = room_topology_generation(dim, p_change_directions, num_steps) <... | Generates a Sokoban room, represented by an integer matrix. The elements are encoded as follows:
wall = 0
empty space = 1
box target = 2
box not on target = 3
box on target = 4
player = 5
:param dim:
:param p_change_directions:
:param num_steps:
:return: Numpy 2d Array | 625941dcd4950a0f3b08c639 |
def safe_rmtree(path): <NEW_LINE> <INDENT> if os.path.isdir(path): <NEW_LINE> <INDENT> shutil.rmtree(path) | Removes the directory safely, i. e. does not raise exception in case when
the directory does not exit.
@param path The path to the directory. | 625941dc50485f2cf553d089 |
def score(self, x_test, y_test,fileToWrite): <NEW_LINE> <INDENT> if self.model: <NEW_LINE> <INDENT> x_test_org=x_test <NEW_LINE> x_test = self.p.transform(x_test) <NEW_LINE> lengths = map(len, y_test) <NEW_LINE> y_pred = self.model.predict(x_test) <NEW_LINE> y_pred = self.p.inverse_transform(y_pred, lengths) <NEW_LINE>... | Returns the f1-micro score on the given test data and labels.
Args:
x_test : array-like, shape = (n_samples, sent_length)
Test samples.
y_test : array-like, shape = (n_samples, sent_length)
True labels for x.
Returns:
score : float, f1-micro score. | 625941dc5510c4643540f6cb |
def test_save_multiple_credentials(self): <NEW_LINE> <INDENT> self.new_credentials.save_credentials() <NEW_LINE> test_credentials = Credentials("Instagram","Gloria Givondo","thegram") <NEW_LINE> test_credentials.save_credentials() <NEW_LINE> self.assertEqual(len(Credentials.credentials_list),2) | method that checks if we can save multiple credentials objects to credentials_list | 625941dc29b78933be1e5995 |
def register_epilogue(func: ExecutionCallback) -> None: <NEW_LINE> <INDENT> _ensure_not_defined(func, _EPILOGUE_HOOKS) <NEW_LINE> _EPILOGUE_HOOKS.append(CallbackHook(func, None)) | Register an execution epilogue callback function.
:param func: The callback function to run. | 625941dc5e10d32532c5f214 |
def list_artifacts(self, object_id: str, *, account: str = None, **kwargs ) -> DetailedResponse: <NEW_LINE> <INDENT> if object_id is None: <NEW_LINE> <INDENT> raise ValueError('object_id must be provided') <NEW_LINE> <DEDENT> headers = {} <NEW_LINE> sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, ... | Get artifacts.
This endpoint returns a list of artifacts for an object.
:param str object_id: The object's unique ID.
:param str account: (optional) This changes the scope of the request
regardless of the authorization header. Example scopes are `account` and
`global`. `account=global` is reqired if ope... | 625941dcd486a94d0b98e435 |
def badges_uid(self, uid): <NEW_LINE> <INDENT> if request.method == 'DELETE': <NEW_LINE> <INDENT> result = self.database.delete_badge(uid) <NEW_LINE> if result != False: <NEW_LINE> <INDENT> log.info("DELETE Request for /badges/{0} suceeded".format(uid)) <NEW_LINE> return json.dumps({'success': True, 'id': result}) <NEW... | GET: /badges/<uid>
DELETE: /badges/<uid>
return s a JSON blob with all the badge attributes
Deletes a badge with the given uid | 625941dcbaa26c4b54cb140b |
def long_tube_coeff(mass_flux, D, c_p, mu, k): <NEW_LINE> <INDENT> Pr = mu * c_p / k <NEW_LINE> Re = mass_flux * D / mu <NEW_LINE> h = 0.023 * mass_flux * c_p * Re**-0.2 * Pr**-0.67 <NEW_LINE> return h | Convection coefficient for flow in a long tube.
This model for convection was developed from experiments with fully-developed
flow in long tubes. It is taken from Eq. 11.35 in Hill & Peterson:
.. math::
rac{h}{G c_p} = 0.023 (rac{G D}{ \mu_b})^{-0.2} (rac{\mu c_p}{k})_b^{-0.67}
where :math:`G` is the average ... | 625941dc30dc7b7665901c51 |
def scale_bbox(x, y, h, w, class_id, confidence, h_scale, w_scale): <NEW_LINE> <INDENT> xmin = int((x - w / 2) * w_scale) <NEW_LINE> ymin = int((y - h / 2) * h_scale) <NEW_LINE> xmax = int(xmin + w * w_scale) <NEW_LINE> ymax = int(ymin + h * h_scale) <NEW_LINE> return dict(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, cl... | Scale bounding box to fit on the frame.
:param x: X coordinate
:param y: Y coordinate
:param h: Height of the bbox
:param w: Width of the bbox
:param class_id: Class label
:param confidence: Prediction probability
:param h_scale: Height scaling factor
:param w_scale: ... | 625941dc1f5feb6acb0c4e39 |
def list(self, endpoint=None, query_params=None, limit=None): <NEW_LINE> <INDENT> list_of_user_object = [] <NEW_LINE> if limit == 0: <NEW_LINE> <INDENT> return list_of_user_object <NEW_LINE> <DEDENT> for count in self.stream(endpoint=endpoint, query_params=query_params): <NEW_LINE> <INDENT> list_of_user_object.append(c... | Lists the specified endpoint data field parameters
:param endpoint: Endpoint
:param query_params: query parameters
:param limit: limit count for the list
:return: list of resource object | 625941dc5fdd1c0f98dc0522 |
def copy(self,data=True): <NEW_LINE> <INDENT> if data: <NEW_LINE> <INDENT> return deepcopy(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> retval = nddata(0) <NEW_LINE> retval.dimlabels = list(self.dimlabels) <NEW_LINE> retval.data = None <NEW_LINE> retval.data_error = None <NEW_LINE> if hasattr(self,'data_units')... | Return a full copy of this instance.
Because methods typically change the data in place, you might want to
use this frequently.
Parameters
----------
data : boolean
Default to True.
False doesn't copy the data -- this is for internal use,
*e.g.* when you want to copy all the metadata and perform a
cal... | 625941dc7b180e01f3dc4ae6 |
def _translate_device_rates(val, numeric_rate=True): <NEW_LINE> <INDENT> val = _map_vals(val, 'Path', 'Rate') <NEW_LINE> for idx in range(len(val)): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> is_abs = os.path.isabs(val[idx]['Path']) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> is_abs = False <NEW_LI... | CLI input is a list of PATH:RATE pairs, but the API expects a list of
dictionaries in the format [{'Path': path, 'Rate': rate}] | 625941dcadb09d7d5db6ca7c |
def split(self, split_on:SplitFuncOrIdxList)->None: <NEW_LINE> <INDENT> if isinstance(split_on,Callable): split_on = split_on(self.model) <NEW_LINE> self.layer_groups = split_model(self.model, split_on) | split the model at `split_on` | 625941dc8da39b475bd65264 |
def parse_contig_file(infile): <NEW_LINE> <INDENT> contigs = OrderedDict() <NEW_LINE> with open(infile, 'r') as file: <NEW_LINE> <INDENT> for name, seq in read_fasta(file): <NEW_LINE> <INDENT> contigs[name[1:]] = len(seq) <NEW_LINE> <DEDENT> <DEDENT> cntg_order = [ k for k, v in sorted( contigs.items(), key=lambda item... | Parses contig fasta file. Returns dict sorted by contig length:
{contig_name: length} | 625941dc009cb60464c6369e |
def _CheckStatus(self, package, caps, status): <NEW_LINE> <INDENT> request = capability_stub.IsEnabledRequest() <NEW_LINE> request.package = package <NEW_LINE> list(map(request.capability.append, caps or ['*'])) <NEW_LINE> response = capability_stub.IsEnabledResponse() <NEW_LINE> self.stub._Dynamic_IsEnabled(request, r... | Checks the status of a package and capabilities list. | 625941dc7b25080760e39746 |
def game_states(gamestate): <NEW_LINE> <INDENT> for spell in spells.keys(): <NEW_LINE> <INDENT> game = Game.makegame(gamestate) <NEW_LINE> player_plays(game, spell) <NEW_LINE> if game.winner: <NEW_LINE> <INDENT> if type(game.winner) == Game.Player: <NEW_LINE> <INDENT> yield game <NEW_LINE> <DEDENT> continue <NEW_LINE> ... | Generate all possible game states for given game state.
Will apply all spells possible, and if the spell results in a winner,
or is not invalid, yields the game state. | 625941dc0c0af96317bb84d6 |
def exec(self, exec_id: str) -> Exec: <NEW_LINE> <INDENT> return Exec(self.docker, exec_id, None) | Return Exec instance for already created exec object. | 625941dc507cdc57c6306fce |
def load_data_split(data_path, split, wordsep, sample_rate): <NEW_LINE> <INDENT> wav_scp_file = os.path.join(data_path, 'mscoco2k_wav.scp') <NEW_LINE> text_file = os.path.join(data_path, 'text') <NEW_LINE> split_file = os.path.join(data_path, 'mscoco2k_retrieval_split.txt') <NEW_LINE> if split == 'train': <NEW_LINE> <I... | Returns:
examples : a list of mappings of
{ "audio": filename of audio,
"text": a list of tokenized words,
"duration": float} | 625941dc99cbb53fe6792ed4 |
def run(args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> authorisation = Authorisation.from_data(args["authorisation"]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise PermissionError( "Only an authorised admin can dump the keys") <NEW_LINE> <DEDENT> service = get_this_service(need_private_access=True) <NEW_LI... | Call this function to force the service to save its keys
to the object store
Args:
args (dict): contains authorisaton details for key dump | 625941dc507cdc57c6306fcf |
def chocolatey_version(): <NEW_LINE> <INDENT> if 'chocolatey._version' in __context__: <NEW_LINE> <INDENT> return __context__['chocolatey._version'] <NEW_LINE> <DEDENT> def find_version(legacy=False): <NEW_LINE> <INDENT> cmd = [_find_chocolatey(__context__, __salt__)] <NEW_LINE> if legacy: <NEW_LINE> <INDENT> cmd.appen... | .. versionadded:: 2014.7.0
Returns the version of Chocolatey installed on the minion.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.chocolatey_version | 625941dc2eb69b55b151cba0 |
def cap(v, l): <NEW_LINE> <INDENT> s = str(v) <NEW_LINE> return s if len(s) <= l else s[-l:] | Shortens string is above certain length. | 625941dcbe7bc26dc91cd8e9 |
def test_non_ber_decoding(self): <NEW_LINE> <INDENT> self.assertEqual(InterchangeObject.ber_decode_length('0100'.decode('hex_codec'), 2), 256) <NEW_LINE> self.assertEqual(InterchangeObject.ber_decode_length('01e5'.decode('hex_codec'), 2), 485) | Test usability of the method for non BER decoding. | 625941dca79ad161976cc434 |
def delete(self, item): <NEW_LINE> <INDENT> self.ping_objects.remove(item) <NEW_LINE> Thread(target=item.stop_thread).start() | Removes an item from pinging | 625941dc23849d37ff7b337b |
def third(num_list): <NEW_LINE> <INDENT> result = None <NEW_LINE> for num in num_list: <NEW_LINE> <INDENT> if num_list.count(num) % 2: <NEW_LINE> <INDENT> result = num <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return result or 'There is no odd-times appearing int!' | More pythonic (i hope) version | 625941dccdde0d52a9e53323 |
def get_unique_name_list(self, list_size=5, item_length=None): <NEW_LINE> <INDENT> name_list = [] <NEW_LINE> for i in range(0, list_size): <NEW_LINE> <INDENT> name_list.append(self.get_unique_name(item_length[i])) <NEW_LINE> <DEDENT> return name_list | Get a list of valid email ids
Parameters:
list_size: Number of names. Default is 5 names in a list
item_length: It should be a list containing number of items equal to the listSize
This determines the length of the each item in the list -> [1, 2, 3, 4, 5] | 625941dcec188e330fd5aa88 |
def MaterialEnvironmentMap(material_index, filename=None): <NEW_LINE> <INDENT> mat = scriptcontext.doc.Materials[material_index] <NEW_LINE> if mat is None: return scriptcontext.errorhandler() <NEW_LINE> texture = mat.GetEnvironmentTexture() <NEW_LINE> rc = texture.FileName if texture else "" <NEW_LINE> if filename: <NE... | Returns or modifies a material's environment bitmap filename.
Parameters:
material_index = zero based material index
filename[opt] = the environment bitmap filename
Returns:
if filename is not specified, the current environment bitmap filename
if filename is specified, the previous environment bitmap filename
... | 625941dc21a7993f00bc7fe2 |
def _send_open_connection(self): <NEW_LINE> <INDENT> frame = pamqp_connection.Open( virtual_host=self.parameters['virtual_host'] ) <NEW_LINE> self._write_frame(frame) | Send Open Connection frame.
:return: | 625941dc7c178a314d6ef752 |
def _create_filter(names): <NEW_LINE> <INDENT> if names == "*": <NEW_LINE> <INDENT> return lambda k: False <NEW_LINE> <DEDENT> names = names.split("|") <NEW_LINE> return lambda k: k not in names | Create a filter function matching names. | 625941dc10dbd63aa1bd2e90 |
def loadFromCache(self,redis_wrapper,key='default'): <NEW_LINE> <INDENT> if key == 'default': <NEW_LINE> <INDENT> key = self.showId() <NEW_LINE> <DEDENT> logger.info('Retrieving information from NestedGriddedTaxonomy. \n This can take some time') <NEW_LINE> r = redis_wrapper <NEW_LINE> nt_dump = r.get(key) <NEW_LINE> i... | .. loadFromCache
This method loads the Nested Taxonomy object stored from the Redis
Cache Backend.
Parameters
==========
redis_wrapper : StrictRedis object
This is the redis connection to be used.
Needs to have specified host, database and port
key : string
The key used for retrieving ... | 625941dc8c3a8732951586ab |
def load_gene_map(map_file): <NEW_LINE> <INDENT> return pd.read_csv(map_file) | Reads in a file mapping genes to contigs
:param map_file: The mapping file with gene ids and contigs comma-separated
:return: a pandas dataframe | 625941dca219f33f34628c54 |
def query_input(question): <NEW_LINE> <INDENT> valid = {"1": Platform.Ubuntu, "2": Platform.CentOS,} <NEW_LINE> prompt = " [1/2] " <NEW_LINE> while True: <NEW_LINE> <INDENT> sys.stdout.write(question + prompt) <NEW_LINE> if check_python_version() == 'new': <NEW_LINE> <INDENT> choice = input().lower() <NEW_LINE> <DEDENT... | 一个简单的脚本里面交互的函数
用法:query_yes_no("确定吗?") 如果按yes 则函数返回值为True | 625941dcde87d2750b860083 |
@manager.command <NEW_LINE> def wheel(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> clean_() <NEW_LINE> wheel_() <NEW_LINE> <DEDENT> except CalledProcessError as e: <NEW_LINE> <INDENT> exit(e.returncode) | Create a wheel package | 625941dcd10714528d5fffd4 |
def reset(self): <NEW_LINE> <INDENT> self._env_packages_cache = {} | Clear cached packages. | 625941dc32920d7e50b284c1 |
def _import_upload(self, upload_id, repo_id): <NEW_LINE> <INDENT> self.logger.info('Importing pulp upload {0} into {1}'.format(upload_id, repo_id)) <NEW_LINE> url = '{0}/pulp/api/v2/repositories/{1}/actions/import_upload/'.format(self._server_url, repo_id) <NEW_LINE> payload = { 'upload_id': upload_id, 'unit_type_id': ... | Import uploaded content | 625941dc4f6381625f114d2a |
def p_ArgumentList(p): <NEW_LINE> <INDENT> if(len(p[:]) == 2): <NEW_LINE> <INDENT> p[0] = p[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = p[1:] | ArgumentList : Expression
| ArgumentList ',' Expression | 625941dc94891a1f4081bd99 |
def apk_update_secret(self, app_id: str, key_pair: tuple): <NEW_LINE> <INDENT> self._app_key_manager[app_id] = key_pair | 自有AppKey管理工具的密钥对更新
@param {str} app_id - 要更新的app_id
@param {tuple} key_pair - (app_key, app_secret) 密钥对 | 625941dc8c0ade5d55d3ecab |
def max(*args): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsVLVD_max(*args) | max(itkVariableLengthVectorD a) -> itkVariableLengthVectorD | 625941dc07f4c71912b11773 |
def __init__(self, api): <NEW_LINE> <INDENT> self.api = api <NEW_LINE> self.wss = websocket.WebSocketApp( self.api.wss_url, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, on_open=self.on_open ) | :param api: The instance of :class:`BinaryAPI
<binaryapi.api.BinaryAPI>`. | 625941dccad5886f8bd272c7 |
def __init__(self, key, db, dbcollection='mongolocker', ttl=600, timeparanoid=True): <NEW_LINE> <INDENT> self.uuid = str(uuid.uuid4()) <NEW_LINE> self.host = getfqdn() <NEW_LINE> self.pid = getpid() <NEW_LINE> self.ts_expire = None <NEW_LINE> self.timeparanoid = timeparanoid <NEW_LINE> self.dbcollection = dbcollection ... | :param key: Name of distributed lock
:type key: str
:param dbconn: Pymongo client connection to mongodb
:type dbconn: PyMongo db connection
:param dbname: name of database (defaults to 'mongoelector')
:type dbname: str
:param dbname: name of collection (defaults to 'mongolocker')
:type dbname: str
:param ttl: Lock will... | 625941dcdd821e528d63b496 |
def get_load_avg(self) -> Optional[List[str]]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res: List[str] = ( str( self.run_command( "cat /proc/loadavg", capture_stdout=True, timeout=15 ) ) .rstrip() .split(" ") ) <NEW_LINE> assert len(res) >= 3 <NEW_LINE> return res <NEW_LINE> <DEDENT> except nixops.ssh_util.SSHConne... | Get the load averages on the machine. | 625941dce64d504609d74b2e |
def get_glcm_statistics(volume): <NEW_LINE> <INDENT> image_medians = [0, 0, 0] <NEW_LINE> image_medians[0] = volume[int(volume.shape[0] / 2), :, :] <NEW_LINE> image_medians[1] = volume[:, int(volume.shape[1] / 2), :] <NEW_LINE> image_medians[2] = volume[:, :, int(volume.shape[2] / 2)] <NEW_LINE> all_d = [] <NEW_LINE> a... | Get statistics realted to GLCM. | 625941dc21a7993f00bc7fe3 |
def read_unpulled_salaries(self): <NEW_LINE> <INDENT> return self._conn.execute(_sql['Salary']['read_not_pulled']).fetchall() | Returns all rows in the Salary table that haven't been pulled yet | 625941dc16aa5153ce362766 |
def instantiate_system(): <NEW_LINE> <INDENT> begin = time.time() <NEW_LINE> global df_boston, business_df, svd_model, df_words_user, df_words_business, df_boston_parsed_text <NEW_LINE> global dict_words_business, dict_words_user, dict_stars, top_10 <NEW_LINE> df_boston = data.load_df_boston() <NEW_LINE> business_df = ... | Loads the data from dataset and creates and trains the
models. | 625941dc099cdd3c635f0f49 |
def create_stats_run_synchronous_cascade(N=1000, p=.5, num_seeds=1, phi_values=.5): <NEW_LINE> <INDENT> cascadeNet = GlobalCascadeNetwork(N=N, p=p, num_seeds=num_seeds, phi_values=phi_values) <NEW_LINE> cascadeNet.synchronous_cascade() <NEW_LINE> return (cascadeNet.cascade_fraction()) | function for creating and running a **synchronous** cascade | 625941dc3346ee7daa2b305c |
def test_get_colors_not_label_encoded(self): <NEW_LINE> <INDENT> X, y = self.discrete <NEW_LINE> oz = DataVisualizer(classes="abcde").fit(X, y) <NEW_LINE> with pytest.raises(YellowbrickKeyError, match="could not determine color"): <NEW_LINE> <INDENT> oz.get_colors(["foo"]) | Assert exception is raised on unknown class label for get_colors | 625941dc50812a4eaa59c60e |
def converttohex(self, endian='big'): <NEW_LINE> <INDENT> return self.converttostring(endian).encode('hex') | return the value of self converted to hex | 625941dcbe8e80087fb20f2e |
def destroy_control(self): <NEW_LINE> <INDENT> if self.control: <NEW_LINE> <INDENT> logger.debug('Destroying control in ProjectEditor [%s]', self) <NEW_LINE> self.project.register_editor(self.resource, self, remove=True) <NEW_LINE> <DEDENT> super(ProjectEditor, self).destroy_control() <NEW_LINE> return | Destroys the toolkit-specific control that represents the editor.
Extended to ensure that the current project stops associating us
with its resources. | 625941dcb7558d58953c51fe |
def refresh_objects(objects, modules=None): <NEW_LINE> <INDENT> for name, obj in objects.copy().items(): <NEW_LINE> <INDENT> if type(obj) is list: <NEW_LINE> <INDENT> for obj_ in obj: <NEW_LINE> <INDENT> refresh_class(obj_.__class__, modules) <NEW_LINE> <DEDENT> <DEDENT> elif type(obj) is dict: <NEW_LINE> <INDENT> for ... | Updates objects recursively so that they and all of their members
have classes that match the current version of those classes.
Use with locals() to update everything in a notebook. | 625941dc3cc13d1c6d3c7668 |
def load_module(self, fullname): <NEW_LINE> <INDENT> path = find_notebook(fullname, self.path) <NEW_LINE> with io.open(path, 'r', encoding='utf-8') as f: <NEW_LINE> <INDENT> nb = read(f, 4) <NEW_LINE> <DEDENT> mod = types.ModuleType(fullname) <NEW_LINE> mod.__file__ = path <NEW_LINE> mod.__loader__ = self <NEW_LINE> mo... | import a notebook as a module | 625941dc63f4b57ef0001401 |
def Create(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('Create') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params) | Creates a snapshot from the requested subscription.<br><br>.
<b>ALPHA:</b> This feature is part of an alpha release. This API might be
changed in backward-incompatible ways and is not recommended for production
use. It is not subject to any SLA or deprecation policy.
If the snapshot already exists, returns `ALREADY_EXI... | 625941dce76e3b2f99f3aaf6 |
def dataReceived(self, data): <NEW_LINE> <INDENT> self.bytesReceived += len(data) <NEW_LINE> if self.bytesReceivedLimit and self.bytesReceived > self.bytesReceivedLimit: <NEW_LINE> <INDENT> log.msg(eventid='cowrie.direct-tcpip.data', format='Data upload limit reached') <NEW_LINE> self.eofReceived() <NEW_LINE> ... | Input received from user | 625941dc4a966d76dd551300 |
def testLoginMobileUser(self): <NEW_LINE> <INDENT> user, device_id = self._tester.RegisterFacebookUser(self._facebook_user_dict) <NEW_LINE> user2, device_id2 = self._tester.LoginFacebookUser(self._facebook_user_dict, self._mobile_device_dict) <NEW_LINE> self.assertEqual(user.user_id, user2.user_id) <NEW_LINE> self.asse... | Test successful login of mobile user. | 625941dc1d351010ab855e0a |
def translate_number(self, number): <NEW_LINE> <INDENT> if not isinstance(number, (int, long)): <NEW_LINE> <INDENT> raise ValueError('number must be integer') <NEW_LINE> <DEDENT> if number == 0: <NEW_LINE> <INDENT> return self.CHINESE_ZERO <NEW_LINE> <DEDENT> words = [] <NEW_LINE> if number < 0: <NEW_LINE> <INDENT> wor... | :type number: int | long
:rtype: unicode | 625941dcbf627c535bc134be |
def canJump(self, nums): <NEW_LINE> <INDENT> def helper(idx): <NEW_LINE> <INDENT> if memo[idx] != 0: <NEW_LINE> <INDENT> return memo[idx] <NEW_LINE> <DEDENT> maxidx = min(len(nums)-1, idx+nums[idx]) <NEW_LINE> for i in range(idx+1, maxidx+1): <NEW_LINE> <INDENT> if helper(i) == 1: <NEW_LINE> <INDENT> memo[idx] = 1 <NEW... | :type nums: List[int]
:rtype: bool | 625941dcd10714528d5fffd5 |
def use(self) -> Any: <NEW_LINE> <INDENT> if inspect.iscoroutinefunction(self.callable_object): <NEW_LINE> <INDENT> loop = asyncio.get_event_loop() <NEW_LINE> call = self.callable_object(*self.args, **self.kwargs) <NEW_LINE> if loop.is_running(): <NEW_LINE> <INDENT> return call <NEW_LINE> <DEDENT> function = asyncio.en... | Runs the given example, giving back the result returned from running the example call. | 625941dc76e4537e8c351964 |
def ball_volume(n, N=10000): <NEW_LINE> <INDENT> raise ValueError("Problem 1 Incomplete") | Estimate the volume of the n-dimensional unit ball.
Parameters:
n (int): The dimension of the ball. n=2 corresponds to the unit circle,
n=3 corresponds to the unit sphere, and so on.
N (int): The number of random points to sample.
Returns:
(float): An estimate for the volume of the n-dimensional u... | 625941dc3c8af77a43ae3a91 |
def pd_to_vec(A): <NEW_LINE> <INDENT> L = torch.potrf(A, upper=False) <NEW_LINE> return trilpd_to_vec(L) | Convert a positive-definite matrix A to a vector l of entries from
its cholesky factor. Diagonal entries are logged so they occupy the full
real line, and still map back to positive values. | 625941dcbe383301e01b5770 |
def maxProfit(self, prices, fee): <NEW_LINE> <INDENT> if len(prices) < 2: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> hold, not_hold = float('-inf'), 0 <NEW_LINE> for x in prices: <NEW_LINE> <INDENT> hold, not_hold = max(hold, not_hold - x), max(hold + x - fee, not_hold) <NEW_LINE> <DEDENT> return max(hold, not_ho... | :type prices: List[int]
:type fee: int
:rtype: int | 625941dc5e10d32532c5f215 |
def assert_called(mock: Mock): <NEW_LINE> <INDENT> if mock.call_count == 0: <NEW_LINE> <INDENT> msg = f"Expected '{mock._mock_name or 'mock'}' to have been called." <NEW_LINE> raise AssertionError(msg) | assert that the mock was called at least once | 625941dcf8510a7c17cf99ed |
def interleave(self, map_func, cycle_length, block_length=1, num_parallel_calls=None): <NEW_LINE> <INDENT> if num_parallel_calls is None: <NEW_LINE> <INDENT> return InterleaveDataset(self, map_func, cycle_length, block_length) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ParallelInterleaveDataset(self, map_func... | Maps `map_func` across this dataset, and interleaves the results.
For example, you can use `Dataset.interleave()` to process many input files
concurrently:
```python
# Preprocess 4 files concurrently, and interleave blocks of 16 records from
# each file.
filenames = ["/var/data/file1.txt", "/var/data/file2.txt", ...]... | 625941dc71ff763f4b54997f |
def test_case20(self): <NEW_LINE> <INDENT> sess = self._db.get_session() <NEW_LINE> self.set_job(sess, 'Test Case 20', 'b942f21c-4039-e6e9-09dc-9685985a1b84', job=(True, False, True), rollback=None, mail=False) <NEW_LINE> self.run_job(sess) <NEW_LINE> self.check_job(sess, jg=RES_ABNORMAL_TERMINATION, job=(RES_NORMAL_EN... | Test Case 11
- Job Group : Abnormal termination
- Job : Second Job Abnormal termination
- Rollback : None
- Send Mail : Abnormal termination | 625941dcfff4ab517eb2f72c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.