code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _getHighestAvailableNetwork(session_id, base, basesize, allocsize): <NEW_LINE> <INDENT> allocmask = bitsToNetmask(allocsize) <NEW_LINE> basemask = bitsToNetmask(basesize) <NEW_LINE> topnet = ipbroadcast(base, basemask) <NEW_LINE> botnet = ipnetwork(base, allocmask) <NEW_LINE> base = topnet <NEW_LINE> while base >= ... | Returns the lowest network not in use in the specified base netblock.
Uses basesize and allocsize to determine the bounds of each network. | 625941de2ae34c7f2600d47a |
def forward(self, memory, read_strengths, read_vectors): <NEW_LINE> <INDENT> unnormalized_similarity = torch.bmm(memory, read_vectors) <NEW_LINE> norms_vectors = torch.norm(read_vectors, 2, dim=1) <NEW_LINE> norms_memory = torch.norm(memory, 2, dim=2) <NEW_LINE> normalizer = batch_ger(norms_memory, norms_vectors) <NEW_... | :param (B, N, W) memory
:param (B, R) read strengths
:param (B, W, R) read vectors
:return (B, N, R) tensor that defines a probability distribution
over memory locations for each read vector. | 625941de21bff66bcd684c98 |
def create_selected_summaries_dict(summaries_list): <NEW_LINE> <INDENT> selected_summaries = dict() <NEW_LINE> for h in summaries_list: <NEW_LINE> <INDENT> selected_summaries[h] = hdr_summary[h] <NEW_LINE> <DEDENT> return selected_summaries | Creates a dictionary with summary column headers.
Examples:
>>> summaries_to_output = ["discharge_capacity", "charge_capacity"]
>>> summaries_to_output_dict = create_selected_summaries_dict(
>>> summaries_to_output
>>> )
>>> print(summaries_to_output_dict)
{'discharge_capacity': "Discharge_C... | 625941dea79ad161976cc48f |
def __point_in_cylinder(self, c_nodeA, c_nodeB, radius, point, length_sq=None, radius_sq=None): <NEW_LINE> <INDENT> if length_sq is None: <NEW_LINE> <INDENT> if c_nodeA == c_nodeB: <NEW_LINE> <INDENT> logger.warning('__point_in_cylinder: distance between nodeA and nodeB is zero!!') <NEW_LINE> raise Exception('distance ... | Tests if point is inside a cylinder
http://www.flipcode.com/archives/Fast_Point-In-Cylinder_Test.shtml | 625941ded99f1b3c44c678d3 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, CustomMultiSelectJson): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941decad5886f8bd27322 |
def test_color_re(self): <NEW_LINE> <INDENT> good_vals = ( "#m<magenta>", "#b<blue>", "#g<green>", "#y<yellow>", "#c<cyan>", "#w<white>", "#db<darkblue>", "#dc<darkcyan>", "#dg<darkgreen>", "#dm<darkmagenta>", "#dr<darkred>", "#dy<darkyellow>", ) <NEW_LINE> bad_vals = ("Some text", "#f<fuscia>", "#m[magenta]") <NEW_LIN... | Test matching basic values | 625941dede87d2750b8600df |
def map_onem2m_error_to_http_error(self, response): <NEW_LINE> <INDENT> self.logger.debug("Mapping OneM2M error: %s", response) <NEW_LINE> try: <NEW_LINE> <INDENT> status_code = response.status_code <NEW_LINE> headers = { "x-m2m-ri": str(response.rqi), "x-m2m-rsc": str(response.rsc) } <NEW_LINE> <DEDENT> except Attribu... | Maps a OneM2M error response to a HTTP response.
:param response: the OneM2MResponse object to be mapped
:returns: Response -- the resulting Response object
:raises: OpenMTCError | 625941deb830903b967e9c51 |
def stackAutoEncoder(self, input_size, hidden_size): <NEW_LINE> <INDENT> input_layer = Input(shape=(input_size,)) <NEW_LINE> encoded = Dense(hidden_size, activation=self.activationFunc,kernel_regularizer=regularizers.l2())( input_layer) <NEW_LINE> dropout = Dropout(self.dropoutRate)(encoded) <NEW_LINE> decoded = Dense(... | Builds a single autoencoder and append it to the autoencoders list.
:param input_size: Input layer size of the autoencoder
:param hidden_size: Hidden layer size of the autoencoder
:return: | 625941de8da39b475bd652c0 |
def get_instance(self, payload): <NEW_LINE> <INDENT> return ApplicationInstance( self._version, payload, account_sid=self._solution['account_sid'], ) | Build an instance of ApplicationInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.application.ApplicationInstance
:rtype: twilio.rest.api.v2010.account.application.ApplicationInstance | 625941de7047854f462a174f |
def _get_number_of_days(self, date_from, date_to): <NEW_LINE> <INDENT> DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" <NEW_LINE> from_dt = datetime.datetime.strptime(date_from, DATETIME_FORMAT) <NEW_LINE> to_dt = datetime.datetime.strptime(date_to, DATETIME_FORMAT) <NEW_LINE> beginnetje = datetime.date.toordinal(from_dt) <NEW_L... | Returns a float equals to the timedelta between two dates given as string. | 625941decb5e8a47e48b7def |
def set_snippet_lic_comment(self, doc, text): <NEW_LINE> <INDENT> self.assert_snippet_exists() <NEW_LINE> if not self.snippet_lic_comment_set: <NEW_LINE> <INDENT> self.snippet_lic_comment_set = True <NEW_LINE> if validations.validate_snip_lic_comment(text): <NEW_LINE> <INDENT> doc.snippet[-1].license_comment = str_from... | Set the snippet's license comment.
Raise OrderError if no snippet previously defined.
Raise CardinalityError if already set.
Raise SPDXValueError if the data is a malformed value. | 625941de851cf427c661a856 |
def get_completions(self, candidates): <NEW_LINE> <INDENT> return {candidate: self._completion_value for candidate in candidates} | Return the (dummy) completion values for each specified candidate
block. | 625941deb545ff76a891415f |
@Infix <NEW_LINE> def l(p1,p2): <NEW_LINE> <INDENT> def p(t): <NEW_LINE> <INDENT> tl1, r1 = p1(t) <NEW_LINE> if r1 != None: return tl1, r1 <NEW_LINE> return p2(t) <NEW_LINE> <DEDENT> return p | Try one parser if that fails, try the second | 625941de3617ad0b5ed68240 |
def edit_record(self, old_nickname: str, new_record: dict) -> (bool, str): <NEW_LINE> <INDENT> new_nickname = new_record['nickname'] <NEW_LINE> if old_nickname != new_nickname: <NEW_LINE> <INDENT> handler_answer = self.nickname_handler(new_record, HANDLER_EDIT) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> handler_answ... | Edits record from database
:param old_nickname: nickname before editing
:param new_record: record with new nickname
:type old_nickname: str
:type new_record: dict
:returns: False (in error case) or True and Error/Done message | 625941de32920d7e50b2851c |
@receiver(reset_password_token_created) <NEW_LINE> def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): <NEW_LINE> <INDENT> context = { 'current_user': reset_password_token.user, 'username': reset_password_token.user.username, 'email': reset_password_token.user.email, 'reset_passwo... | Modified from: django-rest-passwordreset
Handles password reset tokens
When a token is created, an e-mail needs to be sent to the user
:param sender: View Class that sent the signal
:param instance: View Instance that sent the signal
:param reset_password_token: Token Model Object
:param args:
:param kwargs:
:return: | 625941decdde0d52a9e5337e |
def slot_b_ricerca(self): <NEW_LINE> <INDENT> if self.tipo_rubrica == "T": <NEW_LINE> <INDENT> intestazioni = ['Azienda','Dipendente','Telefono','Reparto','Email','Mansione'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> intestazioni = ['Azienda','Dipendente','Email','Reparto','Mansione'] <NEW_LINE> <DEDENT> matrice_da... | esegue la ricerca | 625941decc0a2c11143dd1db |
def resolve(self, rosdep_args): <NEW_LINE> <INDENT> def coerce_to_list(options): <NEW_LINE> <INDENT> if isinstance(options, list): <NEW_LINE> <INDENT> return options <NEW_LINE> <DEDENT> elif isinstance(options, _basestring): <NEW_LINE> <INDENT> return options.split() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ... | See :meth:`Installer.resolve()` | 625941de5510c4643540f726 |
def setBlendingMode(self, value): <NEW_LINE> <INDENT> if value!=self.__blendingMode: <NEW_LINE> <INDENT> self.__blendingMode=value <NEW_LINE> self.__fingerPrint='' <NEW_LINE> self.__updated('blendingMode') | Set blending mode | 625941de5fdd1c0f98dc057e |
def manipulate_given_class(self, class_to_test, class_to_test_str, manipulate_func=mytest.manipulate_class, step_all=False): <NEW_LINE> <INDENT> pych_obj = pycharacterize.Runner(step_all=step_all) <NEW_LINE> pych_obj.set_class_to_watch(class_to_test, class_to_test_str) <NEW_LINE> pych_obj.do_runcall(manipulate_func, cl... | Tests the given class using manipulate_class() | 625941de30bbd722463cc111 |
def upload_samples_url(user, output, dataset, schema, samples, updatedDsList): <NEW_LINE> <INDENT> call = 'upload_url' <NEW_LINE> url = compose_url(module,call) <NEW_LINE> url = url.format(datasetName=dataset) <NEW_LINE> content = dict() <NEW_LINE> samples = samples.replace('__amp__', '&') <NEW_LINE> schema = schema.re... | Upload a dataset given the urls of the samples and their schema | 625941de3eb6a72ae02ec82f |
def _login(self): <NEW_LINE> <INDENT> url = urljoin(self._base_url, "user/login") <NEW_LINE> data = { "_csrf": self._get_csrf_token(), "user_name": self._username, "password": self._password } <NEW_LINE> response = self._req_session.post(url=url, data=data) <NEW_LINE> status_code = response.status_code <NEW_LINE> logge... | 进行登录操作
| 625941de50812a4eaa59c668 |
def __init__(self, client_id, client_secret, redirect_uri, state=None, scope=None, cache_path=None, proxies=None): <NEW_LINE> <INDENT> self.client_id = client_id <NEW_LINE> self.client_secret = client_secret <NEW_LINE> self.redirect_uri = redirect_uri <NEW_LINE> self.state=state <NEW_LINE> self.cache_path = cache_path ... | Creates a SpotifyOAuth object
Parameters:
- client_id - the client id of your app
- client_secret - the client secret of your app
- redirect_uri - the redirect URI of your app
- state - security state
- scope - the desired scope of the request
- cache_path - path to location to save token... | 625941de3c8af77a43ae3aed |
def wait(socket, pkt, server): <NEW_LINE> <INDENT> socket.sendto(pkt, server) <NEW_LINE> print("-----------------------------") <NEW_LINE> print("-----------------------------") <NEW_LINE> print("Request packet sent to {0}: ".format(server)) <NEW_LINE> print(pkt) <NEW_LINE> print("-----------------------------") <NEW_L... | Sending the request packet to the server and then waiting
one second for a response
:param socket: The clients socket
:param pkt: The packet to be sent
:param server: The address of the server to send the packet to | 625941de498bea3a759b9df8 |
def __init__(self,addr=("127.0.0.1",8000)): <NEW_LINE> <INDENT> self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) <NEW_LINE> self.log_file = open("err_log.txt","a") <NEW_LINE> try: <NEW_LINE> <INDENT> self.sock.connect(addr) <NEW_LINE> <DEDENT> except TimeoutError as e: <NEW_LINE> <INDENT> self.sock = None <... | addr must be a tuple as ("ipaddress",port) | 625941de4d74a7450ccd450d |
def pair_to_count(tuple_list): <NEW_LINE> <INDENT> dict_count = {} <NEW_LINE> for pair in tuple_list: <NEW_LINE> <INDENT> if pair in dict_count: <NEW_LINE> <INDENT> dict_count[pair] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dict_count[pair] = 1 <NEW_LINE> <DEDENT> <DEDENT> return dict_count | Strips out each word, make a dictionary, counts how often each word appears and | 625941de63f4b57ef000145a |
def p_argument4(self, p): <NEW_LINE> <INDENT> p[0] = [CMakeSymbol("(")] + p[2] + [CMakeSymbol(")")] | argument : LPAREN argument_list RPAREN | 625941deeab8aa0e5d26dea3 |
def jsonify(obj, **kwargs): <NEW_LINE> <INDENT> class EdgeEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, obj): <NEW_LINE> <INDENT> if hasattr(obj, 'tolist'): <NEW_LINE> <INDENT> return obj.tolist() <NEW_LINE> <DEDENT> elif hasattr(obj, 'timestamp'): <NEW_LINE> <INDENT> return obj.timestamp() <NEW_LINE... | A version of json.dumps that can handle numpy arrays
by creating a custom encoder for numpy dtypes.
Parameters
--------------
obj : JSON-serializable blob
**kwargs :
Passed to json.dumps
Returns
--------------
dumped : str
JSON dump of obj | 625941de627d3e7fe0d6919b |
def array_intersect(col1, col2): <NEW_LINE> <INDENT> return col(ArrayIntersect(parse(col1), parse(col2))) | :rtype: Column | 625941deb7558d58953c5258 |
def send_file_sftp_pair(host, port, username, password, path_pair): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> trans = paramiko.Transport(host, port) <NEW_LINE> trans.connect(username=username, password=password) <NEW_LINE> sftp = paramiko.sftp_client.SFTPClient.from_transport(trans) <NEW_LINE> for single_pair in pat... | :param local_path:
:param remote_path:
:return: | 625941deec188e330fd5aae3 |
def update(self, plan): <NEW_LINE> <INDENT> amount = int(plan.amount * 100) <NEW_LINE> json_data = { 'name': plan.name, 'amount': amount, } <NEW_LINE> try: <NEW_LINE> <INDENT> plan_obj = conekta.Plan.find(plan.id) <NEW_LINE> response = plan_obj.update(json_data) <NEW_LINE> self.response.success = True <NEW_LINE> self.r... | Update plan | 625941ded164cc6175783099 |
@task <NEW_LINE> @with_remote_configuration <NEW_LINE> def test(remote_configuration=None): <NEW_LINE> <INDENT> run('uname -a; uptime; cat /etc/lsb-release 2>/dev/null; echo $USER — $PWD') | Just run `uname -a; uptime` remotely, to test the connection
or sparks core libs. | 625941de566aa707497f48ae |
def get_rank_difference_magnitudes(self, other) -> list: <NEW_LINE> <INDENT> self_rank_list, other_rank_list = self.__get_rank_lists(other) <NEW_LINE> ret = list() <NEW_LINE> for idx, (_, as_) in enumerate(self_rank_list): <NEW_LINE> <INDENT> other_idx = next(i for i, v in enumerate(other_rank_list) if v[1] == as_) <NE... | Calculate the magnitude of rank differences and return them
in a list.
The magnitude refers to the positional difference between the
ranks of one AS in self and other. It is calculated with
self.pos - other.pos. | 625941de046cf37aa974d08f |
def get(self, uuid): <NEW_LINE> <INDENT> invite = calenvite.show_invite(uuid) <NEW_LINE> if invite is None: <NEW_LINE> <INDENT> raise ResourceNotFound('Unknown invitation id.') <NEW_LINE> <DEDENT> return dict(subject=invite.subject, length=invite.length, uuid=invite.uuid) | Handles invitations
``GET /invitation/<uuid>``
Returns:
gets the subject/length details of the given invitation. | 625941de76d4e153a657ee7c |
def planck(t: NPType, l: NPType) -> NPType: <NEW_LINE> <INDENT> return 2 * h * c ** 2 / l ** 5 / (exp(h * c / (l * k * t)) - 1) | Radiance of a black body as a function of wavelength.
Parameters
----------
t
Black body temperature [K]
l
Wavelength [m]
Returns
-------
L : float or ndarray
Back body radiance [W m^-2 sr^-1] | 625941de99cbb53fe6792f30 |
def number_end_str(self): <NEW_LINE> <INDENT> if hasattr(self, 'number'): <NEW_LINE> <INDENT> end_string = "th" <NEW_LINE> if self.number % 10 == 1: <NEW_LINE> <INDENT> end_string = "st" <NEW_LINE> <DEDENT> elif self.number % 10 == 2: <NEW_LINE> <INDENT> end_string = "nd" <NEW_LINE> <DEDENT> elif self.number % 10 == 3:... | Should return a number ending string for groupings that are numbered (squad and platoon)
:param grouping: the grouping to get the ending string for
:return: the ending string | 625941dee8904600ed9f227b |
def work(self) -> bool: <NEW_LINE> <INDENT> checksum_filename = "checksum.md5" <NEW_LINE> self.log(f"Generating checksums for {self._package_id}") <NEW_LINE> package_builder = package_creater.InplacePackage(self._source) <NEW_LINE> package_builder.create_checksum_report(self.subtask_working_dir) <NEW_LINE> generated_ch... | Generate the checksum. | 625941debe7bc26dc91cd944 |
def draw_tools(surface, currenttool, currentseed, imgloader, drawnearcursor=True): <NEW_LINE> <INDENT> if currenttool == 'harvest': <NEW_LINE> <INDENT> pygame.draw.rect(surface, (255, 255, 255), (10, 10, 48, 48), 1) <NEW_LINE> <DEDENT> if currenttool == 'plant': <NEW_LINE> <INDENT> pygame.draw.rect(surface, (255, 255, ... | Draw selection on selected tool
:param surface:
:param currenttool:
:param currentseed:
:param imgloader:
:param drawnearcursor:
:return: | 625941ded8ef3951e3243888 |
def _compile_values(self, obj, attr): <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> temp_obj = [] <NEW_LINE> if isinstance(obj, list) or isinstance(obj, tuple): <NEW_LINE> <INDENT> for each in obj: <NEW_LINE> <INDENT> value = self._compile_values(each, attr) <NEW_LINE> if value: <NE... | :param obj: A list or dict of instance attributes
:param attr: A key
:return The value(s) found via the attr | 625941de8a349b6b435e84bd |
def send_rsa_public_key(self): <NEW_LINE> <INDENT> self.crypto_conn.connect((self.unicast_addr_dct[self.master][ 0], Session.MULTICAST_CONTROL_PORT)) <NEW_LINE> Logger.info('Creating RSA keypair.') <NEW_LINE> self.rsa_keypair = RSA.generate(Session.RSA_KEYS_SIZE) <NEW_LINE> Logger.info('RSA keypair generation complete.... | Generates and sends RSA public key to call master for receiving
cryptographic info. | 625941de91f36d47f21ac840 |
def _check_container_runtime(self): <NEW_LINE> <INDENT> if self.opts.container_runtime != 'auto': <NEW_LINE> <INDENT> crun = self.opts.container_runtime.lower() <NEW_LINE> if crun in ['none', 'off', 'diabled']: <NEW_LINE> <INDENT> self.policy.runtimes = {} <NEW_LINE> self.soslog.info( "Disabled all container runtimes p... | Check the loaded container runtimes, and the policy default runtime
(if set), against any requested --container-runtime value. This can be
useful for systems that have multiple runtimes, such as RHCOS, but do
not have a clearly defined 'default' (or one that is determined based
entirely on configuration). | 625941de26068e7796caf02d |
def svd_1d(A, epsilon=1e-10): <NEW_LINE> <INDENT> n, m = A.shape <NEW_LINE> x = randomUnitVector(min(n,m)) <NEW_LINE> lastV = None <NEW_LINE> currentV = x <NEW_LINE> if n > m: <NEW_LINE> <INDENT> B = np.dot(A.T, A) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> B = np.dot(A, A.T) <NEW_LINE> <DEDENT> iterations = 0 <NEW_... | The one-dimensional SVD | 625941dea05bb46b383ecb6a |
def forward(self, field): <NEW_LINE> <INDENT> self.field_f = af.fft2(field) <NEW_LINE> if self.update_method == "GaussNewton": <NEW_LINE> <INDENT> self.approx_hessian[:, :] += self.field_f*af.conjg(self.field_f) <NEW_LINE> <DEDENT> field_pupil = af.ifft2(self.pupil * self.field_f)[self.row_crop, self... | Apply pupil | 625941de15fb5d323cde0e5e |
def to_hmc_yaml(self): <NEW_LINE> <INDENT> hmc_dict = self.to_hmc_dict() <NEW_LINE> hmc_yaml = yaml.dump( hmc_dict, encoding=None, allow_unicode=True, default_flow_style=False, indent=2, Dumper=yamlloader.ordereddict.CSafeDumper) <NEW_LINE> return hmc_yaml | Inspect the HMC of this client and return the HMC and its resources
as an HMC definition YAML string.
This method can be used on clients for sessions to real HMCs and
faked sessions.
The returned YAML string can be used to instantiate a faked session
using :meth:`zhmcclient_mock.FakedSession.from_hmc_yaml`.
The retu... | 625941de23849d37ff7b33d7 |
def parse_overrides(override_file): <NEW_LINE> <INDENT> global default_overrides <NEW_LINE> filp = open(override_file, "r") <NEW_LINE> for line in filp: <NEW_LINE> <INDENT> line = clean_line(line) <NEW_LINE> if not line: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> override_data = line.split() <NEW_LINE> if len(ove... | Given a file of:
# Config Override value
SOME_THING yes
Build a map of these. We'll then update the defaults before creating the
config files. | 625941ded486a94d0b98e491 |
def train(self, X, Y): <NEW_LINE> <INDENT> seperated = {} <NEW_LINE> for i in range(len(Y)): <NEW_LINE> <INDENT> x, y = X[i], Y[i] <NEW_LINE> if y not in seperated: <NEW_LINE> <INDENT> seperated[y] = [x] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> seperated[y].append(x) <NEW_LINE> <DEDENT> <DEDENT> mean = {} <NEW_LIN... | #input
X,Y: nunpy array | 625941dea8ecb033257d3416 |
def act(self): <NEW_LINE> <INDENT> raise NotImplementedError("Should have implemented this") | Execute one step in the environment, possible terminating an episode
:return: | 625941de5fc7496912cc3cc8 |
def installedMultipluginId(self): <NEW_LINE> <INDENT> return firstIdOfClass(self._acl_users(), MultiPlugin) | Return the installed multiplugin or, if none is installed, None. | 625941de4e696a04525c9797 |
def first_snowflake_for_timestamp(timestamp: int, machine_id: int=0) -> int: <NEW_LINE> <INDENT> return ( ((timestamp - config.EPOCH) << timestamp_shift) | (machine_id << machine_id_shift) | 0 ) | First Snowflake ID for timestamp and Machine ID. | 625941de4f6381625f114d86 |
def min(self, expr, extra_constraints=(), solver=None, model_callback=None): <NEW_LINE> <INDENT> if self._solver_required and solver is None: <NEW_LINE> <INDENT> raise BackendError("%s requires a solver for evaluation" % self.__class__.__name__) <NEW_LINE> <DEDENT> return self._min(self.convert(expr), extra_constraints... | Return the minimum value of `expr`.
:param expr: expression (an AST) to evaluate
:param solver: a solver object, native to the backend, to assist in
the evaluation (for example, a z3.Solver)
:param extra_constraints: extra constraints (as ASTs) to add to the solver for this solve
:param model_callback: ... | 625941de73bcbd0ca4b2c3c0 |
def get_train_data(self, idx): <NEW_LINE> <INDENT> img_info = self.get_per_img_info(idx) <NEW_LINE> file_name = img_info['file_name'] <NEW_LINE> image_path = os.path.join(self.img_path, file_name) <NEW_LINE> img = cv2.imread(image_path) <NEW_LINE> if img is None: <NEW_LINE> <INDENT> print('image {} read failed.'.format... | Load image and annotation
:param idx:
:return: meta-data (a dict containing image, annotation and other information) | 625941de293b9510aa2c35dd |
def _coerce_to_dict(input_arg): <NEW_LINE> <INDENT> if not isinstance(input_arg, dict): <NEW_LINE> <INDENT> if isinstance(input_arg, Iterable): <NEW_LINE> <INDENT> if not isinstance(input_arg[0], Iterable): <NEW_LINE> <INDENT> input_arg = [input_arg] <NEW_LINE> <DEDENT> <DEDENT> input_arg = [input_arg] if isinstance(in... | Constructs a dict from the provided arg.
If input_arg is:
dict then returns it unchanged.
string or collection of Strings or Sequence[int],
returns a dict {str(value): value, ...}
Parameters
----------
input_arg : String or Collection[str or Int or Sequence[Int]]
or Dict[str, str or np.array]
Can be of th... | 625941de76d4e153a657ee7d |
def to_dict(self): <NEW_LINE> <INDENT> d = super(TargetPort, self).to_dict() <NEW_LINE> d['portName'] = self.port_name <NEW_LINE> return d | Save this target port into a dictionary. | 625941de442bda511e8be75e |
def collections_to_dsk(collections, optimize_graph=True, **kwargs): <NEW_LINE> <INDENT> optimizations = kwargs.pop("optimizations", None) or config.get("optimizations", []) <NEW_LINE> if optimize_graph: <NEW_LINE> <INDENT> groups = groupby(optimization_function, collections) <NEW_LINE> groups = {opt: _extract_graph_and... | Convert many collections into a single dask graph, after optimization | 625941de56ac1b37e6264514 |
def with_dropout(self): <NEW_LINE> <INDENT> return True | "Check whether network has dropout | 625941dee5267d203edcdfe3 |
def test_match_get_problem_multiple(self): <NEW_LINE> <INDENT> with captured_output() as (cap_stdout, cap_stderr): <NEW_LINE> <INDENT> with self.assertRaises(SystemExit): <NEW_LINE> <INDENT> match_get_problem('pavucontrol') <NEW_LINE> <DEDENT> <DEDENT> stdout = cap_stdout.getvalue() <NEW_LINE> self.assertIn("Ambiguous"... | Test that match_get_problem fails when multiple problems match | 625941de956e5f7376d711b7 |
def is_superset(self, that): <NEW_LINE> <INDENT> s1 = self.get_node_ids() <NEW_LINE> s2 = that.get_node_ids() <NEW_LINE> return s1.issuperset(s2) | Checks if this clique is a superset of that clique.
:param that: Clique.
:return: A boolean indicating if this clique is a superset of the clique passed in. | 625941de7d847024c06be60a |
def RK4_step(F,x,y,h): <NEW_LINE> <INDENT> k1 = h*F(x,y); <NEW_LINE> k2 = h*F(x + h/2,y + k1/2); <NEW_LINE> k3 = h*F(x + h/2,y + k2/2); <NEW_LINE> k4 = h*F(x,y+k3); <NEW_LINE> return y + k1/6 + k2/3 + k3/3 + k4/6; | Perform one Runge-Kutta 4th order step (locally 5th order)
with derivative function F using stepsize h. | 625941de63b5f9789fde7430 |
def by_pk(self, pk): <NEW_LINE> <INDENT> return self.get_queryset().get(pk=pk) | Get an object by pk | 625941de4527f215b584c79e |
def modify_contribution(self, morph, direction): <NEW_LINE> <INDENT> categories = get_categories() <NEW_LINE> counts = self._emission_counts[morph] <NEW_LINE> for (i, category) in enumerate(categories): <NEW_LINE> <INDENT> self._contribution_helper(morph, category, counts[i] * direction) | Removes or readds the complete contribution of a morph to the
cost function. The contribution must be removed using the same
probability value as was used when adding it, making ordering of
operations important. | 625941de3cc13d1c6d3c76c3 |
def __init__(self, word = '$'): <NEW_LINE> <INDENT> self.word = word <NEW_LINE> self.subs = [None] * 27 | @self.word : str = whole word, not '$' for leaf only
@self.subs : list[TrieNode] = childrens | 625941de16aa5153ce3627c2 |
def get_image_plugin(request): <NEW_LINE> <INDENT> pass | Get the currently selected plugin (adapter) that this user has selected for
profile picture.
If the selected system is broken it will return None and not default to anything. | 625941de15fb5d323cde0e5f |
def init(): <NEW_LINE> <INDENT> @click.command(name='autoscale') <NEW_LINE> @click.option( '--ipa-certs', required=False, envvar='TREADMILL_IPA_CERTS', callback=aws_cli.handle_context_opt, is_eager=True, default='/etc/ipa/ca.crt', expose_value=False ) <NEW_LINE> @click.option( '--interval', required=False, default=_DEF... | Autoscale Treadmill cell capacity. | 625941defff4ab517eb2f789 |
def assertRaisesMsgSubstring(self, excClass, msg, callableObj, *args, **kwargs): <NEW_LINE> <INDENT> return self._assertRaisesMsgSubstring(excClass, msg, True, callableObj, *args, **kwargs) | Just like assertRaisesMsg, but looks for substring in the message. | 625941ded10714528d600031 |
def get_next_job(session): <NEW_LINE> <INDENT> return session.query(model.Job).filter_by( finished=0).order_by(model.Job.creation_time).first() | Get the next unfinished job from the database. | 625941de3539df3088e2e695 |
def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Check whether ``self`` is not equal to ``other``.
EXAMPLES::
sage: from sage.modular.local_comp.smoothchar import SmoothCharacterGroupQp
sage: G = SmoothCharacterGroupQp(3, QQ)
sage: G != SmoothCharacterGroupQp(3, QQ[I])
True
sage: G != 7
True
sage: G != SmoothCharacterGroupQp(7, QQ)
T... | 625941de9c8ee82313fbbac1 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, DirectoryExport): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941de5fc7496912cc3cc9 |
def test_sql_predicat(self): <NEW_LINE> <INDENT> idx = {'using': 'btree', 'predicat': 'foo > 3'} <NEW_LINE> res = "WHERE foo > 3" <NEW_LINE> self.assertEqual(util.sql_predicat(idx), res) | Build the column part of index | 625941de6e29344779a6295b |
def is_registered(self) -> bool: <NEW_LINE> <INDENT> if config["devicetoken"]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Is the client is registered to remarkable's cloud
Returns:
bool: True if the client is registered | 625941ded18da76e23532824 |
def __init__( self, magfile ): <NEW_LINE> <INDENT> from numpy import append <NEW_LINE> self.sources = [] <NEW_LINE> fin = open( magfile, 'r' ) <NEW_LINE> linelist = fin.readlines() <NEW_LINE> fin.close() <NEW_LINE> i = 0 <NEW_LINE> while i<len(linelist) : <NEW_LINE> <INDENT> line = linelist[i] <NEW_LINE> if line.starts... | read in the apphot output from magfile | 625941dee1aae11d1e74a005 |
def visit_Slice(self, node): <NEW_LINE> <INDENT> slice_values = [node.lower, node.upper, node.step] <NEW_LINE> if self.nopython: <NEW_LINE> <INDENT> raise error.NumbaError(node, "Cannot slice in nopython context") <NEW_LINE> <DEDENT> if node.variable.is_constant: <NEW_LINE> <INDENT> return self.visit(nodes.ObjectInject... | Rewrite slice objects. Do this late in the pipeline so that other
code can still recognize the code structure. | 625941de009cb60464c636fa |
def run_1QubitState_tests(self, initial_states, collapsed_states, probabilities, num_iterations, tolerance): <NEW_LINE> <INDENT> outcomes = [0, 1] <NEW_LINE> operator = get_measurement_operator(outcomes, collapsed_states) <NEW_LINE> expected_results = {} <NEW_LINE> for outcome in outcomes: <NEW_LINE> <INDENT> expected_... | Run the measurements for the given 1-qubit states and probabilities. | 625941de0fa83653e4657304 |
def compute_last(start_set: List[int], number: int) -> int: <NEW_LINE> <INDENT> memory = {} <NEW_LINE> for turn in range(len(start_set)): <NEW_LINE> <INDENT> memory[start_set[turn]] = turn+1 <NEW_LINE> <DEDENT> last = data[-1] <NEW_LINE> for turn in range(len(start_set)+1, number+1): <NEW_LINE> <INDENT> if last in memo... | compute_last computes the nth number of the elves game given an input
set.
Args:
start_set (List[int]): the input starting set parsed to ints.
number (int): target number.
Returns:
int: the nth number of the game. | 625941ded7e4931a7ee9e26a |
def _get_static_parameters(self): <NEW_LINE> <INDENT> return json.loads(self._static_param) | Get static parameters as a dictionary | 625941de97e22403b379d2e6 |
def launch_gscan(self): <NEW_LINE> <INDENT> if cylc.flags.debug: <NEW_LINE> <INDENT> stdout = sys.stdout <NEW_LINE> stderr = sys.stderr <NEW_LINE> command = ["cylc", "gscan", "--debug"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stdout = open(os.devnull, "w") <NEW_LINE> stderr = STDOUT <NEW_LINE> command = ["cylc", ... | Launch gscan. | 625941de283ffb24f3c55c49 |
def get_field_valdt(self, name): <NEW_LINE> <INDENT> field = self.get_field(name) <NEW_LINE> if field is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return field.valdt | Given a name, get field.valdt status, True if validators can be added, False if not | 625941de009cb60464c636fb |
def addIdle(self, callback, args): <NEW_LINE> <INDENT> pass | add a callback that is called once the main loop becomes idle | 625941de56b00c62f0f149a6 |
def build_path(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> filename = text.clean_path( self.formatter.vformat(self.filename_fmt, self.keywords)) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> raise exception.FormatError(exc, "filename") <NEW_LINE> <DEDENT> filename = os.sep + filename <NEW_LIN... | Use filename-keywords and directory to build a full path | 625941deb57a9660fec33bd4 |
def deploy(self, template, token, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() | Deploy the stack define by a template. Will return identifier for this
stack.
:param template: The template.
:param token: token for this request.
:param kwargs: Optional arguments. | 625941dedd821e528d63b4f2 |
def printObjects(self): <NEW_LINE> <INDENT> if len(self.objects) > 0: <NEW_LINE> <INDENT> print("\nObjects found:") <NEW_LINE> for obj in self.objects: <NEW_LINE> <INDENT> print(" {o}".format(o=obj.getName())) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print("\nNo objects found") | Print all found objects | 625941de29b78933be1e59f2 |
def className(self): <NEW_LINE> <INDENT> return _osgText.TextBase_className(self) | className(TextBase self) -> char const * | 625941dea79ad161976cc491 |
def concat_niimgs(niimgs, dtype=np.float32, ensure_ndim=None, memory=Memory(cachedir=None), memory_level=0, auto_resample=False, verbose=0): <NEW_LINE> <INDENT> target_fov = 'first' if auto_resample else None <NEW_LINE> first_niimg = None <NEW_LINE> iterator, literator = itertools.tee(iter(niimgs)) <NEW_LINE> try: <NEW... | Concatenate a list of 3D/4D niimgs of varying lengths.
The niimgs list can contain niftis/paths to images of varying dimensions
(i.e., 3D or 4D) as well as different 3D shapes and affines, as they
will be matched to the first image in the list if auto_resample=True.
Parameters
----------
niimgs: iterable of Niimg-lik... | 625941de99cbb53fe6792f31 |
def unload(self): <NEW_LINE> <INDENT> for action in self.actions: <NEW_LINE> <INDENT> self.iface.removePluginMenu( tr(plugin_name()), action) <NEW_LINE> self.iface.removeToolBarIcon(action) | Removes the plugin menu item and icon from QGIS GUI. | 625941ded10714528d600032 |
def _expand_xytan(x, y): <NEW_LINE> <INDENT> a = 0.027 <NEW_LINE> return x*a, y*a | Undo _redux_xytan() transform | 625941de96565a6dacc8fa16 |
def sub_ground(f, c): <NEW_LINE> <INDENT> return f.per(dmp_sub_ground(f.rep, f.dom.convert(c), f.lev, f.dom)) | Subtract an element of the ground domain from `f`. | 625941de01c39578d7e75187 |
def get_changed_gc_name(self): <NEW_LINE> <INDENT> name_change_class_list = ["_7UhW9", "PIoXz", "qyrsm","_0PwGv", "se6yk"] <NEW_LINE> name_change_contains_string = self.make_xpath_contains_string(name_change_class_list) <NEW_LINE> name_change_xpath = "//span[" + name_change_contains_string + "]" <NEW_LINE> try: <NEW_LI... | Changes self.group_chat_to_monitor to the new name if the gc name is changed. | 625941de57b8e32f524837e8 |
def test_target(self): <NEW_LINE> <INDENT> manifest_input = self.manifest_tmpl % self.uses_sdk(min='26', target='27') <NEW_LINE> expected = self.manifest_tmpl % self.uses_sdk(min='28', target='27') <NEW_LINE> output = self.raise_min_sdk_version_test(manifest_input, '28', '29', False) <NEW_LINE> self.assertEqual(output,... | Tests an existing targetSdkVersion is preserved. | 625941deb545ff76a8914161 |
def cr_pack(self, chname, chinfo): <NEW_LINE> <INDENT> return comedi.CR_PACK( self.get_channel(chname), self.ranges[chname], self.get_config(self.reference_value), ) | Packs data properly whether this is digital or analog | 625941de0a366e3fb873eb68 |
def minimumSizeHint(self): <NEW_LINE> <INDENT> pass | QMdiSubWindow.minimumSizeHint() -> QSize | 625941de4f6381625f114d87 |
def relu_back(x, y): <NEW_LINE> <INDENT> raise NotImplementedError('Need to implement for Task 0.1') | :math:`f(x) =` y if x is greater than 0 else 0 | 625941de3c8af77a43ae3aee |
def getVDIInfo(lvmCache): <NEW_LINE> <INDENT> vdis = {} <NEW_LINE> lvs = getLVInfo(lvmCache) <NEW_LINE> haveVHDs = False <NEW_LINE> for uuid, lvInfo in lvs.iteritems(): <NEW_LINE> <INDENT> if lvInfo.vdiType == vhdutil.VDI_TYPE_VHD: <NEW_LINE> <INDENT> haveVHDs = True <NEW_LINE> <DEDENT> vdiInfo = VDIInfo(uuid) <NEW_LIN... | Load VDI info (both LV and if the VDI is not raw, VHD info) | 625941de10dbd63aa1bd2eee |
def fetch_commits(repo_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r = requests.get('https://api.github.com/repos/iScrE4m/{}/commits'.format(repo_name)) <NEW_LINE> <DEDENT> except requests.exceptions.ConnectionError: <NEW_LINE> <INDENT> log.error("Connection error when connecting to Github: %s", format_exc()) <... | Cached commits from GitHub API
:return: JSON with commits api | 625941de187af65679ca546b |
def github_login(request): <NEW_LINE> <INDENT> cfg = ptah.get_settings(ptahcrowd.CFG_ID_AUTH, request.registry) <NEW_LINE> scope = cfg['github_scope'] <NEW_LINE> client_id = cfg['github_id'] <NEW_LINE> gh_url = '{0}?{1}'.format( 'https://github.com/login/oauth/authorize', url_encode({'scope': scope, 'client_id': client... | Initiate a github login | 625941ded18da76e23532825 |
def audit_aws_keys(): <NEW_LINE> <INDENT> print ("Started AWS SSH Audit ") <NEW_LINE> with open('reports/AWS/aws_audit/%s/%s/delta/keys' % (account_name, timestmp), 'w') as output: <NEW_LINE> <INDENT> subprocess.call(['./scripts/audit_aws_keys.sh'], stdout=output) <NEW_LINE> if os.stat('reports/AWS/aws_audit/%s/%s/delt... | this function is to audit Instances | 625941de38b623060ff0b139 |
def retrieve_cloudwatch_logs(log_group, info_type, do_zip=False, instance_id=None): <NEW_LINE> <INDENT> log_streams = cloudwatch.describe_log_streams(log_group, log_stream_name_prefix=instance_id) <NEW_LINE> instance_ids = [] <NEW_LINE> if len(log_streams['logStreams']) == 0: <NEW_LINE> <INDENT> io.log_error(strings['l... | Retrieves cloudwatch logs for every stream under the log group unless the instance_id is specified. If tail
logs is enabled we will only get the last 100 lines and return the result to a pager for the user to use. If
bundle info type is chosen we will get all of the logs and save them to a dir under .elasticbeanstalk... | 625941de3346ee7daa2b30b9 |
def __init__(self, text): <NEW_LINE> <INDENT> self.text = text <NEW_LINE> self.valid_words = load_wordlist(WORDLIST_FILENAME) | Initializes a CipherText object
text: a string
a CipherText object has two attributes:
self.text (string, determined by input text)
self.valid_words (list, determined using helper function load_wordlist) | 625941de498bea3a759b9dfa |
def BlitFramebuffer(p0: int, p1: int, p2: int, p3: int, p4: int, p5: int, p6: int, p7: int, p8: int, p9: int): <NEW_LINE> <INDENT> pass | :type p0: int
:type p1: int
:type p2: int
:type p3: int
:type p4: int
:type p5: int
:type p6: int
:type p7: int
:type p8: int
:type p9: int | 625941de435de62698dfdf99 |
def deleteLast(self) -> 'bool': <NEW_LINE> <INDENT> if self.isEmpty(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.real_cap -= 1 <NEW_LINE> self.__rear = (self.__rear - 1 + self.capacity) % self.capacity <NEW_LINE> self.data[self.__rear] = -1 <NEW_LINE> <DEDENT> return True | Deletes an item from the rear of Deque. Return true if the operation is successful. | 625941ded6c5a10208144399 |
@pytest.mark.usefixtures('config') <NEW_LINE> def test_match_spec_env(mock_packages, mutable_mock_env_path): <NEW_LINE> <INDENT> check_defaults = spack.cmd.parse_specs(['a'], concretize=True)[0] <NEW_LINE> assert not check_defaults.satisfies('foobar=baz') <NEW_LINE> e = ev.create('test') <NEW_LINE> e.add('a foobar=baz'... | Concretize a spec with non-default options in an environment. Make
sure that when we ask for a matching spec when the environment is
active that we get the instance concretized in the environment. | 625941ded164cc617578309a |
def get_RNAfold(fasta_file, out_file=None): <NEW_LINE> <INDENT> bashCommand = "RNAfold --noPS %s" %(fasta_file) <NEW_LINE> process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE) <NEW_LINE> RNAfold_output = process.communicate()[0] <NEW_LINE> RNA_ids, seq_len, energys = parse_RNAfold_out(RNAfold_output... | get energy score from mfold. Make sure you have installed mfold.
| 625941de21a7993f00bc8041 |
def from_map(self, schema, intemplates): <NEW_LINE> <INDENT> for key in intemplates: <NEW_LINE> <INDENT> if not key.startswith('text search template '): <NEW_LINE> <INDENT> raise KeyError("Unrecognized object type: %s" % key) <NEW_LINE> <DEDENT> tst = key[21:] <NEW_LINE> self[(schema.name, tst)] = template = TSTemplate... | Initialize the dictionary of templates by examining the input map
:param schema: schema owning the templates
:param intemplates: input YAML map defining the templates | 625941de8da39b475bd652c3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.