content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from io import StringIO def unparse(input_dict, output=None, encoding='utf-8', **kwargs): """Emit an XML document for the given `input_dict` (reverse of `parse`). The resulting XML document is returned as a string, but if `output` (a file-like object) is specified, it is written there instead. Dictionary keys p...
31cd6225144fcd1296105a66d2318c6d1a22bcca
3,648,900
import os def create_callbacks(model, data, ARGS): """Create keras custom callback with checkpoint and logging""" # Create callbacks if not os.path.exists(ARGS.out_directory): os.makedirs(ARGS.out_directory) # log to Model/log.txt as specified by ARGS.out_directory checkpoint_cb = ModelCh...
10719e27298d41c2a4362d4bf190b3c2b4e606d1
3,648,901
import os import urllib def fetch_or_use_cached(temp_dir, file_name, url): # type: (str, str, str) -> str """ Check for a cached copy of the indicated file in our temp directory. If a copy doesn't exist, download the file. Arg: temp_dir: Local temporary dir file_name: Name of the file within the t...
29dfcf983a35c277c15f290f044a07ecee05dd0f
3,648,902
def to_bin(val): """ Receive int and return a string in binary. Padded by 32 bits considering 2's complement for negative values """ COMMON_DIGITS = 32 val_str = "{:b}".format(val) # Count '-' in negative case padded_len = len(val_str) + ((COMMON_DIGITS - (len(val_str) % COMMON_DIGITS)) % COMMON...
819d1c0a9d387f6ad1635f0fe0e2ab98b3ca17b0
3,648,903
def PSingle (refLamb2, lamb2, qflux, qsigma, uflux, usigma, err, nterm=2): """ Fit RM, EVPA0 to Q, U flux measurements Also does error analysis Returns array of fitter parameters, errors for each and Chi Squares of fit refLamb2 = Reference lambda^2 for fit (m^2) lamb2 = Array of lambda^2 f...
29c3fd75203317265cccc804b1114b5436fd12bc
3,648,904
from typing import List def exec_waveform_function(wf_func: str, t: np.ndarray, pulse_info: dict) -> np.ndarray: """ Returns the result of the pulse's waveform function. If the wf_func is defined outside quantify-scheduler then the wf_func is dynamically loaded and executed using :func:`~quantify...
29c44de1cc94f6d63e41fccbbef5c23b67870b4d
3,648,905
def generate_straight_pipeline(): """ Simple linear pipeline """ node_scaling = PrimaryNode('scaling') node_ridge = SecondaryNode('ridge', nodes_from=[node_scaling]) node_linear = SecondaryNode('linear', nodes_from=[node_ridge]) pipeline = Pipeline(node_linear) return pipeline
2ef1d8137aeb100f6216d6a853fe22953758faf3
3,648,906
def get_socialnetwork_image_path(instance, filename): """ Builds a dynamic path for SocialNetwork images. This method takes an instance an builds the path like the next pattern: /simplesite/socialnetwork/PAGE_SLUG/slugified-path.ext """ return '{0}/{1}/{2}/{3}'.format(instance._meta.app_label, ...
b54e53f0c2a79b3b4e6d4d496d6a85264fffcef1
3,648,907
def openReadBytesFile(path: str): """ 以只读模式打开二进制文件 :param path: 文件路径 :return: IO文件对象 """ return openFile(path, "rb")
72fd2be5264a27a2c5c328cb7a8a4e818d799447
3,648,908
from datetime import datetime def diff_time(a:datetime.time,b:datetime.time): """ a-b in seconds """ return 3600 * (a.hour -b.hour) + 60*(a.minute-b.minute) + (a.second-b.second) + (a.microsecond-b.microsecond)/1000000
e0557d3d3e1e9e1184d7ea7a84665813e7d32760
3,648,909
def _create_pseudo_names(tensors, prefix): """Creates pseudo {input | output} names for subclassed Models. Warning: this function should only be used to define default names for `Metics` and `SavedModel`. No other use cases should rely on a `Model`'s input or output names. Example with dict: `{'a': [x1, ...
5e4ee64026e9eaa8aa70dab85d8dcf0ad0b6d89f
3,648,910
import sqlite3 def search_for_breakpoint(db_name, ids): """ Function will retrieve ID of last caluclated grid node to continue interrupted grid caclulation. :param db_name: str; :param ids: numpy.array; list of grid node ids to calculate in this batch :return: int; grid node from which start the ...
3354fcd505de9aefae5f0b4448e1ada7eab0a092
3,648,911
import os def reddit_client_secret() -> str: """Client secret of the reddit app.""" value = os.getenv("REDDIT_CLIENT_SECRET") if not value: raise ValueError("REDDIT_CLIENT_SECRET environment variable not set") return value
dfddbb4b7306b9638b68f3b75721471a82118a64
3,648,912
def rgetattr(obj, attr): """ Get named attribute from an object, i.e. getattr(obj, 'a.a') is equivalent to ``obj.a.a''. - obj: object - attr: attribute name(s) >>> class A: pass >>> a = A() >>> a.a = A() >>> a.a.a = 1 >>> rgetattr(a, 'a.a') 1 >>> rgetattr(a, 'a.c') ...
5fb58634c4ba910d0a20753c04addf667614a07f
3,648,913
def lambda1_plus_lambda2(lambda1, lambda2): """Return the sum of the primary objects tidal deformability and the secondary objects tidal deformability """ return lambda1 + lambda2
4ac3ef51bb66861b06b16cec564f0773c7692775
3,648,914
import os def __create_resource_management_client(): """ Create a ResourceManagementClient object using the subscription ID from environment variables """ subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", None) if subscription_id is None: return None return ResourceManagement...
99ced5240542eb41ff33f4ea88c1b170e5e0a9bd
3,648,915
def create_cut_sht(stockOutline,array,features,partSpacing,margin): """ """ numParts = len(array) basePlanes = generate_base_planes_from_array(array) targetPlanes = create_cut_sht_targets(stockOutline,array,margin,partSpacing) if targetPlanes == None: return None else: # converts...
12d8f56a7b38b06cd89d86fdbf0096f5c8d6e869
3,648,916
def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool """ assert isinstance(u_string, str) try: u_string.encode('ascii') return Tru...
2a742c7334d68fe0bf6b546fb79bf00a338355f9
3,648,917
def duplicate_item(api_key: str, board_id: str, item_id: str, *args, **kwargs): """Duplicate an item. Parameters api_key : `str` The monday.com v2 API user key. board_id : `str` The board's unique identifier. item_id : `str` ...
9e24952a2443b4bcf40d2ae5e3e9d65b8485fece
3,648,918
import re def hdparm_secure_erase(disk_name, se_option): """ Secure erase using hdparm tool :param disk_name: disk to be erased :param se_option: secure erase option :return: a dict includes SE command exitcode and SE message """ # enhance_se = ARG_LIST.e log_file = disk_name.split("/"...
7232abd8caaa2cbf52ebf2e7e852c81475ec2ca2
3,648,919
def compute_loss(retriever_logits, retriever_correct, reader_logits, reader_correct): """Compute loss.""" # [] retriever_loss = marginal_log_loss(retriever_logits, retriever_correct) # [] reader_loss = marginal_log_loss( tf.reshape(reader_logits, [-1]), tf.reshape(reader_correct, [-1])...
2576191d23a303e9d045cb7c8bbeccbd49b22b43
3,648,920
import os def is_using_git(): """True if git checkout is used.""" return os.path.exists(os.path.join(REPO_ROOT, '.git', 'objects'))
23df0df4a97c52f8576ba5fc1437695601c94cc2
3,648,921
def index() -> render_template: """ The main part of the code that is ran when the user visits the address. Parameters: covid_data: This is a dictionary of the data returned from the API request. local_last7days_cases: The number of local cases in the last 7 days. national_last7days_cases: The ...
d9357f29c9329c901e8389497435ead319841242
3,648,922
def r(x): """ Cartesian radius of a point 'x' in 3D space Parameters ---------- x : (3,) array_like 1D vector containing the (x, y, z) coordinates of a point. Returns ------- r : float Radius of point 'x' relative to origin of coordinate system """ return np.sqr...
3729f91a6671c17bc9fda7eebb9809d316a0d714
3,648,923
def solve(*args): """ Crunch the numbers; solve the problem. solve(IM A, IM b) -> IM solve(DM A, DM b) -> DM solve(SX A, SX b) -> SX solve(MX A, MX b) -> MX solve(IM A, IM b, str lsolver, dict opts) -> IM solve(DM A, DM b, str lsolver, dict opts) -> DM solve(SX A, SX b, str lsolver,...
8866fba2efa51e7117d1d39fd7d2b7a259209c66
3,648,924
def NonNegativeInteger(num): """ Ensures that the number is non negative """ if num < 0: raise SmiNetValidationError("A non-negative integer is required") return num
dc5241e8dd7dbd07c5887c35a790ec4eab2593f0
3,648,925
def to_cartesian(r, ang): """Returns the cartesian coordinates of a polar point.""" x = r * np.cos(ang) y = r * np.sin(ang) return x, y
bc4e2e21c42b31a7a45185e58fb20a7b4a4b52e4
3,648,926
def _get_filtered_partially_learnt_topic_summaries( topic_summaries, topic_ids): """Returns a list of summaries of the partially learnt topic ids and the ids of topics that are no longer present. Args: topic_summaries: list(TopicSummary). The list of topic summary domain objects...
c977966381dea0b1b91e904c3f9ec4823d26b006
3,648,927
def build_bar_chart_with_two_bars_per_label(series1, series2, series1_label, series2_label, series1_labels, series2_labels, title, x_axis_label, y_axis_label, output_file_name): """ This function builds a bar chart that has ...
f43c4e525f0a2dd07b815883753974e1aa2e08cf
3,648,928
def calculateDescent(): """ Calculate descent timestep """ global descentTime global tod descentTime = myEndTime line = len(originalTrajectory) for segment in reversed(originalTrajectory): flInit = int(segment[SEGMENT_LEVEL_INIT]) flEnd = int(segment[SEGMENT_LEVEL_END]) status = segment[STATUS] if flIn...
11c04e49ef63f7f51cb874bf19cd245c40f0f6f4
3,648,929
def update_tutorial(request,pk): """View function for updating tutorial """ tutorial = get_object_or_404(Tutorial, pk=pk) form = TutorialForm(request.POST or None, request.FILES or None, instance=tutorial) if form.is_valid(): form.save() messages.success(request=request, message="Congra...
06fe827f26537fe376e79bc95d2ab04f879b971a
3,648,930
def get_transform_dest_array(output_size): """ Returns a destination array of the desired size. This is also used to define the order of points necessary for cv2.getPerspectiveTransform: the order can change, but it must remain consistent between these two arrays. :param output_size: The size to mak...
84f092b5f263f3dd65ea9dfb18890454666e982d
3,648,931
def fetch(url): """ 引数urlで与えられたURLのWebページを取得する。 WebページのエンコーディングはContent-Typeヘッダーから取得する。 戻り値:str型のHTML """ f = urlopen(url) # HTTPヘッダーからエンコーディングを取得する(明示されていない場合はutf-8とする)。 encoding = f.info().get_content_charset(failobj="utf-8") html = f.read().decode(encoding) # 得られたエンコーディングを指定して文字...
31b69019f35e983a7a6c9d60b4367502b6540c56
3,648,932
import grp import os import subprocess def _is_industrial_user(): """Checking if industrial user is trying to use relion_it..""" if not grp: # We're not on a linux/unix system, therefore not at Diamond return False not_allowed = ["m10_valid_users", "m10_staff", "m08_valid_users", "m08_sta...
8b462431a96b25b7fc9a456807bfcd087a799651
3,648,933
def get_rounded_coordinates(point): """Helper to round coordinates for use in permalinks""" return str(round(point.x, COORDINATE_ROUND)) + '%2C' + str(round(point.y, COORDINATE_ROUND))
a707864e4b62a91e609b3674bdfe0de7fdddf154
3,648,934
def rgb_to_hls(image: np.ndarray, eps: float = 1e-8) -> np.ndarray: """Convert a RGB image to HLS. Image data is assumed to be in the range of [0.0, 1.0]. Args: image (np.ndarray[B, 3, H, W]): RGB image to be converted to HLS. eps (float): Epsilon value to avoid div ...
841379110bd273a7a6239e3598656c46acbde583
3,648,935
def array_max_dynamic_range(arr): """ Returns an array scaled to a minimum value of 0 and a maximum value of 1. """ finite_arr = arr[np.isfinite(arr)] low = np.nanmin(finite_arr) high = np.nanmax(finite_arr) return (arr - low)/(high - low)
b2182c43dea2981b3759119cf1381a82a9e168b1
3,648,936
def production(*args): """Creates a production rule or list of rules from the input. Supports two kinds of input: A parsed string of form "S->ABC" where S is a single character, and ABC is a string of characters. S is the input symbol, ABC is the output symbols. Neither...
bcb3e415a283f654ab65e0656a3c7e3912eeb53b
3,648,937
def _unpack_compute(input_place, num, axis): """Unpack a tensor into `num` tensors along axis dimension.""" input_shape = get_shape(input_place) for index, _ in enumerate(input_shape): input_shape[index] = input_shape[index] if index != axis else 1 output_shape_list = [input_shape for i in ran...
89972e932d3c0bf3b5cbc548633dd2b2a6173c85
3,648,938
def flatten(items): """Convert a sequence of sequences to a single flat sequence. Works on dictionaries, tuples, lists. """ result = [] for item in items: if isinstance(item, list): result += flatten(item) else: result.append(item) return result
d44e3391f791dfd2ec9b323c37c510a415bb23bf
3,648,939
from typing import Dict def _datum_to_cap(datum: Dict) -> float: """Cap value of a datum.""" return _cap_str_to_mln_float(datum["cap"])
4554cb021f077e3b69495a6266a2596a968ee79d
3,648,940
def add_eval_to_game(game: chess.pgn.Game, engine: chess.engine.SimpleEngine, analysis_time: float, should_re_add_analysis: bool = False) -> chess.pgn.Game: """ MODIFIES "game" IN PLACE """ current_move = game while len(current_move.variations): if "eval" in current_move...
72c677fc9f71cafca6af5b86cca69d896547835d
3,648,941
def MC_no(a,b,N,pi,mp): """ Monte Carlo simulation drawn from beta distribution for the uninsured agents Args: N (integer): number of draws a (integer): parameter b (integer): parameter Returns: (numpy float): Monte Carlo integration that computes expe...
7910a1894839eaac89af9df61a3f64fbb1eaf933
3,648,942
def get_conflicting_types(type, tyepdef_dict): """Finds typedefs defined in the same class that conflict. General algo is: Find a type definition that is identical to type but for a different key. If the type definitions is coming from a different class, neglect it. This is a pretty slow function for...
5270ddfbf8a1f887de7ea9fcf2dcd32511ce6a32
3,648,943
from typing import Tuple def extract_entity_type_and_name_from_uri(uri: str) -> Tuple[str, str]: """ 从entity uri中提取出其type和name :param uri: 如 http://www.kg.com/kg/ontoligies/ifa#Firm/百度 :return: ('Firm', '百度') """ name_separator = uri.rfind('/') type_separator = uri.rfind('#') return ur...
a70b1fdb5490f029cc6a88bee53eee048731a709
3,648,944
import os import typing def resolve_raw_resource_description( raw_rd: GenericRawRD, root_path: os.PathLike, nodes_module: typing.Any ) -> GenericResolvedNode: """resolve all uris and sources""" rd = UriNodeTransformer(root_path=root_path).transform(raw_rd) rd = SourceNodeTransformer().transform(rd) ...
63d9643a2b957d43155912365eed91616802cd8f
3,648,945
def ret_dict() -> dict: """ Returns ------- """ # blahs return {}
79a29f69f5d0389d266f917500d25d696415c25a
3,648,946
def load_rokdoc_well_markers(infile): """ Function to load well markers exported from RokDoc in ASCII format. """ with open(infile, 'r') as fd: buf = fd.readlines() marker = [] well = [] md = [] tvdkb = [] twt = [] tvdss = [] x = [] y = [] ...
f3a781accdd84ff2f5aff12e59aeff05aa428d6a
3,648,947
def get_fees(): """ Returns all information related to fees configured for the institution. :returns: String containing xml or an lxml element. """ return get_anonymous('getFees')
17d16c65d8aefa5989f0c371ed2db2527691ccf9
3,648,948
import torch from typing import Tuple def resample_uv_to_bbox( predictor_output: DensePoseChartPredictorOutput, labels: torch.Tensor, box_xywh_abs: Tuple[int, int, int, int], ) -> torch.Tensor: """ Resamples U and V coordinate estimates for the given bounding box Args: predictor_outpu...
655fa330a0fb68d0a6f94084b1a4fde2e1368792
3,648,949
def run(cmd, capture_output=True): """ Run command locally with current user privileges :returns: command output on success :raises: LocalExecutionFailed if command failed""" try: LOG.debug("Running '%s' locally", cmd) return api.local(cmd, capture=capture_output) except (SystemE...
6022961e2be94527a9fe6a0f3fe8b2418b263c78
3,648,950
from typing import List def get_error_code(output: int, program: List[int] ) -> int: """ Determine what pair of inputs, "noun" and "verb", produces the output. The inputs should be provided to the program by replacing the values at addresses 1 and 2. The value pl...
a3ff93557217197c3988b1f2ffde0a114ec6de81
3,648,951
def page(page_id): """Gets one page from the database.""" page = Page.objects.get(id=page_id) return render_template('page.html', page=page)
011d0d96564e328674c9e919eed3647c41ebb0a4
3,648,952
def compute_Csigma_from_alphaandC(TT,minT,alphaT,CT,ibrav=4): """ This function calculate the difference between the constant stress heat capacity :math:`C_{\sigma}` and the constant strain heat capacity :math:`C_{\epsilon}` from the *V* (obtained from the input lattice parameters *minT*, the thermal ...
66159810aeeadd4614f66b6c7bc43a11a5ebf28d
3,648,953
def services(request): """ """ context = {} services = Service.objects.filter(active=True, hidden=False) context["services"] = services context["services_nav"] = True return render(request, "services.html", context)
45792f2032236a74f8edd2141bf10a2dd7b6c075
3,648,954
def _create_presigned_url(method, object_name, duration_in_seconds=600): """ Create presigned S3 URL """ s3_client = boto3.client('s3', endpoint_url=CONFIG.get('s3', 'url'), aws_access_key_id=CONFIG.get('s3', 'access_key_id'), ...
f285d90058d3f6d450e82917d883f97100b78889
3,648,955
def read_data(model_parameters, ARGS): """Read the data from provided paths and assign it into lists""" data = pd.read_pickle(ARGS.path_data) y = pd.read_pickle(ARGS.path_target)['target'].values data_output = [data['codes'].values] if model_parameters.numeric_size: data_output.append(data[...
66f89d87b22579f3d06a1d8f0faf0db4bc0fd13d
3,648,956
def _is_src(file): """ Returns true if the file is a source file Bazel allows for headers in the srcs attributes, we need to filter them out. Args: file (File): The file to check. """ if file.extension in ["c", "cc", "cpp", "cxx", "C", "c++", "C++"] and \ file.is_source: return ...
b0466073d4d1b05c5cab37946fb6ca8432dc752d
3,648,957
def constructResponseObject(responsePassed): """ constructs an Error response object, even if the """ if (not (responsePassed is None)): temp_resp = Response() temp_resp.status_code = responsePassed.status_code or 404 if((temp_resp.status_code >= 200) and (temp_resp.status_code ...
e5f5aa0f87db30598e85fe66e8bf3062eac4388c
3,648,958
def calculate_signal_strength(rssi): # type: (int) -> int """Calculate the signal strength of access point.""" signal_strength = 0 if rssi >= -50: signal_strength = 100 else: signal_strength = 2 * (rssi + 100) return signal_strength
d5a0955446e0fe0548639ddd1a849f7e7901c36b
3,648,959
from datetime import datetime async def verify_email(token: str, auth: AuthJWT = Depends()): """Verify the user's email with the supplied token""" # Manually assign the token value auth._token = token # pylint: disable=protected-access user = await User.by_email(auth.get_jwt_subject()) if user.em...
4e6eebd22b6206fa20f9c03230c09b470c414740
3,648,960
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up a National Weather Service entry.""" hass_data = hass.data.setdefault(DOMAIN, {}) station = entry.data[CONF_STATION] radar = Nexrad(station) radar_update = Debouncer( hass, _LOGGER, cooldown=60, immediate=True,...
eb05efea751b2dc739157e394a7c892788a3bf3f
3,648,961
def lookAtThisMethod( first_parameter, second_paramter=None, third_parameter=32, fourth_parameter="a short string as default argument", **kwargs ): """The point of this is see how it reformats parameters It might be fun to see what goes on Here I guess it should respect this spacing, since we are in...
8dab028b40184bb7cf686c524d5abd452cee2bc3
3,648,962
from typing import Sequence from typing import Callable from typing import List from typing import Set def data_incremental_benchmark( benchmark_instance: GenericCLScenario, experience_size: int, shuffle: bool = False, drop_last: bool = False, split_streams: Sequence[str] = ("train",), custom_...
e24756245b3d6b5126d32fb66541e4cd23a993c2
3,648,963
import typing def generate_doc_from_endpoints( routes: typing.List[tornado.web.URLSpec], *, api_base_url, description, api_version, title, contact, schemes, security_definitions, security ): """Generate doc based on routes""" from tornado_swagger.model import export_swa...
943a3c7a8bdd71bce92089c9dd89a7c262124dc0
3,648,964
def _filter_builds(build: Build) -> bool: """ Determine if build should be filtered. :param build: Build to check. :return: True if build should not be filtered. """ if build.display_name.startswith("!"): return True return False
c3bbc91595752b92b77034afcdd35d4a0b70f737
3,648,965
def load_transformers(model_name, skip_model=False): """Loads transformers config, tokenizer, and model.""" config = AutoConfig.from_pretrained(model_name) tokenizer = AutoTokenizer.from_pretrained( model_name, add_prefix_space=True, additional_special_tokens=('[T]', '[P]'), ) ...
49b8809745ba70b2a2a8ccd6063bbe2ea3acbae0
3,648,966
def build_test_data(data): """ Generates various features needed to predict the class of the news. Input: DataFrame Returns Array of generated features. """ data = process(data) generators = [ CountFeatureGenerator, TfidfFeatureGenerator, ...
a4bd3af16deff190471ffbd6028cb47b314d498f
3,648,967
def set_password_for_sub_account(account_id, password): """ Create a message to set the password for a given sub-account. :param account_id: Integer representing the ID of the account :param password: String representing the password for the sub-account :return: Message (dict) """ data = san...
02887e73bd11c551f472c033e256882206e9042a
3,648,968
def post(req, api): """ Append a story to our rpg Input: content: string Output: string """ api.debug(req.body['content']) return 'Success'
008313afcd838a525268959118cfc19b3c23535e
3,648,969
def generate_batch(n, batch_size): """ Generates a set of batch indices Args: n: total number of samples in set batch_size: size of batch Returns: batch_index: a list of length batch_size containing randomly sampled indices """ batch_index = a.sample(range...
a8fe7d9356b30824210c89e2defa4b6bae697ffd
3,648,970
def solve(si, y, infile): """Conducts the solution step, based on the dopri5 integrator in scipy :param si: the simulation info object :type si: SimInfo :param y: the solution vector :type y: np.ndarray :param infile: the imported infile module :type infile: imported module """ n = ...
079e97394befb39d6c65dc0c8a7eb2d57cf37920
3,648,971
def base(request, format=None): """Informational version endpoint.""" message = f"Welcome to {VERSION} of the Cannlytics API. Available endpoints:\n\n" for endpoint in ENDPOINTS: message += f"{endpoint}\n" return Response({ "message": message}, content_type="application/json")
51d8deaa6b5fda2b69fc8674e0d9d927d910c0ba
3,648,972
def discover(discover_system: bool = True) -> Discovery: """ Discover Reliably capabilities from this extension. """ logger.info("Discovering capabilities from chaostoolkit-reliably") discovery = initialize_discovery_result( "chaostoolkit-reliably", __version__, "reliably" ) discove...
78bb7bcb086d08099f5585c3e27452647ecb8d64
3,648,973
from collections import Counter def frequent_word(message: str) -> str: """get frequent word.""" words = Counter(message.split()) result = max(words, key=words.get) print(result) return result
86af88287a8874d824b96e1a96e430555db64f2e
3,648,974
def parse_bjobs_nodes(output): """Parse and return the bjobs command run with options to obtain node list, i.e. with `-w`. This function parses and returns the nodes of a job in a list with the duplicates removed. :param output: output of the `bjobs -w` command :type output: str :return: c...
a582307d0d869d2dbde454928571246320cb6e31
3,648,975
def find_nearest_array(array, array_comparison, tol = 1e-4): """ Find nearest array @ In, array, array-like, the array to compare from @ In, array_comparison, array-like, the array to compare to @ In, tol, float, the tolerance """ array_comparison = np.asarray(array_comparison) indeces = np.zero...
5c15cb58d50eef03ae7bcffed18bc60587fec0fc
3,648,976
import os def create_bar_filled_line_fusion_chart(fname, frame_data, chart_dir=''): """Create the bar filled line fusion chart from window data""" path_to_image = os.path.join(chart_dir, ChartType.BAR_FLINE_FUSION.value, "%s.png" % fname) if not os.path.exists(path_to_image): fig_obj, ax_fline_obj...
8fb33cb18fe919447e29c1b931e400f11ca4d771
3,648,977
from datetime import datetime def create_block_statistics_on_addition( block_hash: str, block_hash_parent: str, chain_name: str, deploy_cost_total: int, deploy_count: int, deploy_gas_price_avg: int, era_id: int, height: int, is_switch_block: bool, network: str, size_bytes: ...
921e7045ff0df080a3769d0e62753e0e5a13e4af
3,648,978
import argparse def get_arg(): """解析参数""" parser = argparse.ArgumentParser(prog='prcdns', description='google dns proxy.') parser.add_argument('--debug', help='debug model,default NO', default=False) parser.add_argument('-l', '--listen', help='listening IP,default 0.0.0.0', default='0.0.0.0') pars...
21be51cbace8714dd10d7c18a4f2e5bcddcfc1da
3,648,979
def text(title='Text Request', label='', parent=None, **kwargs): """ Quick and easy access for getting text input. You do not have to have a QApplication instance, as this will look for one. :return: str, or None """ # -- Ensure we have a QApplication instance q_app = qApp() # -- Get t...
c3d0c4fab15f6882fea614f5eec252738abc3e1c
3,648,980
def get_key_score(chroma_vector, keys, key_index): """Returns the score of an approximated key, given the index of the key weights to try out""" chroma_vector = np.rot90(chroma_vector,3) chroma_vector = chroma_vector[0,:] key_vector = keys[key_index,:] score = np.dot(key_vector,chroma_vector) return score
b41d4f3af4d621ba46b8786a5c906c470454fcc1
3,648,981
def app(): """Create the test application.""" return flask_app
01fbd44671a342be38560bc4c5b089a55214caf3
3,648,982
def coord_for(n, a=0, b=1): """Function that takes 3 parameters or arguments, listed above, and returns a list of the interval division coordinates.""" a=float(a) b=float(b) coords = [] inc = (b-a)/ n for x in range(n+1): coords.append(a+inc*x) return coords
57e12200dcc113786c9deeb4865d7906d74c763f
3,648,983
def find_indeces_vector(transect_lons, transect_lats, model_lons, model_lats, tols={ 'NEMO': {'tol_lon': 0.104, 'tol_lat': 0.0388}, 'GEM2.5': {'tol_lon': 0.016, 'tol_lat': 0.012}, }): """Find all indeces for the ...
93ad7a8cd16e154069618e606293e64ee3266501
3,648,984
def _make_prediction_ops(features, hparams, mode, num_output_classes): """Returns (predictions, predictions_for_loss).""" del hparams, mode logits = tf.layers.dense( features, num_output_classes, name='logits') confidences = tf.nn.softmax(logits) confidence_of_max_prediction = tf.reduce_max(confidences...
0a58ab8753a39b3e9da67dfc7988383585e6562e
3,648,985
def manhattan_loadings( iteration, gtf, loadings, title=None, size=4, hover_fields=None, collect_all=False, n_divisions=500, ): """modify hail manhattan plot""" palette = [ '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8...
5f99c1f5a16ee35c056ef019870d2d89a31ba988
3,648,986
def preprocess_point(p, C): """Preprocess a single point (a clip). WARN: NAN-preserving Arguments: p {ndarray} -- shape = (variable, C.joint_n, C.joint_d) C {DDNetConfig} -- A Config object Returns: ndarray, ndarray -- X0, X1 to input to the net """ assert p.shape[1...
a1f2c1eda877562439c0b194490a6ac50df6bd81
3,648,987
def link_to_existing_user_by_email_if_backend_is_trusted(backend, details, user=None, *args, **kwargs): """Return user entry with same email address as one returned on details.""" if user or not _is_trusted_email_backend(backend): return email = details.get('email') if email: # try to ...
58f2363030ae0b8f8d3533dedbae6c7af304136c
3,648,988
import os import glob from typing import OrderedDict def _monthlyfile(yr, path, ppath, force, layer, ANfn, latmax, latmin, lonmin, lonmax): """ Function to proccess the monthl;y data into an annual file args: yr: int year path: str dir to do the work in ppath: str processed path """ # ========== ...
8633f65b08052aa3f8a6998a45af7ed964413638
3,648,989
def get_global_threshold(image_gray, threshold_value=130): """ 이미지에 Global Threshold 를 적용해서 흑백(Binary) 이미지객체를 반환합니다. 하나의 값(threshold_value)을 기준으로 이미지 전체에 적용하여 Threshold 를 적용합니다. 픽셀의 밝기 값이 기준 값 이상이면 흰색, 기준 값 이하이면 검정색을 적용합니다. 이 때 인자로 입력되는 이미지는 Gray-scale 이 적용된 2차원 이미지여야 합니다. :param image_gray: ...
03c344a40c5a84027d790ddf404106efe29716e9
3,648,990
import torch def get_batch(src_gen, trgt_gen, batch_size=10): """ Return a batch of batch_size of results as in get_rotated_src_target_spirals Args: batch_size (int): number of samples in the batch factor (float): scaling factor for the spiral Return: [torch.tensor,torch.tensor]: s...
6e0e4549c12fb252c54496f7947e5787970b64eb
3,648,991
def compute_crop_parameters(image_size, bbox, image_center=None): """ Computes the principal point and scaling factor for focal length given a square bounding box crop of an image. These intrinsic parameters are used to preserve the original principal point even after cropping the image. Args:...
18ca5822bf86fb01ff8652fc9239ce6ae4d2801f
3,648,992
def input_fn_builder(input_file, seq_length, num_labels, is_training, drop_remainder): """Creates an `input_fn` closure to be passed to TPUEstimator.""" name_to_features = { "input_ids": tf.FixedLenFeature([seq_length], tf.int64), "input_mask": tf.FixedLenFeature([seq_lengt...
ad82ded8691561eb8f60b645497200cd36d94a21
3,648,993
def get_user_by_username(username): """Return User by username""" try: return User.objects.get(username=username) except User.DoesNotExist: return None
b6c676d22c7ef586392b20a072d2239c2dfce7e6
3,648,994
def get_xyz_to_rgb_matrix(name): """ XYZ to RGB の Matrix を求める。 DCI-P3 で D65 の係数を返せるように内部関数化した。 """ if name != "DCI-P3": xyz_to_rgb_matrix = RGB_COLOURSPACES[name].XYZ_to_RGB_matrix else: rgb_to_xyz_matrix\ = calc_rgb_to_xyz_matrix(RGB_COLOURSPACES[DCI_P3].primaries, ...
007b71f52af4e23ada073c712a840e05c0ac33a5
3,648,995
def find_bordering_snapnums( snap_times_gyr, dGyr=.005, tmin=None, tmax=None): """ """ ## handle default maximum time tmax = snap_times_gyr[-1] if tmax is None else tmax ## handle default minimum time if tmin is None: tmin = snap_times_gyr[0] ## remove dGyr so that...
23a58ecce4036d9b7a6a91991de237dd30b87129
3,648,996
def maxIterationComb(N,k,l): """ title:: maxIterationComb description:: Compute N!/k!l!(N-k-l)! (max iterations). attributes:: N Number of targets (graph size) k Number of human patrollers l Number of drones returns::...
d0019a1498a50f3733474fb0212627d1b061484d
3,648,997
def create_project_details_list (project): """makes a projects details section for the html Parameters ---------- project: HeatRecovery A HeatRecovery object thats run function has been called Returns ------- dict with values used by summary """ try: costs =...
74c68b0592939cc819091ac2d30bee44b455f27b
3,648,998
def compute_cluster_top_objects_by_distance(precomputed_distances, max_top_number=10, object_clusters=None): """ Compute the most representative objects for each cluster using the precomputed_distances. Parameters ...
2ff29d6b59d2db3d9e169a44c0addf42d9abea9b
3,648,999