content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def ldr_vartime_blockedby_pp_hat(arr_rate, pp_mean_svctime, pp_cap, pp_cv2_svctime): """ Approximate unconditional variance of time blocked in ldr waiting for a pp bed. Modeling pp as an M/G/c queue and using approximation by Whitt. """ pp_svcrate = 1.0 / pp_mean_svctime vartime = qng.ggm_qwait_whitt_varw(arr_rate, pp_svcrate, int(pp_cap), 1.0, pp_cv2_svctime) return vartime
4ec8a552473c07fb65a2b044fda906a01c7b7f1c
34,689
def identify_crossing_events(df): """Identifies pore crossing events in data frame of domain indices. Given a data frame of domain indices alongside time stamps and particle IDs, this function identifies crossing events, i.e. a particle moving from one side of the membrane to the other THROUGH THE PORE REGION. Cases where a particle moves through the periodic boundary or through the membrane itself (i.e. outside the cylindrical protein region) are not counted as crossing events. The return value is a data frame in which each row corresponds to a crossing event and the columns identify times at which the particle entered and exited the pore, the mean of these times, and the ID of the particle which crosses the pore. Note that the input data frame should contain only a single unique particle ID, i.e. this function should by run on the domain index data frame grouped by particle indices. In addition, a further column contains a crossing number indicating the direction in which the particle passed the pore. This is done by first calculating the difference between subsequent domain indices. Where this difference is zero, the particle stayed in the given domain and the corresponding row can be ignored. Where this difference is +1/-1, the particle moved into or out of the pore. Where the difference is +2/-2, the particle moved across the periodic boundary or through the membrane. The time series of domain index differences is then partitioned into individual series between periodic boundary jump events. In each such subdivision the target particle is known to start outside the pore domain. A crossing event can then be identified by averaging over the sum of pairs of subsequent domain index differences. Note that for a particle that starts out inside the pore domain at the beginning of the trajectory no clear crossing direction can be established (i.e. is it going back to the domain it came from or is it moving across the pore to the opposite domain). By convention, these events will therefore not be counted as pore crossing events. """ # make copy of input data frame to avoid overwriting contents: df = df.copy() # calculate difference between subsequent indices: df["domain_diff"] = df["domain_idx"].shift(0) - df["domain_idx"].shift(1) df["t"] = 0.5*(df["t"].shift(0) + df["t"].shift(1)) df = df.dropna() df = df.drop(columns=["domain_idx"]) # drop cases where particle did not change domain at all: df = df.loc[np.abs(df["domain_diff"]) != 0.0, ] # create index for number of jumps across period boundary (or through the # membrane) df["pbcjump"] = 0 df.pbcjump[(df.domain_diff == -2) | (df.domain_diff == 2)] = 1 df.pbcjump = df.pbcjump.cumsum() # drop all pbcjump groupings with less then two non-pbcjump events: df = df.loc[(df.domain_diff != -2) & (df.domain_diff != 2), ] df["pbccount"] = df.groupby("pbcjump").domain_diff.transform("count") df = df.loc[df.pbccount > 1, ] df = df.drop(columns=["pbccount"]) # handle special case of empty data frame: if df.empty is True: # manually add columns: df["crossing_number"] = None df["t_enter"] = None df["t_mean"] = None df["t_exit"] = None else: # aggregate pairwise domain index differences: df = df.groupby("pbcjump").apply(aggregate_event_pairs) # remove unneccessary columns and indices: df = df.drop(columns=["t", "domain_diff", "pbcjump"]) df = df.reset_index(drop=True) # return data frame: return(df)
583469263c319db59724e56a46c6f422486a230b
34,690
from datetime import datetime import calendar import time def timecode(acutime): """ Takes the time code produced by the ACU status stream and returns a ctime. Args: acutime (float): The time recorded by the ACU status stream, corresponding to the fractional day of the year """ sec_of_day = (acutime-1)*60*60*24 year = datetime.datetime.now().year gyear = calendar.timegm(time.strptime(str(year), '%Y')) comptime = gyear+sec_of_day return comptime
41e5298777e1685041018e8aeee046a758ee4912
34,691
def calc_timedelta_in_years(start, end) -> float: """Computes timedelta between start and end dates, in years To use this function, start and end dates should come from a series of daily frequency. Args: start: start date end: end date Returns: float: time delta in number of years """ # datetime representation of number of days in 1 year one_year = pd.to_timedelta(365.25, unit="D") one_day = pd.to_timedelta(1, unit="D") # Compute the duration of the series in terms of number of years years = (end - start + one_day) / one_year return years
1833b69492b9c16a2b657da658f2f17dce2c3884
34,692
def listen(recognizer, mic, keywords, uses_google_api): """ Listens for a set of (keyword, priority) tuples and returns the response :param recognizer: speech_recognition Recognizer object :param mic: speech_recognition Microphone object :param keywords: Iterable of (keyword, priority) tuples :param uses_google_api: True if Google API should be used :return: response string """ response = None with mic as source: recognizer.adjust_for_ambient_noise(source) audio = recognizer.listen(source) try: if uses_google_api: response = recognizer.recognize_google(audio) else: response = recognizer.recognize_sphinx(audio, keyword_entries=keywords) except sr.RequestError: print('Voice control setup missing or not working.') except sr.UnknownValueError: print('Could not recognize speech') return response
1af6674edc6709da7a81e72cbfa84ec2df1eff64
34,694
from pynetio import Netio def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Netio platform.""" host = config.get(CONF_HOST) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) port = config.get(CONF_PORT) if not DEVICES: hass.http.register_view(NetioApiView) dev = Netio(host, port, username, password) DEVICES[host] = Device(dev, []) # Throttle the update for all Netio switches of one Netio dev.update = util.Throttle(MIN_TIME_BETWEEN_SCANS)(dev.update) for key in config[CONF_OUTLETS]: switch = NetioSwitch( DEVICES[host].netio, key, config[CONF_OUTLETS][key]) DEVICES[host].entities.append(switch) add_entities(DEVICES[host].entities) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, dispose) return True
955a9b62f19eb4478c19339456cd74037f4ffdca
34,695
def extract_username(message: Message) -> str: """ Extracts the appropriate username depending on whether * it was mentioned in an Entity, * it's accessible on message.author.id (discord) * it's accessible on message.author (pyttman dev mode) :param message: :return: str """ # Default to message.author.id unless provided as an entity if (username_for_query := message.entities.get( "username_for_query")) is None: try: username_for_query = message.author.id except AttributeError: username_for_query = message.author else: username_for_query = username_for_query.value return str(username_for_query)
58a181abce89306b65228fd3f51c63925b5a467b
34,696
def application(app_plan, custom_application, request, lifecycle_hooks): """ Creates an application with a application plan defined in the specified fixture """ application = custom_application(rawobj.Application(blame(request, "limited_app"), app_plan), hooks=lifecycle_hooks) return application
6519af0a6aea26b4f4d7a39c325a06c9c993fda6
34,697
def reward_user_required(view_func): """ Decorator for views that checks that the user is logged in and can use reward points. """ def check_user(user): return can_reward_points_be_used_by(user) return user_passes_test(check_user)(view_func)
aa499dc61d35537fc7e74404e0ead227da46a461
34,698
def dnv_registry_listing_soup(alphabetLetter, output_file_base): """ A method for collecting the list of ships that are in the DNV registry. From this list a list of available dnv-ids can be generated. :param alphabetLetter: A capital letter of the alphabet :param output_file_base: The base_name of the output file :return: Creates a file with db from the collection """ url = 'https://exchange.dnv.com/exchange/Main.aspx?extool=VReg&Search=%s' % alphabetLetter opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] # open the page try: page = opener.open(url) soup = BeautifulSoup(page.read()) except Exception, m: print m.message # try to read the header try: validPage = soup.find('title').contents[0] if 'Exchange' not in validPage.split(): return 'page not found' except Exception as m: print m.message # pick up the table dataTable = soup.find('table', id='ucMainControl_ToolContainer__ctl1_selectVesselOutputControl_mGrid') dataRows = dataTable.find_all('tr', attrs={'class':'Data'}) db = {} j = 0 for row in dataRows: row_tag = alphabetLetter+str(j) db[row_tag] = { 'status_s': row.contents[1].text.strip() if row.contents[1].text.strip() else None, 'name_s': row.contents[2].text.strip() if row.contents[2].text.strip() else None, 'dnv_id': row.contents[3].text.strip() if row.contents[3].text.strip() else None, 'dnv_type_s': row.contents[4].text.strip() if row.contents[2].text.strip() else None, 'build_year_n': row.contents[5].text.strip() if row.contents[5].text.strip() else None, 'builder_s': row.contents[6].text.strip() if row.contents[6].text.strip() else None } j+=1 if output_file_base: file_name = output_file_base + '_' + alphabetLetter + '.txt' db_to_file(db, file_name) print 'Completed collection of %s-letter ships from DNV exchange db' % alphabetLetter
942404c074113b424f38a12af97619843b6109cb
34,699
from corehq.apps.cloudcare import api def get_cloudcare_app(): """ Total hack function to get direct links to the cloud care application pages """ app = api.get_cloudcare_app(PACT_DOMAIN, PACT_CLOUD_APPNAME) app_id = app['_id'] pact_cloudcare = [x for x in app['modules'] if x['name']['en'] == PACT_CLOUDCARE_MODULE] forms = pact_cloudcare[0]['forms'] ret = dict((f['name']['en'], ix) for (ix, f) in enumerate(forms)) ret['app_id'] = app_id ret['build_id'] = get_latest_build_id(PACT_DOMAIN, app_id) return ret
3ff30de2549547902039df5bc5a0f140f3402954
34,700
from typing import Generator def train_test_k_fold(n_folds: int, n_instances: int, rng: Generator = default_rng()) -> list: """ Generate train and test indices at each fold. Args: n_folds (int): Number of folds n_instances (int): Total number of instances random_generator (np.random.Generator): A random generator. Defaults to np.random.default_rng(). Returns: list: a list of length n_folds. Each element in the list is a list (or tuple) with two elements: a numpy array containing the train indices, and another numpy array containing the test indices. """ # split the dataset into k splits split_indices = k_fold_split(n_folds, n_instances, rng) folds = [] for k in range(n_folds): test_indices = split_indices[k] train_indices = np.concatenate( split_indices[:k] + split_indices[k + 1:] ) folds.append([train_indices, test_indices]) return folds
f3ce954ddf5ff83cd12b852d4e22e0ad7757301f
34,701
def table_append(row, category='default'): """ Take any number of string args and put them together as a HTML table row. """ html_row = '</td><td>'.join(row) html_row = f'<tr><td>{html_row}</td></tr>' if category == 'header': html_row = html_row.replace('td>', 'th>') return html_row
cd0aa400c80ebc0ac8aad199439d5fc20d7a99a3
34,702
import six def before_sleep_func_accept_retry_state(fn): """Wrap "before_sleep" function to accept "retry_state".""" if not six.callable(fn): return fn if func_takes_retry_state(fn): return fn @_utils.wraps(fn) def wrapped_before_sleep_func(retry_state): # retry_object, sleep, last_result warn_about_non_retry_state_deprecation( 'before_sleep', fn, stacklevel=4) return fn( retry_state.retry_object, sleep=getattr(retry_state.next_action, 'sleep'), last_result=retry_state.outcome) return wrapped_before_sleep_func
7354548bdd1da1d59ce4faac4cbc5a1b819a40e2
34,703
def _calculate_type_helper(primary_type, secondary_types): """ :type primary_type: :class:`mbdata.models.ReleaseGroupPrimaryType` :type secondary_types: :class:`(mbdata.models.ReleaseGroupSecondaryType)` """ if primary_type.name == 'Album': if secondary_types: secondary_type_list = dict((obj.secondary_type.name, obj.secondary_type) for obj in secondary_types) # The first type in the ordered secondary type list # is returned as the result for type_ in SECONDARY_TYPE_ORDER: if type_ in secondary_type_list: return secondary_type_list[type_] # If primary type is not 'Album' or # the secondary type list is empty or does not have # values from the predetermined secondary order list # return the primary type return primary_type
24a973acd93b8c5d2cb1f2d2df14afc38c364a9d
34,704
def detach_all_devices(): """ Detaches all currently attached devices """ process = ractl.detach_all() if process["status"]: flash(_("Detached all SCSI devices")) return redirect(url_for("index")) flash(process["msg"], "error") return redirect(url_for("index"))
c874441d9a64d30b2f706fcc8e49181378541f36
34,706
def md5sum(text): """Return the md5sum of a text string.""" return md5_constructor(text).hexdigest()
29972c7bab3e7a6d2d78644b263bb058eb3677b6
34,709
def get_requests_to_user(user_id): #myrequests. Requests made to the user """ Returns the reviews for a listing given the listing id """ requests = ListingRequest.objects.filter(recipient__pk=user_id) return requests
e4a6e74ebf8f153db4f1f2614a7e6b07c082c9c8
34,710
def descriptor(request): """ Replies with the XML Metadata SPSSODescriptor. """ acs_url = saml2sp_settings.SAML2SP_ACS_URL entity_id = _get_entity_id(request) pubkey = xml_signing.load_cert_data(saml2sp_settings.SAML2SP_CERTIFICATE_FILE) tv = { 'acs_url': acs_url, 'entity_id': entity_id, 'cert_public_key': pubkey, } return xml_response(request, 'saml2sp/spssodescriptor.xml', tv)
d739ca1b1792c5c059cbe0974e24229cb9f217dd
34,711
def type_bframe(stage, bin, data=None): """BFrame""" if data == None: return 1 if stage == 1: return (str(data),'') try: v = int(data) if 0 > v or v > 255: raise except: raise PyMSError('Parameter',"Invalid BFrame value '%s', it must be a number in the range 0 to 256" % data) return v
0ee1fe1d82f0f964899e70534989a035020763ab
34,712
def last(data, ignore_nodata=UNSET) -> ProcessBuilder: """ Last element :param data: An array with elements of any data type. :param ignore_nodata: Indicates whether no-data values are ignored or not. Ignores them by default. Setting this flag to `false` considers no-data values so that `null` is returned if the last value is such a value. :return: The last element of the input array. """ return process('last', data=data, ignore_nodata=ignore_nodata)
97fdea2baf57e7efcc8aaf55b362852efe95ba60
34,714
def angle_wrap_pi(x): """wrap angle to [-pi, pi). Arguments: x -- angle to be wrapped """ return (x - np.pi) % (2 * np.pi) - np.pi
8a6e4f5e3e9b467cae8afbda09fa35f6184f1247
34,715
def contains_end_of_message(message, end_sequence): """Función que dado un string message, verifica si es que end_sequence es un substring de message. Parameters: message (str): Mensaje en el cual buscar la secuencia end_sequence. end_sequence (str): Secuencia que buscar en el string message. Returns: bool: True si end_sequence es substring de message y False de lo contrario. """ return False if message.find(end_sequence) == -1 else True
3966e3e2ddf62843c2eb12cf6ae144e53408c360
34,716
import pandas def decisionTree(dataFrame:pandas.DataFrame,predictors,outColumn,nFolds:int): """ Method for computing accuray and cross-validation using decision-tree """ if dataFrame is None: return None dataFrame=_encodeLabels(dataFrame) model = DecisionTreeClassifier() return classificationModel(model, dataFrame,predictors,outColumn,nFolds)
82f6c4e7f7956710cd613cc975aeb8fd6af6e7c1
34,717
def _cv2_show_tracks(img, bboxes, labels, ids, classes=None, thickness=2, font_scale=0.4, show=False, wait_time=0, out_file=None): """Show the tracks with opencv.""" assert bboxes.ndim == 2 assert labels.ndim == 1 assert ids.ndim == 1 assert bboxes.shape[0] == labels.shape[0] assert bboxes.shape[1] == 5 if isinstance(img, str): img = mmcv.imread(img) img_shape = img.shape bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1]) bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0]) text_width, text_height = 10, 15 for bbox, label, id in zip(bboxes, labels, ids): x1, y1, x2, y2 = bbox[:4].astype(np.int32) score = float(bbox[-1]) # bbox bbox_color = random_color(id) bbox_color = [int(255 * _c) for _c in bbox_color][::-1] cv2.rectangle(img, (x1, y1), (x2, y2), bbox_color, thickness=thickness) # id text = str(id) width = len(text) * text_width img[y1:y1 + text_height, x1:x1 + width, :] = bbox_color cv2.putText( img, str(id), (x1, y1 + text_height - 2), cv2.FONT_HERSHEY_COMPLEX, font_scale, color=(0, 0, 0)) # score text = '{:.02f}'.format(score) width = len(text) * text_width img[y1 - text_height:y1, x1:x1 + width, :] = bbox_color cv2.putText( img, text, (x1, y1 - 2), cv2.FONT_HERSHEY_COMPLEX, font_scale, color=(0, 0, 0)) if show: mmcv.imshow(img, wait_time=wait_time) if out_file is not None: mmcv.imwrite(img, out_file) return img
06c4b17c0bcd6bd4442637bff5542437c59562d1
34,718
def get_centers(bins): """Return the center of the provided bins. Example: >>> get_centers(bins=np.array([0.0, 1.0, 2.0])) array([ 0.5, 1.5]) """ bins = bins.astype(float) return (bins[:-1] + bins[1:]) / 2
31047e21eea7c6d86ba713509fdac42b3b0c33cc
34,719
def scale_by_yogi( b1: float = 0.9, b2: float = 0.999, eps: float = 1e-3, eps_root: float = 0.0, initial_accumulator_value: float = 1e-6 ) -> base.GradientTransformation: """Rescale updates according to the Yogi algorithm. Supports complex numbers, see https://gist.github.com/wdphy16/118aef6fb5f82c49790d7678cf87da29 References: [Zaheer et al, 2018](https://papers.nips.cc/paper/2018/hash/90365351ccc7437a1309dc64e4db32a3-Abstract.html) #pylint:disable=line-too-long Args: b1: decay rate for the exponentially weighted average of grads. b2: decay rate for the exponentially weighted average of variance of grads. eps: term added to the denominator to improve numerical stability. eps_root: term added to the denominator inside the square-root to improve numerical stability when backpropagating gradients through the rescaling. initial_accumulator_value: The starting value for accumulators. Only positive values are allowed. Returns: An (init_fn, update_fn) tuple. """ def init_fn(params): value_like = lambda p: jnp.full_like(p, initial_accumulator_value) mu = jax.tree_map(value_like, params) # First moment nu = jax.tree_map(value_like, params) # Second Central moment return ScaleByAdamState(count=jnp.zeros([], jnp.int32), mu=mu, nu=nu) def update_fn(updates, state, params=None): del params mu = _update_moment(updates, state.mu, b1, 1) nu = jax.tree_multimap( lambda g, v: v - (1 - b2) * jnp.sign(v - _abs_sq(g)) * _abs_sq(g), updates, state.nu) count_inc = numerics.safe_int32_increment(state.count) mu_hat = _bias_correction(mu, b1, count_inc) nu_hat = _bias_correction(nu, b2, count_inc) updates = jax.tree_multimap( lambda m, v: m / (jnp.sqrt(v + eps_root) + eps), mu_hat, nu_hat) return updates, ScaleByAdamState(count=count_inc, mu=mu, nu=nu) return base.GradientTransformation(init_fn, update_fn)
c65d1069741755bf5e5a5719b97c6553bfe525b7
34,720
def download(request): """ Serves patients full summary as a downloadable text file. :param request: The request with user information :return: Downloadable text file, in lieu of a conventional response """ Pat = Patient.objects.all().get(user=request.user) content = MediInfoExport(Pat, request.user, False) response = HttpResponse(content, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename="%s_Info.txt"' % \ str(request.user.get_full_name()).replace(' ', '-') return response
8cae4bbe27853a19848059f0c6bc11c48865f151
34,721
def gradient_descent(F,x0,args=(),delta=1e-14,gamma0=1e-12,adapt=False,plot=False): """ Find a local minimum of a scalar-valued function of a vector (scalar field) by the Gradient Descent method. https://en.wikipedia.org/wiki/Gradient_descent :param function F: Function to minimize. Initial use case is a cost function computed as a sum of squares of difference between points on a calculated trajectory and observed points on the same trajectory :param numpy vector x0: Initial guess as to minimum of function. This method will "probably" find the local minimum nearest to this point :param float delta: Amount to perturb the function parameters to calculate the gradient :param float gamma0: Initial step size. The step size is adaptive after the first step, so this controls the size of that first step. Gradient descent minimizes the function by steps. At each step, it figures out the gradient of the function. This is a vector which points in the direction of maximum increase of the function. Since we want to minimize, we take a step in the opposite direction. Gamma is a scale factor which determines how far to step in that direction. \delta_x=\gamma_n*grad(F(x_n) x_{n+1}=x_{n+1}-\delta_x Now the only hard part is to figure out the right gamma. A simple non-working optimizer would use the gradient function to project to zero, and take a step of that size. Unfortunately, that is only sound if the minimum is exactly zero. The wiki (boo!) gives a formula for gamma as: \gamma_n=\frac{(x_n-x_{n-1})^T[grad(F(x_n))-grad(F(x_{n-1}))]} {norm(grad(F(x_n))-grad(F(x_{n-1})))**2} Since this requires the gradient both at the current step and the previous one, we need an initial step size in order to take that first step. """ def grad(F,x0,delta,*args): """ Estimate the gradient of a scalar field by finite differences :param function F: Function to calculate the value of the field at a given point :param numpy vector x0: Point to take the gradient at :param float delta: Step size to take :return: Estimate of gradient vector """ F0=F(x0,*args) kd=np.zeros(x0.size) result=np.zeros(x0.size) min=True for i in range(x0.size): kd[i]=delta Fp=F(x0+kd,*args) Fm=F(x0-kd,*args) if Fp<F0 or Fm<F0: min=False result[i]=(Fp-Fm)/(2*delta) kd[i]=0.0 return (result,F0,min) #Take the first step xnm1=x0 gFxnm1,Fxnm1,min=grad(F,x0,delta,*args) if min: #won't be able to find an improvement, delta is too big return x0 xn=xnm1-gamma0*gFxnm1 #Now take steps with dynamic step size done=False Fs=[Fxnm1] xs=[0.0] ys=[0.0] zs=[0.0] while not done: gFxn,Fxn,min=grad(F,xn,delta,*args) Fs.append(Fxn) xs.append(xn[0]-x0[0]) ys.append(xn[1]-x0[1]) zs.append(xn[2]-x0[2]) if adapt: #Adaptive size (doesn't work for my problem) dx=xn-xnm1 dF=gFxn-gFxnm1 gamma=np.dot(dx,dF)/np.dot(dF,dF) else: gamma=gamma0 xnm1=xn gFxnm1=gFxn xn=xnm1-gamma*gFxnm1/np.linalg.norm(gFxnm1) done=min if plot: mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure(3) ax = fig.gca(projection='3d') ax.plot(ys, zs, Fs) plt.show() return xn
b710a768656a8bb0db16eafa87b88c91e83b38fd
34,723
def superop2pauli_liouville(superop: np.ndarray): """ Converts a superoperator into a pauli_liouville matrix. This is achieved by a linear change of basis. :param superop: a dim**2 by dim**2 superoperator :return: dim**2 by dim**2 pauli-liouville matrix """ dim = int(np.sqrt(superop.shape[0])) c2p_basis_transform = computational2pauli_basis_matrix(dim) return c2p_basis_transform @ superop @ c2p_basis_transform.conj().T * dim
f7b9cd9a0dce0bf2f1e20c6f8024021acf85ef07
34,724
def utility_num2columnletters(num): """ Takes a column number and converts it to the equivalent excel column letters :param int num: column number :return str: excel column letters """ def pre_num2alpha(num): if num % 26 != 0: num = [num // 26, num % 26] else: num = [(num - 1) // 26, 26] if num[0] > 26: num = pre_num2alpha(num[0]) + [num[1]] else: num = list(filter(lambda x: False if x == 0 else True, num)) return num return "".join(list(map(lambda x: chr(x + 64), pre_num2alpha(num))))
295b8c5391d5250f91781c2f6df1626a0acb8022
34,725
def binarize(query, mlb): """Transform a single query into binary representation Parameters ---------- query : ndarray, shape = [n_samples, n_classes] The tags. n_samples : int The number of samples in the training set. Returns ------- bin_query_vector : ndarray, shape = [n_samples] Binary query vector. """ return mlb.transform([query]).ravel()
aafd2072569c0c740b034caa0f8591da231b5b6d
34,727
from typing import Optional from typing import Dict def no_response_from_crawl(stats: Optional[Dict]) -> bool: """ Check that the stats dict has received an HTTP 200 response :param stats: Crawl stats dictionary :return: True if the dict exists and has no 200 response """ if not stats or not isinstance(stats, Dict): return False status_codes = stats.get("status_codes", {}) if not status_codes or not isinstance(status_codes, Dict): return False return 200 not in status_codes
461d3deb9ec6a162dfd7f3f3c0ac73262090c35b
34,728
def evaluate_surprisals_continuous(text, window_params, tot_params): """ Get the probability mass functions for each token's semantic similarity using a beta distribution. :param text: text to analyze; results are returned token-wise Can be a string or a spaCy-parsed document. :param params: tuple; parameter for scipy.stats.beta distribution :return: """ window_dist = beta(*window_params) tot_dist = beta(*tot_params) # if not isinstance(text, spacy.tokens.doc.Doc): text = NLP(text) sims_5 = [np.nan] sims_tot = [np.nan] for i in range(1, len(text)): try: sims_5.append(cosine(text[max(0, i-5):i].vector, text[i].vector)) except ZeroDivisionError: sims_5.append(np.nan) try: sims_tot.append(cosine(text[:i].vector, text[i].vector)) except ZeroDivisionError: sims_tot.append(np.nan) # zip up the dataframe and return it df = pd.DataFrame({ "Token":[i.text for i in text], "Position":[i.i for i in text], "Windowed Similarity":sims_5, "Totaled Similarity":sims_tot, "Windowed PDF":[-np.log(window_dist.pdf(i)) if not pd.isnull(i) else np.nan for i in sims_5], "Totaled PDF":[-np.log(tot_dist.pdf(i)) if not pd.isnull(i) else np.nan for i in sims_tot], }) return df
7fe58fadc0fa9943a47aee1217b1246a8c0d9c13
34,730
def getUSBFile(): """ Retrieves USB.ids database from the web. """ url = 'http://www.linux-usb.org/usb.ids' return urllib2.urlopen(url)
8199b9694db871ba9dcbd3b1338a416e8f4ac358
34,732
import time import math def get_local_time_zone(): """Return the current local UTC offset in hours and minutes.""" utc_offset_seconds = -time.timezone if time.localtime().tm_isdst == 1 and time.daylight: utc_offset_seconds = -time.altzone utc_offset_minutes = (utc_offset_seconds // 60) % 60 utc_offset_hours = math.floor(utc_offset_seconds / float(3600)) if \ utc_offset_seconds > 0 else math.ceil(utc_offset_seconds / float(3600)) return int(utc_offset_hours), utc_offset_minutes
4e90d0a0bf2e831aaf6629542451e75c0a1942a4
34,733
def connect_genes(t_trans_to_gene, t_trans_to_q_proj, q_proj_to_q_gene): """Create orthology relationships graph.""" o_graph = nx.Graph() genes = set(t_trans_to_gene.values()) o_graph.add_nodes_from(genes) q_genes_all = [] print(f"Added {len(genes)} reference genes on graph") conn_count = 0 for t_trans, t_gene in t_trans_to_gene.items(): projections = t_trans_to_q_proj[t_trans] q_genes = set(q_proj_to_q_gene[p] for p in projections) for q_gene in q_genes: conn_count += 1 q_genes_all.append(q_gene) o_graph.add_edge(t_gene, q_gene) q_genes_all = set(q_genes_all) print(f"Added {len(q_genes_all)} query genes on graph") print(f"Graph contains {conn_count} connections") return o_graph
f062fd61dbe21472cca609b3f0b43a0663944cb7
34,734
def gbsGetSelectedBounds(): """ Get bonding box of features from selection """ clayer = iface.mapCanvas.currentLayer() if not clayer or clayer.type() != QgsMapLayer.VectorLayer: return None box = clayer.boundingBoxOfSelected() return box.toRectF()
6e82fab64c2356f10b7e00d04a4a6b09ffbec499
34,735
from typing import Optional def pixelmatch( img1: ImageSequence, img2: ImageSequence, width: int, height: int, output: Optional[MutableImageSequence] = None, threshold: float = 0.1, includeAA: bool = False, alpha: float = 0.1, aa_color: RGBTuple = (255, 255, 0), diff_color: RGBTuple = (255, 0, 0), diff_mask: bool = False, fail_fast: bool = False, ) -> int: """ Compares two images, writes the output diff and returns the number of mismatched pixels. 'Raw image data' refers to a 1D, indexable collection of image data in the format [R1, G1, B1, A1, R2, G2, ...]. :param img1: Image data to compare with img2. Must be the same size as img2 :param img2: Image data to compare with img2. Must be the same size as img1 :param width: Width of both images (they should be the same). :param height: Height of both images (they should be the same). :param output: Image data to write the diff to. Should be the same size as :param threshold: matching threshold (0 to 1); smaller is more sensitive, defaults to 1 :param includeAA: whether or not to skip anti-aliasing detection, ie if includeAA is True, detecting and ignoring anti-aliased pixels is disabled. Defaults to False :param alpha: opacity of original image in diff output, defaults to 0.1 :param aa_color: tuple of RGB color of anti-aliased pixels in diff output, defaults to (255, 255, 0) (yellow) :param diff_color: tuple of RGB color of the color of different pixels in diff output, defaults to (255, 0, 0) (red) :param diff_mask: whether or not to draw the diff over a transparent background (a mask), defaults to False :param fail_fast: if true, will return after first different pixel. Defaults to false :return: number of pixels that are different or 1 if fail_fast == true """ if len(img1) != len(img2): raise ValueError("Image sizes do not match.", len(img1), len(img2)) if output and len(output) != len(img1): raise ValueError( "Diff image size does not match img1 & img2.", len(img1), len(output) ) if len(img1) != width * height * 4: raise ValueError( "Image data size does not match width/height.", len(img1), width * height * 4, ) # fast path if identical if img1 == img2: if output and not diff_mask: for i in range(width * height): draw_gray_pixel(img1, 4 * i, alpha, output) return 0 # maximum acceptable square distance between two colors; # 35215 is the maximum possible value for the YIQ difference metric maxDelta = 35215 * threshold * threshold diff = 0 aaR, aaG, aaB = aa_color diffR, diffG, diffB = diff_color # compare each pixel of one image against the other one for y in range(height): for x in range(width): pos = (y * width + x) * 4 # squared YUV distance between colors at this pixel position delta = color_delta(img1, img2, pos, pos) # the color difference is above the threshold if delta > maxDelta: # check it's a real rendering difference or just anti-aliasing if not includeAA and ( antialiased(img1, x, y, width, height, img2) or antialiased(img2, x, y, width, height, img1) ): # one of the pixels is anti-aliasing; draw as yellow and do not count as difference # note that we do not include such pixels in a mask if output and not diff_mask: draw_pixel(output, pos, aaR, aaG, aaB) else: # found substantial difference not caused by anti-aliasing; draw it as red if output: draw_pixel(output, pos, diffR, diffG, diffB) if fail_fast: return 1 diff += 1 elif output: # pixels are similar; draw background as grayscale image blended with white if not diff_mask: draw_gray_pixel(img1, pos, alpha, output) # return the number of different pixels return diff
95690f4584c7e90c63bb432418bb22068d3ab63e
34,737
def binary_search(array, target): """ Does a binary search on to find the index of an element in an array. WARNING - ARRAY HAS TO BE SORTED Keyword arguments: array - the array that contains the target target - the target element for which its index will be returned returns the index of target in array """ lower = 0 upper = len(array) while lower < upper: x = lower + (upper - lower) // 2 val = array[x] if target == val: return x elif target > val: if lower == x: break lower = x elif target < val: upper = x
6dfe09367e2dd7ae2e30f45009fa7059d0da0f18
34,738
import re import ast def _get_matrix_from_string(string): """Get a network connection matrix from a string. Parameters ---------- string : str String from which to read the matrix. It should have the format of a string representation of a NumPy array. Raises ------ FormatError If the string does not have the correct format. """ if string[-1] == '\n': string = string[:-1] string = re.sub(r'\[\s+', '[', string) string = re.sub(r'\s+\]', ']', string) string = re.sub(r'\s+', ',', string) try: matrix = ast.literal_eval(string) except Exception as err: raise FormatError('The string could be converted to a matrix.') from err return matrix
1d9a052e7506c379addd7f20ff2af5671f6a82ff
34,739
import warnings def classification_report(y_true, y_pred, labels=None, target_names=None, sample_weight=None, digits=2, output_dict=False, zero_division="warn"): """Build a text report showing the main classification metrics. Read more in the :ref:`User Guide <classification_report>`. Parameters ---------- y_true : 1d array-like, or label indicator array / sparse matrix Ground truth (correct) target values. y_pred : 1d array-like, or label indicator array / sparse matrix Estimated targets as returned by a classifier. labels : array, shape = [n_labels] Optional list of label indices to include in the report. target_names : list of strings Optional display names matching the labels (same order). sample_weight : array-like of shape (n_samples,), default=None Sample weights. digits : int Number of digits for formatting output floating point values. When ``output_dict`` is ``True``, this will be ignored and the returned values will not be rounded. output_dict : bool (default = False) If True, return output as dict zero_division : "warn", 0 or 1, default="warn" Sets the value to return when there is a zero division. If set to "warn", this acts as 0, but warnings are also raised. Returns ------- report : string / dict Text summary of the precision, recall, F1 score for each class. Dictionary returned if output_dict is True. Dictionary has the following structure:: {'label 1': {'precision':0.5, 'recall':1.0, 'f1-score':0.67, 'support':1}, 'label 2': { ... }, ... } The reported averages include macro average (averaging the unweighted mean per label), weighted average (averaging the support-weighted mean per label), and sample average (only for multilabel classification). Micro average (averaging the total true positives, false negatives and false positives) is only shown for multi-label or multi-class with a subset of classes, because it corresponds to accuracy otherwise. See also :func:`precision_recall_fscore_support` for more details on averages. Note that in binary classification, recall of the positive class is also known as "sensitivity"; recall of the negative class is "specificity". See also -------- precision_recall_fscore_support, confusion_matrix, multilabel_confusion_matrix Examples -------- >>> from sklearn.metrics import classification_report >>> y_true = [0, 1, 2, 2, 2] >>> y_pred = [0, 0, 2, 2, 1] >>> target_names = ['class 0', 'class 1', 'class 2'] >>> print(classification_report(y_true, y_pred, target_names=target_names)) precision recall f1-score support <BLANKLINE> class 0 0.50 1.00 0.67 1 class 1 0.00 0.00 0.00 1 class 2 1.00 0.67 0.80 3 <BLANKLINE> accuracy 0.60 5 macro avg 0.50 0.56 0.49 5 weighted avg 0.70 0.60 0.61 5 <BLANKLINE> >>> y_pred = [1, 1, 0] >>> y_true = [1, 1, 1] >>> print(classification_report(y_true, y_pred, labels=[1, 2, 3])) precision recall f1-score support <BLANKLINE> 1 1.00 0.67 0.80 3 2 0.00 0.00 0.00 0 3 0.00 0.00 0.00 0 <BLANKLINE> micro avg 1.00 0.67 0.80 3 macro avg 0.33 0.22 0.27 3 weighted avg 1.00 0.67 0.80 3 <BLANKLINE> """ y_type, y_true, y_pred = _check_targets(y_true, y_pred) labels_given = True if labels is None: labels = unique_labels(y_true, y_pred) labels_given = False else: labels = np.asarray(labels) # labelled micro average micro_is_accuracy = ((y_type == 'multiclass' or y_type == 'binary') and (not labels_given or (set(labels) == set(unique_labels(y_true, y_pred))))) if target_names is not None and len(labels) != len(target_names): if labels_given: warnings.warn( "labels size, {0}, does not match size of target_names, {1}" .format(len(labels), len(target_names)) ) else: raise ValueError( "Number of classes, {0}, does not match size of " "target_names, {1}. Try specifying the labels " "parameter".format(len(labels), len(target_names)) ) if target_names is None: target_names = ['%s' % l for l in labels] headers = ["precision", "recall", "f1-score", "support"] # compute per-class results without averaging p, r, f1, s = precision_recall_fscore_support(y_true, y_pred, labels=labels, average=None, sample_weight=sample_weight, zero_division=zero_division) rows = zip(target_names, p, r, f1, s) if y_type.startswith('multilabel'): average_options = ('micro', 'macro', 'weighted', 'samples') else: average_options = ('micro', 'macro', 'weighted') if output_dict: report_dict = {label[0]: label[1:] for label in rows} for label, scores in report_dict.items(): report_dict[label] = dict(zip(headers, [i.item() for i in scores])) else: longest_last_line_heading = 'weighted avg' name_width = max(len(cn) for cn in target_names) width = max(name_width, len(longest_last_line_heading), digits) head_fmt = '{:>{width}s} ' + ' {:>9}' * len(headers) report = head_fmt.format('', *headers, width=width) report += '\n\n' row_fmt = '{:>{width}s} ' + ' {:>9.{digits}f}' * 3 + ' {:>9}\n' for row in rows: report += row_fmt.format(*row, width=width, digits=digits) report += '\n' # compute all applicable averages for average in average_options: if average.startswith('micro') and micro_is_accuracy: line_heading = 'accuracy' else: line_heading = average + ' avg' # compute averages with specified averaging method avg_p, avg_r, avg_f1, _ = precision_recall_fscore_support( y_true, y_pred, labels=labels, average=average, sample_weight=sample_weight, zero_division=zero_division) avg = [avg_p, avg_r, avg_f1, np.sum(s)] if output_dict: report_dict[line_heading] = dict( zip(headers, [i.item() for i in avg])) else: if line_heading == 'accuracy': row_fmt_accuracy = '{:>{width}s} ' + \ ' {:>9.{digits}}' * 2 + ' {:>9.{digits}f}' + \ ' {:>9}\n' report += row_fmt_accuracy.format(line_heading, '', '', *avg[2:], width=width, digits=digits) else: report += row_fmt.format(line_heading, *avg, width=width, digits=digits) if output_dict: if 'accuracy' in report_dict.keys(): report_dict['accuracy'] = report_dict['accuracy']['precision'] return report_dict else: return report
bf900670dee3ba3988ae987dd1a7067949bd224b
34,741
def paralog_cn_str(paralog_cn, paralog_qual, min_qual_value=5): """ Returns - paralog CN: string, - paralog qual: tuple of integers, - any_known: bool (any of the values over the threshold). If paralog quality is less than min_qual_value, corresponding CN is replaced with '?' and quality is replaced with 0. Additionally, quality is rounded down to integers. """ paralog_cn_str = [] new_paralog_qual = [] any_known = False for cn, qual in zip(paralog_cn, paralog_qual): if qual < min_qual_value: paralog_cn_str.append('?') new_paralog_qual.append(0) else: paralog_cn_str.append(str(cn)) new_paralog_qual.append(int(qual)) any_known = True return ','.join(paralog_cn_str), tuple(new_paralog_qual), any_known
07012dd9b065622365798ba65024c316cdb8c0c7
34,742
def offbyK(s1,s2,k): """Input: two strings s1,s2, integer k Process: if both strings are of same length, the function checks if the number of dissimilar characters is less than or equal to k Output: returns True when conditions are met otherwise False is returned""" if len(s1)==len(s2): flag=0 for i in range(len(s1)): if s1[i]!=s2[i]: flag=flag+1 if flag==k: return True else: return False else: return False
a64c02b85acca64427852fc988ed2f769f750aa7
34,743
def calc_e_Gx(trainDataArr, trainLabelArr, n, div, rule, D): """计算分类错误率""" e = 0 # 初始化误分类误差率为0 x = trainDataArr[:, n] y = trainLabelArr predict = [] if rule == 'LisOne': L = 1 H = -1 else: L = -1 H = 1 for i in range(trainDataArr.shape[0]): if x[i] < div: predict.append(L) if y[i] != L: e += D[i] elif x[i] >= div: predict.append(H) if y[i] != H: e += D[i] return np.array(predict), e
6b282e078746be5ba90944cfedfabf64e29fc1c6
34,744
from typing import Dict from typing import List from typing import Union def compute_gap( gold_mapping: Dict[str, int], ranked_candidates: List[str], ) -> Union[float, None]: """ Method for computing GAP metric. Args: gold_mapping: Dictionary that maps gold word to its annotators number. ranked_candidates: List of ranked candidates. Returns: gap: computed GAP score. """ if not gold_mapping: return None cumsum = np.cumsum(list(gold_mapping.values())) arange = np.arange(1, len(gold_mapping) + 1) gap_denominator = (cumsum / arange).sum() gap_nominator = compute_gap_nominator(ranked_candidates, gold_mapping) return gap_nominator / gap_denominator
1701679c313e96792596ffa6623cb0aec4d2ca2a
34,745
def SmiNetDate(python_date): """ Date as a string in the format `YYYY-MM-DD` Original xsd documentation: SmiNetLabExporters datumformat (ÅÅÅÅ-MM-DD). """ return python_date.strftime("%Y-%m-%d")
8d43d99516fed915b344f42da8171689f8f9ef0b
34,746
def get_node_with_children(node, model): """ Return a short list of this top node and all its children. Note, maximum depth of 10. """ if node is None: return model new_model = [node] i = 0 # not really needed, but keep for ensuring an exit from while loop new_model_changed = True while model != [] and new_model_changed and i < 10: new_model_changed = False append_list = [] for n in new_model: for m in model: if m['supercatid'] == n['catid']: append_list.append(m) for n in append_list: new_model.append(n) model.remove(n) new_model_changed = True i += 1 return new_model
6ea214063f7937eacec5bbe5abd5c78c5b7badbd
34,747
def correct_capitalization(s): """Capitalizes a string with various words, except for prepositions and articles. :param s: The string to capitalize. :return: A new, capitalized, string. """ toret = "" if s: always_upper = {"tic", "i", "ii", "iii", "iv", "v", "vs", "vs.", "2d", "3d", "swi", "gnu", "c++", "c/c++", "c#"} articles = {"el", "la", "las", "lo", "los", "un", "unos", "una", "unas", "a", "an", "the", "these", "those", "that"} preps = {"en", "de", "del", "para", "con", "y", "e", "o", "in", "of", "for", "with", "and", "or"} words = s.strip().lower().split() capitalized_words = [] for word in words: if word in always_upper: word = word.upper() elif (not word in articles and not word in preps): word = word.capitalize() capitalized_words.append(word) toret = ' '.join(capitalized_words) return toret
f49b3203bf7ea19b84ac707bcc506c2571082e39
34,748
def mockedservice(fake_service=None, fake_types=None, address='unix:@test', name=None, vendor='varlink', product='mock', version=1, url='http://localhost'): """ Varlink mocking service To mock a fake service and merely test your varlink client against. The mocking feature is for testing purpose, it's allow you to test your varlink client against a fake service which will returned self handed result defined in your object who will be mocked. Example: >>> import unittest >>> from varlink import mock >>> import varlink >>> >>> >>> types = ''' >>> type MyPersonalType ( >>> foo: string, >>> bar: string, >>> ) >>> ''' >>> >>> >>> class Service(): >>> >>> def Test1(self, param1: int) -> dict: >>> ''' >>> return test: MyPersonalType >>> ''' >>> return { >>> "test": { >>> "foo": "bim", >>> "bar": "boom" >>> } >>> } >>> >>> def Test2(self, param1: str) -> dict: >>> ''' >>> return (test: string) >>> ''' >>> return {"test": param1} >>> >>> def Test3(self, param1: int) -> dict: >>> ''' >>> return (test: int, boom: string, foo: string, bar: 42) >>> ''' >>> return { >>> "test": param1 * 2, >>> "boom": "foo", >>> "foo": "bar", >>> "bar": 42, >>> } >>> >>> >>> class TestMyClientWithMockedService(unittest.TestCase): >>> >>> @mock.mockedservice( >>> fake_service=Service, >>> fake_types=types, >>> name='org.service.com', >>> address='unix:@foo' >>> ) >>> def test_my_client_against_a_mock(self): >>> with varlink.Client("unix:@foo") as client: >>> connection = client.open('org.service.com') >>> self.assertEqual( >>> connection.Test1(param1=1)["test"]["bar"], "boom") >>> self.assertEqual( >>> connection.Test2(param1="foo")["test"], "foo") >>> self.assertEqual( >>> connection.Test3(param1=6)["test"], 12) >>> self.assertEqual( >>> connection.Test3(param1=6)["bar"], 42) First you need to define a sample class that will be passed to your decorator `mock.mockedservice` and then a service will be initialized and launched automatically, and after that you just need to connect your client to him and to establish your connection then now you can call your methods and it will give you the expected result. You can also mock some types too, to help you to mock more complex service and interfaces like podman by example. You can define the return type by using the method docstring like the method Test1 in our previous example. The mocking module is only compatible with python 3 or higher version of python because this module require annotation to generate interface description. If you try to use it with python 2.x it will raise an ``ImportError``. """ def decorator(func): def wrapper(*args, **kwargs): with MockedService(fake_service, fake_types, name=name, address=address): try: func(*args, **kwargs) except BrokenPipeError: # manage fake service stoping pass return return wrapper return decorator
b318f44b3091cf332922a59222795a61d2a0d48e
34,749
def dsigmoid(x): """ return differential for sigmoid """ ## # D ( e^x ) = ( e^x ) - ( e^x )^2 # - --------- --------- --------- # Dx (1 + e^x) (1 + e^x) (1 + e^x)^2 ## return x * (1 - x)
685362146d7bfcaa3df47db8a10a04e6accb805d
34,750
def get_filetype(location): """ LEGACY: Return the best filetype for location using multiple tools. """ T = get_type(location) return T.filetype_file.lower()
8fcb9f7fc77f4a50e5c20a5d46b7f6699520a314
34,751
def eps_r_op_2s_AA12(x, AA12, A3, A4, op): """Implements the right epsilon map with a non-trivial nearest-neighbour operator. Uses a pre-multiplied tensor for the ket AA12[s, t] = A1[s].dot(A2[t]). See eps_r_op_2s_A(). Parameters ---------- x : ndarray The argument matrix. AA12: ndarray The combined MPS ket tensor for the first and second sites. A3: ndarray The MPS bra tensor for the first site. A4: ndarray The MPS bra tensor for the second site. op: ndarray Nearest-neighbour operator matrix elements op[s, t, u, v] = <st|op|uv> Returns ------ res : ndarray The resulting matrix. """ res = np.zeros((AA12.shape[2], A3.shape[1]), dtype=A3.dtype) zeros_like = np.zeros_like for u in xrange(A3.shape[0]): for v in xrange(A4.shape[0]): subres = zeros_like(AA12[0, 0]) for s in xrange(AA12.shape[0]): for t in xrange(AA12.shape[1]): opval = op[u, v, s, t] if opval != 0: subres += opval * AA12[s, t] res += subres.dot(x.dot((A3[u].dot(A4[v])).conj().T)) return res
661528e04d56e78c399f7c0db7964f11eaba3441
34,752
def _bem_specify_coils(bem, coils, coord_frame, n_jobs): """Set up for computing the solution at a set of coils""" # Compute the weighting factors to obtain the magnetic field # in the linear potential approximation coils, coord_frame = _check_coil_frame(coils, coord_frame, bem) # leaving this in in case we want to easily add in the future #if method != 'simple': # in ['ferguson', 'urankar']: # raise NotImplementedError #else: func = _bem_lin_field_coeffs_simple # Process each of the surfaces rmags = np.concatenate([coil['rmag'] for coil in coils]) cosmags = np.concatenate([coil['cosmag'] for coil in coils]) counts = np.array([len(coil['rmag']) for coil in coils]) ws = np.concatenate([coil['w'] for coil in coils]) lens = np.cumsum(np.r_[0, [len(s['rr']) for s in bem['surfs']]]) coeff = np.empty((len(counts), lens[-1])) for o1, o2, surf, mult in zip(lens[:-1], lens[1:], bem['surfs'], bem['field_mult']): coeff[:, o1:o2] = _lin_field_coeff(surf, mult, rmags, cosmags, ws, counts, func, n_jobs) # put through the bem sol = np.dot(coeff, bem['solution']) return sol
b860dbaf3d844248d75c69d7c45aefabe76b28e9
34,753
def extract_plate_and_well_names(col_meta, plate_field=PLATE_FIELD, well_field=WELL_FIELD): """ Args: col_meta (pandas df) plate_field (string): metadata field for name of plate well_field (string): metadata field for name of well Returns: plate_names (numpy array of strings) well_names (numpy array of strings) """ # Extract plate metadata plate_names = col_meta[plate_field].values # Extract well metadata well_names = col_meta[well_field].values return plate_names, well_names
0aa3a34a537183fca17e6575853df628f1204b62
34,754
import torch from typing import List from typing import Any import itertools def apply_masked_reduction_along_dim(op, input, *args, **kwargs): """Applies reduction op along given dimension to strided x elements that are valid according to mask tensor. The op is applied to each elementary slice of input with args and kwargs with the following constraints: 1. Prior applying the op: A. if kwargs contains an item with key 'dim_position' then it is removed from kwargs. The value of 'dim_position' is an integer that describes the dim argument position: while typically the dim argument appears at the 0-th position of the op arguments (excluding input), for instance, sum(input, dim), then there exists reductions that have extra arguments prior the dim argument, for instance, norm(input, ord, dim). B. if args or kwargs contains dim or keepdim arguments, these will be removed or replaced with None so that the op is applied to elementary slice using the default dim and keepdim value. 2. The elementary slice of the input is defined as the flattened slice that has no masked out elements and when op is applied, the result will be a scalar value (assuming keepdim=False). For example, an input tensor to a reduction operation op having dim=0 and keepdim=True argument: [[1 * 2 * *] [* 3 4 * 5]] (* denotes masked out elements) has the following elementary slices: [1, 2] and [3, 4, 5]. The result of apply_masked_reduction_along_dim is [[op([1, 2], *args0, **kwargs, dim=None, keepdim=False)] [op([3, 4, 5], *args0, **kwargs, dim=None, keepdim=False)]] where args0 is args where dim value is replased with None if present. Using the same example data, if the op is called with dim=(0, 1) and keepdim=False, there is one elementary slice: [1, 2, 3, 4, 5]; and the corresponding result of the op is: op([1, 2, 3, 4, 5], *args0, **kwargs, dim=None, keepdim=False) 3. If the elementary slice is empty, the corresponding output value is nan if dtype is float, otherwise, 0. An empty elementary slice corresponds to fully masked-out output, so, the corresponding specific value of the output will not be important because we used masked equality check for comparing the results of masked operations. """ # eliminate mask and dim_position keyword arguments: mask = kwargs.pop('mask', None) dim_pos = kwargs.pop('dim_position', 0) dtype = kwargs.get('dtype', input.dtype) if input.ndim == 0: # scalar input is an elementary slice return op(input, *args, **kwargs).to(dtype=dtype) # eliminate keepdim keyword argument if specified: keepdim = kwargs.pop('keepdim', False) # eliminate dim argument that may appear both as args or kwargs # element: if dim_pos < len(args): # dim is specified in args assert 'dim' not in kwargs, (args, kwargs) dim = args[dim_pos] args0 = args[:dim_pos] + (None,) + args[dim_pos + 1:] else: # dim may be specified in kwargs dim = kwargs.pop('dim', None) args0 = args # dimensions along which the reduction operation is applied: dim_ = torch._masked._canonical_dim(dim, input.ndim) # slices in product(*ranges) define all elementary slices: ranges: List[Any] = [] # shape of output for the keepdim=True case: shape = [] for i in range(input.ndim): if i in dim_: ranges.append((slice(None),)) shape.append(1) else: ranges.append(range(input.shape[i])) shape.append(input.shape[i]) # keepdim=True version of the output, filled with nan or 0: output = input.new_full(shape, float('nan') if dtype.is_floating_point else 0, dtype=dtype) # apply op to all elementary slices: inpmask = torch._masked._input_mask(input, mask=mask) for s in itertools.product(*ranges): # data of an elementary slice is 1D sequence and has only # masked-in elements: data = input[s].flatten()[inpmask[s].flatten().argwhere()] if not data.numel(): # empty elementary slice continue output[s][0] = op(data, *args0, **kwargs) if not keepdim: # reshape output for the keepdim=False case shape = [shape[i] for i in range(len(shape)) if i not in dim_] output = output.reshape(shape) return output
ccc1364404ca359732f85a470284310b852f4287
34,755
def index_gen(x): """Index generator. """ indices = np.arange(*x, dtype='int').tolist() inditer = it.product(indices, indices) return inditer
1ef5cd55ea7a8627bc2a1a14425035a2c5f7172e
34,756
def pad_xr_dims(input_xr, padded_dims=None): """Takes an xarray and pads it with dimensions of size 1 according to the supplied dims list Inputs input_xr: xarray to pad padded_dims: ordered list of final dims; new dims will be added with size 1. If None, defaults to standard naming scheme for pipeline Outputs padded_xr: xarray that has had additional dims added of size 1 Raises: ValueError: If padded dims includes existing dims in a different order ValueError: If padded dims includes duplicate names """ if padded_dims is None: padded_dims = ["fovs", "stacks", "crops", "slices", "rows", "cols", "channels"] # make sure that dimensions which are present in both lists are in same order old_dims = [dim for dim in padded_dims if dim in input_xr.dims] if not old_dims == list(input_xr.dims): raise ValueError("existing dimensions in the xarray must be in same order") if len(np.unique(padded_dims)) != len(padded_dims): raise ValueError('Dimensions must have unique names') # create new output data output_vals = input_xr.values output_coords = [] for idx, dim in enumerate(padded_dims): if dim in input_xr.dims: # dimension already exists, using existing values and coords output_coords.append(input_xr[dim]) else: output_vals = np.expand_dims(output_vals, axis=idx) output_coords.append(range(1)) padded_xr = xr.DataArray(output_vals, coords=output_coords, dims=padded_dims) return padded_xr
73f558b010527360f47b6558350a929041557cce
34,757
from datetime import datetime def get_list_projects_xlsx(proposals): """ Excel export of proposals with sharelinks :param proposals: :return: """ wb = Workbook() # grab the active worksheet ws = wb.active ws.title = "BEP Projects" ws['A1'] = 'Projects from {}'.format(settings.NAME_PRETTY) ws['A1'].style = 'Headline 2' ws['F1'] = "Exported on: " + str(datetime.now()) header = ['Title', 'Track', 'Research Group', 'Responsible', 'email', 'Sharelink'] h = ['A', 'B', 'C', 'D', 'E', 'F'] ws.append(header) for hr in h: ws.column_dimensions[hr].width = 25 ws[hr + '2'].style = 'Headline 3' ws.column_dimensions['F'].width = 100 for p in proposals: ws.append([p.Title, str(p.Track), str(p.Group), p.ResponsibleStaff.usermeta.get_nice_name(), p.ResponsibleStaff.email, get_share_link(p.pk)]) return save_virtual_workbook(wb)
668e70eb5d9d61ac879a270cdce54953fd7c2f5b
34,758
import logging def get(model=None, algorithm=None, trainer=None): """Get an instance of the server.""" if hasattr(Config().server, 'type'): server_type = Config().server.type else: server_type = Config().algorithm.type if server_type in registered_servers: logging.info("Server: %s", server_type) registered_server = registered_servers[server_type](model=model, algorithm=algorithm, trainer=trainer) else: raise ValueError('No such server: {}'.format(server_type)) return registered_server
e2c93998424ea381b8638408512181e5c50a2839
34,759
def par_impar(n): """ Par Impar Admite un numero y evalua si es par Parameters ----------- n : int Numero a evaluar Returns ------- bool Resultado de evaluar si es par el numero """ if n%2 == 0 : return True else: return False
c81141b3fad9ed2cdb5537867a7414cd4e7ec03d
34,760
import csv def get_attacks_percent (a_data, a_index, dataset= None): """ Return the % for each attack in a_index of the dataset """ percents = {} attacks = {} #for a, index in attacks_map.items(): #percents[a]= 0 for a, index in _attack_classes.items(): percents[a] = 0 total = 0 if dataset is None: print('Dont open file here') for row in np.transpose(a_data)[a_index]: total += 1 for a, index in _attack_classes_num.items(): #print(str(row)) if row[a_index] == index : percents[a]=percents[a]+1 break else: with open(dataset, 'r') as file: reader = csv.reader(file, delimiter = ',') for row in reader: total += 1 for a, index in attacks_map.items(): if row[a_index] == a : #percents[a]=percents[a]+1 four_attack = _attack_classes[row[variable_index]] percents[four_attack] = percents[four_attack]+1 break for a, index in attacks_map.items(): percents[a]= 100*percents[a]/total return percents
bd86b9ef507790aca4be8d7a8a371e8000253065
34,761
import requests import json import collections def do_login(user, password): """Log-in and return auth token""" login_payload = { "login": { "email": user, "password": password } } login_response = requests.post(URL_LOGIN, json=login_payload) login_ans = json.loads(login_response.text) id_token = login_ans['auth']['id_token'] token = collections.namedtuple('AuthToken', ['user_id', 'header']) token.user_id = login_ans['user']['id'] token.header = {'Authorization': 'Bearer ' + id_token} return token
fe3a8158e7539f69eaa6c7f3daf4e9a5c3fa0770
34,762
def pow(x, y): """Return x raised to the power y. :type x: numbers.Real :type y: numbers.Real :rtype: float """ return 0.0
618f0e03b7d6f476d7fbde8fcbeb699ce23d2a6c
34,763
def make_secondary_variables(): """Make secondary variables for modelling""" secondary = read_secondary() secondary_out = secondary.rename(columns={"geography_code": "geo_cd"})[ ["geo_cd", "variable", "value"] ] compl = make_complexity() return pd.concat([secondary_out, compl])
0faaa916c1251fa61b3438f59b05c5ff21f8f253
34,764
def normalize_tuple(value, rank): """Repeat the value according to the rank.""" value = nest.flatten(value) if len(value) > rank: return (value[i] for i in range(rank)) else: return tuple([value[i] for i in range(len(value))] + [value[-1] for _ in range(len(value), rank)])
1c1c105c50399770029e48c05ba998b921e8c834
34,765
def standard_Purge(*args): """ * Deallocates the storage retained on the free list and clears the list. Returns non-zero if some memory has been actually freed. :rtype: int """ return _Standard.standard_Purge(*args)
7accaa2d1686ef54a2e233f563ee47f962fa418a
34,766
def metrics(label: np.ndarray, pred: np.ndarray, num_class: int): """ :param label: (h, w) :param pred: (h, w) :param num_class: :return: """ label = label.astype(np.uint8) pred = np.round(pred) mat: np.ndarray = np.zeros((num_class, num_class)) [height, width] = label.shape for i in range(height): for j in range(width): pixel_label = label[i][j] pixel_pred = pred[i][j] mat[pixel_label][pixel_pred] += 1 total_is = np.sum(mat, axis=1) # 水平和 total_n_jis = np.sum(mat, axis=0) # 竖直和 ious = [] # a list of intersection over union for each i t_n_ii = [] # the total number of pixels of class i that is correctly predicted total_iou_n_ii = [] # a list of (iou * n_ii) for each i total_n_ii_divied_t_i = [] for i in range(1, num_class): # calculate iou for class in [1, num_class] n_ii = mat[i][i] # the number of pixels of class i that is correctly predicted total_i = total_is[i] # the total number of pixels of class i total_n_ji = total_n_jis[i] # the total number of pixels predicted to be class i # Ignore the category that doesn't show in the image. if total_i == 0: continue t_n_ii.append(n_ii) total_n_ii_divied_t_i.append(n_ii * 1.0 / total_i) # Calculate iou. if n_ii == 0: iou = 0 # intersection over union else: iou = (n_ii + 0.0) / (total_i + total_n_ji - n_ii) total_iou_n_ii.append(iou * total_i) ious.append(iou) # print(ious) pixel_acc = np.sum(t_n_ii) / np.sum(mat[1:, 1:]) mean_acc = np.sum(total_n_ii_divied_t_i) / len(t_n_ii) mean_intersection_over_union = np.mean(np.array(ious)) frequency_weighted_iu = np.sum(total_iou_n_ii) * 1.0 / np.sum(mat) return pixel_acc, mean_acc, mean_intersection_over_union, frequency_weighted_iu
26409f0645fa0f47b4241cbb2c9804299ed34f22
34,767
def is_transpositionally_related(set1, set2): """ Returns a tuple consisting of a boolean that tells if the two sets are transpositionally related, the transposition that maps set1 to set2, and the transposition that maps set2 to set1. If the boolean is False, the transpositions are None. Params: * set1 (tuple or string): the pitches of the first set * set2 (tuple or string): the pitches of the second set """ if isinstance(set1, tuple): set1 = _tuple_to_string(set1) if isinstance(set2, tuple): set2 = _tuple_to_string(set2) set1 = normalize(set1) set2 = normalize(set2) set1 = normal_form(set1) set2 = normal_form(set2) set1_intervals = get_intervals(set1, use_mod_12=True) set2_intervals = get_intervals(set2, use_mod_12=True) if set1_intervals != set2_intervals: return (False, None, None) # set2 = Tn(set1) # set1 = Tm(set2) set2_minus_set1 = [mod_12(x[1] - x[0]) for x in zip(set1, set2)] if float(sum(set2_minus_set1)) / float(len(set2_minus_set1)) \ == float(set2_minus_set1[0]): # return (True, n, m) return (True, set2_minus_set1[0], mod_12(12 - set2_minus_set1[0])) else: return (False, None, None)
4eb7375de84af2b531b330bf5a0aaa6d3b7825dc
34,769
from typing import List def find_dimension_coordinate_mismatch( first_cube: Cube, second_cube: Cube, two_way_mismatch: bool = True ) -> List[str]: """Determine if there is a mismatch between the dimension coordinates in two cubes. Args: first_cube: First cube to compare. second_cube: Second cube to compare. two_way_mismatch: If True, a two way mismatch is calculated e.g. second_cube - first_cube AND first_cube - second_cube If False, a one way mismatch is calculated e.g. second_cube - first_cube Returns: List of the dimension coordinates that are only present in one out of the two cubes. """ first_dim_names = [coord.name() for coord in first_cube.dim_coords] second_dim_names = [coord.name() for coord in second_cube.dim_coords] if two_way_mismatch: mismatch = list(set(second_dim_names) - set(first_dim_names)) + list( set(first_dim_names) - set(second_dim_names) ) else: mismatch = list(set(second_dim_names) - set(first_dim_names)) return mismatch
64ffb776e652a68aee39ccfcb4b5dc718ca46b44
34,770
def patch_python(filename, dart=False, python='PYTHONJS', backend=None): """Rewrite the Python code""" code = patch_assert(filename) ## a main function can not be simply injected like this for dart, ## because dart has special rules about what can be created outside ## of the main function at the module level. #if dart: # out = [] # main_inserted = False # for line in code.splitlines(): # if line.startswith('TestError') or line.startswith('TestWarning'): # if not main_inserted: # out.append('def main():') # main_inserted = True # out.append( '\t'+line ) # else: # out.append( line ) # code = '\n'.join( out ) a = [ _patch_header, 'PYTHON="%s"'%python, 'BACKEND="%s"'%backend, code ] if not dart: a.append( 'main()' ) return '\n'.join( a )
20909844b686e9887aee893c9d7cb2759c64bb75
34,771
from typing import List from typing import Union def get_standard_binary_metrics() -> List[Union[AUC, str, BinaryMetric]]: """Return standard list of binary metrics. The set of metrics includes accuracy, balanced accuracy, AUROC, AUPRC, F1 Score, Recall, Specificity, Precision, Miss rate, Fallout and Matthews Correlation Coefficient. """ return [ *get_minimal_multiclass_metrics(), F1Score(name="f1_score"), BalancedAccuracy(name="balanced_accuracy"), Specificity(name="specificity"), MissRate(name="miss_rate"), FallOut(name="fall_out"), MatthewsCorrelationCoefficient(name="mcc"), ]
7f21eb48a84cda194343c75e9416deb6f7157081
34,772
def Xor(n): """Return a DataSet with n examples of 2-input xor.""" return Parity(2, n, name="xor")
5f4682413eb21ecb05506762405347678f7ad699
34,773
def feature_selection(dataframe, method, missing_value_threshold=60, variance_threshold=0, correlation_threshold=0.75, target_variable=None, task=None, algorithm='RandomForest', n_features_to_select=5, scoring=None, cv=5, n_jobs=None): """ This function is used for selecting set of important Independent features for given dataset. Parameters: dataframe : Dataset in the form of Dataframe as input. method: Method for Feature Selection; Valid parameter:['missing_value_filter','low_variance_filter','feature_importance','high_correlation_filter','Forward','Backward'] missing_value_threshold: Mising threshold value for Missing value filter method, default value is 60 variance_threshold: Variance threshold value for Low variance filter method, default value is 0 correlation_threshold: Integer value (0,1),Correlation threshold value for High Correlation Filter method ;default value is 0.75 target_variable: Consider dependent variable of dataset task: Used for feature importance, forward and backward methods; Valid parameter:["Classification","Regression"] #estimators: algorithm to use. used for feature importance, forward and backward methods. algorithm: algorithm to use. used for feature importance, forward and backward methods. n_features_to_select: Any Integer value less than total number of independent features in dataset, the number of features to select for forward and backward method ; default = 5 scoring: metric function defined for Classification and Regression task for forward and backward method. cv: Integer value, determines the cross-validation splitting strategy. n_jobs: Number of jobs to run in parallel. :rtype: Modified data wirh respect to the input method. """ # To check if columns dataframe is not empty list assert len(dataframe) > 0, "Please ensure that Dataframe is not empty" # To make sure that input provided with Pandas Dataframe assert (isinstance(dataframe, pd.DataFrame)), "Make sure Input is DataFrame" # Check supported methods allowed_method = ['missing_value_filter', 'low_variance_filter', 'feature_importance', 'high_correlation_filter', 'forward', 'backward'] method = method.lower() assert method in allowed_method, f"Please select *method* from {allowed_method}" if method == 'missing_value_filter': # Calculate missing ratio percentage of each column in dataframe missing_value = dataframe.isnull().sum() / len(dataframe) # Checking of Missing value Threshold missing_value_imputed = missing_value[missing_value <= missing_value_threshold] reduced_data = dataframe[missing_value_imputed.index] elif method == 'low_variance_filter': df = dataframe.select_dtypes([np.number]) data_scaled = normalize(df) data_scaled = pd.DataFrame(data_scaled) variance = data_scaled.var() # Checking of Variance Threshold high_variance_columns = list(variance[variance >= variance_threshold].index) reduced_data = dataframe.iloc[:, high_variance_columns] elif method == 'high_correlation_filter': df_corr = dataframe.corr() # Retrieving upper triangle correlation coefficient from correlation grid df_corr = df_corr.mask(np.tril(np.ones(df_corr.shape)).astype(np.bool)) # Checking of Correlation threshold if correlation_threshold > 0: reduced_data = df_corr[df_corr >= correlation_threshold].stack().reset_index() else: reduced_data = df_corr[df_corr <= correlation_threshold].stack().reset_index() reduced_data = reduced_data.rename( columns={"level_0": 'Feature_1', "level_1": 'Feature_2', 0: 'correlation_coefficient'}) elif method == 'feature_importance': if target_variable is None: raise ValueError("Please enter a valid target_variable") # Check supported models allowed_task = ['classification', 'regression'] if task is None: raise ValueError(f"Please select *task* from {allowed_task}") task = task.lower() assert task in allowed_task, f"Please select *task* from {allowed_task}" # Check supported models allowed_algorithm = ["RandomForest", "XGradientBoosting", "DecisionTrees", "ExtraTrees"] assert algorithm in allowed_algorithm, f"Please select *algorithm* from {allowed_algorithm}" X = dataframe.drop(target_variable, axis=1) y = dataframe[target_variable] # preparation of dataset X_train, y_train = data_preparation(X, y) # Checking for algorithm and fitting of algorithm if task is None: raise ValueError("Please select Classification or Regression for 'task'") X = dataframe.drop(target_variable, axis=1) if algorithm == "RandomForest": model = RandomForestClassifier() if task == 'classification' else RandomForestRegressor() elif algorithm == "XGradientBoosting": model = XGBClassifier() if task == 'classification' else XGBRegressor() elif algorithm == "DecisionTrees": model = DecisionTreeClassifier() if task == 'classification' else DecisionTreeRegressor() elif algorithm == "ExtraTrees": model = ExtraTreesClassifier() if task == 'classification' else ExtraTreeRegressor() # Model-fitting model.fit(X_train, y_train) reduced_data = pd.DataFrame({'Features': X.columns, 'Importance': model.feature_importances_}) reduced_data = reduced_data.sort_values(by='Importance', ascending=False) elif method == "forward" or method == "backward": if target_variable is None: raise ValueError("Please enter a valid target_variable") direction = 'forward' if method == 'forward' else 'backward' # Check supported models allowed_task = ['classification', 'regression'] if task is None: raise ValueError(f"Please select *task* from {allowed_task}") task = task.lower() assert task in allowed_task, f"Please select *task* from {allowed_task}" # Check supported models allowed_algorithm = ["RandomForest", "XGradientBoosting", "DecisionTrees", "ExtraTrees"] allowed_algorithm = allowed_algorithm + [ "KNearestNeighbour"] if task == 'classification' else allowed_algorithm + ["LogisticRegression", "LinearRegression"] assert algorithm in allowed_algorithm, f"Please select *algorithm* from {allowed_algorithm}" X = dataframe.drop(target_variable, axis=1) y = dataframe[target_variable] # prepare input data X_train, y_train = data_preparation(X, y) # Checking for algorithm and fitting of algorithm if algorithm == "RandomForest": estimator = RandomForestClassifier() if task == 'classification' else RandomForestRegressor() elif algorithm == "XGradientBoosting": estimator = XGBClassifier() if task == 'classification' else XGBRegressor() elif algorithm == "DecisionTrees": estimator = DecisionTreeClassifier() if task == 'classification' else DecisionTreeRegressor() elif algorithm == "ExtraTrees": estimator = ExtraTreesClassifier() if task == 'classification' else ExtraTreeRegressor() elif algorithm == "KNearestNeighbour": estimator = KNeighborsClassifier() elif algorithm == "LinearRegression": estimator = LinearRegression() elif algorithm == "LogisticRegression": estimator = LogisticRegression() # Fitting of Sequential Feature Selector feature_selector = SequentialFeatureSelector(estimator=estimator, n_features_to_select=n_features_to_select, direction=direction, scoring=scoring, cv=cv, n_jobs=n_jobs).fit(X_train, y_train) feature_names = X.columns.values reduced_data = pd.DataFrame() reduced_data['Features_selected'] = feature_names[feature_selector.get_support()] return reduced_data
1b1b760f39a8e679ab0a3ab5d22f55047c3a71ab
34,774
import numpy def shaped_reverse_arange(shape, xp=nlcpy, dtype=numpy.float32): """Returns an array filled with decreasing numbers. Args: shape(tuple of int): Shape of returned ndarray. xp(numpy or nlcpy): Array module to use. dtype(dtype): Dtype of returned ndarray. Returns: numpy.ndarray or nlcpy.ndarray: The array filled with :math:`N, \\cdots, 1` with specified dtype with given shape, array module. Here, :math:`N` is the size of the returned array. If ``dtype`` is ``numpy.bool_``, evens (resp. odds) are converted to ``True`` (resp. ``False``). """ dtype = numpy.dtype(dtype) size = internal.prod(shape) a = numpy.arange(size, 0, -1) if dtype == '?': a = a % 2 == 0 elif dtype.kind == 'c': a = a + a * 1j if a.size > 0: return xp.array(a.astype(dtype).reshape(shape)) else: return xp.array(a.astype(dtype))
3f2634e8299d52a54b2fe2baba41b25187b1c720
34,775
def then(value): """ Creates an action that ignores the passed state and returns the value. >>> then(1)("whatever") 1 >>> then(1)("anything") 1 """ return lambda _state: value
5cf3f7b64b222a8329e961fa6c8c70f6c2c4cab0
34,776
def compute_cvm(predictions, masses, n_neighbours=200, step=50): """ Computing Cramer-von Mises (cvm) metric on background events: take average of cvms calculated for each mass bin. In each mass bin global prediction's cdf is compared to prediction's cdf in mass bin. :param predictions: array-like, predictions :param masses: array-like, in case of Kaggle tau23mu this is reconstructed mass :param n_neighbours: count of neighbours for event to define mass bin :param step: step through sorted mass-array to define next center of bin :return: average cvm value """ predictions = np.array(predictions) masses = np.array(masses) assert len(predictions) == len(masses) # First, reorder by masses predictions = predictions[np.argsort(masses)] # Second, replace probabilities with order of probability among other events predictions = np.argsort(np.argsort(predictions, kind='mergesort'), kind='mergesort') # Now, each window forms a group, and we can compute contribution of each group to CvM cvms = [] for window in __rolling_window(predictions, window_size=n_neighbours)[::step]: cvms.append(__cvm(subindices=window, total_events=len(predictions))) return np.mean(cvms)
cc34cb799211016d04d0431479252fb7fc77f186
34,777
import tqdm def get_pmat(index_df:PandasDf, properties:dict) -> tuple((PandasDf, PandasDf)): """ Run Stft analysis on signals retrieved using rows of index_df. Parameters ---------- index_df : PandasDf, experiment index properties: Dict Returns ------- index_df: PandasDf, experiment index power_df: PandasDf, with power matrix and frequency """ # drop rows containing NaNs index_df = index_df.dropna().reset_index() index_df = index_df.drop(['index'], axis = 1) # create empty series dataframe df = pd.DataFrame(np.empty((len(index_df), 2)), columns = ['freq', 'pmat'], dtype = object) for i in tqdm(range(len(index_df))): # iterate over dataframe # get properties file_properties = index_df[AdiGet.input_parameters].loc[i].to_dict() # get signal signal = AdiGet(file_properties).get_data_adi() # add sampling rate properties.update({'sampling_rate':int(file_properties['sampling_rate'])}) # Init Stft object with required properties selected_keys = Properties.types.keys() selected_keys = list(selected_keys) # select key-value pairs from dictionary selected_properties = {x: properties[x] for x in selected_keys} # convert time series to frequency domain stft_obj = Stft(selected_properties) df.at[i, 'freq'], df.at[i, 'pmat'] = stft_obj.run_stft(signal) return index_df, df
79da78dc8c9e63e8f8aee1ac96a079a5d6c626ab
34,778
def delete_upload_collection(upload_id: str) -> str: """Delete a multipart upload collection.""" uploads_db = uploads_database(readonly=False) if not uploads_db.has_collection(upload_id): raise UploadNotFound(upload_id) uploads_db.delete_collection(upload_id) return upload_id
c110ddf2d60e2f55a16b550f48abdfbc99c70975
34,779
import numpy def setup_hull(domain,isDomainFinite,abcissae,hx,hpx,hxparams): """setup_hull: set up the upper and lower hull and everything that comes with that Input: domain - [.,.] upper and lower limit to the domain isDomainFinite - [.,.] is there a lower/upper limit to the domain? abcissae - initial list of abcissae (must lie on either side of the peak in hx if the domain is unbounded hx - function that evaluates h(x) hpx - function that evaluates hp(x) hxparams - tuple of parameters for h(x) and h'(x) Output: list with: [0]= c_u [1]= xs [2]= h(xs) [3]= hp(xs) [4]= zs [5]= s_cum [6]= hu(zi) History: 2009-05-21 - Written - Bovy (NYU) """ nx= len(abcissae) #Create the output arrays xs= numpy.zeros(nx) hxs= numpy.zeros(nx) hpxs= numpy.zeros(nx) zs= numpy.zeros(nx-1) scum= numpy.zeros(nx-1) hus= numpy.zeros(nx-1) #Function evaluations xs= numpy.sort(abcissae) for ii in range(nx): hxs[ii]= hx(xs[ii],hxparams) hpxs[ii]= hpx(xs[ii],hxparams) #THERE IS NO CHECKING HERE TO SEE WHETHER IN THE INFINITE DOMAIN CASE #WE HAVE ABCISSAE ON BOTH SIDES OF THE PEAK #zi for jj in range(nx-1): zs[jj]= (hxs[jj+1]-hxs[jj]-xs[jj+1]*hpxs[jj+1]+xs[jj]*hpxs[jj])/( hpxs[jj]-hpxs[jj+1]) #hu for jj in range(nx-1): hus[jj]= hpxs[jj]*(zs[jj]-xs[jj])+hxs[jj] #Calculate cu and scum if isDomainFinite[0]: scum[0]= 1./hpxs[0]*(numpy.exp(hus[0])-numpy.exp( hpxs[0]*(domain[0]-xs[0])+hxs[0])) else: scum[0]= 1./hpxs[0]*numpy.exp(hus[0]) if nx > 2: for jj in range(nx-2): if hpxs[jj+1] == 0.: scum[jj+1]= (zs[jj+1]-zs[jj])*numpy.exp(hxs[jj+1]) else: scum[jj+1]=1./hpxs[jj+1]*(numpy.exp(hus[jj+1])-numpy.exp(hus[jj])) if isDomainFinite[1]: cu=1./hpxs[nx-1]*(numpy.exp(hpxs[nx-1]*( domain[1]-xs[nx-1])+hxs[nx-1]) - numpy.exp(hus[nx-2])) else: cu=- 1./hpxs[nx-1]*numpy.exp(hus[nx-2]) cu= cu+numpy.sum(scum) scum= numpy.cumsum(scum)/cu out=[] out.append(cu) out.append(xs) out.append(hxs) out.append(hpxs) out.append(zs) out.append(scum) out.append(hus) return out
9848b9cd08724b4c830d7590cd48a2d3047422e7
34,780
def get_candidates(arrange_mode_attr): """ According current `arrange_mode` and `condition`, to find out candidates data returns to caller return candidates for displaying Variables: arrange_mode: Different mode has different method to select candidates arrange_condition: The type_id list of data_type will be used by some arrange_mode orderById: According to arrange_mode, the candidates should sort by id or not conditionAssigned: According to arrange_mode, the candidates should in arrange_condition or not. """ try: return_msg = {} return_msg["result"] = "fail" deal_result = [] try: arrange_mode = arrange_mode_attr["arrange_mode"] arrange_condition = arrange_mode_attr.get('condition',[]) except: return_msg["error"] = "input parameter missing" return return_msg orderById = ModeUtil.checkOrderById(arrange_mode) conditionAssigned = ModeUtil.checkConditionAssigned(arrange_mode) with TextDao() as textDao: test_candidates= textDao.findActivities(conditionAssigned,orderById,arrange_mode,arrangeCondition=arrange_condition) with ImageDao() as imageDao: image_candidates= imageDao.findActivities(conditionAssigned,orderById,arrange_mode,arrangeCondition=arrange_condition) candidates = list(test_candidates) + list(image_candidates) for result_row in candidates: if len(result_row)==2: deal_result.append([result_row[0], int(result_row[1])]) elif len(result_row)==3: deal_result.append([result_row[0], int(result_row[1]), float(result_row[2])]) else: "DO NOTHING" candidates = ModeUtil.selectDisplayCandidates(arrange_mode,deal_result) return_msg["ans_list"] = candidates return_msg["result"] = "success" return return_msg except DB_Exception as e: return_msg["error"] = gen_error_msg(e.args[1]) return return_msg
1be9737ec48804589c8a711f7ae1ae0c70523020
34,781
def img_to_array(model_input: any) -> any: """Converts the incoming image into an array.""" model_input = keras.preprocessing.image.img_to_array(model_input) return model_input
bee59b1d6da102f2f11410f38c3e5587a28cf7b4
34,782
def add_word_vector_feature(dataset, propositionSet, parsedPropositions, word2VecModel=None, pad_no=35, has_2=True, ): """Add word2vec feature to the dataset """ if word2VecModel is None: KV = gensim.models.KeyedVectors word2VecModel = KV.load_word2vec_format(WORD2WEC_EMBEDDING_FILE, binary=True) wordVectorFeature = list() feature_vector = np.zeros(300) for proposition in parsedPropositions: propositionVector = list() for word in proposition: if word[0] in word2VecModel.vocab: feature_vector = word2VecModel[word[0]] propositionVector.append(feature_vector) wordVectorFeature.append(propositionVector) wordVectorFeature = np.array(wordVectorFeature) wordVectorFeature = kp_pad_sequences(wordVectorFeature, maxlen=pad_no, value=0, padding='post', dtype=float) wordVectorFrame = pd.DataFrame({'arg1': propositionSet, 'vector1': wordVectorFeature.tolist()}) dataset = pd.merge(dataset, wordVectorFrame, on='arg1') if has_2: wordVectorFrame = wordVectorFrame.rename(columns={'arg1': 'arg2', 'vector1': 'vector2', }) dataset = pd.merge(dataset, wordVectorFrame, on='arg2') return dataset
d9708b61c1a7f16d3ee35f9dfa4ccc2d0b8c96b7
34,783
def clustering(vertice): """Calcula el coeficiente de clustering de un vertice. Obs: Devuelve -1 si el coeficiente no es calculable. Pre: EL vertice existe y es de clase Vertice. """ # Cuento las conexiones (por duplicado) aristas_entre_vecinos = 0 for vecino in vertice.iter_de_adyacentes(): for segundo_vecino in vecino.iter_de_adyacentes(): if vertice.esta_conectado_a(segundo_vecino): aristas_entre_vecinos += 1 # Calculo coeficiente try: ady = vertice.cantidad_adyacentes() max_aristas_posibles = ady * (ady-1) return aristas_entre_vecinos / float(max_aristas_posibles) except ZeroDivisionError: return -1
0654ab7207174c47d9d0b626ca92894e6330612f
34,784
import requests def main(formato, full=False): """ Get dict of mains and dict of sides. :formato: str (e.g.: "standard" or "modern") :full: bool (True for scraping all decks from /full#paper and False for scraping only first decks from /#paper url) :return: """ url_start = "https://www.mtggoldfish.com/metagame/" if full is True: url_end = "/full#paper" else: url_end = "/#paper" mainboards = dict() sideboards = dict() url = url_start + formato + url_end print(f"Getting links from {url}") page = requests.get(url) links = grab_links(page.text).values() print(f"{len(links)} links grabbed!!\n") for link in links: print(f"Getting data from:\n{link}") try: page = requests.get(link).text name, mainb, side = scrape_deck_page(page) if name in mainboards: print(f"{name} is a CONFLICTING NAME and will not be saved.") else: mainboards[name] = mainb sideboards[name] = side except TimeoutError: print("The connection FAILED due to a TimeOut Error.") except Exception as e: print(e, "\n", link, "will not be scraped") return mainboards, sideboards
2f5bdcb98185e11bafc1b5aba0df28962c6c4890
34,785
def pipeline(img, mtx, dist): """ The pipeline applies all image pre-processing steps to the image (or video frame). 1) Undistort the image using the given camera matrix and the distortion coefficients 2) Warp the image to a bird's-eye view 3) Apply color space conversion :param img: Input image (BGR) :param mtx: Camera matrix :param dist: Distortion coefficients :return: Binary image, ideally only of the lane lines (in bird's-eye view) """ # Undistort image dst = undistort(img, mtx, dist) # Apply perpective transfomation warped = warp(dst) # Apply color space operations binary = cvt_color_space(warped) return binary
dd84f0296eb22cc41e0795c4e4c3821deb8e0896
34,786
def get_coverage_value(coverage_report): """ extract coverage from last line: TOTAL 116 22 81% """ coverage_value = coverage_report.split()[-1].rstrip('%') coverage_value = int(coverage_value) return coverage_value
ffd47b6c4ecec4851aab65dcb208ef776d12e36f
34,787
import textwrap def collapse_single_path(digraph, path): """ :param digraph: networkx.DiGraph :param path: list of nodes (simple path of digraph) :return: networkx.DiGraph with only first and last nodes and one edge between them The original graph is an attribute of the edge """ digraph_ordered = digraph.subgraph( path ) # in each element node 0 is card, node 1 is text part res = nx.DiGraph() # Add first and last nodes with their respective attributes res.add_node(path[0], **digraph.nodes[path[0]]) res.add_node(path[-1], **digraph.nodes[path[-1]]) # edge_attr = {'full_original_path_graph': digraph} edge_attr = {} labels = [] for i, node in enumerate(path): label = "" if not i: continue # dict: attributes of each edge in order e_at = digraph_ordered.edges[path[i - 1], node] edge_attr[f"edge-{i}"] = e_at label += e_at.get("part_type_full", None) or e_at.get("label") + ":" if dict(digraph_ordered[node]): # dict: attributes of each node in order n_at = dict(digraph_ordered.nodes[node]) edge_attr[f"node-{i}"] = dict(digraph_ordered.nodes[node]) label += n_at.get("label") labels.append(label) res.add_edge( path[0], path[-1], **edge_attr, label="".join(textwrap.wrap(f'{" | ".join(labels)}')), ) return res
f65c98bdc29ffc2cc51f8570f545093fb4afa709
34,788
import random def generate_data(train_test_split): """ Generates the training and testing data from the splited data :param train_test_split: train_test_split - array[list[list]]: Contains k arrays of training and test data splices of dataset Example: [[[0.23, 0.34, 0.33, 0.12, 0.45, 0.68], [0.13, 0.35, 0.01, 0.72, 0.25, 0.08], ....] , .... , [[0.12, 0.45, 0.23, 0.64, 0.67, 0.98], [0.20, 0.50, 0.23, 0.12, 0.32, 0.88], ....]] :param test_index: test_index - int : Index of the test data to be split from the train_test_split Example: 5 Yields: train_data: train_data - array[list]: Contains k arrays of train data of dataset Example: [[0.23, 0.34, 0.33, 0.12, 0.45, 0.68], [0.13, 0.35, 0.01, 0.72, 0.25, 0.08], ... , .... , [0.12, 0.45, 0.23, 0.64, 0.67, 0.98], [0.20, 0.50, 0.23, 0.12, 0.32, 0.88], ....] train_data: test_data - array[list]: Contains k arrays of test data of dataset Example: [[0.23, 0.34, 0.33, 0.12, 0.45, 0.68], [0.13, 0.35, 0.01, 0.72, 0.25, 0.08], ... , .... , [0.12, 0.45, 0.23, 0.64, 0.67, 0.98], [0.20, 0.50, 0.23, 0.12, 0.32, 0.88], ....] """ test_index = eval( input("\nPlease enter the partition number to be used as test data (Press 0 for random partition): ")) while type(test_index) != int: test_index = eval(input("\nPlease enter an integer values for the partition to be used as test data: ")) split = train_test_split[:] if test_index != 0: real_index = test_index - 1 else: real_index = random.randrange(0, len(split)) test_data = split[real_index] split.remove(test_data) train_data = [] for x in split: for y in x: train_data.append(y) return train_data, test_data
8de3cbab8b58be3ff7ff289d9aa8d3cd9e2581f8
34,789
import time def process_roses(stations, ncpus, roses_fp, discard_obs_fp): """ For each station we need one trace for each direction. Each direction has a data series containing the frequency of winds within a certain range. Columns: sid - stationid direction_class - number between 0 and 35. 0 represents directions between 360-005º (north), and so forth by 10 degree intervals. speed_range - text fragment from luts.py for the speed class month - 0 for year, 1-12 for month Args: stations (pandas.Dataframe): Processed raw station data Returns: filepath where pre-processed wind rose data was saved """ print("Preprocessing wind rose frequency counts.") tic = time.perf_counter() # drop gusts column, discard obs with NaN in direction or speed stations = stations.drop(columns="gust_mph").dropna() # set all nonzero wind speeds with 0 direction to 360. This might not be necessary. stations.loc[(stations["wd"] == 0) & (stations["ws"] != 0), "wd"] = 360 # first process roses for all available stations - that is, stations # with data at least as old as 2010-01-01 min_ts = stations.groupby("sid")["ts"].min() keep_sids = min_ts[min_ts < pd.to_datetime("2010-06-01")].index.values # stations to be used in the summary summary_stations = stations[stations["sid"].isin(keep_sids)].copy() # Set the decade column to "none" to indicate these are for all available data summary_stations["decade"] = "none" # set month column to 0 for annual rose data summary_stations["month"] = 0 # drop calms for chunking to rose summary_stations = summary_stations[summary_stations["ws"] != 0].reset_index( drop=True ) # create summary rose data # break out into df by station for multithreading station_dfs = [df for sid, df in summary_stations.groupby("sid")] with Pool(ncpus) as pool: summary_roses = pd.concat(pool.map(chunk_to_rose, station_dfs)) print(f"Summary roses done, {round(time.perf_counter() - tic, 2)}s.") tic = time.perf_counter() # now assign actual month, break up by month and station and re-process summary_stations["month"] = summary_stations["ts"].dt.month station_dfs = [df for items, df in summary_stations.groupby(["sid", "month"])] with Pool(ncpus) as pool: monthly_roses = pd.concat(pool.map(chunk_to_rose, station_dfs)) print(f"Monthly summary roses done, {round(time.perf_counter() - tic, 2)}s.") tic = time.perf_counter() # now focus on rose data for stations that will allow wind rose comparison # filter out stations where first obs is more recent than 1991-01-01 keep_sids = min_ts[min_ts < pd.to_datetime("1991-01-01")].index.values stations = stations[stations["sid"].isin(keep_sids)] # break out into df by station for multithreading # add 0 for month column first stations["month"] = 0 station_dfs = [df for sid, df in stations.groupby("sid")] # check sufficient data for each station, and return the station date for # only 2010s and the oldest decade available between 80s and 90s with Pool(ncpus) as pool: compare_station_dfs = pool.map( check_sufficient_comparison_rose_data, station_dfs ) compare_station_dfs = [df for df in compare_station_dfs if df is not None] # now can discard observations to achieve sampling parity between decades with Pool(ncpus) as pool: adjustment_results = pool.map(adjust_sampling, compare_station_dfs) # break up tuples of data/discarded data compare_station_dfs = [tup[0] for tup in adjustment_results] discarded_obs = pd.concat([tup[1] for tup in adjustment_results]) print( f"Station data adjusted, chunking comparison roses, {round(time.perf_counter() - tic, 2)}s." ) tic = time.perf_counter() # finally can chunk to rose for comparison roses - first filter out calms compare_station_dfs = [ df[df["ws"] != 0].reset_index(drop=True) for df in compare_station_dfs ] # then break up by decade for chunking to rose compare_station_dfs = [ df for station in compare_station_dfs for decade, df in station.groupby("decade") ] with Pool(ncpus) as pool: compare_roses = pd.concat(pool.map(chunk_to_rose, compare_station_dfs)) roses = pd.concat([summary_roses, monthly_roses, compare_roses]) # concat and pickle it roses.to_pickle(roses_fp) discarded_obs.to_csv(discard_obs_fp) print(f"Comparison roses done, {round(time.perf_counter() - tic, 2)}s.") print(f"Preprocessed data for wind roses written to {roses_fp}") print( f"Discarded observations for comparison wind roses written to {discard_obs_fp}" ) return roses
032e3f16dccd6361b036dcbd47ea41f1d723da0c
34,790
from typing import Tuple def find_tsm_marker(content: bytes, initial_key: bytes) -> Tuple[int, int]: """Search binary lua for an attribute start and end location.""" start = content.index(initial_key) brack = 0 bracked = False for _end, char in enumerate(content[start:].decode("ascii")): if char == "{": brack += 1 bracked = True if char == "}": brack -= 1 bracked = True if brack == 0 and bracked: break _end += start + 1 return start, _end
735bd61ed97654d9f78eee8dce055b06598ffb57
34,791
import torchvision def create_fashion_mnist_dataset(train_transforms, valid_transforms): """ Creates Fashion MNIST train dataset and a test dataset. Args: train_transforms: Transforms to be applied to train dataset. test_transforms: Transforms to be applied to test dataset. """ # This code can be re-used for other torchvision Image Dataset too. train_set = torchvision.datasets.FashionMNIST( "./data", download=True, train=True, transform=train_transforms ) valid_set = torchvision.datasets.FashionMNIST( "./data", download=True, train=False, transform=valid_transforms ) return train_set, valid_set
6d77907a715a9e7eabccb29dc62c4213f6748e10
34,792
def get_user_profile(request): """Method to get a user Recieves: request, relevant email Returns: httpresponse showing user """ if request.method != "POST": return HttpResponse("only POST calls accepted", status=404) #input validation try: user = User.objects.get(email=request.session["email"]) return JsonResponse(to_dict(UserProfile.objects.get(user=user))) except Exception as e: return HttpResponse(e, status=401)
f3298ca1f671fe28600d122ca3ea1554c26107db
34,793
async def read_product( *, product_id: int, db_product: Product = Depends(get_product_or_404) ): """ Get the product type by id """ # Le righe commentate sotto, sostituite dalla nuova Depends # Nota: il parametro product_id a get_product_or_404 è preso dal path # p = session.get(Product, product_id) # if not p: # raise HTTPException( # status_code=404, # detail="Product type not found" # ) profiling_api( f"Product:read:by_id:{product_id}", db_product["start_time"], db_product["username"], ) return db_product["db_product"]
8d31c7bd94959828a471bb3b521549db93b89ec3
34,794
def geometry_file_path(prefix, bath, pot): """ geometry file path """ return GEOMETRY_FILE.path([prefix, bath, pot])
45afe3bfcb49ecfcae6876e0d1e1bb9f9e15bf80
34,795
def find_hessian_diag(point, vars=None, model=None): """ Returns Hessian of logp at the point passed. Parameters ---------- model: Model (optional if in `with` context) point: dict vars: list Variables for which Hessian is to be calculated. """ model = modelcontext(model) H = model.fastfn(hessian_diag(model.logpt, vars)) return H(Point(point, model=model))
6998b6bf575babfec3fd97890bed315f26f21ac1
34,797
def apply_with_random_selector(x, func, num_cases): """Computes func(x, sel), with sel sampled from [0...num_cases-1]. Args: x: input Tensor. func: Python function to apply. num_cases: Python int32, number of cases to sample sel from. Returns: The result of func(x, sel), where func receives the value of the selector as a python integer, but sel is sampled dynamically. """ sel = tf.random_uniform([], maxval=num_cases, dtype=tf.int32) # Pass the real x only to one of the func calls. return control_flow_ops.merge([ func(control_flow_ops.switch(x, tf.equal(sel, case))[1], case) for case in range(num_cases)])[0]
7dae42b240932fa90e3d6dabceba05375a024c56
34,798
def fitted_model(dates, spectra_obs, max_iter, avg_days_yr, num_coefficients): """Create a fully fitted lasso model. Args: dates: list or ordinal observation dates spectra_obs: list of values corresponding to the observation dates for a single spectral band num_coefficients: how many coefficients to use for the fit max_iter: maximum number of iterations that the coefficients undergo to find the convergence point. Returns: sklearn.linear_model.Lasso().fit(observation_dates, observations) Example: fitted_model(dates, obs).predict(...) """ coef_matrix = coefficient_matrix(dates, avg_days_yr, num_coefficients) lasso = linear_model.Lasso(max_iter=max_iter) model = lasso.fit(coef_matrix, spectra_obs) predictions = model.predict(coef_matrix) rmse, residuals = calc_rmse(spectra_obs, predictions, num_pm=num_coefficients) return FittedModel(fitted_model=model, rmse=rmse, residual=residuals)
4754cafc79edfc52f47f925b909e3221c6b16f86
34,799
def example_bytes(values): """Input must be float32 np.array""" return tf.train.Example( features=tf.train.Features( feature={'dosages': _bytes_feature(values.tobytes())} ) )
1db2de7db6b93e414e7636107a40c510dda1cadd
34,800
def _build_extension_download_url( extension_name: str, publisher_name: str, version: str ) -> str: """ Build the download url for the given parameters. Just a shortcut for the string formatting. :param extension_name: Desired extension name. :type extension_name: str :param publisher_name: Desired extension publisher's name. :type publisher_name: str :param version: Desired extension version. :type version: str :return: The formatted download url. :rtype: str """ return MARKETPLACE_DOWNLOAD_LINK.format( extension_name=extension_name, publisher_name=publisher_name, version=version )
884ad99bb7e2d1c7d4fe7cc53f277962eb47414d
34,802