content
stringlengths
22
815k
id
int64
0
4.91M
def visualize_demux(base_dir, data_artifact): """ :param base_dir: Main working directory filepath :param data_artifact: QIIME2 data artifact object :return: QIIME2 demux visualization object """ logging.info('Visualizing demux...') # Path setup export_path = os.path.join(base_dir, 'demux_summary.qzv') # Prepare and save demux summary visualization demux_viz = demux.visualizers.summarize(data=data_artifact) demux_viz.visualization.save(export_path) logging.info('Saved {}'.format(export_path)) return demux_viz
8,000
def socfaker_dns_answers(): """ A list of DNS answers during a DNS request Returns: list: A random list (count) of random DNS answers during a DNS request """ if validate_request(request): return jsonify(str(socfaker.dns.answers))
8,001
def create_app(): """Create and configure and instance of the Flask Application""" app = Flask(__name__) # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3' app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('HEROKU_POSTGRESQL_COPPER_URL') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['ENV'] = config('ENV') DB.init_app(app) @app.route('/') def root(): return render_template('base.html', title='Home', users=User.query.all()) @app.route('/update') def update(): update_all_users() return render_template('base.html', title='Update all users!', users=User.query.all()) @app.route('/user', methods=['POST']) @app.route('/user/<name>', methods=['GET']) def user(name=None, message=''): name = name or request.values['user_name'] try: if request.method == 'POST': add_or_update_user(name) message = "User {} successfully added".format(name) tweets = User.query.filter(User.name == name).one().tweets except Exception as e: message = "Error adding {}: {}".format(name, e) return message else: return render_template('user.html', title=name, tweets=tweets, message=message) @app.route('/compare', methods=['POST']) def predict(message=''): user1, user2 = sorted((request.values['user1'], request.values['user2'])) if user1 == user2: message = 'Cannot compare a user the same user in both fields!' else: comparison = predict_user(user1, user2, request.values['tweet_text']) user1_name = comparison.user1_name user2_name = comparison.user2_name user1_prob = comparison.user1_prob user2_prob = comparison.user2_prob prediction = comparison.predicted_user message = '"{}" is more likely to be said by {} than {}'.format( request.values['tweet_text'], user1_name if prediction else user2_name, user2_name if prediction else user1_name) return render_template('prediction.html', title='Prediction', message=message, user1_name=user1_name, user1_prob=user1_prob, user2_name=user2_name, user2_prob=user2_prob ) @app.route("/reset") def reset(): DB.drop_all() DB.create_all() add_users() return render_template('base.html', title='Reset database!') return app
8,002
def bilin(x, y, data, datax, datay): # --DC """ x, y ARE COORDS OF INTEREST data IS 2x2 ARRAY CONTAINING NEARBY DATA datax, datay CONTAINS x & y COORDS OF NEARBY DATA""" lavg = ( (y - datay[0]) * data[1,0] + (datay[1] - y) * data[0,0] ) / (datay[1] - datay[0]) ravg = ( (y - datay[0]) * data[1,1] + (datay[1] - y) * data[0,1] ) / (datay[1] - datay[0]) return ( (x - datax[0]) * ravg + (datax[1] - x) * lavg ) / (datax[1] - datax[0])
8,003
def _process_asset(trackable_asset, asset_info, resource_map): """Add `trackable_asset` to `asset_info` and `resource_map`.""" original_path_tensor = trackable_asset.asset_path original_path = tensor_util.constant_value(original_path_tensor) try: original_path = str(original_path.astype(str)) except AttributeError: # Already a string rather than a numpy array pass path = builder_impl.get_asset_filename_to_add( asset_filepath=original_path, asset_filename_map=asset_info.asset_filename_map) # TODO(andresp): Instead of mapping 1-1 between trackable asset # and asset in the graph def consider deduping the assets that # point to the same file. asset_path_initializer = array_ops.placeholder( shape=original_path_tensor.shape, dtype=dtypes.string, name="asset_path_initializer") asset_variable = resource_variable_ops.ResourceVariable( asset_path_initializer) asset_info.asset_filename_map[path] = original_path asset_def = meta_graph_pb2.AssetFileDef() asset_def.filename = path asset_def.tensor_info.name = asset_path_initializer.name asset_info.asset_defs.append(asset_def) asset_info.asset_initializers_by_resource[original_path_tensor] = ( asset_variable.initializer) asset_info.asset_index[trackable_asset] = len(asset_info.asset_defs) - 1 resource_map[original_path_tensor] = asset_variable
8,004
def slice_data(xdata, ydata, x_range): """ crops or slices the data in xdata,ydata in the range x_range on the x axis """ data = zip(xdata, ydata) sliced_data = [d for d in data if d[0] >= x_range[0] and d[0] <= x_range[1]] return array(zip(*sliced_data))
8,005
def displaySmoothness(q=1,all=1,bn=1,dc=1,du="int",dv="int",f=1,hl=1,ps="int",pw="int",po="int",rt=1,su="int",sv="int"): """ http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/displaySmoothness.html ----------------------------------------- displaySmoothness is undoable, queryable, and NOT editable. This command is responsible for setting the display smoothness of NURBS curves and surfaces to either predefined or custom values. It also sets display modes for smoothness such as hulls and the hull simplification factors. At present, this command is NOT un-doable. ----------------------------------------- Return Value: None In query mode, return type is based on queried flag. ----------------------------------------- Flags: ----------------------------------------- all : all [boolean] ['query'] Change smoothness for all curves and surfaces ----------------------------------------- bn : boundary [boolean] ['query'] Display wireframe surfaces using only the boundaries of the surface Not fully implemented yet ----------------------------------------- dc : defaultCreation [boolean] ['query'] The default values at creation (applies only -du, -dv, -pw, -ps) ----------------------------------------- du : divisionsU [int] ['query'] Number of isoparm divisions per span in the U direction. The valid range of values is [0,64]. ----------------------------------------- dv : divisionsV [int] ['query'] Number of isoparm divisions per span in the V direction. The valid range of values is [0,64]. ----------------------------------------- f : full [boolean] ['query'] Display surface at full resolution - the default. ----------------------------------------- hl : hull [boolean] ['query'] Display surface using the hull (control points are drawn rather than surface knot points). This mode is a useful display performance improvement when modifying a surface since it doesn't require evaluating points on the surface. ----------------------------------------- ps : pointsShaded [int] ['query'] Number of points per surface span in shaded mode. The valid range of values is [1,64]. ----------------------------------------- pw : pointsWire [int] ['query'] Number of points per surface isoparm span or the number of points per curve span in wireframe mode. The valid range of values is [1,128]. Note: This is the only flag that also applies to nurbs curves. ----------------------------------------- po : polygonObject [int] ['query'] Display the polygon objects with the given resolution ----------------------------------------- rt : renderTessellation [boolean] ['query'] Display using render tesselation parameters when in shaded mode. ----------------------------------------- su : simplifyU [int] ['query'] Number of spans to skip in the U direction when in hull display mode. ----------------------------------------- sv : simplifyV [int] Number of spans to skip in the V direction when in hull display mode. """
8,006
def run(): """ Execute the rotation of AWS keys """ aws_profile = get_current_aws_profile() aws_credentials_file = get_aws_credentials_file() backup_aws_credentials(aws_credentials_file) aws_credentials = open_aws_credentials(aws_credentials_file) current_access_key = get_current_access_key_from_config(aws_credentials, aws_profile) new_access_key = create_new_access_key() aws_credentials.set(aws_profile, 'aws_access_key_id', new_access_key['AccessKeyId']) aws_credentials.set(aws_profile, 'aws_secret_access_key', new_access_key['SecretAccessKey']) write_aws_credentials(aws_credentials, aws_credentials_file) delete_old_access_key(current_access_key)
8,007
def main(): """ call GET /access/2/catalog/models/attributes and GET /access/2/catalog/models/referenceAttributes the /access/2/catalog/models/attributes call returns all attributes (system + custom), so we filter for only the custom attrs these start with "com.infa.appmodels.ldm. output - prints the attribute name, id and some other properties to console TODO: - add logging to file """ global resturl global verify global sess # create and initialize the header for the output csv file fCSVFile = open(outputFile, "w", newline="", encoding="utf-8") print("custom attributes csv file initialized: " + outputFile) colWriter = csv.writer(fCSVFile) colWriter.writerow(["Name", "Id", "Type", "Facetable", "Sortable", "AttributeType"]) # extract for all "attributes" baseurl = catalogUrl + "/access/2/catalog/models/" attrCount, custAttrCount = getCustomAttribute( sess, baseurl + "attributes", colWriter ) # extract all "referenceAttributes" allClassifications, classificationCount = getCustomAttribute( sess, baseurl + "referenceAttributes", colWriter ) print("") print("Finished - run time = %s seconds ---" % (time.time() - start_time)) print("total attributes=" + str(attrCount)) print("custom attributes=" + str(custAttrCount)) print("total classification attributes=" + str(allClassifications)) print("custom classification attributes=" + str(classificationCount)) fCSVFile.close() return
8,008
def best_low_rank(A, rank): """ Finding the best low rank approximation by SVD """ u, s, vh = np.linalg.svd(A) s = np.sqrt(s[:rank]) return u[:, range(rank)] @ np.diag(s), np.diag(s) @ vh[range(rank)]
8,009
def get_bangumi(uid: int, type_: str = "bangumi", limit: int = 114514, callback=None, verify: utils.Verify = None): """ 自动循环获取追番/追剧列表 :param callback: 回调函数 :param uid: :param type_: :param limit: :param verify: :return: """ if verify is None: verify = utils.Verify() bangumi = [] page = 1 count = 0 while count < limit: data = get_bangumi_raw(uid=uid, pn=page, type_=type_, verify=verify) if len(data["list"]) == 0: break bangumi += data["list"] if callable(callback): callback(data["list"]) count += len(data["list"]) page += 1 return bangumi[:limit]
8,010
def local_cases_range(start_date='2020-06-01',end_date='2020-07-01',areaname='Hartlepool'): """calculate new cases in a time range""" try: q=DailyCases.objects.filter(areaname=areaname,specimenDate=start_date)[0] start_total=q.totalLabConfirmedCases q=DailyCases.objects.filter(areaname=areaname,specimenDate=end_date)[0] end_total=q.totalLabConfirmedCases return end_total-start_total except Exception as e: log.info(e) return None
8,011
def ecal_phisym_flattables(process, produce_by_run : bool=False): """ Add the NanoAOD flat table producers. This functions adjust also the output columns. Should be called once nMisCalib has been set in the EcalPhiSymRecHitProducer """ process.load('Calibration.EcalCalibAlgos.EcalPhiSymFlatTableProducers_cfi') nmis = process.EcalPhiSymRecHitProducerRun.nMisCalib.value() for imis in range(1, nmis+1): # get the naming and indexing right. if imis<nmis/2+1: var_name = 'sumEt_m'+str(abs(int(imis-(nmis/2)-1))) var = Var(f'sumEt({imis})', float, doc='ECAL PhiSym rechits: '+str(imis-(nmis/2)-1)+'*miscalib et', precision=23) else: var_name = 'sumEt_p'+str(int(imis-(nmis/2))) var = Var(f'sumEt({imis})', float, doc='ECAL PhiSym rechits: '+str(imis-(nmis/2))+'*miscalib et', precision=23) if produce_by_run: setattr(process.ecalPhiSymRecHitRunTableEB.variables, var_name, var) setattr(process.ecalPhiSymRecHitRunTableEE.variables, var_name, var) flattable_sequence = cms.Sequence( process.ecalPhiSymRecHitRunTableEB + process.ecalPhiSymRecHitRunTableEE + process.ecalPhiSymInfoRunTable ) else: setattr(process.ecalPhiSymRecHitLumiTableEB.variables, var_name, var) setattr(process.ecalPhiSymRecHitLumiTableEE.variables, var_name, var) flattable_sequence = cms.Sequence( process.ecalPhiSymRecHitLumiTableEB + process.ecalPhiSymRecHitLumiTableEE + process.ecalPhiSymInfoLumiTable ) return flattable_sequence
8,012
def nx_add_prefix(graph, prefix): """ Rename graph to obtain disjoint node labels """ assert isinstance(graph, nx.DiGraph) if prefix is None: return graph def label(x): if isinstance(x, str): name = prefix + x else: name = prefix + repr(x) return name return nx.relabel_nodes(graph, label)
8,013
def infected_asymptomatic_20x80(): """ Real Name: b'Infected asymptomatic 20x80' Original Eqn: b'Infected asymptomatic 20+Infected asymptomatic 80' Units: b'person' Limits: (None, None) Type: component b'' """ return infected_asymptomatic_20() + infected_asymptomatic_80()
8,014
async def test_step_reauth( hass, config, config_entry, reauth_config, setup_simplisafe, sms_config ): """Test the re-auth step (testing both username and user ID as unique ID).""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_REAUTH}, data=config ) assert result["step_id"] == "reauth_confirm" assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=reauth_config ) assert result["step_id"] == "sms_2fa" assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=sms_config ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "reauth_successful" assert len(hass.config_entries.async_entries()) == 1 [config_entry] = hass.config_entries.async_entries(DOMAIN) assert config_entry.unique_id == USER_ID assert config_entry.data == config
8,015
def make_forecast_json(data: str): """Generate custom forecast file in JSON format :param data: JSON string containing weather.gov data """ try: if data: # Current conditions conditions_now: str = data["properties"]["periods"][0] # Determine where in the data object tomorrow's forecast will come from if is_day(data, 0): conditions_tomorrow: str = data["properties"]["periods"][2] else: conditions_tomorrow: str = data["properties"]["periods"][1] # Currently current_temperature: str = conditions_now["temperature"] current_wind: str = conditions_now["windSpeed"] current_advice: str = advice(current_temperature) # Tomorrow tomorrow_temperature: str = conditions_tomorrow["temperature"] tomorrow_wind: str = conditions_tomorrow["windSpeed"] tomorrow_advice: str = advice(tomorrow_temperature) weather_forecast: dict = { "current_conditions": f"It's currently {current_temperature}°f. {current_advice}. Wind speeds are {current_wind}.", "tomorrow_conditions": f"Tomorrow will be {tomorrow_temperature}°f. {tomorrow_advice}. Wind speeds will be {tomorrow_wind}." } # Convert forecast dict to JSON forecast_json = json.dumps(weather_forecast) # Save JSON file output_directory = os.path.sep.join(["json_output", "noaa"]) forecast_file = open( os.path.sep.join( [output_directory, "forecast.json"]), "w+" ) forecast_file.write(forecast_json) forecast_file.close() return print("Forecast creation complete.") except Exception as e: print(e)
8,016
def biosample_table_data(): """Return a dictionary containing the expected values of the BioSample Table""" columns = [ "id", "BioSample_id", "BioSampleAccession", "BioSampleAccessionSecondary", "BioSampleBioProjectAccession", "BioSampleSRAAccession", "BioSampleOrganism", "BioSampleStrain", "BioSampleSubmissionDate", "BioSampleComment", ] metadata = [ "1", "12991206", "SAMN12991206", "", "", "SRS5502739", "TestOrganism1", "TestStrain1", "2019-10-08T07:15:03.950", "", ] table_dict = {} # Populate the dict with data for i in range(0, len(columns)): key = columns[i] value = metadata[i] table_dict[key] = value return table_dict
8,017
def grid_adapter3D( out_dim=(100.0, 100.0), in_dim=(50.0, 50.0), z_dim=-10.0, out_res=(10.0, 10.0, 10.0), in_res=(5.0, 5.0, 5.0), out_pos=(0.0, 0.0), in_pos=(25.0, 25.0), z_pos=0.0, in_mat=0, out_mat=0, fill=False, ): """ Generate a grid adapter. 3D adapter from an outer grid resolution to an inner grid resolution with gmsh. Parameters ---------- out_dim : list of 2 float xy-Dimension of the outer block in_dim : list of 2 float xy-Dimension of the inner block z_dim : float z-Dimension of the whole block out_res : list of 3 float Grid resolution of the outer block in_res : list of 3 float Grid resolution of the inner block out_pos : list of 2 float xy-Position of the origin of the outer block in_pos : list of 2 float xy-Position of the origin of the inner block z_dim : float z-Position of the origin of the whole block in_mat : integer Material-ID of the inner block out_mat : integer Material-ID of the outer block fill : bool, optional State if the inner block should be filled with a rectangular mesh. Default: False. Returns ------- result : dictionary Result contains one '#FEM_MSH' block of the OGS mesh file with the following information (sorted by keys): mesh_data : dict dictionary containing information about - AXISYMMETRY (bool) - CROSS_SECTION (bool) - PCS_TYPE (str) - GEO_TYPE (str) - GEO_NAME (str) - LAYER (int) nodes : ndarray Array with all node postions elements : dict contains nodelists for elements sorted by element types material_id : dict contains material ids for each element sorted by element types element_id : dict contains element ids for each element sorted by element types """ out = gmsh( gmsh_grid_adapt3D( out_dim, in_dim, z_dim, out_res, in_res, out_pos, in_pos, z_pos ), import_dim=3, ) out["material_id"] = gen_std_mat_id(out["elements"], out_mat) if fill: element_no = [ int(in_dim[0] / in_res[0]), int(in_dim[1] / in_res[1]), int(abs(z_dim) / in_res[2]), ] mesh_in = rectangular( dim=3, mesh_origin=in_pos + (z_pos + min(z_dim, 0.0),), element_no=element_no, element_size=in_res, ) mesh_in["material_id"] = gen_std_mat_id(mesh_in["elements"], in_mat) dec = int(np.ceil(-np.log10(min(min(in_res), min(out_res)))) + 2.0) * 2 out = combine(mesh_in, out, dec) return out
8,018
def concat_dtypes(ds: Sequence[np.dtype]) -> np.dtype: """Concat structured datatypes.""" def _concat( acc: Tuple[Mapping[Any, Any], int], a: np.dtype ) -> Tuple[DTYPE_FIELDS_T, int]: acc_fields, acc_itemsize = acc fields = dtype_fields(a).throw() intersection = set(acc_fields).intersection(set(fields)) if intersection != set(): raise ValueError(f'dtypes have overlapping fields: {intersection}') return ( { **acc_fields, **{k: (d[0], d[1] + acc_itemsize) for k, d in fields.items()} }, acc_itemsize + a.itemsize ) # dtype.fields() doesn't match dtype constructor despite being compatible return np.dtype(reduce(_concat, ds, (cast(DTYPE_FIELDS_T, {}), 0))[0])
8,019
def repeatedly0( loader: Iterator, nepochs: int = sys.maxsize, nbatches: int = sys.maxsize ): """Repeatedly returns batches from a DataLoader.""" for epoch in range(nepochs): for sample in itt.islice(loader, nbatches): yield sample
8,020
def mutation(param_space, config, mutation_rate, list=False): """ Mutates given configuration. :param param_space: space.Space(), will give us information about parameters :param configs: list of configurations. :param mutation_rate: integer for how many parameters to mutate :param list: boolean whether returning one or more alternative configs :return: list of dicts, list of mutated configurations """ parameter_object_list = param_space.get_input_parameters_objects() rd_config = dict() for name, obj in parameter_object_list.items(): x = obj.randomly_select() single_valued_param = False param_type = param_space.get_type(name) if param_type == 'real' or param_type == 'integer': if obj.get_max() == obj.get_min(): single_valued_param = True else: if obj.get_size() == 1: single_valued_param = True mutation_attempts = 0 while x == config[name] and single_valued_param == False: x = obj.randomly_select() mutation_attempts += 1 if mutation_attempts > 1000000: break rd_config[name] = x parameter_names_list = param_space.get_input_parameters() nbr_params = len(parameter_names_list) configs = [] n_configs = nbr_params if list else 1 for _ in range(n_configs): indices = rd.permutation(nbr_params)[:mutation_rate] for idx in indices: mutation_param = parameter_names_list[idx] # Should I do something if they are the same? temp = config.copy() temp[mutation_param] = rd_config[mutation_param] configs.append(temp) return configs
8,021
def uncertainty_batch_sampling(classifier: Union[BaseLearner, BaseCommittee], X: Union[np.ndarray, sp.csr_matrix], n_instances: int = 20, metric: Union[str, Callable] = 'euclidean', n_jobs: Optional[int] = None, **uncertainty_measure_kwargs ) -> Tuple[np.ndarray, Union[np.ndarray, sp.csr_matrix]]: """ Batch sampling query strategy. Selects the least sure instances for labelling. This strategy differs from :func:`~modAL.uncertainty.uncertainty_sampling` because, although it is supported, traditional active learning query strategies suffer from sub-optimal record selection when passing `n_instances` > 1. This sampling strategy extends the interactive uncertainty query sampling by allowing for batch-mode uncertainty query sampling. Furthermore, it also enforces a ranking -- that is, which records among the batch are most important for labeling? Refer to Cardoso et al.'s "Ranked batch-mode active learning": https://www.sciencedirect.com/science/article/pii/S0020025516313949 Args: classifier: One of modAL's supported active learning models. X: Set of records to be considered for our active learning model. n_instances: Number of records to return for labeling from `X`. metric: This parameter is passed to :func:`~sklearn.metrics.pairwise.pairwise_distances` n_jobs: If not set, :func:`~sklearn.metrics.pairwise.pairwise_distances_argmin_min` is used for calculation of distances between samples. Otherwise it is passed to :func:`~sklearn.metrics.pairwise.pairwise_distances`. **uncertainty_measure_kwargs: Keyword arguments to be passed for the :meth:`predict_proba` of the classifier. Returns: Indices of the instances from `X` chosen to be labelled; records from `X` chosen to be labelled. """ uncertainty = classifier_uncertainty(classifier, X, **uncertainty_measure_kwargs) query_indices = ranked_batch(classifier, unlabeled=X, uncertainty_scores=uncertainty, n_instances=n_instances, metric=metric, n_jobs=n_jobs) return query_indices, X[query_indices]
8,022
def only_digits(raw, force_int=False): """Strips all not digit characters from string. Args: raw (str or unicode): source string. Kwargs: force_int (boolean): not to seek for dot, seek only for int value. Returns: int or float: in dependence of "raw" argument content. None: if raw is None, empty or not contains digits. """ if isinstance(raw, (unicode, str)) and len(raw): if not force_int and re.search(r'\d\.\d', raw): try: return float(u''.join(u'{0}'.format(one) for one in raw if one.isdigit() or one == one.__class__(u'.'))) except (TypeError, ValueError): return None else: try: return int(u''.join(u'{0}'.format(one) for one in raw if one.isdigit())) except (TypeError, ValueError): return None elif isinstance(raw, (float, int)): return raw else: return None
8,023
def log_global_state(): """ Executed periodically. Requets local and global state and logs (outputs it). """ global last_log_timestamp global last_local_pcount global last_global_pcount # receive local values t_get_local_start = time.time() pcount_local = get_ecounter("pcount") matchcount_local = get_ecounter("matchcount") time_local_request = time.time() - t_get_local_start # receive global values t_get_global_start = time.time() pcount_global = get_ecounter_global_sum("pcount") matchcount_global = get_ecounter_global_sum("matchcount") # if we should use dummy state with given size, ensure to fetch it always! if dummy_state_size > 0: dummydata = es.get_global("dummystate", red_latest) #print dummydata time_global_request = time.time() - t_get_global_start # calculate pps timespan = abs(time.time() - last_log_timestamp) last_log_timestamp = time.time() if timespan == 0: raise Exception("We have a zero timespan for PPS calculation") pps_local = (pcount_local - last_local_pcount) / timespan last_local_pcount = pcount_local pps_global = (pcount_global - last_global_pcount) / timespan last_global_pcount = pcount_global # generate log output print("LOG_NETWORK_MONITOR:" "%f;%f;%f;%f;%f;%f;%f;%f;%f;" % (time.time(), pps_local, pps_global, pcount_local, pcount_global, matchcount_local, matchcount_global, time_local_request, time_global_request))
8,024
def namedtuple(typename, field_names, verbose=False): """Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point', 'x y') >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessable by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22) """ # Parse and validate the field names. Validation serves two purposes, # generating informative error messages and preventing template injection attacks. if isinstance(field_names, basestring): field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas field_names = tuple(map(str, field_names)) for name in (typename,) + field_names: if not all(c.isalnum() or c=='_' for c in name): raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name) if _iskeyword(name): raise ValueError('Type names and field names cannot be a keyword: %r' % name) if name[0].isdigit(): raise ValueError('Type names and field names cannot start with a number: %r' % name) seen_names = set() for name in field_names: if name.startswith('_'): raise ValueError('Field names cannot start with an underscore: %r' % name) if name in seen_names: raise ValueError('Encountered duplicate field name: %r' % name) seen_names.add(name) # Create and fill-in the class template numfields = len(field_names) argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes reprtxt = ', '.join('%s=%%r' % name for name in field_names) dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names)) template = '''class %(typename)s(tuple): '%(typename)s(%(argtxt)s)' \n __slots__ = () \n _fields = %(field_names)r \n def __new__(_cls, %(argtxt)s): return _tuple.__new__(_cls, (%(argtxt)s)) \n @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new %(typename)s object from a sequence or iterable' result = new(cls, iterable) if len(result) != %(numfields)d: raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result)) return result \n def __repr__(self): return '%(typename)s(%(reprtxt)s)' %% self \n def _asdict(t): 'Return a new dict which maps field names to their values' return {%(dicttxt)s} \n def _replace(_self, **kwds): 'Return a new %(typename)s object replacing specified fields with new values' result = _self._make(map(kwds.pop, %(field_names)r, _self)) if kwds: raise ValueError('Got unexpected field names: %%r' %% kwds.keys()) return result \n def __getnewargs__(self): return tuple(self) \n\n''' % locals() for i, name in enumerate(field_names): template += ' %s = _property(_itemgetter(%d))\n' % (name, i) if verbose: print template # Execute the template string in a temporary namespace and # support tracing utilities by setting a value for frame.f_globals['__name__'] namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename, _property=property, _tuple=tuple) try: exec template in namespace except SyntaxError, e: raise SyntaxError(e.message + ':\n' + template) result = namespace[typename] # For pickling to work, the __module__ variable needs to be set to the frame # where the named tuple is created. Bypass this step in enviroments where # sys._getframe is not defined (Jython for example). if hasattr(_sys, '_getframe'): result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__') return result
8,025
def save_image(image, path, extension="tif"): """Save an image. The input image should have between 2 and 5 dimensions, with boolean, (unsigned) integer, or float. The dimensions should be in the following order: (round, channel, z, y, x). Parameters ---------- image : np.ndarray Image to save. path : str Path of the saved image. extension : str Default extension to save the image (among ``png``, ``jpg``, ``jpeg``, ``tif`` or ``tiff``). Notes ----- * If the image has more than 2 dimensions, ``tif`` and ``tiff`` extensions are required (``png`` extension does not handle 3-d images other than (M, N, 3) or (M, N, 4) shapes). * A 2-d boolean image can be saved in ``png``, ``jpg`` or ``jpeg`` (cast in np.uint8). * A multidimensional boolean image should be saved with :func:`bigfish.stack.save_array` or as a boolean images with ``tif``/ ``tiff`` extension. """ # check image and parameters check_parameter(path=str, extension=str) check_array(image, dtype=[np.uint8, np.uint16, np.uint32, np.uint64, np.int8, np.int16, np.int32, np.int64, np.float16, np.float32, np.float64, bool], ndim=[2, 3, 4, 5], allow_nan=False) # check extension and build path if "/" in path: path_ = path.split("/") filename = path_[-1] if "." in filename: extension = filename.split(".")[-1] else: filename += ".{0}".format(extension) path_[-1] = filename path = "/".join(path_) else: if "." in path: extension = path.split(".")[-1] else: path += ".{0}".format(extension) if extension not in ["png", "jpg", "jpeg", "tif", "tiff"]: raise ValueError("{0} extension is not supported, please choose among " "'png', 'jpg', 'jpeg', 'tif' or 'tiff'." .format(extension)) # warn about extension if (extension in ["png", "jpg", "jpeg"] and len(image.shape) > 2 and image.dtype != bool): raise ValueError("Extension {0} is not fitted with multidimensional " "images. Use 'tif' or 'tiff' extension instead." .format(extension)) if (extension in ["png", "jpg", "jpeg"] and len(image.shape) == 2 and image.dtype != bool): warnings.warn("Extension {0} is not consistent with dtype. To prevent " "'image' from being cast you should use 'tif' or 'tiff' " "extension.".format(extension), UserWarning) if (extension in ["png", "jpg", "jpeg"] and len(image.shape) == 2 and image.dtype == bool): warnings.warn("Extension {0} is not consistent with dtype. To prevent " "'image' from being cast you should use " "'bigfish.stack.save_array' function instead." .format(extension), UserWarning) if (extension in ["tif", "tiff"] and len(image.shape) == 2 and image.dtype == bool): raise ValueError("Extension {0} is not fitted with boolean images. " "Use 'png', 'jpg' or 'jpeg' extension instead." .format(extension)) if (extension in ["png", "jpg", "jpeg", "tif", "tiff"] and len(image.shape) > 2 and image.dtype == bool): raise ValueError("Extension {0} is not fitted with multidimensional " "boolean images. Use 'bigfish.stack.save_array' " "function instead.".format(extension)) # save image without warnings with warnings.catch_warnings(): warnings.filterwarnings(action="ignore", category=UserWarning) io.imsave(path, image)
8,026
def get_users(compartment_id: Optional[str] = None, external_identifier: Optional[str] = None, filters: Optional[Sequence[pulumi.InputType['GetUsersFilterArgs']]] = None, identity_provider_id: Optional[str] = None, name: Optional[str] = None, state: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetUsersResult: """ This data source provides the list of Users in Oracle Cloud Infrastructure Identity service. Lists the users in your tenancy. You must specify your tenancy's OCID as the value for the compartment ID (remember that the tenancy is simply the root compartment). See [Where to Get the Tenancy's OCID and User's OCID](https://docs.cloud.oracle.com/iaas/Content/API/Concepts/apisigningkey.htm#five). ## Example Usage ```python import pulumi import pulumi_oci as oci test_users = oci.identity.get_users(compartment_id=var["tenancy_ocid"], external_identifier=var["user_external_identifier"], identity_provider_id=oci_identity_identity_provider["test_identity_provider"]["id"], name=var["user_name"], state=var["user_state"]) ``` :param str compartment_id: The OCID of the compartment (remember that the tenancy is simply the root compartment). :param str external_identifier: The id of a user in the identity provider. :param str identity_provider_id: The id of the identity provider. :param str name: A filter to only return resources that match the given name exactly. :param str state: A filter to only return resources that match the given lifecycle state. The state value is case-insensitive. """ __args__ = dict() __args__['compartmentId'] = compartment_id __args__['externalIdentifier'] = external_identifier __args__['filters'] = filters __args__['identityProviderId'] = identity_provider_id __args__['name'] = name __args__['state'] = state if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('oci:identity/getUsers:getUsers', __args__, opts=opts, typ=GetUsersResult).value return AwaitableGetUsersResult( compartment_id=__ret__.compartment_id, external_identifier=__ret__.external_identifier, filters=__ret__.filters, id=__ret__.id, identity_provider_id=__ret__.identity_provider_id, name=__ret__.name, state=__ret__.state, users=__ret__.users)
8,027
def server(ctx, source, destination, station_id, max_message_per_sec, max_message_per_mmsi_per_sec, notifier): """Example: aisdownsampler server '{"type": "listen", "listen":"tcp:4711"}' '{"type": "listen", "listen":"tcp:4712"}' """ aisdownsampler.server.server( notifier = notifier, source = json.loads(source), destination = json.loads(destination), station_id = station_id, session = aisdownsampler.downsampler.Session( max_message_per_sec=max_message_per_sec, max_message_per_mmsi_per_sec=max_message_per_mmsi_per_sec))
8,028
def _jvm_import_external(repository_ctx): """Implementation of `java_import_external` rule.""" if (repository_ctx.attr.generated_linkable_rule_name and not repository_ctx.attr.neverlink): fail("Only use generated_linkable_rule_name if neverlink is set") name = repository_ctx.attr.generated_rule_name or repository_ctx.name urls = repository_ctx.attr.artifact_urls sha = repository_ctx.attr.artifact_sha256 extension = repository_ctx.attr.rule_metadata["extension"] file_extension = "." + extension path = repository_ctx.name + file_extension for url in urls: if url.endswith(file_extension): path = url[url.rindex("/") + 1:] break srcurls = repository_ctx.attr.srcjar_urls srcsha = repository_ctx.attr.srcjar_sha256 srcpath = repository_ctx.name + "-src.jar" if srcurls else "" for url in srcurls: if url.endswith(file_extension): srcpath = url[url.rindex("/") + 1:].replace("-sources.jar", "-src.jar") break lines = [_HEADER, ""] if repository_ctx.attr.rule_load: lines.append(repository_ctx.attr.rule_load) lines.append("") if repository_ctx.attr.default_visibility: lines.append("package(default_visibility = %s)" % ( repository_ctx.attr.default_visibility )) lines.append("") lines.append("licenses(%s)" % repr(repository_ctx.attr.licenses)) lines.append("") lines.extend(_serialize_given_rule_import( name = name, additional_rule_attrs = repository_ctx.attr.additional_rule_attrs, attrs = repository_ctx.attr, import_attr = repository_ctx.attr.rule_metadata["import_attr"], path = path, props = _PASS_PROPS, rule_name = repository_ctx.attr.rule_name, srcpath = srcpath, )) if (repository_ctx.attr.neverlink and repository_ctx.attr.generated_linkable_rule_name): lines.extend(_serialize_given_rule_import( name = repository_ctx.attr.generated_linkable_rule_name, additional_rule_attrs = repository_ctx.attr.additional_rule_attrs, attrs = repository_ctx.attr, import_attr = repository_ctx.attr.rule_metadata["import_attr"], path = path, props = [p for p in _PASS_PROPS if p != "neverlink"], rule_name = repository_ctx.attr.rule_name, srcpath = srcpath, )) extra = repository_ctx.attr.extra_build_file_content if extra: lines.append(extra) if not extra.endswith("\n"): lines.append("") repository_ctx.download(urls, path, sha) if srcurls and _should_fetch_sources_in_current_env(repository_ctx): repository_ctx.download(srcurls, srcpath, srcsha) repository_ctx.file("BUILD", "\n".join(lines)) repository_ctx.file("%s/BUILD" % extension, "\n".join([ _HEADER, "", "package(default_visibility = %r)" % ( repository_ctx.attr.visibility or repository_ctx.attr.default_visibility ), "", "alias(", " name = \"%s\"," % extension, " actual = \"@%s\"," % repository_ctx.name, ")", "", "filegroup(", " name = \"file\",", " srcs = [\"//:%s\"]," % path, ")", ]))
8,029
def se_resnet20(num_classes: int = 10, in_channels: int = 3 ) -> ResNet: """ SEResNet by Hu+18 """ return resnet(num_classes, 20, in_channels, block=partial(SEBasicBlock, reduction=16))
8,030
def test_load_related__JSONB_objects(n): """ Test making JSONB on the server. Make objects with row_to_json() """ query = QUERY_TEMPLATE.format( # Use JSONB for nested objects AGG_FUNCTION='jsonb_agg', # Select rows as JSONB objects # Select ids needed for joining as well USERS_SELECT='users.id, to_jsonb(users) AS user', ARTICLES_SELECT='articles.id, articles.uid, to_jsonb(articles) AS article', COMMENTS_SELECT='comments.id, comments.aid, to_jsonb(comments) AS comment', ) for i in range(n): users = list(ssn.execute(query))
8,031
def parallel_threaded(function): """ A decorator for running a function within a parallel thread """ def decorator(*args, **kwargs): t = ParallelThread(target=function, args=args, kwargs=kwargs) t.daemon = True t.start() return t return decorator
8,032
def Upsample(x, size): """ Wrapper Around the Upsample Call """ return nn.functional.interpolate(x, size=size, mode="bilinear", align_corners=True)
8,033
def xcode_project(**kwargs): """ Generate an Xcode project name: attr.string name of the target targets: attr.label_list bazel: attr.string path to Bazel used during Xcode builds xchammer: attr.string path to xchammer project_name: (optional) target_config: (optional) struct(target_config) project_config: (optional) struct(target_config) """ proj_args = kwargs rule_name = kwargs["name"] if not kwargs.get("project_name"): proj_args["project_name"] = kwargs["name"] # Build an XCHammer config Based on inputs targets_json = [str(t) for t in kwargs.get("targets")] # XCHammer development only xchammer_target = "//:xchammer" if xchammer_target in targets_json: proj_args["xchammer_bazel_build_target"] = xchammer_target if "target_config" in proj_args: str_dict = {} for k in proj_args["target_config"]: str_dict[k] = proj_args["target_config"][k].to_json() proj_args["target_config"] = _dict_to_json(str_dict) else: proj_args["target_config"] = "{}" proj_args["name"] = rule_name + "_impl" proj_args["project_config"] = proj_args["project_config"].to_json() if "project_config" in proj_args else None _xcode_project(**proj_args) # Note: _xcode_project does the hermetic, reproducible bits # and then, we install this xcode project into the root directory. _install_xcode_project( name=rule_name, xcodeproj=kwargs["name"], testonly=proj_args.get("testonly", False), )
8,034
def get_user_playlists(spotipy_obj, username): """Gets and returns all Spotify playlists owned by the username specified. Parameters: spotipy_obj: Spotipy object username: Spotify username Returns: List of dictionaries, each dictionary a Spotify playlist object. """ # Grab all user playlists, including private ones initial_playlists = spotipy_obj.user_playlists(username) final_playlists = [] while initial_playlists: for playlist in initial_playlists["items"]: if playlist["owner"]["id"] == username: final_playlists.append(playlist) if initial_playlists["next"]: initial_playlists = spotipy_obj.next(initial_playlists) else: initial_playlists = None return final_playlists
8,035
def run(coro) -> Any: """ Create a new task from the given coroutine and run it until it completes. Returns the value returned by *coro*. """ ...
8,036
def test_blur_effect_channel_axis(): """Test that passing an RGB image is equivalent to passing its grayscale version. """ image = astronaut() B0 = blur_effect(image, channel_axis=-1) B1 = blur_effect(rgb2gray(image)) B0_arr = blur_effect(image, channel_axis=-1, reduce_func=None) B1_arr = blur_effect(rgb2gray(image), reduce_func=None) assert 0 <= B0 < 1 assert B0 == B1 assert_array_equal(B0_arr, B1_arr)
8,037
def osu_run1(data_set="osu_run1", sample_every=4): """Ohio State University's Run1 motion capture data set.""" path = os.path.join(access.DATAPATH, data_set) if not access.data_available(data_set): import zipfile access.download_data(data_set) zip = zipfile.ZipFile(os.path.join(access.DATAPATH, data_set, "run1TXT.ZIP"), "r") for name in zip.namelist(): zip.extract(name, path) from . import mocap Y, connect = mocap.load_text_data("Aug210106", path) Y = Y[0:-1:sample_every, :] return access.data_details_return({"Y": Y, "connect": connect}, data_set)
8,038
def package_data(pkg, root_list): """ Generic function to find package_data for `pkg` under `root`. """ data = [] for root in root_list: for dirname, _, files in os.walk(os.path.join(pkg, root)): for fname in files: data.append(os.path.relpath(os.path.join(dirname, fname), pkg)) return {pkg: data}
8,039
async def validate_ws(hass: core.HomeAssistant, data): """Validate the user input allows us to connect over WS.""" ws_port = data.get(CONF_WS_PORT) if not ws_port: return host = data[CONF_HOST] port = data[CONF_PORT] username = data.get(CONF_USERNAME) password = data.get(CONF_PASSWORD) ssl = data.get(CONF_SSL) session = async_get_clientsession(hass) _LOGGER.debug("Connecting to %s:%s over WebSocket", host, ws_port) kwc = get_kodi_connection( host, port, ws_port, username, password, ssl, session=session ) try: await kwc.connect() if not kwc.connected: _LOGGER.warning("Cannot connect to %s:%s over WebSocket", host, ws_port) raise WSCannotConnect() kodi = Kodi(kwc) await kodi.ping() except CannotConnectError as error: raise WSCannotConnect from error
8,040
def create(dataset, target, features=None, l2_penalty=1e-2, l1_penalty=0.0, solver='auto', feature_rescaling=True, convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'], step_size = _DEFAULT_SOLVER_OPTIONS['step_size'], lbfgs_memory_level = _DEFAULT_SOLVER_OPTIONS['lbfgs_memory_level'], max_iterations = _DEFAULT_SOLVER_OPTIONS['max_iterations'], validation_set = "auto", verbose=True): """ Create a :class:`~turicreate.linear_regression.LinearRegression` to predict a scalar target variable as a linear function of one or more features. In addition to standard numeric and categorical types, features can also be extracted automatically from list- or dictionary-type SFrame columns. The linear regression module can be used for ridge regression, Lasso, and elastic net regression (see References for more detail on these methods). By default, this model has an l2 regularization weight of 0.01. Parameters ---------- dataset : SFrame The dataset to use for training the model. target : string Name of the column containing the target variable. features : list[string], optional Names of the columns containing features. 'None' (the default) indicates that all columns except the target variable should be used as features. The features are columns in the input SFrame that can be of the following types: - *Numeric*: values of numeric type integer or float. - *Categorical*: values of type string. - *Array*: list of numeric (integer or float) values. Each list element is treated as a separate feature in the model. - *Dictionary*: key-value pairs with numeric (integer or float) values Each key of a dictionary is treated as a separate feature and the value in the dictionary corresponds to the value of the feature. Dictionaries are ideal for representing sparse data. Columns of type *list* are not supported. Convert such feature columns to type array if all entries in the list are of numeric types. If the lists contain data of mixed types, separate them out into different columns. l2_penalty : float, optional Weight on the l2-regularizer of the model. The larger this weight, the more the model coefficients shrink toward 0. This introduces bias into the model but decreases variance, potentially leading to better predictions. The default value is 0.01; setting this parameter to 0 corresponds to unregularized linear regression. See the ridge regression reference for more detail. l1_penalty : float, optional Weight on l1 regularization of the model. Like the l2 penalty, the higher the l1 penalty, the more the estimated coefficients shrink toward 0. The l1 penalty, however, completely zeros out sufficiently small coefficients, automatically indicating features that are not useful for the model. The default weight of 0 prevents any features from being discarded. See the LASSO regression reference for more detail. solver : string, optional Solver to use for training the model. See the references for more detail on each solver. - *auto (default)*: automatically chooses the best solver for the data and model parameters. - *newton*: Newton-Raphson - *lbfgs*: limited memory BFGS - *fista*: accelerated gradient descent The model is trained using a carefully engineered collection of methods that are automatically picked based on the input data. The ``newton`` method works best for datasets with plenty of examples and few features (long datasets). Limited memory BFGS (``lbfgs``) is a robust solver for wide datasets (i.e datasets with many coefficients). ``fista`` is the default solver for l1-regularized linear regression. The solvers are all automatically tuned and the default options should function well. See the solver options guide for setting additional parameters for each of the solvers. See the user guide for additional details on how the solver is chosen. feature_rescaling : boolean, optional Feature rescaling is an important pre-processing step that ensures that all features are on the same scale. An l2-norm rescaling is performed to make sure that all features are of the same norm. Categorical features are also rescaled by rescaling the dummy variables that are used to represent them. The coefficients are returned in original scale of the problem. This process is particularly useful when features vary widely in their ranges. validation_set : SFrame, optional A dataset for monitoring the model's generalization performance. For each row of the progress table, the chosen metrics are computed for both the provided training dataset and the validation_set. The format of this SFrame must be the same as the training set. By default this argument is set to 'auto' and a validation set is automatically sampled and used for progress printing. If validation_set is set to None, then no additional metrics are computed. The default value is 'auto'. convergence_threshold : float, optional Convergence is tested using variation in the training objective. The variation in the training objective is calculated using the difference between the objective values between two steps. Consider reducing this below the default value (0.01) for a more accurately trained model. Beware of overfitting (i.e a model that works well only on the training data) if this parameter is set to a very low value. lbfgs_memory_level : int, optional The L-BFGS algorithm keeps track of gradient information from the previous ``lbfgs_memory_level`` iterations. The storage requirement for each of these gradients is the ``num_coefficients`` in the problem. Increasing the ``lbfgs_memory_level`` can help improve the quality of the model trained. Setting this to more than ``max_iterations`` has the same effect as setting it to ``max_iterations``. max_iterations : int, optional The maximum number of allowed passes through the data. More passes over the data can result in a more accurately trained model. Consider increasing this (the default value is 10) if the training accuracy is low and the *Grad-Norm* in the display is large. step_size : float, optional (fista only) The starting step size to use for the ``fista`` and ``gd`` solvers. The default is set to 1.0, this is an aggressive setting. If the first iteration takes a considerable amount of time, reducing this parameter may speed up model training. verbose : bool, optional If True, print progress updates. Returns ------- out : LinearRegression A trained model of type :class:`~turicreate.linear_regression.LinearRegression`. See Also -------- LinearRegression, turicreate.boosted_trees_regression.BoostedTreesRegression, turicreate.regression.create Notes ----- - Categorical variables are encoded by creating dummy variables. For a variable with :math:`K` categories, the encoding creates :math:`K-1` dummy variables, while the first category encountered in the data is used as the baseline. - For prediction and evaluation of linear regression models with sparse dictionary inputs, new keys/columns that were not seen during training are silently ignored. - Any 'None' values in the data will result in an error being thrown. - A constant term is automatically added for the model intercept. This term is not regularized. - Standard errors on coefficients are only available when `solver=newton` or when the default `auto` solver option chooses the newton method and if the number of examples in the training data is more than the number of coefficients. If standard errors cannot be estimated, a column of `None` values are returned. References ---------- - Hoerl, A.E. and Kennard, R.W. (1970) `Ridge regression: Biased Estimation for Nonorthogonal Problems <http://amstat.tandfonline.com/doi/abs/10.1080/00401706.1970.10488634>`_. Technometrics 12(1) pp.55-67 - Tibshirani, R. (1996) `Regression Shrinkage and Selection via the Lasso <h ttp://www.jstor.org/discover/10.2307/2346178?uid=3739256&uid=2&uid=4&sid=2 1104169934983>`_. Journal of the Royal Statistical Society. Series B (Methodological) 58(1) pp.267-288. - Zhu, C., et al. (1997) `Algorithm 778: L-BFGS-B: Fortran subroutines for large-scale bound-constrained optimization <https://dl.acm.org/citation.cfm?id=279236>`_. ACM Transactions on Mathematical Software 23(4) pp.550-560. - Barzilai, J. and Borwein, J. `Two-Point Step Size Gradient Methods <http://imajna.oxfordjournals.org/content/8/1/141.short>`_. IMA Journal of Numerical Analysis 8(1) pp.141-148. - Beck, A. and Teboulle, M. (2009) `A Fast Iterative Shrinkage-Thresholding Algorithm for Linear Inverse Problems <http://epubs.siam.org/doi/abs/10.1137/080716542>`_. SIAM Journal on Imaging Sciences 2(1) pp.183-202. - Zhang, T. (2004) `Solving large scale linear prediction problems using stochastic gradient descent algorithms <https://dl.acm.org/citation.cfm?id=1015332>`_. ICML '04: Proceedings of the twenty-first international conference on Machine learning p.116. Examples -------- Given an :class:`~turicreate.SFrame` ``sf`` with a list of columns [``feature_1`` ... ``feature_K``] denoting features and a target column ``target``, we can create a :class:`~turicreate.linear_regression.LinearRegression` as follows: >>> data = turicreate.SFrame('https://static.turi.com/datasets/regression/houses.csv') >>> model = turicreate.linear_regression.create(data, target='price', ... features=['bath', 'bedroom', 'size']) For ridge regression, we can set the ``l2_penalty`` parameter higher (the default is 0.01). For Lasso regression, we set the l1_penalty higher, and for elastic net, we set both to be higher. .. sourcecode:: python # Ridge regression >>> model_ridge = turicreate.linear_regression.create(data, 'price', l2_penalty=0.1) # Lasso >>> model_lasso = turicreate.linear_regression.create(data, 'price', l2_penalty=0., l1_penalty=1.0) # Elastic net regression >>> model_enet = turicreate.linear_regression.create(data, 'price', l2_penalty=0.5, l1_penalty=0.5) """ # Regression model names. model_name = "regression_linear_regression" solver = solver.lower() model = _sl.create(dataset, target, model_name, features=features, validation_set = validation_set, solver = solver, verbose = verbose, l2_penalty=l2_penalty, l1_penalty = l1_penalty, feature_rescaling = feature_rescaling, convergence_threshold = convergence_threshold, step_size = step_size, lbfgs_memory_level = lbfgs_memory_level, max_iterations = max_iterations) return LinearRegression(model.__proxy__)
8,041
def argument(*name_or_flags, **kwargs): """Convenience function to properly format arguments to pass to the subcommand decorator. """ args = list() for arg in name_or_flags: args.append(arg) return args, kwargs
8,042
def get_logger(): """ Provides the stem logger. :returns: **logging.Logger** for stem """ return LOGGER
8,043
def test_raise_exception_if_rootdir_not_found(tmp_path): """Raises exception if no rootdir is found (rootdir is None).""" os.chdir(tmp_path) with pytest.raises(SystemExit): _form_backupsub_pathname()
8,044
def get_graphql_type_for_model(model): """ Return the GraphQL type class for the given model. """ app_name, model_name = model._meta.label.split('.') # Object types for Django's auth models are in the users app if app_name == 'auth': app_name = 'users' class_name = f'{app_name}.graphql.types.{model_name}Type' try: return dynamic_import(class_name) except AttributeError: raise GraphQLTypeNotFound(f"Could not find GraphQL type for {app_name}.{model_name}")
8,045
def load_image_files(container_path, dimension=(64, 64)): """ Load image files with categories as subfolder names which performs like scikit-learn sample dataset """ image_dir = Path(container_path) folders = [directory for directory in image_dir.iterdir() if directory.is_dir()] categories = [fo.name for fo in folders] descr = "A image classification dataset" images = [] flat_data = [] target = [] for i, direc in enumerate(folders): for file in direc.iterdir(): img = imread(file) img_resized = resize(img, dimension, anti_aliasing=True, mode='reflect') flat_data.append(img_resized.flatten()) images.append(img_resized) target.append(i) flat_data = np.array(flat_data) target = np.array(target) images = np.array(images) print('done') return Bunch(data=flat_data, target=target, target_names=categories, images=images, DESCR=descr)
8,046
def trim_whitespace( input_file_name, output_file_name, border_width_pixels=10, convert_exe_name=DEFAULT_CONVERT_EXE_NAME): """Trims whitespace around edge of image. :param input_file_name: Path to input file (may be in any format handled by ImageMagick). :param output_file_name: Path to output file. :param border_width_pixels: Desired border width (whitespace). :param convert_exe_name: Path to executable file for ImageMagick's "convert" function. If you installed ImageMagick with root access, this should be the default. Regardless, the pathless file name should be just "convert". :raises: ValueError: if ImageMagick command (which is ultimately a Unix command) fails. """ error_checking.assert_file_exists(input_file_name) file_system_utils.mkdir_recursive_if_necessary(file_name=output_file_name) error_checking.assert_is_integer(border_width_pixels) error_checking.assert_is_geq(border_width_pixels, 0) error_checking.assert_file_exists(convert_exe_name) command_string = ( '"{0:s}" "{1:s}" -trim -bordercolor White -border {2:d} "{3:s}"' ).format( convert_exe_name, input_file_name, border_width_pixels, output_file_name ) exit_code = os.system(command_string) if exit_code == 0: return raise ValueError(ERROR_STRING)
8,047
def create_calendar(year=None, month=None): """ Create an inline keyboard with the provided year and month :param int year: Year to use in the calendar, if None the current year is used. :param int month: Month to use in the calendar, if None the current month is used. :return: Returns the InlineKeyboardMarkup object with the calendar. """ now = datetime.datetime.now() if year is None: year = now.year if month is None: month = now.month data_ignore = create_callback_data("IGNORE", year, month, 0) keyboard = [] # First row - Month and Year row = [] row.append(InlineKeyboardButton( calendar.month_name[month]+" "+str(year), callback_data=data_ignore) ) keyboard.append(row) # Second row - Week Days row = [] for day in ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"]: row.append(InlineKeyboardButton(day, callback_data=data_ignore)) keyboard.append(row) my_calendar = calendar.monthcalendar(year, month) for week in my_calendar: row = [] for day in week: if day == 0: row.append(InlineKeyboardButton( " ", callback_data=data_ignore) ) else: row.append(InlineKeyboardButton( str(day), callback_data=create_callback_data( "DAY", year, month, day )) ) keyboard.append(row) # Last row - Buttons row = [] row.append(InlineKeyboardButton( "<", callback_data=create_callback_data( "PREV-MONTH", year, month, day )) ) row.append(InlineKeyboardButton( " ", callback_data=data_ignore) ) row.append(InlineKeyboardButton( ">", callback_data=create_callback_data( "NEXT-MONTH", year, month, day )) ) keyboard.append(row) return InlineKeyboardMarkup(keyboard)
8,048
def format_allowed_section(allowed): """Format each section of the allowed list""" if allowed.count(":") == 0: protocol = allowed ports = [] elif allowed.count(":") == 1: protocol, ports = allowed.split(":") else: return [] if ports.count(","): ports = ports.split(",") elif ports: ports = [ports] return_val = {"IPProtocol": protocol} if ports: return_val["ports"] = ports return return_val
8,049
def upload_image(): """ form-data: image: a jpeg picture :return: a file pathname, assigned by backend. """ if 'image' not in request.files: return '', 400 f = request.files['image'] if f.filename == '': return '', 400 if not _allowed_file(f.filename): return '', 400 # filename = secure_filename(f.filename) filename = hash_filename(f) pathname = os.path.join(app.config['UPLOAD_FOLDER'], filename) f.save(pathname) return pathname
8,050
def get_airmass(when, ra, dec): """Return the airmass of (ra,dec) at the specified observing time. Uses :func:`cos_zenith_to_airmass`. Parameters ---------- when : astropy.time.Time Observation time, which specifies the local zenith. ra : astropy.units.Quantity Target RA angle(s) dec : astropy.units.Quantity Target DEC angle(s) Returns ------- array or float Value of the airmass for each input (ra,dec). """ target = astropy.coordinates.ICRS(ra=ra, dec=dec) zenith = get_observer(when, alt=90 * u.deg, az=0 * u.deg ).transform_to(astropy.coordinates.ICRS) # Calculate zenith angle in degrees. zenith_angle = target.separation(zenith) # Convert to airmass. return cos_zenith_to_airmass(np.cos(zenith_angle))
8,051
def get_metadata(class_): """Returns a list of MetaDataTuple structures. """ return list(get_metadata_iterator(class_))
8,052
def get_register(regname): """ Get register value. Exception will be raised if expression cannot be parse. This function won't catch on purpose. @param regname: expected register @return register value """ t = gdb.lookup_type("unsigned long") reg = gdb.parse_and_eval(regname) return long( reg.cast(t) )
8,053
def test_MultiPhaseModel_4(): """Test the eval method""" model = mod.MultiPhaseModel("a * x") model.set_value(a=1) x = np.linspace(0, 5, 6) y = np.zeros(6) model.set_data(x, y) model.eval() assert np.array_equal(model.get_profile().ycalc, x)
8,054
def create_queries(project_id, ticket_number, pids_project_id, pids_dataset_id, pids_table): """ Creates sandbox and truncate queries to run for EHR deactivated retraction :param project_id: bq name of project :param ticket_number: Jira ticket number to identify and title sandbox table :param pids_project_id: deactivated ehr pids table in bq's project_id :param pids_dataset_id: deactivated ehr pids table in bq's dataset_id :param pids_table: deactivated pids table in bq's table name :return: list of queries to run """ queries_list = [] dataset_list = set() final_date_column_df = pd.DataFrame() # Hit bq and receive df of deactivated ehr pids and deactivated date client = get_client(project_id) deactivated_ehr_pids_df = client.query( DEACTIVATED_PIDS_QUERY.render(project=pids_project_id, dataset=pids_dataset_id, table=pids_table)).to_dataframe() date_columns_df = get_date_info_for_pids_tables(project_id, client) LOGGER.info( "Dataframe creation complete. DF to be used for creation of retraction queries." ) for date_row in date_columns_df.itertuples(index=False): # Filter to only include tables containing deactivated pids with the earliest deactivated date LOGGER.info( f'Checking table: {date_row.project_id}.{date_row.dataset_id}.{date_row.table}' ) if check_pid_exist(date_row, client, pids_project_id, pids_dataset_id, pids_table): dataset_list.add(date_row.dataset_id) row = { 'project_id': date_row.project_id, 'dataset_id': date_row.dataset_id, 'table': date_row.table, 'date_column': date_row.date_column, 'start_date_column': date_row.start_date_column, 'end_date_column': date_row.end_date_column } final_date_column_df = final_date_column_df.append( row, ignore_index=True) LOGGER.info( "Looping through the deactivated PIDS df to create queries based on the retractions needed per PID table" ) for ehr_row in deactivated_ehr_pids_df.itertuples(index=False): LOGGER.info(f'Creating retraction queries for PID: {ehr_row.person_id}') for date_row in final_date_column_df.itertuples(index=False): # Determine if dataset is deid to correctly pull pid or research_id and check if ID exists in dataset or if # already retracted if re.match(DEID_REGEX, date_row.dataset_id): pid = get_research_id(date_row.project_id, date_row.dataset_id, ehr_row.person_id, client) else: pid = ehr_row.person_id # Get or create sandbox dataset sandbox_dataset = check_and_create_sandbox_dataset( date_row.project_id, date_row.dataset_id) # Create queries based on type of date field LOGGER.info( f'Creating Query to retract {pid} from {date_row.dataset_id}.{date_row.table}' ) if pd.isnull(date_row.date_column): sandbox_query = SANDBOX_QUERY_END_DATE.render( project=date_row.project_id, sandbox_dataset=sandbox_dataset, dataset=date_row.dataset_id, table=date_row.table, pid=pid, deactivated_pids_project=pids_project_id, deactivated_pids_dataset=pids_dataset_id, deactivated_pids_table=pids_table, end_date_column=date_row.end_date_column, start_date_column=date_row.start_date_column) clean_query = CLEAN_QUERY_END_DATE.render( project=date_row.project_id, dataset=date_row.dataset_id, table=date_row.table, pid=pid, deactivated_pids_project=pids_project_id, deactivated_pids_dataset=pids_dataset_id, deactivated_pids_table=pids_table, end_date_column=date_row.end_date_column, start_date_column=date_row.start_date_column) else: sandbox_query = SANDBOX_QUERY_DATE.render( project=date_row.project_id, sandbox_dataset=sandbox_dataset, dataset=date_row.dataset_id, table=date_row.table, pid=pid, deactivated_pids_project=pids_project_id, deactivated_pids_dataset=pids_dataset_id, deactivated_pids_table=pids_table, date_column=date_row.date_column) clean_query = CLEAN_QUERY_DATE.render( project=date_row.project_id, dataset=date_row.dataset_id, table=date_row.table, pid=pid, deactivated_pids_project=pids_project_id, deactivated_pids_dataset=pids_dataset_id, deactivated_pids_table=pids_table, date_column=date_row.date_column) queries_list.append({ clean_consts.QUERY: sandbox_query, clean_consts.DESTINATION: date_row.project_id + '.' + sandbox_dataset + '.' + (ticket_number + '_' + date_row.table), clean_consts.DESTINATION_DATASET: date_row.dataset_id, clean_consts.DESTINATION_TABLE: date_row.table, clean_consts.DISPOSITION: bq_consts.WRITE_APPEND, 'type': 'sandbox' }) queries_list.append({ clean_consts.QUERY: clean_query, clean_consts.DESTINATION: date_row.project_id + '.' + date_row.dataset_id + '.' + date_row.table, clean_consts.DESTINATION_DATASET: date_row.dataset_id, clean_consts.DESTINATION_TABLE: date_row.table, clean_consts.DISPOSITION: bq_consts.WRITE_TRUNCATE, 'type': 'retraction' }) LOGGER.info( f"Query list complete, retracting ehr deactivated PIDS from the following datasets: " f"{dataset_list}") return queries_list
8,055
def getAxisValueInPercentage(axisValue:float)->int: """This function takes in an axisValue and outputs a percentage as an int"""
8,056
def test_folder_with_one_label(): """[summary] """ # Empty dir empty_dir(TEST_DIRECTORY_PATH) # Build catalog nb_labels = 1 catalog_path, label_paths, img_paths = build_catalog(TEST_DIRECTORY_PATH, nb_labels=nb_labels) # Get all labels from catalog labels = get_labels_from_catalog(catalog_path) # Assert assert len(labels) == nb_labels for label_path in label_paths: label_name = label_path.split("/")[-1] assert label_name in labels # Delete delete_catalog(TEST_DIRECTORY_PATH, catalog_path, label_paths, img_paths)
8,057
def test_handle_rsvp_bad_id( mock_send_reply, make_handler_params, make_time, ): """ Ensures that handle_rsvp failes correctly when the plan ID is not malformed but does not correspond to a plan. """ params = make_handler_params("rsvp not-tjs") plan = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = {plan.uuid: plan} handle_rsvp(params) params.storage.put.assert_not_called() mock_send_reply.assert_called_with( params.client, params.message, "That lunch_id doesn't exist! Type show-plans to see each lunch_id and its associated lunch plan.", )
8,058
def div(spreadsheet: t.IO[str]) -> None: """Each row has one evenly divisible pair - each divided pair is summed.""" click.echo(str(divisor_checksum(spreadsheet)))
8,059
def load_and_estimate(file, arguments, denoise=medfilt, data=None): """Loads mean+std images and evaluates noise. Required for parallelization.""" # Pipeline for µCT data if data is not None: # Evaluate noise on data noises = np.zeros(len(metrics)) for m in range(len(metrics)): noise = estimate_noise(data, metrics[m], kernel_size=kernel_size, denoise_method=denoise) noises[m] = noise return np.array(noises) # Pipeline for images # Get images path = arguments.image_path # Load images image_surf, image_deep, image_calc = load_vois_h5(path, file) # Auto crop if arguments.auto_crop: image_deep, cropped = auto_corner_crop(image_deep) image_calc, cropped = auto_corner_crop(image_calc) # Evaluate noise on mean+std images noises_surf, noises_deep, noises_calc = np.zeros(len(metrics)), np.zeros(len(metrics)), np.zeros(len(metrics)) for m in range(len(metrics)): noise_surf = estimate_noise(image_surf, metrics[m], kernel_size=kernel_size, denoise_method=denoise) noise_deep = estimate_noise(image_deep, metrics[m], kernel_size=kernel_size, denoise_method=denoise) noise_calc = estimate_noise(image_calc, metrics[m], kernel_size=kernel_size, denoise_method=denoise) noises_surf[m] = noise_surf noises_deep[m] = noise_deep noises_calc[m] = noise_calc return np.array((noises_surf, noises_deep, noises_calc))
8,060
def make_fig(): """ make a figure No need to close figures or clean up since the objects will be destroyed when they go out of scope """ fig = Figure() #ax = fig.add_subplot(111) # add a standard subplot # add an axes at left, bottom, width, height; by making the bottom # at 0.3, we save some extra room for tick labels ax = fig.add_axes([0.2, 0.3, 0.7, 0.6]) line, = ax.plot([1,2,3], 'ro--', markersize=12, markerfacecolor='g') # make a translucent scatter collection x = np.random.rand(100) y = np.random.rand(100) area = np.pi*(10 * np.random.rand(100))**2 # 0 to 10 point radiuses c = ax.scatter(x,y,area) c.set_alpha(0.5) # add some text decoration ax.set_title('My first image') ax.set_ylabel('Some numbers') ax.set_xticks( (.2,.4,.6,.8) ) labels = ax.set_xticklabels(('Bill', 'Fred', 'Ted', 'Ed')) # To set object properties, you can either iterate over the # objects manually, or define you own set command, as in setapi # above. for l in labels: l.set_rotation(45) l.set_fontsize(12) canvas = FigureCanvasAgg(fig) canvas.print_figure('webapp', dpi=150)
8,061
def _update_from(x: Dict[str, Any], y: Dict[str, Any], attrs: Sequence[str]) -> None: """ A utility function for copying attributes from one object to another """ for attr in attrs: val = y.get(attr, None) if val is not None: x[attr] = get_val(val)
8,062
def calc_self_attn( bert_model: BertModel, protein: dict, device="cuda:0", **kwargs ): """Calculate self-attention matrices given Bert model for one protein. Args: bert_model: a BertModel instance protein: a dict object from LM-GVP formatted data (json record). device: device to do the computation Returns: torch.tensor of shape: [n_maps, seqlen, seqlen] """ bert_model = bert_model.to(device) bert_model.eval() with torch.no_grad(): self_attn_mats = bert_model( protein["input_ids"].unsqueeze(0).to(device), attention_mask=protein["attention_mask"].unsqueeze(0).to(device), output_attentions=True, ).attentions # gather self-attention map from all layers together n_layers = len(self_attn_mats) batch_size, n_heads, seqlen, _ = self_attn_mats[0].size() self_attn_mats = torch.stack(self_attn_mats, dim=1).view( batch_size, n_layers * n_heads, seqlen, seqlen ) # remove [CLS] and [SEP] self_attn_mats = self_attn_mats[..., 1:-1, 1:-1] if self_attn_mats.size()[0] == 1: self_attn_mats = self_attn_mats.squeeze(0) self_attn_mats = self_attn_mats.detach().cpu() return self_attn_mats
8,063
def MakeDir(path): """Make dir, succeed if it already exists.""" try: os.makedirs(path) except OSError, e: if e.errno != errno.EEXIST: raise
8,064
def compute_median_survival_time(times, surv_function): """ Computes a median survival time estimate by looking for where the survival function crosses 1/2. Parameters ---------- times : 1D numpy array Sorted list of unique times (in ascending order). surv_function : 1D numpy array A survival function evaluated at each of time in `times`, in the same order. Returns ------- output : float Median survival time estimate. """ t_left = times[0] t_right = times[-1] if surv_function[-1] > 1/2: # survival function never crosses 1/2; just output this last time point return t_right for t, s in zip(times, surv_function): if s >= 0.5: t_left = t for t, s in zip(reversed(times), reversed(surv_function)): if s <= 0.5: t_right = t return (t_left + t_right) / 2.
8,065
def TDMAsolver_no_vec(coeffs): """ TDMA solver, a b c d can be NumPy array type or Python list type. refer to http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm and to http://www.cfd-online.com/Wiki/Tridiagonal_matrix_algorithm_-_TDMA_(Thomas_algorithm) """ a = coeffs[1:, 0] b = coeffs[:, 1] c = coeffs[:-1, 2] d = coeffs[:, 3] nf = len(d) # number of equations ac, bc, cc, dc = map(np.array, (a, b, c, d)) # copy arrays for it in range(1, nf): mc = ac[it-1]/bc[it-1] bc[it] = bc[it] - mc*cc[it-1] dc[it] = dc[it] - mc*dc[it-1] xc = bc xc[-1] = dc[-1]/bc[-1] for il in range(nf-2, 1, -1): xc[il] = (dc[il]-cc[il]*xc[il+1])/bc[il] return xc
8,066
def aggregate_ant(data, sub_num, response_type="full"): """ Aggregate data from the ANT task. Calculates various summary statistics for the ANT task for a given subject. Parameters ---------- data : dataframe Pandas dataframe containing a single subjects trial data for the task. sub_num : str Subject number to which the data file belongs. response_type : {'full', 'correct', 'incorrect'}, optional Should the summary data be calculated using all trials? Only correct trials? Or only incorrect trials? This is not supported in all tasks. Returns ------- stats : list List containing the calculated data for the subject. """ # Calculate times following errors and correct responses df = data follow_error_rt = df.loc[df.correct.shift() == 0, "RT"].mean() follow_correct_rt = df.loc[df.correct.shift() == 1, "RT"].mean() if response_type == "correct": df = data[data["correct"] == 1] elif response_type == "incorrect": df = data[data["correct"] == 0] elif response_type == "full": df = data # Aggregated descriptives ## congruency conditions grouped_congruency = df.groupby("congruency") neutral_rt = grouped_congruency.mean().get_value("neutral", "RT") congruent_rt = grouped_congruency.mean().get_value("congruent", "RT") incongruent_rt = grouped_congruency.mean().get_value("incongruent", "RT") neutral_rtsd = grouped_congruency.std().get_value("neutral", "RT") congruent_rtsd = grouped_congruency.std().get_value("congruent", "RT") incongruent_rtsd = grouped_congruency.std().get_value("incongruent", "RT") neutral_rtcov = neutral_rtsd / neutral_rt congruent_rtcov = congruent_rtsd / congruent_rt incongruent_rtcov = incongruent_rtsd / incongruent_rt neutral_correct = grouped_congruency.sum().get_value("neutral", "correct") congruent_correct = grouped_congruency.sum().get_value("congruent", "correct") incongruent_correct = grouped_congruency.sum().get_value("incongruent", "correct") ## cue conditions grouped_cue = df.groupby("cue") nocue_rt = grouped_cue.mean().get_value("nocue", "RT") center_rt = grouped_cue.mean().get_value("center", "RT") spatial_rt = grouped_cue.mean().get_value("spatial", "RT") double_rt = grouped_cue.mean().get_value("double", "RT") nocue_rtsd = grouped_cue.std().get_value("nocue", "RT") center_rtsd = grouped_cue.std().get_value("center", "RT") spatial_rtsd = grouped_cue.std().get_value("spatial", "RT") double_rtsd = grouped_cue.std().get_value("double", "RT") nocue_rtcov = nocue_rtsd / nocue_rt center_rtcov = center_rtsd / center_rt spatial_rtcov = spatial_rtsd / spatial_rt double_rtcov = double_rtsd / double_rt nocue_correct = grouped_cue.sum().get_value("nocue", "correct") center_correct = grouped_cue.sum().get_value("center", "correct") spatial_correct = grouped_cue.sum().get_value("spatial", "correct") double_correct = grouped_cue.sum().get_value("double", "correct") # OLS regression conflict_intercept, conflict_slope = congruent_rt, incongruent_rt - congruent_rt conflict_slope_norm = conflict_slope / congruent_rt alerting_intercept, alerting_slope = double_rt, nocue_rt - double_rt alerting_slope_norm = alerting_slope / double_rt orienting_intercept, orienting_slope = spatial_rt, center_rt - spatial_rt orienting_slope_norm = orienting_slope / spatial_rt return [ sub_num, follow_error_rt, follow_correct_rt, neutral_rt, congruent_rt, incongruent_rt, neutral_rtsd, congruent_rtsd, incongruent_rtsd, neutral_rtcov, congruent_rtcov, incongruent_rtcov, neutral_correct, congruent_correct, incongruent_correct, nocue_rt, center_rt, spatial_rt, double_rt, nocue_rtsd, center_rtsd, spatial_rtsd, double_rtsd, nocue_rtcov, center_rtcov, spatial_rtcov, double_rtcov, nocue_correct, center_correct, spatial_correct, double_correct, conflict_intercept, conflict_slope, conflict_slope_norm, alerting_intercept, alerting_slope, alerting_slope_norm, orienting_intercept, orienting_slope, orienting_slope_norm, ]
8,067
def parse_search_after(params): """Validate search_after and return it as a list of [score, ID].""" search_pair = params.get("search_after") sort = params.get("sort") if not search_pair or not sort: return if '_' not in search_pair or len(search_pair.split("_")) != 2: return _score, _id = search_pair.split("_") _sort = sort.split("_")[0] if _sort not in ["relevance", "created"]: log.error("{} is not a supported sort value.".format(_sort)) return if _sort == "relevance": score = test_float(_score) if score is None: log.error("Search_after relevance score is not a float.") return elif _sort == "created": if not str(_score).isdigit(): log.error("Search_after date score is not an integer.") return score = int(_score) return [score, _id]
8,068
def read_csv(filepath_or_buffer: str, usecols: List[Literal["e", "b", "a"]]): """ usage.modin: 1 """ ...
8,069
def compute_cosine_distance( features, others=None, cuda=False, ): """Computes cosine distance. Args: input1 (torch.Tensor): 2-D feature matrix. input2 (torch.Tensor): 2-D feature matrix. Returns: torch.Tensor: distance matrix. """ if others is None: if cuda: features = features.cuda() features = F.normalize(features, p=2, dim=1) dist_m = 1 - torch.mm(features, features.t()) else: if cuda: features = features.cuda() others = others.cuda() features = F.normalize(features, p=2, dim=1) others = F.normalize(others, p=2, dim=1) dist_m = 1 - torch.mm(features, others.t()) return dist_m.cpu().numpy()
8,070
def convert_dict_keys_case(obj: Any, case_style: str = CaseStyle.CAMEL): """ This function recursively changes the case of all the keys in the obj argument """ case_style = process_case_style(case_style=case_style) if isinstance(obj, (tuple, list)): return type(obj)( [convert_dict_keys_case(item, case_style) for item in obj] ) elif isinstance(obj, dict): return { convert_string_case(key, case_style): convert_dict_keys_case( value, case_style ) for key, value in obj.items() if key } else: return obj
8,071
def tmobilenet(lanes): """Mobilenet test template. Paramters --------- lanes : Int The number of vector lanes. """ if skip_test(): return if not is_tflite_available(): return model = get_mobilenet_model() mod, params = compile_model_to_relay(model) mod = offload(mod) lib = compile_hardware(lanes) opts = compiler_opts(lib) clear_stats() res = run_model(mod, params, opts) values = stats() check_result(res) print_test_info(lanes, values["cycle_counter"])
8,072
def chain_exception(new_exc, old_exc): """Set the __cause__ attribute on *new_exc* for explicit exception chaining. Returns the inplace modified *new_exc*. """ if DEVELOPER_MODE: new_exc.__cause__ = old_exc return new_exc
8,073
def wrap_class(cls, class_name, class_method_inst): """ wrap class methods with instrumentation calls """ if not cls: return for (method, method_log_args) in class_method_inst.iteritems(): fn = getattr(cls, method, None) if not fn: # Not all methods may be in all versions of pymongo... continue kvs = { 'Class': '%s.%s' % (cls.__module__, cls.__name__), 'Function': method, 'Action': '%s.%s' % (class_name, method), } # XXX Not Python2.4-friendly setattr(cls, method, oboe.log_method(PYMONGO_LAYER, entry_kvs=kvs, **method_log_args)(fn))
8,074
def make_input_fn(x_out, prob_choice): """Use py_func to yield elements from the given generator.""" inp = {"inputs": np.array(x_out).astype(np.int32), "problem_choice": prob_choice} flattened = tf.contrib.framework.nest.flatten(inp) types = [t.dtype for t in flattened] shapes = [[None] * len(t.shape) for t in flattened] first_ex_list = [inp] def py_func(): if first_ex_list: example = first_ex_list.pop() else: example = inp return tf.contrib.framework.nest.flatten(example) def input_fn(): flat_example = tf.py_func(py_func, [], types) _ = [t.set_shape(shape) for t, shape in zip(flat_example, shapes)] example = tf.contrib.framework.nest.pack_sequence_as(inp, flat_example) return example return input_fn
8,075
def test_artifact_ungroup(element_factory): """Test removal of artifact from node.""" n = element_factory.create(UML.Node) a = element_factory.create(UML.Artifact) assert group(n, a) assert ungroup(n, a) assert not n.deployment assert not element_factory.lselect(UML.Deployment)
8,076
def url_validate(url): """ URL验证 用于登录传递URL """ regex = r'^\?next=((/\w+)*)' if isinstance(url, str) and re.match(regex, url): return url.split('?next=')[-1] return '/'
8,077
def mie_harmonics(x: np.ndarray, L: int) -> Tuple[np.ndarray]: """Calculates the spherical harmonics of the mie field. The harmonics are calculated up to order L using the iterative method. Parameters ---------- x : ndarray The cosine of the angle defined by the line passing through origo parallel to the propagation direction and the evaluation point, with the corner at origo. L : int The order up to which to evaluate the harmonics. The L:th Returns ------- ndarray, ndarray Tuple of ndarray of shape (L, *x.shape) """ PI = np.zeros((L, *x.shape)) TAU = np.zeros((L, *x.shape)) PI[0, :] = 1 PI[1, :] = 3 * x TAU[0, :] = x TAU[1, :] = 6 * x * x - 3 for i in range(3, L + 1): PI[i - 1] = (2 * i - 1) / (i - 1) * x * PI[i - 2] - i / (i - 1) * PI[i - 3] TAU[i - 1] = i * x * PI[i - 1] - (i + 1) * PI[i - 2] return PI, TAU
8,078
def is_version_dir(vdir): """Check whether the given directory contains an esky app version. Currently it only need contain the "esky-files/bootstrap-mainfest.txt" file. """ if exists(pathjoin(vdir,ESKY_CONTROL_DIR,"bootstrap-manifest.txt")): return True return False
8,079
def session_decrypt_raw(encrypted_message, destination_key): """ Decrypts the message from a random session key, encrypted with the destination key. Superior alternative when the destination key is slow (ex RSA). """ block_size = destination_key.block_size encrypted_session_key = encrypted_message[:block_size] message = encrypted_message[block_size:] session_key = AesKey(destination_key.decrypt_raw(encrypted_session_key)) return session_key.decrypt_raw(message)
8,080
def gef_pybytes(x): """Returns an immutable bytes list from the string given as input.""" return bytes(str(x), encoding="utf-8")
8,081
def plot_2d_morphing_basis( morpher, xlabel=r"$\theta_0$", ylabel=r"$\theta_1$", xrange=(-1.0, 1.0), yrange=(-1.0, 1.0), crange=(1.0, 100.0), resolution=100, ): """ Visualizes a morphing basis and morphing errors for problems with a two-dimensional parameter space. Parameters ---------- morpher : PhysicsMorpher PhysicsMorpher instance with defined basis. xlabel : str, optional Label for the x axis. Default value: r'$\theta_0$'. ylabel : str, optional Label for the y axis. Default value: r'$\theta_1$'. xrange : tuple of float, optional Range `(min, max)` for the x axis. Default value: (-1., 1.). yrange : tuple of float, optional Range `(min, max)` for the y axis. Default value: (-1., 1.). crange : tuple of float, optional Range `(min, max)` for the color map. Default value: (1., 100.). resolution : int, optional Number of points per axis for the rendering of the squared morphing weights. Default value: 100. Returns ------- figure : Figure Plot as Matplotlib Figure instance. """ basis = morpher.basis assert basis is not None, "No basis defined" assert basis.shape[1] == 2, "Only 2d problems can be plotted with this function" xi, yi = (np.linspace(xrange[0], xrange[1], resolution), np.linspace(yrange[0], yrange[1], resolution)) xx, yy = np.meshgrid(xi, yi) xx, yy = xx.reshape((-1, 1)), yy.reshape((-1, 1)) theta_test = np.hstack([xx, yy]) squared_weights = [] for theta in theta_test: wi = morpher.calculate_morphing_weights(theta, None) squared_weights.append(np.sum(wi * wi) ** 0.5) squared_weights = np.array(squared_weights).reshape((resolution, resolution)) fig = plt.figure(figsize=(6.5, 5)) ax = plt.gca() pcm = ax.pcolormesh( xi, yi, squared_weights, norm=matplotlib.colors.LogNorm(vmin=crange[0], vmax=crange[1]), cmap="viridis_r" ) cbar = fig.colorbar(pcm, ax=ax, extend="both") plt.scatter(basis[:, 0], basis[:, 1], s=50.0, c="black") plt.xlabel(xlabel) plt.ylabel(ylabel) cbar.set_label(r"$\sqrt{\sum w_i^2}$") plt.xlim(xrange[0], xrange[1]) plt.ylim(yrange[0], yrange[1]) plt.tight_layout() return fig
8,082
def test_masterdata__Table__3(address_book, browser, login): """It renders no add link for any calendar user.""" browser.login(login) browser.open(browser.CALENDAR_MASTERDATA_EVENTVIEW_URL) with pytest.raises(LinkNotFoundError): browser.getLink(EVENT_VIEW_CONFIGURATION_ADD_TEXT)
8,083
def single_lut_conversion(lookup_table): """ This constructs the function to convert data using a single lookup table. Parameters ---------- lookup_table : numpy.ndarray Returns ------- callable """ _validate_lookup(lookup_table) def converter(data): if not isinstance(data, numpy.ndarray): raise ValueError('requires a numpy.ndarray, got {}'.format(type(data))) if data.dtype.name not in ['uint8', 'uint16']: raise ValueError('requires a numpy.ndarray of uint8 or uint16 dtype, ' 'got {}'.format(data.dtype.name)) if len(data.shape) == 3 and data.shape[2] != 1: raise ValueError('Requires a three-dimensional numpy.ndarray, ' 'with single band in the last dimension. Got shape {}'.format(data.shape)) return lookup_table[data[:, :, 0]] return converter
8,084
def signal_average(cov,bin_edges=None,bin_width=40,kind=3,lmin=None,dlspace=True,return_bins=False,**kwargs): """ dcov = cov * ellfact bin dcov in annuli interpolate back on to ell cov = dcov / ellfact where ellfact = ell**2 if dlspace else 1 """ modlmap = cov.modlmap() assert np.all(np.isfinite(cov)) dcov = cov*modlmap**2. if dlspace else cov.copy() if lmin is None: minell = maps.minimum_ell(dcov.shape,dcov.wcs) else: minell = modlmap[modlmap<=lmin].max() if bin_edges is None: bin_edges = np.append([2],np.arange(minell,modlmap.max(),bin_width)) binner = stats.bin2D(modlmap,bin_edges) cents,c1d = binner.bin(dcov) outcov = enmap.enmap(maps.interp(cents,c1d,kind=kind,fill_value=c1d[-1],**kwargs)(modlmap),dcov.wcs) with np.errstate(invalid='ignore'): outcov = outcov / modlmap**2. if dlspace else outcov outcov[modlmap<2] = 0 assert np.all(np.isfinite(outcov)) if return_bins: return cents,c1d,outcov else: return outcov
8,085
def count_sort(data: list, log: bool=False) -> None: """Sorts a list of positive integers from least to greatest. The count sort algorithm is a type of integer sorting algorithm. It sorts a list by finding the maximum number within that list, creating a different list of that maximum size, and using this list to perform index arithmetic to calculate the position of the different numbers in order to create a sorted list. If the list is of length n with a maximum positive integer in there of size k, then this algorithm has a time complexity of O(n + k). Params: data (list[float or int]): a list of comparable items log (bool): a truth value to tell the algorithm to log the different steps in sorting """ n = len(data) k = max(data) + 1 # Create count array and output array. count = [0]*k output = [0]*n # Get the frequencies of all number in the data array. for i in data: count[i] += 1 # Create the cumulative frequency array. for i in range(1, k): count[i] += count[i-1] # Fill in the output array and decrease the frequency values once done. for i in data: output[count[i]-1] = i count[i] -= 1 if log: COUNT_DATA.append(data.copy()) # Copy output array into data array. for i in range(n): if log: COUNT_DATA.append(data.copy()) data[i] = output[i]
8,086
def _create_parameters_file(path): """ Saves an example parameters json file where the sprites and the settings are specified. :param str path: path where to save file """ settings = agglomerate.SheetSettings(_default_algorithm, _default_format) settings_dict = settings.to_dict() sprites = ["example/path/*.png"] root = { "sprites": sprites, "settings": settings_dict } # create json string indented by 4 spaces json_string = json.dumps(root, indent=4) with open(path, "w") as f: f.write(json_string)
8,087
def find_tree_diameter(g): """ Standard awesome problem So for each node, I want to find the maximum distance to another node :param n: :param g: :return: """ # First finding the arbitary node that is maximum distance from root # DFS - First time q = deque() q.append((1,0)) arbitrary_node = None visited = set() curr_max_length = 0 while q: node, length = q.pop() visited.add(node) if length > curr_max_length: curr_max_length = length arbitrary_node = node for nei in g[node]: if nei not in visited: q.append((nei, length + 1)) # Now keep this arbitary node as root, and find the node that is the maximum depth to it # That is the diameter of the tree # DFS second time q2 = deque() q2.append((arbitrary_node, 0)) diameter_of_tree = 0 visited2 = set() while q2: node, length = q2.pop() visited2.add(node) if length >= diameter_of_tree: diameter_of_tree = length for nei in g[node]: if nei not in visited2: q2.append((nei, length + 1)) return diameter_of_tree
8,088
def edge_list_to_adjacency(edges): """ Create adjacency dictionary based on a list of edges :param edges: edges to create adjacency for :type edges: :py:list :rtype: :py:dict """ adjacency = dict([(n, []) for n in edge_list_to_nodes(edges)]) for edge in edges: adjacency[edge[0]].append(edge[1]) return adjacency
8,089
def __renormalized_likelihood_above_threshold_lnlikelihood(data, thr=__thr, alpha=models.__alpha, beta=models.__beta, num_mc=models.__num_mc, **kwargs): """ only include data that is above thr, treats them all as signals, and renormalizes the likelihood so that it only covers "detectable data" """ truth = data[:,0]>=thr if np.any(truth): norm = 1-np.exp(models.signalData_lncdf(thr, alpha=alpha, beta=beta, num_mc=num_mc)) ### normalization of likelihood for data above threshold return np.sum(models.signalData_lnpdf(data[truth][:,0], alpha=alpha, beta=beta, num_mc=num_mc) - np.log(norm)) else: return 0
8,090
def run(options, configfile): """Run waterpy with a model configuration file. The model configuration file contains the specifications for a model run. This command takes in the path to model configuration file. """ try: click.echo("Running model...") waterpy(configfile, options) click.echo("Finished!") click.echo("Output saved as specified in the model config file.") except Exception as err: click.echo(err, traceback.print_exc()) sys.exit(1) if options.verbose: click.echo("Verbose on") if options.show: click.echo("Show on")
8,091
def _build_tags(model_uri, model_python_version=None, user_tags=None): """ :param model_uri: URI to the MLflow model. :param model_python_version: The version of Python that was used to train the model, if the model was trained in Python. :param user_tags: A collection of user-specified tags to append to the set of default tags. """ tags = dict(user_tags) if user_tags is not None else {} tags["model_uri"] = model_uri if model_python_version is not None: tags["python_version"] = model_python_version return tags
8,092
def test_token(current_user: usermodels.User = Depends(get_current_user)): """ Test access token """ return current_user
8,093
def student_list_prof_request(): """Return a JSON containing adding instructor requests, or raise 401 if not authorized.""" role_student = Role.query.filter_by(name='student').first() if current_user.is_authenticated and has_membership(current_user.id, role_student): list_approved = request.args.get('approved', type=int) or 0 list_pending = request.args.get('pending', type=int) or 0 list_declined = request.args.get('declined', type=int) or 0 prof_requests = [] if list_approved: prof_requests.extend(AddProfRequest.query.filter_by( user_id=current_user.id, approved=ApprovalType.APPROVED, ).all()) if list_pending: prof_requests.extend(AddProfRequest.query.filter_by( user_id=current_user.id, approved=ApprovalType.PENDING, ).all()) if list_declined: prof_requests.extend(AddProfRequest.query.filter_by( user_id=current_user.id, approved=ApprovalType.DECLINED, ).all()) ret = [] for prof_request in prof_requests: ret.append({ 'id': prof_request.id, 'name': prof_request.name, 'department_id': prof_request.department.id, 'course_id': prof_request.course.id, 'term_id': prof_request.term.id, 'approved': prof_request.approved.value, }) return jsonify(ret) else: abort(401)
8,094
def set_complete(request, id): """ Marque un ticket comme complet :param request: :param id: """ ticket = Tickets.objects.get(pk=id) ticket.complete = 1 ticket.save() return redirect('/ticket/id=%s' % id)
8,095
def parse_version_from_path(path): """Get version parts from a path name.""" path = pathlib.Path(path).absolute() version = path.name try: parts = version.split("_") ret = {} ret["major"] = try_int(parts[0]) ret["minor"] = try_int(parts[1]) ret["protocol"] = try_int(parts[2]) ret["build"] = try_int(parts[3]) ret["string"] = version.replace("_", ".") ret["file"] = version except Exception: error = "Bad API version in '{p}', must look like: '7_2_314_3181'" error = error.format(p=path) raise Exception(error) return ret
8,096
def assign_partitions_to_actors( ip_to_parts: Dict[int, Any], actor_rank_ips: Dict[int, str]) -> Dict[int, Sequence[Any]]: """Assign partitions from a distributed dataframe to actors. This function collects distributed partitions and evenly distributes them to actors, trying to minimize data transfer by respecting co-locality. This function currently does _not_ take partition sizes into account for distributing data. It assumes that all partitions have (more or less) the same length. Instead, partitions are evenly distributed. E.g. for 8 partitions and 3 actors, each actor gets assigned 2 or 3 partitions. Which partitions are assigned depends on the data locality. The algorithm is as follows: For any number of data partitions, get the Ray object references to the shards and the IP addresses where they currently live. Calculate the minimum and maximum amount of partitions per actor. These numbers should differ by at most 1. Also calculate how many actors will get more partitions assigned than the other actors. First, each actor gets assigned up to ``max_parts_per_actor`` co-located partitions. Only up to ``num_actors_with_max_parts`` actors get the maximum number of partitions, the rest try to fill the minimum. The rest of the partitions (all of which cannot be assigned to a co-located actor) are assigned to actors until there are none left. """ num_partitions = sum(len(parts) for parts in ip_to_parts.values()) num_actors = len(actor_rank_ips) min_parts_per_actor = max(0, math.floor(num_partitions / num_actors)) max_parts_per_actor = max(1, math.ceil(num_partitions / num_actors)) num_actors_with_max_parts = num_partitions % num_actors # This is our result dict that maps actor objects to a list of partitions actor_to_partitions = defaultdict(list) # First we loop through the actors and assign them partitions from their # own IPs. Do this until each actor has `min_parts_per_actor` partitions partition_assigned = True while partition_assigned: partition_assigned = False # Loop through each actor once, assigning for rank, actor_ip in actor_rank_ips.items(): num_parts_left_on_ip = len(ip_to_parts[actor_ip]) num_actor_parts = len(actor_to_partitions[rank]) if num_parts_left_on_ip > 0 and \ num_actor_parts < max_parts_per_actor: if num_actor_parts >= min_parts_per_actor: # Only allow up to `num_actors_with_max_parts actors to # have the maximum number of partitions assigned. if num_actors_with_max_parts <= 0: continue num_actors_with_max_parts -= 1 actor_to_partitions[rank].append(ip_to_parts[actor_ip].pop(0)) partition_assigned = True # The rest of the partitions, no matter where they are located, could not # be assigned to co-located actors. Thus, we assign them # to actors who still need partitions. rest_parts = list(itertools.chain(*ip_to_parts.values())) partition_assigned = True while len(rest_parts) > 0 and partition_assigned: partition_assigned = False for rank in actor_rank_ips: num_actor_parts = len(actor_to_partitions[rank]) if num_actor_parts < max_parts_per_actor: if num_actor_parts >= min_parts_per_actor: if num_actors_with_max_parts <= 0: continue num_actors_with_max_parts -= 1 actor_to_partitions[rank].append(rest_parts.pop(0)) partition_assigned = True if len(rest_parts) <= 0: break if len(rest_parts) != 0: raise RuntimeError( "There are still partitions left to assign, but no actor " "has capacity for more. This is probably a bug. Please go " "to https://github.com/ray-project/xgboost_ray to report it.") return actor_to_partitions
8,097
async def test_dyson_set_temperature_when_cooling_mode( mocked_login, mocked_devices, hass ): """Test set climate temperature when heating is off.""" await async_setup_component(hass, DYSON_DOMAIN, _get_config()) await hass.async_block_till_done() device = mocked_devices.return_value[0] device.temp_unit = TEMP_CELSIUS await hass.services.async_call( DOMAIN, SERVICE_SET_TEMPERATURE, {ATTR_ENTITY_ID: "climate.temp_name", ATTR_TEMPERATURE: 23}, True, ) set_config = device.set_configuration assert set_config.call_args == call( heat_mode=HeatMode.HEAT_ON, heat_target=HeatTarget.celsius(23) )
8,098
def infer(test_reader, vocab_tag, use_cuda, model_path): """ inference function """ place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace() exe = fluid.Executor(place) with fluid.scope_guard(fluid.core.Scope()): infer_program, feed_target_names, fetch_vars = fluid.io.load_inference_model( model_path, exe) t0 = time.time() step_id = 0 true_num = 0 all_num = 0 size = len(vocab_tag) value = [] for data in test_reader(): step_id += 1 lod_text_seq = utils.to_lodtensor([dat[0] for dat in data], place) lod_tag = utils.to_lodtensor([dat[1] for dat in data], place) lod_pos_tag = utils.to_lodtensor([dat[2] for dat in data], place) para = exe.run( infer_program, feed={ "text": lod_text_seq, "pos_tag": lod_tag}, fetch_list=fetch_vars, return_numpy=False) value.append(para[0]._get_float_element(0)) if step_id % size == 0 and step_id > 1: all_num += 1 true_pos = [dat[2] for dat in data][0][0] if value.index(max(value)) == int(true_pos): true_num += 1 value = [] if step_id % 1000 == 0: print(step_id, 1.0 * true_num / all_num) t1 = time.time()
8,099