anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
Download the FashionMNIST dataset and then load it into memory.
def load_data_fashion_mnist(batch_size, resize=None): #@save (x_train, y_train), (x_test,y_test) = tf.keras.datasets.fashion_mnist.load_data() x_train,x_test = x_train/255, x_test/255 print(y_train.shape) # Divide all numbers by 255 so that all pixel values are between # 0 and 1, add a batch dimen...
Report CV results and save them to file
def report_cv_results(self, results, scores=['score'], filename=None, n_top=5): res = "" for score in scores: res += "{}\n".format(score) res += "-------------------------------\n" for i in range(1, n_top + 1): candidates = np.flatnonzero(results['ran...
test expected data is being loaded into db
def test_sample_one_date(self): self.assertEqual(self.test_sample.date, datetime.datetime(2016, 2, 12, 7, 34, 26))
Sets the density threshold below which the functional will not be evaluated.
def set_dens_threshold(self, dens_threshold): if dens_threshold < 0: raise ValueError("The density threshold cannot be smaller than 0.") core.xc_func_set_dens_threshold(self.xc_func, ctypes.c_double(dens_threshold))
Need a global enumerated list, not a local one, or there will be errors if one .gnt file skips a character
def saveImages(saveImagePath,dataForSaving,enumeratedList): for i in range(len(dataForSaving[0])): singleChar = dataForSaving[0][i] singleImage = dataForSaving[1][i] if singleChar not in enumeratedList: enumeratedList.append(singleChar) ...
Tests of try rotation with min_size in configuration
def test_process_log_with_min_size_in_configuration(self): with tempfile.TemporaryDirectory() as sandbox: with mock.patch('sys.stdout', new=io.StringIO()) as fake_stdout: srcfile = Path(sandbox, 'pokus.log') srcfile.touch() destfile = Path(sandbox, 'ba...
Performs a 'set' using the nodes specified and returns the result.
def perform_set(self, nodes=[]): # Input validation try: # Works for XGNodeDict input set_nodes = nodes.get_updates() except (AttributeError, TypeError): # Assume list instead set_nodes = nodes if not isinstance(set_nodes, list): ...
This operation applies only to sharded cluster instances. For more information, see [Apply for an endpoint for a shard or Configserver node](~~134037~~). > The requested endpoint can only be accessed over the internal network. If you want to access the endpoint over the Internet, call the [AllocatePublicNetworkAddress]...
def allocate_node_private_network_address( self, request: dds_20151201_models.AllocateNodePrivateNetworkAddressRequest, ) -> dds_20151201_models.AllocateNodePrivateNetworkAddressResponse: runtime = util_models.RuntimeOptions() return self.allocate_node_private_network_address_with_op...
Executes a subprocess and returns its exit code and output.
def GetCmdStatusAndOutput(args, cwd=None, shell=False, env=None, merge_stderr=False): status, stdout, stderr = GetCmdStatusOutputAndError( args, cwd=cwd, shell=shell, env=env, merge_stderr=merge_stderr) if...
return for the current row of the matching dataFrame a list of dictionary containing the mean of all the review from the nth
def mean_more_n_reviews(x, n, review_books_df): asin_1 = x['asin_1'] asin_2 = x['asin_2'] dic_1 = {} dic_2 = {} if (len(review_books_df.query('asin == @asin_1')) > n and len(review_books_df.query('asin == @asin_2')) > 20): overall_reviews_1 = review_books_df.query('asin == @asin_1'...
Finish the auth process once the access_token was retrieved
def do_auth(self, access_token, *args, **kwargs): data = self.user_data(access_token, *args, **kwargs) response = kwargs.get('response') or {} response.update(data or {}) if 'access_token' not in response: response['access_token'] = access_token kwargs.update({'respon...
Test for t(tau,x) = tau(1+asin(bx))
def flattenTest(): x = rampfloat(0,0,1,n1,n2) t = rampfloat(0,1,0,n1,n2) smax = 5.0 a = smax/(n1-1) b = 2*PI/(n2-1) bx = mul(b,x) bt = mul(b,t) cosbx = cos(bx) sinbx = sin(bx) acosbx = mul(a,cosbx) asinbx = mul(a,sinbx) p2 = div(mul(bt,acosbx),add(1,asinbx)) el = fillfloat(1,n1,n2) fl = Flat...
Compute exterior orientation parameters. This function can be used in conjecture with ``self.__ComputeDesignMatrix(groundPoints)`` and ``self__ComputeObservationVector(imagePoints)``
def ComputeExteriorOrientation_RzRyRz(self, imagePoints, groundPoints, epsilon): # cameraPoints = self.ImageToCamera(imagePoints) cameraPoints = imagePoints self.exteriorOrientationParameters[0:3] = np.dot(self.rotationMatrix_RzRyRz, self.exteriorOrientationParameters[0:3]) self.exterior...
Check all files against the defined precommit hooks.
def lint(session): session.install("pre-commit") session.run("pre-commit", "run", "--all-files")
Returns when execution step is IN PROGRESS
def wait_for_execution_step_status_is_in_progress(self, execution_id, document_name, step_name, time_to_wait): start_time = time.time() step_status = self._get_execution_step_status(execution_id, step_name) elapsed_time = time.time() - start_time # Wait for execution step to resolve in ...
Berlekamp's algorithm only in Z/pZ
def factor_unit(P): assert all(isinstance(c, ModInt) for c in P) assert len(set(c.n for c in P)) == 1 if P.deg == 1: return defaultdict(int, {P: 1}) p = P[0].n S = Polynomial.gcd(P, P.prime()) if S.deg == P.deg: # P' = 0 so P = R^p R ...
Ask for a number between low and high until actually given one. Ask for a number, and if the response is outside the bounds keep asking until you get a number that you think is OK
def stubborn_asker(low, high): import random a=random.randint(1,100) for i in range(1,10): n=input('enter the number: ') if n.isdigit(): n=int(n) if n==a: return('Correct') break elif n>a: return('The number ...
Function to perform a 3 year window filter for a single land cover value (such as Forest as 1) for the first year in an image. The image bands do not need to be in order, but the bandNames argument must be in chronological order. For the first year of land cover classifications, a three consecutive years window is used...
def applyMask3first(imagem, value, bandNames): mask = imagem.select(bandNames[0]).neq(value) \ .bitwiseAnd(imagem.select(bandNames[1]).eq(value)) \ .bitwiseAnd(imagem.select(bandNames[2]).eq(value)) change_img = imagem.select(bandNames[0]).mask(mask.eq(1)).where(mask.eq(1), value) img_out = ...
Getter for the reference (initial board state) biosafe output.
def get_reference(self): return self.PotTax_reference
Adds margin of zeros around an input sparse matrix.
def zero_pad_sparse(mat, margin_h, margin_v, fmt="coo"): sm, sn = mat.shape padded_mat = mat.copy() # Up and down margins initialized with zeros and filled as needed margin_h_0 = sp.csr_matrix((sm, margin_h), dtype=mat.dtype) margin_v_0 = sp.csr_matrix((margin_v, sn + 2 * margin_h), dtype=mat.dtype...
Return the icon for this node type.
def get_icon(self): return QIcon()
Initialize appointment's creation workflow; Pass to date definition
def create_appointment(): msg = render_template('date') return question(msg)
Specifies the output format of the exposed resources, defaults to "1"
def divisor(self) -> Optional['outputs.CSIPowerStoreSpecDriverSideCarsEnvsValueFromResourceFieldRefDivisor']: return pulumi.get(self, "divisor")
Member function return random state of the Operator.
def random_states(self, num_of_states): return numpy.random.choice([-1, 1], size=(num_of_states, ) + self.hilbert_state_shape)
Remove duplicates in a 2D list.
def remove_dupl_2d(arr): arr_len = len(arr) idx = 0 unique = set() while idx < arr_len: if tuple(arr[idx]) in unique: del arr[idx] arr_len -= 1 continue unique.add(tuple(arr[idx])) idx += 1 return arr
Returns the arm's desired x,y,z acceleration in workspace coordinates at time t
def target_acceleration(self, time): pass
Test case for networking_project_network_create
def test_networking_project_network_create(self): pass
Recursively expand slices, iterables, dictionaries into a list of scalar data type. Scalars are returned as a 1 element list.
def _expand_args(arglst): if not isinstance(arglst, Iterable): arglst = [arglst] elif isinstance(arglst, dict): arglst = [arglst] elif ('theano' in sys.modules and isinstance(arglst, _gettheano().graph.basic.Variable)): arglst = [arglst] elif isinstance(arglst, cf.Termi...
Compute the nodal sum of values defined on elements.
def nodalSum2(val,elems,tol): nodes = unique1d(elems) for i in nodes: wi = where(elems==i) vi = val[wi] ai,ni = average_close(vi,tol=tol) ai /= ni.reshape(ai.shape[0],-1) val[wi] = ai
We have changed our branch_dict (or more likely finish_branch_definition()ed a branch within that dict) in a way that invalidates any cached calculations that consumed the branch dict.
def _invalidate_branch_cache(self): self._cached_overlapping_branch_list = None
Download dataset from Public HTTP URL.
def _download_http(source_uri, dest_path, version): try: logger.info("Downloading the dataset.") download_file(source_uri=source_uri, dest_path=dest_path) except DownloadError as e: logger.info( f"The request download from {source_uri} -> {dest_path} ...
Encode splits as intetgers and return the array.
def encode_splits(data): lookup = {'train': 0, 'val': 1, 'test': 2} return [lookup[datum['split']] for datum in data]
Return a dictionary of information about a person
def build_person(first_name,last_name, age =''): person = { 'first': first_name.title(), 'last' : last_name.title()} if age: person['age'] = age return person
Selects most frequent features. Selects the x most frequent ngrams/features (x=FEATURE_LENGTH) to avoid a (possibly) too big featurelist.
def select_features(vec): return sorted(vec, key=vec.get, reverse=True)[ : min(len(vec), FEATURE_LENGTH) ]
This operation is applicable only to generalpurpose localdisk and dedicated localdisk instances. You can call this operation up to 30 times per minute. To call this operation at a higher frequency, use a Logstore. For more information, see [Manage a Logstore](~~48990~~).
def describe_running_log_records_with_options( self, request: dds_20151201_models.DescribeRunningLogRecordsRequest, runtime: util_models.RuntimeOptions, ) -> dds_20151201_models.DescribeRunningLogRecordsResponse: UtilClient.validate_model(request) query = {} if not Ut...
Handle the case where we land on a login screen Sometimes we get redirected to a login URL rather than being logged in, and we've yet to figure out precisely why that happens. Experimentation shows that authentication has already happened, so in this case we'll try going back to the instance url rather than the front d...
def _check_for_login_failure(self): location = self.selenium.get_location() if "//test.salesforce.com" in location or "//login.salesforce.com" in location: login_url = self.cumulusci.org.config["instance_url"] self.builtin.log(f"setting login_url temporarily to {login_url}", "DE...
Update original_schema by adding and/or relaxing mode on columns.
def _GetUpdatedSchema( original_schema, new_columns=None, relaxed_columns=None): orig_field_map = ( {f.name: f for f in original_schema.fields} if original_schema else {}) if relaxed_columns: orig_field_map = _GetRelaxedCols(relaxed_columns, orig_field_map) if new_columns: orig_field_m...
Updates a testing scenario.
def put(self, id): data = request.json update_scenario(id, data) return None, 204
Adds a new weight; params needed for post request's payload
def add_weight(self): # Get the csrf token csrf = self.extract_csrf('https://wger.de/en/weight/add/') # Adding referer to the headers self.headers['Referer'] = API.url_weight # Take the weight entires from TOML file entries = self.cfg.get('payload', {}).get('we...
(Deprecated) Return the value string of a parameter by its name.
def _getParameterValueString(self, name): warnings.warn("This function is deprecated; parameters have been replaced with uniform inputs in 1.38.", DeprecationWarning, stacklevel = 2) return ""
Return the proper location used to export our JSON data.
def set_location(self, location): if not location: location = getcwd() + '/stormpath-exports' return location
Return welcome page for nonlogin user
def login(): user_type = get_admin_type_in_session() login_form = LoginForm(request.form) current_app.logger.info(f'user_type{user_type}') if user_type != UserTypeEnum.NOT_LOGIN: return redirect(url_for('admin.admin')) if 'login' in request.form: # read form data username = ...
Computes minimum interspike frequency (equivalent to maximum interspike interval).
def min_spike_frequency_tV(t, V): intervals = interspike_intervals(t, V) raise_if_not_multiple_spikes(intervals) max_int = np.amax(intervals) return 1/max_int
a help function to print the intentinformation in format
def format_print_jobs(intent): print "\nintentName: %s" %(intent['name']) for k,v in intent.iteritems(): if k <> 'name': print "\t" + str(k) + ": " + str(v)
Calculate the 2D Cartesian (planar) area of each geometry.
def area(self): return _property_op(arctern.ST_Area, self)
Testing {% attr %} with "nocondense" option preserves whitespace
def test_with_nocondense_preserves_whitespace(self): t = Template('{% load djblets_utils %}' '<span{% attr "data-foo" nocondense %}\n' 'some \n\n' 'value\n' '{% endattr %}>') self.assertEqual( t.render(Co...
Adds a new item to a meal and stores information about it in the class dictionary Params needed for post request's payload
def add_item(self, m_id): # Take the meals entires from TOML file meals = self.cfg.get('payload',{}).get('plan',{})[0].get('meal',{}) for entries in meals: # Check for valid entires if entries: # Construct payload for payl...
Downloads media item to given directory (with metadata, except GPS).
def download(self, directory): # Setting filename (full path) and URL of file to download filename = os.path.join(directory, self.name) download_url = '{}=d'.format(self.base_url) # Downloading urlretrieve(download_url, filename) return filename
does this source image have any face alts yet
def hasAnyFaces(self, uri): return self.graph.queryd( 'ASK { ?uri pho:alternate ?alt . ?alt pho:tag "face" .}', initBindings={'uri':uri})
Output the top level cells from the GDSII data. Top level cells are those that are not referenced by any other cells. Returns
def top_level(self): top = set(self) for cell in self: top.difference_update(cell.get_dependencies()) return list(top)
Reorder a given array into a max heap.
def heapify(array): # Start by sifting down the first parent node n = len(array) node = (n - 2) // 2 # Sift down all nodes, finishing with the root while node >= 0: sift_down(array, node, n) node -= 1
Wrapper for parmcheck with default parameters
def run_parmchk ( lig ): # Check if it is a string, otherwise assumes it is a pdb object if isinstance(lig,basestring) : name = lig else : name = lig.name # Remove the extension from the filename out_name = os.path.splitext ( name )[0] cmd = 'parmchk -i %s.prepi -f prepi -o %s.frcm...
Gets the email of this UserBase. The Zulip API email address of the user or bot. If you do not have permission to view the email address of the target user, this will be a fake email address that is usable for the Zulip API but nothing else.
def email(self): return self._email
Map MXNet's log operator attributes to onnx's Log operator and return the created node.
def convert_log(node, **kwargs): return create_basic_op_node('Log', node, kwargs)
Most regressors return a dot product for the prediction
def predict(self, Xtest): ytest = np.dot(Xtest, self.weights) return ytest
Delete all of the SQS Queues that start with the given domain name
def sqs_delete_all(session, domain): client = session.client('sqs') resp = client.list_queues(QueueNamePrefix=domain.replace('.','-')) for url in resp.get('QueueUrls', []): client.delete_queue(QueueUrl=url)
Define the tool (tool name is the name of the class).
def __init__(self): self.label = "CDU-PAT" self.description = "da scrivere" self.canRunInBackground = False
Returns given vm's/templates's disks collection href or list of disk objects
def getObjDisks(name, get_href=True, is_template=False): response = get_disk_attachments( name, 'template' if is_template else 'vm', get_href ) if get_href: return response return get_disk_list_from_disk_attachments(response)
Common is the common specification for both controller and node plugins
def __init__(__self__, *, args: Optional[Sequence[str]] = None, envs: Optional[Sequence['outputs.CSIUnitySpecDriverCommonEnvs']] = None, image: Optional[str] = None, image_pull_policy: Optional[str] = None, name: Optional[str] = None, ...
Test case for networking_project_network_tag_put
def test_networking_project_network_tag_put(self): pass
Compresses a byte array with the xz binary
def compress(value): process = Popen(["xz", "--compress", "--force"], stdin=PIPE, stdout=PIPE) return process.communicate(value)[0]
Read a csv file.
def read_csv(file_name): data = {} with open(file_name) as f: f = MyIter(f) try: for line in f: if not line.strip(): continue if line == 'Points\n': break key, val = read_key_value(line, separator...
Normalises and reshapes the images in the dataset.
def normalise(dataset): # Scale images to the [0, 1] range dataset = dataset.astype("float32") / 255 # Make sure images have shape (28, 28, 1) return np.expand_dims(dataset, -1)
Given a vector of predictions, save results in CSV format.
def save_results(predictions, filename): with open(filename, 'w') as f: f.write("id,ACTION\n") for i, pred in enumerate(predictions): f.write("%d,%f\n" % (i + 1, pred))
Start the client listening to the game. Pass in a function that accepts the available actions and the current state of the game, and returns the action to take. The SDK will handle the rest. Checks if any commandline arguments are passed when running, if there are any, they are assumed to be client keys that are sent t...
def start(turn_handler): if os.environ.get('BOTBOX_SECRET'): print('Using env secret:', os.environ['BOTBOX_SECRET']) headers = {'Authorization': os.environ['BOTBOX_SECRET']} elif len(sys.argv) > 1: print('Using cli secret:', sys.argv[1]) headers = {'Authorization': sys.argv[1]} ...
Garbage collect temporary cached data structures.
def gc(self): self._complete_grid = None
Initialize an Agent object. Params ======
def __init__(self, state_size, action_size, random_seed): self.state_size = state_size self.action_size = action_size self.seed = random.seed(random_seed) # Actor Network (w/ Target Network) self.actor_local = Actor(state_size, action_size, random_seed).to(device) self.a...
Average values from an array according to some specification. The default is to have a direction that is nearly the same. a is a 2dim array
def average_close(a,tol=0.5): if a.ndim != 2: raise ValueError,"array should be 2-dimensional!" n = normalize(a) nrow = a.shape[0] cnt = zeros(nrow,dtype=int32) while cnt.min() == 0: w = where(cnt==0) nw = n[w] wok = where(dotpr(nw[0],nw) >= tol) wi = w[0][wok...
If a listiter_op returns something besides an iterator as output, raise a ValueError.
def test_listiter_op_3(): @ops.listiter_op def f(x): return [4, 5, 6] # Returning a list instead of an iterator with pytest.raises(ValueError): result = f([1, 2, 3])
Return if x == y, if eps is not None, return if abs(xy) <= eps
def all_equal(x, y, eps=None): if eps: return all([abs(i - j) <= eps for i, j in zip(x, y) if i is not None and j is not None]) return all([i == j for i, j in zip(x, y)])
Returns True if the item is in the set
def __contains__(self, item): return item in self._index_map
The SMAPI Audit Logs API provides customers with an audit history of all SMAPI calls made by a developer or developers with permissions on that account.
def query_development_audit_logs_v1(self, get_audit_logs_request, **kwargs): # type: (AuditLogsRequest_13316e3e, **Any) -> Union[ApiResponse, object, Error_fbe913d9, AuditLogsResponse_bbbe1918, BadRequestError_f854b05] operation_name = "query_development_audit_logs_v1" params = locals() ...
Calculate the aggregated mean and stds.
def _get_aggregated_mean_std(self, means, stds, n): mean = means.view(n, -1).sum(0) / n std = ( stds.view(n, -1).sum(0) / n + ((means.view(n, -1) - mean) ** 2).view(n, -1).sum(0) / n ) return mean.detach(), std.detach()
Returns a cash payment based on the dividends that should be paid out according to the accumulated bookkeeping of earned, unpaid, and stock dividends.
def pay_dividends(self, next_trading_day): net_cash_payment = 0.0 try: payments = self._unpaid_dividends[next_trading_day] # Mark these dividends as paid by dropping them from our unpaid del self._unpaid_dividends[next_trading_day] except KeyError: ...
Open vector field with independent directories.
def openVectorWT(w_dir, t_dir): tx_dir, ty_dir = t_dir W = openFile(w_dir) Tx = openFile(tx_dir) Ty = openFile(ty_dir) assert Tx.shape == Ty.shape, "Tx and Ty must have same dimensions." Nt, Nc = W.shape Ny, Nx = Tx.shape V = np.zeros((Nt, 2, Ny, Nx)) for n in range(Nt): V[n...
This function is used for validation process. It returns a list of stockCode items and a list of quantities for each item.
def get_order_lists(self, n_items, n_quantities): arr_stock_code = self._df_invoice_original.StockCode.unique() arr_stock_code = np.random.choice(arr_stock_code, n_items) list_stockCode = list(arr_stock_code) list_quantities = np.ones(arr_stock_code.shape[0]) list_quantities *=n_quantities...
Process the received message based on its type.
def run(self): alogger.info("Recieved message from %s, Message: (%d) %s" % (self.client.getaddress(), self.action_type, self.message)) #Try to call th function associated with this message type. #format = "handle_<type>" (eg: handle_100) fn = globals().get("handle_" + str(self.action_type...
correctly convert to specified moltype
def test_sequence_to_moltype(self): s = Sequence("TTTTTTTTTTAAAA", name="test1") annot1 = s.add_annotation(Feature, "exon", "fred", [(0, 10)]) annot2 = s.add_annotation(Feature, "exon", "trev", [(10, 14)]) got = s.to_moltype("rna") annot1_slice = str(annot1.get_slice()) a...
Restart another round. Check the remaining budget and leave the game if budget <= 0. Create new BJCards
def restart(self): self.state ='active' if self.budget <= 0: return self.leave() self.cards =BJCards() self.bet_amount =0
Get neofunctionalisation events of all enzymes in the core metabolism.
def neofunctionalisations(self, majorityPercentageCoreMetabolism = defaultMajorityPercentageCoreMetabolism, eValue = defaultEValue, considerOnlyECs = None) -> Set[Neofunctionalisation]: # get neofunctionalisations return self._neofunctionalisedEnzymes(majorityPercentageCoreMetabolism, eValue, co...
Tests API call to onboard NS descriptor resources
def test_post_ns_descriptors(post_ns_descriptors_keys): sonata_vnfpkgm = SONATAClient.VnfPkgm(HOST_URL) sonata_nsd = SONATAClient.Nsd(HOST_URL) sonata_auth = SONATAClient.Auth(HOST_URL) _token = json.loads(sonata_auth.auth(username=USERNAME, password=PASSWORD)) _token = json.loads(_token["data"...
Create a onehot encoding of x of size k.
def one_hot(x, k, dtype=np.float32): return np.array(x[:, None] == np.arange(k), dtype)
Return 500 if internal error
def page_not_found(e): return render_template("500.html"), 500
Takes fragment lowest and highest limits as an integers and get all the prime numbers in that range, NOT including the limit itself. Returns a numpy array of the primes. Needs the primes from the first fragment of the program as input.
def get_primes_in_fragment(fragment_lowest, fragment_highest, primes_in_first_fragment): fragment_range = np.arange(fragment_lowest, fragment_highest) prime_mask = np.ones(len(fragment_range), dtype=bool) for p in primes_in_first_fragment: if fragment_lowest % p == 0: ...
Representation of gridded 2 or 3 dimensional data
def __init__(self, path: str = None, buffer: io.BytesIO = None): if not path and not buffer: raise ValueError("Must supply path or buffer") if buffer: memory = buffer.getvalue() buffer.close() path = tempfile.TemporaryFile() else: ...
Creating fake profiles for given number of people using namedtuples
def init_profiles_using_namedtuple(no_profiles: int): profiles = [] Profile = namedtuple('Profile', fake.profile().keys()) for _ in range(no_profiles): profiles.append(Profile(**fake.profile())) return profiles
Returns a URL to the GOES data for the specified date.
def _get_url_for_timerange(self, timerange, **kwargs): timerange = TimeRange(timerange.start.strftime('%Y-%m-%d'), timerange.end) if timerange.end < parse_time("1999/01/15"): goes_file = "%Y/go{satellitenumber:02d}%y%m%d.fits" elif timerange.start < parse_time("1999/01/15") and timer...
Redirect index to students page
def index() -> str: return redirect('/students')
adds a user in db and logs in with client
async def logged_user(client, user_role: UserRole) -> UserDict: async with LoggedUser( client, {"role": user_role.name}, check_if_succeeds=user_role != UserRole.ANONYMOUS, ) as user: print("-----> logged in user", user["name"], user_role) yield user print("<----- ...
Generates a Single SignOn (SSO) session for the iLO Java Applet console and returns the URL to launch it. [Arguments]
def fusion_api_get_server_hardware_java_remote_console_url(self, uri, api=None, headers=None): return self.sh.get(uri=uri, api=api, headers=headers, param='/javaRemoteConsoleUrl')
Iterate over modes. Synchronized iterator to iterate the modes in an order.
def modes(self): try: order = self._current_order except AttributeError: raise AttributeError('Cannot iterate over modes without iterating over orders!') from None mode = -order while mode <= order: yield mode mode += 1
Creates a hard link to dst. dst DNE Dir F SLF SLD SLB s DNR R R N N R R e Dir R R R R R R l F R R R R ? ? f SL R R R R ? ? R means raises. N means new hardlink created.
def link(self, dst): assert isinstance(dst, Path) link(dst._path, self._path)
Test case for change_relation_types
def test_change_relation_types(self): pass
Print a line to the output file, discarding duplicate blank lines.
def write(s): global prev_line if not (prev_line == "\n" and s == "\n"): fo.write(s) prev_line = s
Parses help function related command line arguments
def parse_help_command(args): if len(args) < 2: print_generic_help() elif len(args) == 2: print_specific_help(args[1]) else: print 'Error! Found too many arguments for --help! Use --help with ' \ '0 arguments to print generic help or type --help <tool_name> ' \ ...
Move the monkey across the scree, turnaround when it reaches the end.
def _walk(self): new_pos = self.rect.move((self.move, 0)) # move 9 pixel to the right per frame if self.rect.left < self.area.left or self.rect.right > self.area.right: self.move = -self.move # move to the opposite direction when the chimp position exceeds the screen new_pos = ...
Implementing click view price list detail page inline action button functionality
def click_view_price_list_detail_first_row_inline_action_button(self): self.click_inline_action_button(self.view_price_list_div_id, None, self.view_price_list_column_number, True) self.wait_for_ajax_spinner_load()
Test addition for Complex with Complex, complex, int and float
def test_add(): z = Complex(1, -2) w = Complex(1, 1) assert (z + w) == Complex(2, -1) assert (z + (1+1j)) == Complex(2, -1) assert (z + 2) == Complex(3, -2) assert (z + 2.0) == Complex(3, -2)
List walks, or create a new walks.
def walk_list_api(request): if request.method == 'GET': walks = Walk.objects.filter(user=request.user).order_by("-date") serializer = WalkSerializer(walks, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = WalkSerializer(data=request.data) ...
Retrieve Node object for a domain with a provided uuid.
def ex_get_node_by_uuid(self, uuid): domain = self._get_domain_for_uuid(uuid=uuid) node = self._to_node(domain=domain) return node