code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _build(self, memory, keys, strengths): <NEW_LINE> <INDENT> dot = tf.matmul(keys, memory, adjoint_b=True) <NEW_LINE> memory_norms = _vector_norms(memory) <NEW_LINE> key_norms = _vector_norms(keys) <NEW_LINE> norm = tf.matmul(key_norms, memory_norms, adjoint_b=True) <NEW_LINE> similarity = dot / (norm + _EPSILON) <NE... | Connects the CosineWeights module into the graph.
Args:
memory: A 3-D tensor of shape `[batch_size, memory_size, word_size]`.
keys: A 3-D tensor of shape `[batch_size, num_heads, word_size]`.
strengths: A 2-D tensor of shape `[batch_size, num_heads]`.
Returns:
Weights tensor of shape `[batch_size, num_heads, ... | 625941c826068e7796caed3f |
def miroir2(s : str) -> str: <NEW_LINE> <INDENT> r : str = '' <NEW_LINE> i : int <NEW_LINE> for i in range(1,len(s)+1): <NEW_LINE> <INDENT> r = r + s[-i] <NEW_LINE> <DEDENT> return s + r | ... cf. ci-dessus ...
| 625941c8be383301e01b54e9 |
def view_my_own_handwritten_number(my_number: str): <NEW_LINE> <INDENT> img = io.imread("resources/my_handwritten/"+my_number+".png", as_gray=True) <NEW_LINE> img_data = transform.resize(img, (28,28), mode='symmetric', preserve_range=True) <NEW_LINE> img_data = (img_data / 255.0 * 0.99) + 0.01 <NEW_LINE> print(img_data... | Only for check own handwritten images located in resources/my_handwritten
:param my_number: number to show
:return: | 625941c8b5575c28eb68e061 |
def __init__( self, checkpoint_path: str, device: str = None, embedding_type: str = 'pooled', max_seq_len: Optional[int] = None, permute: bool = False, ) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.checkpoint_path = checkpoint_path <NEW_LINE> self.model_dir = os.path.dirname(os.path.dirname(checkpoi... | Args:
checkpoint_path: path or S3 location of trained model checkpoint
device: device for torch
embedding_type: method to reduce MolBERT encoding to an output set of features. Default: 'pooled'
Other options are embeddings summed or concat across layers, and then averaged
Raw sequence and po... | 625941c815fb5d323cde0b70 |
def load_uri(self, uri): <NEW_LINE> <INDENT> self.__loaded_uri = uri <NEW_LINE> if not uri.startswith("http://") and not uri.startswith("https://"): <NEW_LINE> <INDENT> uri = "http://" + uri <NEW_LINE> <DEDENT> WebKit2.WebView.load_uri(self, uri) | Load uri
@param uri as str | 625941c863b5f9789fde7147 |
def edit_item(self): <NEW_LINE> <INDENT> index = self.listbox.curselection() <NEW_LINE> gui.templates.inser_box.EditNode(index[0], self.distribution, Toplevel()) <NEW_LINE> scl.ScrolledList.__init__(self, self.make_fields_list(), self.list_frame) | Context menu edit option. After operation reloads listbox. | 625941c8e1aae11d1e749d18 |
def detect_hypo(proteins, blasts, type_): <NEW_LINE> <INDENT> protein_names = {} <NEW_LINE> for protein in proteins: <NEW_LINE> <INDENT> name = protein["name"].replace("\n", "") <NEW_LINE> if ("hypothetical" not in name) and ( "Hypothetical" not in name) and ( "Unknown" not in name) and ( "unknown" not in name) and ( "... | remove the hit which is hypothetical protein or unknown | 625941c85510c4643540f448 |
def read_matrix_rows(input_string): <NEW_LINE> <INDENT> input_string = input_string.replace(' ', ', ') <NEW_LINE> return input_string | Function return matrix
Args:
input_string(str): string with matrix separated by spaces and line breaks
Returns:
bool: return matrix | 625941c8d53ae8145f87a2d3 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if hasattr(self, "id") and hasattr(other, "id"): <NEW_LINE> <INDENT> return self.id == other.id <NEW_LINE> <DEDENT> return self._info == other._info | Two resource objects that represent the same entity in the cloud
should be considered equal if they have the same ID. If they
don't have IDs, but their attribute info matches, they are equal. | 625941c86fb2d068a760f0fe |
def sectionTitle(self, typeSection): <NEW_LINE> <INDENT> linker = "" <NEW_LINE> sectionName = "" <NEW_LINE> if typeSection == "originalReference": <NEW_LINE> <INDENT> linker += "id=\"originalReference\"" <NEW_LINE> sectionName += "Original Reference" <NEW_LINE> <DEDENT> elif typeSection == "basicMaskingRegions": <NEW_L... | Creates a linker anchor for the section to be open, it also set section name | 625941c88e71fb1e9831d80b |
def create_modulename(cdef_source, source, sys_version): <NEW_LINE> <INDENT> key = "\x00".join([sys_version[:3], source, cdef_source]) <NEW_LINE> key = key.encode("utf-8") <NEW_LINE> k1 = hex(binascii.crc32(key[0::2]) & 0xffffffff) <NEW_LINE> k1 = k1.lstrip("0x").rstrip("L") <NEW_LINE> k2 = hex(binascii.crc32(key[1::2]... | cffi creates a modulename internally that incorporates the cffi version.
This will cause Fenrir's wheels to break when the version of cffi
the user has does not match what was used when building the wheel. To
resolve this we build our own modulename that uses most of the same code
from cffi but elides the version key. | 625941c84428ac0f6e5ba853 |
def run(self, maxtime=None, avg_time_factor=0.0): <NEW_LINE> <INDENT> time = Timer() <NEW_LINE> self.prepare_env() <NEW_LINE> try: <NEW_LINE> <INDENT> for task in self.iterator: <NEW_LINE> <INDENT> self.prepare_run() <NEW_LINE> try: <NEW_LINE> <INDENT> self.process_task(task) <NEW_LINE> <DEDENT> except Exception as ex:... | Run method of the actor, executes the application code by iterating
over the available tasks in CouchDB. | 625941c8f8510a7c17cf975d |
def LineCount(self): <NEW_LINE> <INDENT> return self.SendMessage(win32defines.EM_GETLINECOUNT) | Return how many lines there are in the Edit | 625941c8167d2b6e31218bf8 |
def get_sinonim(inputs): <NEW_LINE> <INDENT> sinonims = [] <NEW_LINE> sin_inputs = [] <NEW_LINE> with open('file/sinonim.csv', 'r') as csvfile: <NEW_LINE> <INDENT> read_data = csv.reader(csvfile) <NEW_LINE> for r in read_data: <NEW_LINE> <INDENT> sinonims.append(r) <NEW_LINE> <DEDENT> <DEDENT> total_index = -1 <NEW_LIN... | fungsi ini digunakan untuk mencari sinonim dari gejala yang didapat dari input user
:param inputs: inputan user berupa gejala
:return: list sin_input yang berisi daftar gejala yang baru dari hasil sinonim | 625941c8cad5886f8bd2703b |
def __init__(self): <NEW_LINE> <INDENT> self.ErrCode = None <NEW_LINE> self.Message = None <NEW_LINE> self.FileId = None <NEW_LINE> self.FileUrl = None <NEW_LINE> self.FileType = None | :param ErrCode: 错误码
<li>0:成功;</li>
<li>其他值:失败。</li>
注意:此字段可能返回 null,表示取不到有效值。
:type ErrCode: int
:param Message: 错误信息。
注意:此字段可能返回 null,表示取不到有效值。
:type Message: str
:param FileId: 视频拼接源文件的 ID。
注意:此字段可能返回 null,表示取不到有效值。
:type FileId: str
:param FileUrl: 视频拼接源文件的地址。
... | 625941c863f4b57ef000117d |
def __unicode__(self): <NEW_LINE> <INDENT> return u''.join([etree.tostring(e, encoding=str) for e in self]) | xml representation of current nodes | 625941c84428ac0f6e5ba854 |
def StripChars(s): <NEW_LINE> <INDENT> entity_re = re.compile(r"&(#\d+|\w+);") <NEW_LINE> def matchFunc(match): <NEW_LINE> <INDENT> if match.group(1).startswith('#'): return unichr(int(match.group(1)[1:])) <NEW_LINE> replacement = htmlentitydefs.entitydefs.get(match.group(1), "&%s;" % match.group(1)) <NEW_LINE> return ... | Converts any html entities in s to their unicode-decoded equivalents and returns a string. | 625941c87b180e01f3dc4861 |
def count_to_size(self, axis, cell_size): <NEW_LINE> <INDENT> df = DeferredFunction(self._count_to_size, axis, cell_size) <NEW_LINE> self.deferred_functions.append(df) | set number of cells so that cell size equals cell_size | 625941c8b57a9660fec338e5 |
def initialize_dataMatrixList(self,nrows_I,ncolumns_I,na_str_I='NA'): <NEW_LINE> <INDENT> dataMatrixList_O = [na_str_I for r in range(nrows_I*ncolumns_I)]; <NEW_LINE> return dataMatrixList_O; | initialize dataMatrixList with missing values
INPUT:
nrows_I = int, # of rows of data
ncolumns_I - int, # of columns of data
na_str_I = string identifier of a missing value
OUTPUT:
dataMatrixList_O = list of na_str_I of length nrows_I*ncolumns_I | 625941c8a219f33f346289cd |
def green_detect(img): <NEW_LINE> <INDENT> hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) <NEW_LINE> hsv_min = np.array([30, 64, 0]) <NEW_LINE> hsv_max = np.array([90, 255, 255]) <NEW_LINE> mask = cv2.inRange(hsv, hsv_min, hsv_max) <NEW_LINE> return mask | 緑色のマスク生成 | 625941c8dd821e528d63b20b |
def Get(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('Get') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params) | Gets the latest state of a long-running operation. Clients can use this.
method to poll the operation result at intervals as recommended by the API
service.
Args:
request: (TpuProjectsLocationsOperationsGetRequest) input message
global_params: (StandardQueryParameters, default: None) global argu... | 625941c8377c676e9127220b |
def get_conn(options): <NEW_LINE> <INDENT> return ZwiftConnection(options.auth, options.user, options.key, retries=1, auth_version=options.auth_version, os_options=options.os_options, snet=options.snet, cacert=options.os_cacert, insecure=options.insecure, ssl_compression=options.ssl_compression) | Return a connection building it from the options. | 625941c8498bea3a759b9b11 |
def random_max(self): <NEW_LINE> <INDENT> result = self.__db.zrangebyscore(self.__key, self.__max_score, self.__max_score) <NEW_LINE> if len(result) > 0: <NEW_LINE> <INDENT> return choice(result) | return a random proxy ip which has max score | 625941c838b623060ff0ae4f |
def all_actions(self): <NEW_LINE> <INDENT> lists = [[p for p in self.grow_populations], [p for p in self.grow_bodys], [p for p in self.boards_with_traits], [p for p in self.trait_replacements]] <NEW_LINE> items = [item for l in lists for item in l] <NEW_LINE> return items | Get all Actions that aren't to be placed in the center, in a single flat list.
:return: a List<Action> | 625941c80a366e3fb873e87b |
def contact(self, request, input, params, method): <NEW_LINE> <INDENT> code, data = self.__salesforce_table(request, input, params, "contact", self.__contact_fields_compact, self.__contact_fields_normal) <NEW_LINE> return code, data | Handle information about our contacts.
@param request: Information about the HTTP request.
@type request: BaseHttpRequest
@param input: Any data that came in the body of the request.
@type input: string
@param params: Dictionary of parameter values.
@type params: dict
@param method: T... | 625941c838b623060ff0ae50 |
def _get_instrument_data(self): <NEW_LINE> <INDENT> self.log.msg("Loading csv instrument config") <NEW_LINE> filename = os.path.join(self._datapath, "instrumentconfig.csv") <NEW_LINE> instr_data = pd.read_csv(filename) <NEW_LINE> instr_data.index = instr_data.Instrument <NEW_LINE> return instr_data | Get a data frame of interesting information about instruments, either
from a file or cached
:returns: pd.DataFrame
>>> data=csvFuturesData("sysdata.tests")
>>> data._get_instrument_data()
Instrument Pointsize AssetClass Currency
Instrument
EDOLLAR EDOLLAR 2500 STIR USD
US10 ... | 625941c8f8510a7c17cf975e |
def update_annotation_project(annotation_project_id, cog_path): <NEW_LINE> <INDENT> annotation_project = AnnotationProject.from_id(annotation_project_id) <NEW_LINE> task_side_length = get_geotiff_resolution(cog_path)[0] <NEW_LINE> subprocess.check_call( [ "java", "-cp", "/opt/raster-foundry/jars/batch-assembly.jar", "c... | Run the create-task-grid command on an annotation project
Args:
annotation_project_id (str): the annotation project to update
cog_path (str): the location of the cog backing imagery for this project | 625941c8711fe17d825423cf |
def is_ea_consistent(ea, type): <NEW_LINE> <INDENT> [states, alphabet, delta, start_state, accepting_set] = ea <NEW_LINE> if not is_sigma_consistent(alphabet): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for q in accepting_set: <NEW_LINE> <INDENT> if q not in states: <NEW_LINE> <INDENT> print(q.__str__() + " i... | Checks if the given ea is consistent.
:return:
false, iff the ea uses any state/token,
which is not a member of the state-set/ alphabet. | 625941c81b99ca400220ab13 |
def GetPutOpInput(self): <NEW_LINE> <INDENT> assert len(self.items) == 1 <NEW_LINE> return (self.request_body, { "group_name": self.items[0], "dry_run": self.dryRun(), "force": self.useForce(), }) | Assigns nodes to a group.
| 625941c8460517430c3941e9 |
def write_json(self, data=None, status_code=HTTP_OK, location=None): <NEW_LINE> <INDENT> self.send_response(status_code) <NEW_LINE> self.send_header(HTTP_HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON) <NEW_LINE> if location: <NEW_LINE> <INDENT> self.send_header('Location', location) <NEW_LINE> <DEDENT> self.set_session_cookie... | Helper method to return JSON to the caller. | 625941c8dd821e528d63b20c |
def mxticks(*args,**kw): <NEW_LINE> <INDENT> if len(args) > 2: <NEW_LINE> <INDENT> raise TypeError('Illegal number of arguments to mxticks') <NEW_LINE> <DEDENT> ax = kw.pop('axes',None) <NEW_LINE> if ax is None: <NEW_LINE> <INDENT> ax = gca() <NEW_LINE> <DEDENT> locs,labels = _mticks(ax.xaxis,*args,**kw) <NEW_LINE> dra... | mxticks(*args,**kw)
Get or set the current x-axis tick locations and labels
locs, labels = mxticks()
mxticks(arange(6))
mxticks(arange(3),['Tom','Dick','Harry'])
Labels can be specified with a format string:
mxticks(linspace(0,360,5),'{:.2e}°')
Labels can be specified with a callable:
mxticks(linspace(0.0,1.0,5)... | 625941c83617ad0b5ed67f5a |
def test_version_exists(): <NEW_LINE> <INDENT> assert fakturownia.__version__ | This is a stupid test dummy validating import of fakturownia | 625941c8cdde0d52a9e53094 |
def reverseString(self, s): <NEW_LINE> <INDENT> n = len(s) <NEW_LINE> for i in range(0, n): <NEW_LINE> <INDENT> min = int(i) <NEW_LINE> max = int(n-i)-1 <NEW_LINE> if min == max: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tmp = s[max] <NEW_LINE> s[max] = s[min] <NEW_LINE> s[min] = tmp <NEW_... | :type s: str
:rtype: str | 625941c86e29344779a62675 |
def detail(request, takeout_id): <NEW_LINE> <INDENT> takeout = get_object_or_404(Takeout, pk=takeout_id) <NEW_LINE> context = {'takeout': takeout} <NEW_LINE> return render(request, 'control/takeout_detail.html', context) | 반출 내용 출력 | 625941c821bff66bcd6849b6 |
@utils.arg('attributes', metavar='<fs_name=size>', nargs='+', action='append', default=[], help="Modify controller filesystem sizes") <NEW_LINE> def do_controllerfs_modify(cc, args): <NEW_LINE> <INDENT> patch_list = [] <NEW_LINE> for attr in args.attributes[0]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> patch = [] <N... | Modify controller filesystem sizes. | 625941c821a7993f00bc7d50 |
def __str__(self): <NEW_LINE> <INDENT> return f'{self.name} - {self.price}' | Return information about item | 625941c88e7ae83300e4b02e |
def _log(self, msg): <NEW_LINE> <INDENT> if self.verbose: <NEW_LINE> <INDENT> print(msg) | Logs a message, according to verbose level.
Parameters
----------
msg: string
message to log | 625941c8507cdc57c6306d3b |
def blend(hexes): <NEW_LINE> <INDENT> if len(hexes) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> r = 0 <NEW_LINE> g = 0 <NEW_LINE> b = 0 <NEW_LINE> for i in range(len(hexes)): <NEW_LINE> <INDENT> r += HEX_VALS.index(hexes[i][1]) * 16 + HEX_VALS.index(hexes[i][2]) <NEW_LINE> g += HEX_VALS.index(hexes[i][3]... | Assuming a list of appropriate hex values, returns the averaged result in rgb.
:param hexes: List of hex values
:return: Tuple (int, int, int) - tuple of r, g, b values of averaged given hex values. | 625941c82eb69b55b151c910 |
def _test_square(data, quantized): <NEW_LINE> <INDENT> return _test_unary_elemwise(math_ops.square, data, quantized) | One iteration of square | 625941c8090684286d50ed47 |
def start(self, command_name=None, *args, **kwargs): <NEW_LINE> <INDENT> command_name = command_name or self.DEFAULT_COMMAND_NAME <NEW_LINE> self.updater.dispatcher.add_handler(CommandHandler(command=command_name, callback=self._handler, pass_args=self.pass_args, *args, **kwargs)) <NEW_LINE> self.logger.info("Set %s wi... | Start handling the incoming requests of the command.
Args:
command_name(str): name of the command that will be used in telegram chat in order to execute this command.
if not specified, the default command name will be used.
args(tuple): will be passed to the dispatcher handler.
kwar... | 625941c8a17c0f6771cbe0b4 |
def main(): <NEW_LINE> <INDENT> from optparse import OptionParser <NEW_LINE> usage = "usage: %prog [options] mpdURL [dstDir]" <NEW_LINE> parser = OptionParser(usage) <NEW_LINE> parser.add_option("-v", "--verbose", action="store_true", dest="verbose") <NEW_LINE> parser.add_option("-b", "--base_url", dest="baseURLForced"... | Parse command line and start the fetching. | 625941c823e79379d52ee5c7 |
def schema_to_json(schema: dict, indent: int = 2) -> str: <NEW_LINE> <INDENT> import json <NEW_LINE> return json.dumps(schema, indent=indent) | Convert the given JSON schema (dict) into a JSON string. | 625941c899fddb7c1c9de3f4 |
@pytest.mark.django_db() <NEW_LINE> def test_provision_tenant_inactive_user(tenant_user): <NEW_LINE> <INDENT> tenant_user.is_active = False <NEW_LINE> tenant_user.save() <NEW_LINE> with pytest.raises(InactiveError, match='Inactive user passed'): <NEW_LINE> <INDENT> tasks.provision_tenant( 'inactive_test', 'inactive_tes... | Test tenant creation with inactive user. | 625941c857b8e32f524834fd |
def list(self, request): <NEW_LINE> <INDENT> attractions = Attraction.objects.all() <NEW_LINE> area = self.request.query_params.get('area', None) <NEW_LINE> if area is not None: <NEW_LINE> <INDENT> attractions = attractions.filter(area__id=area) <NEW_LINE> <DEDENT> serializer = AttractionSerializer(attractions, many=Tr... | Handle GET requests to park attractions resource
Returns:
Response -- JSON serialized list of park attractions | 625941c84c3428357757c38b |
def csv_to_js_var(input_file, output_file): <NEW_LINE> <INDENT> import pandas as pd <NEW_LINE> import json <NEW_LINE> df = pd.read_csv(input_file) <NEW_LINE> dct = df.to_dict() <NEW_LINE> with open(output_file,'w') as f: <NEW_LINE> <INDENT> f.write('var addressPoints = '+json.dumps([[ll,l,u] for u,l,ll in zip(dc... | Converts a CSV file to a Javascript file with one long list variable.
CSV file must be in the format of: point info, longitude, latitude | 625941c8d18da76e23532538 |
def hex_decode(encoded): <NEW_LINE> <INDENT> if not is_bytes(encoded): <NEW_LINE> <INDENT> raise TypeError("argument must be bytes: got %r" % type(encoded).__name__) <NEW_LINE> <DEDENT> return binascii.a2b_hex(encoded) | Decodes hexadecimal-encoded bytes into raw bytes.
:param encoded:
Hex representation.
:returns:
Raw bytes. | 625941c87047854f462a146d |
def __init__(self, output, overwrite=False, initial_position=0, **options): <NEW_LINE> <INDENT> self.output = output <NEW_LINE> self.overwrite = overwrite <NEW_LINE> self.initial_position = initial_position <NEW_LINE> self.stream = isinstance(output, io.IOBase) | Create a new serializer.
Parameters:
output (`io.IOBase` or `str`): The filename of the destination
or a file handle in which to write the archive.
overwrite (`boolean`): If True, use a temporary file to save
the contents of the archive. Useful when updating an archive
file. **[default:... | 625941c83539df3088e2e3ad |
def get_acl(self): <NEW_LINE> <INDENT> if not self.acl: <NEW_LINE> <INDENT> self.reload_acl() <NEW_LINE> <DEDENT> return self.acl | Get ACL metadata as a :class:`gcloud.storage.acl.BucketACL` object.
:rtype: :class:`gcloud.storage.acl.BucketACL`
:returns: An ACL object for the current bucket. | 625941c84f6381625f114a9e |
def trans_timestamp_to_str(timestamp): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> datetime_temp = datetime.fromtimestamp(timestamp) <NEW_LINE> print(datetime_temp) <NEW_LINE> str = datetime_temp.strftime("%Y_%m_%d_%H_%M_%S_%f") <NEW_LINE> print("str:%s" % str) <NEW_LINE> logger.debug("timestamp:%s, str:%s" % (timesta... | trans timestamp to str
Args:
timestamp:
Returns: | 625941c882261d6c526ab500 |
def set_SchoolID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'SchoolID', value) | Set the value of the SchoolID input for this Choreo. ((optional, string) The Education.com id of the school you want to find.) | 625941c829b78933be1e5710 |
def apply_sub(self, sub): <NEW_LINE> <INDENT> smaller_sub = { v: t for v, t in sub.items() if v not in self.bound } <NEW_LINE> ts = self.t.apply_sub(smaller_sub) <NEW_LINE> return Scheme(self.bound, ts) | This applies a substitution to the type,
skipping any substitution of a variable in the bound set. | 625941c8046cf37aa974cdab |
def save_file_and_preview(self): <NEW_LINE> <INDENT> with wand.image.Image(blob=self.blob) as img: <NEW_LINE> <INDENT> img.save(filename=self.path) <NEW_LINE> resize_coeff = 300/max(img.width, img.height) <NEW_LINE> if resize_coeff >= 1.0: <NEW_LINE> <INDENT> resize_coeff = 1 <NEW_LINE> <DEDENT> img.sample(int(img.widt... | File saving and preview generation | 625941c8f7d966606f6aa066 |
def checkIntegrity(self, ): <NEW_LINE> <INDENT> import os <NEW_LINE> if not os.path.isdir(self.path): return 'FAIL: The folder does not exist.' <NEW_LINE> for folder in self.folders: <NEW_LINE> <INDENT> if not os.path.isdir(folder): return 'FAIL: The folder structure is broken.' <NEW_LINE> <DEDENT> return 'PASS' | A function that checks if all folders are in place | 625941c8fff4ab517eb2f49e |
def _get_optional_data_string(self): <NEW_LINE> <INDENT> if self.optional_data: <NEW_LINE> <INDENT> data_string = '' <NEW_LINE> for key, value in self.optional_data.items(): <NEW_LINE> <INDENT> words = len(str(value).split(' ')) <NEW_LINE> if words > 1: <NEW_LINE> <INDENT> value = '"%s"' % (value,) <NEW_LINE> <DEDENT> ... | Generates the optional data string to tack on to the end of the packet. | 625941c8d58c6744b4257cc3 |
def set_input_timeouts(self, max_wait=None, complete_wait=0.1, resize_wait=0.1): <NEW_LINE> <INDENT> self.max_tenths = 10 | Set the get_input timeout values. All values have a granularity
of 0.1s, ie. any value between 0.15 and 0.05 will be treated as
0.1 and any value less than 0.05 will be treated as 0. The
maximum timeout value for this module is 25.5 seconds.
max_wait -- amount of time in seconds to wait for input when
there is n... | 625941c88c3a87329515841c |
def test_requested_size_float(self): <NEW_LINE> <INDENT> self.assertIsInstance( allocated_size( allocation_unit=10, requested_size=1.0, ), int, ) | ``allocated_size`` returns ``int`` if the supplied
``requested_size`` is of type ``float``. | 625941c8d99f1b3c44c675f2 |
def test_size(mocker): <NEW_LINE> <INDENT> block = discover_block.BlockDevice('test') <NEW_LINE> with mocker.patch.object(discover_block, 'open', return_value=StringIO('10\n')): <NEW_LINE> <INDENT> assert block.size == 10 | Tests the size attribute of the BlockDevice.
| 625941c8925a0f43d2549ed9 |
def gas_profile_to_dCdz(C_array, z_obs, full_gradient=True): <NEW_LINE> <INDENT> dC = np.diff(C_array, axis=1) <NEW_LINE> dz = np.diff(z_obs) <NEW_LINE> dCdz = dC/dz <NEW_LINE> if full_gradient: <NEW_LINE> <INDENT> fulldC = C_array[:,-1] - C_array[:,0] <NEW_LINE> fulldz = dz.sum() <NEW_LINE> fdCdz = fulldC/fulldz <NEW_... | Compute gas concentration gradient (dCdz) from an array of concentration
observations and observation depth information.
Input rows are observations (date) and input columns are depths
Args:
C_array : (ndarray) array of concentration/depth observations in ppm
z_obs : (ndarray) array of observation depths in... | 625941c8cb5e8a47e48b7b0e |
def test_exception_values(self): <NEW_LINE> <INDENT> size = Range(500) <NEW_LINE> with self.assertRaises(RangeValueError): <NEW_LINE> <INDENT> size.components(ValueConfig(min_value=-1)) | Test that exceptions are properly raised on bad params. | 625941c8d10714528d5ffd45 |
def make_new_row(old_row): <NEW_LINE> <INDENT> pass | Requires:
-- list old_row that begins and ends with a 1 and has zero or more
integers in between (has to have at least [1,1])
Returns:
-- list beginning and ending with a 1 and each interior (non 1)
integer is the sum of the corresponding old_row elements
For example if old_row = [ 1,4,6,4,1], then new_row = [... | 625941c815baa723493c3fd8 |
def gradient_descent(self, alpha=0.01, epochs=100): <NEW_LINE> <INDENT> errlist = [] <NEW_LINE> total_exp_err = 0 <NEW_LINE> last_epoch = 0 <NEW_LINE> print('plot') <NEW_LINE> for i in range(epochs): <NEW_LINE> <INDENT> pred_y = self.compute_dot() <NEW_LINE> err = (pred_y - self.Y)**2 <NEW_LINE> total_err = np.sum(err)... | Gradient descent implementation | 625941c8c4546d3d9de72a96 |
def parent(self): <NEW_LINE> <INDENT> return self._parent | returns the loop's parent | 625941c84e4d5625662d443c |
def ManifestFromXMLFile(filename_or_file): <NEW_LINE> <INDENT> manifest = Manifest() <NEW_LINE> manifest.parse(filename_or_file) <NEW_LINE> return manifest | Create and return manifest instance from file | 625941c82eb69b55b151c911 |
def population_update(self): <NEW_LINE> <INDENT> self.individuals = copy.deepcopy(self.parents + self.children) <NEW_LINE> self.order() <NEW_LINE> [c.genotype_update() for c in self.individuals] <NEW_LINE> [c.field_update() for c in self.individuals] <NEW_LINE> [c.fitness_update() for c in self.individuals] <NEW_LINE> ... | Updates population. | 625941c8379a373c97cfaba7 |
def __mul__(self, n): <NEW_LINE> <INDENT> n = int(n) <NEW_LINE> if n == 0: <NEW_LINE> <INDENT> return PointAtInfinity() <NEW_LINE> <DEDENT> point = self <NEW_LINE> for i in range(1, n): <NEW_LINE> <INDENT> point += self <NEW_LINE> <DEDENT> return point | Multiplication with integers: adding @p n copies of the point @p self;
the infix operator @c * calls this method.
This method is used when self was the left factor.
@param n A number object that can be interpreted as an integer. It
determines how often the point will be added to itself.
@exception Valu... | 625941c867a9b606de4a7f1d |
def org_organisation_create_onaccept(form): <NEW_LINE> <INDENT> db = current.db <NEW_LINE> s3db = current.s3db <NEW_LINE> ftable = s3db.pr_forum <NEW_LINE> forum = db(ftable.name == "Reserves").select(ftable.pe_id, limitby = (0, 1) ).first() <NEW_LINE> try: <NEW_LINE> <INDENT> reserves_pe_id = forum.pe_id <NEW_LINE> <D... | Create a Reserves Forum for this Organisation with dual hierarchy to main Reserves Forum & this Organisation | 625941c899cbb53fe6792c49 |
def testReferencedEntity(self): <NEW_LINE> <INDENT> pass | Test ReferencedEntity | 625941c8507cdc57c6306d3c |
def set_depot_degree_constraints(self): <NEW_LINE> <INDENT> for vertex in self.depots: <NEW_LINE> <INDENT> self.set_depot_degree_constraint(vertex) | Define the degree constraints for all the depot vertex | 625941c84d74a7450ccd4227 |
def run(self): <NEW_LINE> <INDENT> while 1: <NEW_LINE> <INDENT> job = self.jobs.get() <NEW_LINE> try: <NEW_LINE> <INDENT> job.run() <NEW_LINE> <DEDENT> except workerpool.exceptions.TerminationNotice: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> tb_msg = traceback.format_exc()... | Get jobs from the queue and perform them as they arrive. | 625941c807f4c71912b114e4 |
def count(gmf_value, gmfs_site_one, gmfs_site_two, delta_prob=0.1, div_factor=2.0): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> lower_bound = gmf_value - delta_prob / div_factor <NEW_LINE> upper_bound = gmf_value + delta_prob / div_factor <NEW_LINE> for v1, v2 in zip(gmfs_site_one, gmfs_site_two): <NEW_LINE> <INDENT> if (... | Count the number of pairs of gmf values
within the specified range.
See https://bugs.launchpad.net/openquake/+bug/1097646
attached Scenario Hazard script. | 625941c8a219f33f346289ce |
def __str__(self): <NEW_LINE> <INDENT> printable_string = '\n{0!s:_^80}\n'.format('Security Label Properties') <NEW_LINE> printable_string += '{0!s:40}\n'.format('Retrievable Methods') <NEW_LINE> printable_string += (' {0!s:<28}: {1!s:<50}\n'.format('name', self.name)) <NEW_LINE> printable_string += (' {0!s:<28}: {1!... | allow object to be displayed with print | 625941c845492302aab5e325 |
def letterCombinations(self, digits): <NEW_LINE> <INDENT> if len(digits) == 0: <NEW_LINE> <INDENT> return[] <NEW_LINE> <DEDENT> dict = {'1':[], '2':['a','b','c'], '3':['d','e','f'], '4':['g','h','i'], '5':['j','k','l'], '6':['m','n','o'], '7':['p','q','r','s'], '8':['t','u','v'], '9':['w','x','y','z']} <NEW_LINE> resul... | :type digits: str
:rtype: List[str] | 625941c84527f215b584c4bb |
def _make_train_step(self, features, labels, params): <NEW_LINE> <INDENT> captured_scaffold_fn = _CapturedObject() <NEW_LINE> def train_step(): <NEW_LINE> <INDENT> estimator_spec = self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN, params) <NEW_LINE> try: <NEW_LINE> <INDENT> captured_scaffold_fn.capture... | Creates a single step of training for xla.compile(). | 625941c8ec188e330fd5a804 |
def test_nested(self): <NEW_LINE> <INDENT> self.file.set('this.is.a.nested.setting', 12.3) <NEW_LINE> settings = self.file._settings <NEW_LINE> self.assertIn('this', settings) <NEW_LINE> settings = settings['this'] <NEW_LINE> self.assertIn('is', settings) <NEW_LINE> settings = settings['is'] <NEW_LINE> self.assertIn('a... | File correctly adds a nested setting.
| 625941c897e22403b379cffd |
def output_signature(self): <NEW_LINE> <INDENT> return _blocks_swig4.or_bb_sptr_output_signature(self) | output_signature(or_bb_sptr self) -> io_signature_sptr | 625941c8462c4b4f79d1d734 |
def get_colour(canv, x, y): <NEW_LINE> <INDENT> if is_point_in_canvas(canv, x, y): <NEW_LINE> <INDENT> x, y = translate_1_based_to_0_based(x, y) <NEW_LINE> return canv[y][x][0] | Gets colour at canvas co-ordinates x, y
:param canv: canvas to lookup
:param x: x co-ordinate
:param y: y co-ordinate
:return: colour string (will be truncated to first character) | 625941c86fb2d068a760f0ff |
def safe_mkdir(directory, clean=False): <NEW_LINE> <INDENT> if clean: <NEW_LINE> <INDENT> safe_rmtree(directory) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> os.makedirs(directory) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> if e.errno != errno.EEXIST: <NEW_LINE> <INDENT> raise | Ensure a directory is present.
If it's not there, create it. If it is, no-op. If clean is True, ensure the dir is empty.
:API: public | 625941c8d8ef3951e32435a0 |
def tokenize(text, lowercase=False, deacc=False, errors="strict", to_lower=False, lower=False): <NEW_LINE> <INDENT> lowercase = lowercase or to_lower or lower <NEW_LINE> text = utils.to_unicode(text, errors=errors) <NEW_LINE> if lowercase: <NEW_LINE> <INDENT> text = text.lower() <NEW_LINE> <DEDENT> if deacc: <NEW_LINE>... | Iteratively yield tokens as unicode strings, removing accent marks
and optionally lowercasing the unidoce string by assigning True
to one of the parameters, lowercase, to_lower, or lower.
Input text may be either unicode or utf8-encoded byte string.
The tokens on output are maximal contiguous sequences of alphabetic
... | 625941c8bd1bec0571d90692 |
def __del__(self): <NEW_LINE> <INDENT> self.topSocket.close() <NEW_LINE> end_timer() | closes socket connection when networkAI object is destroyed.
@param :
@return :
@raise : | 625941c8bf627c535bc13232 |
def cursorscrolldown(self): <NEW_LINE> <INDENT> self._command("D") | Down 1 row with scroll | 625941c899cbb53fe6792c4a |
def _discoverApplications(self): <NEW_LINE> <INDENT> applications = [] <NEW_LINE> if sys.platform == 'darwin': <NEW_LINE> <INDENT> prefix = ['/', 'Applications'] <NEW_LINE> applications.extend(self._searchFilesystem( expression=prefix + [ 'Adobe Photoshop CC .+', 'Adobe Photoshop CC .+.app' ], label='Photoshop CC {vers... | Return a list of applications that can be launched from this host.
An application should be of the form:
dict(
'identifier': 'name_version',
'label': 'Name version',
'path': 'Absolute path to the file',
'version': 'Version of the application',
'icon': 'URL or name of predef... | 625941c845492302aab5e326 |
def get_steps_per_epoc(self,batch_size,date_list): <NEW_LINE> <INDENT> return(int(np.ceil(len(date_list)/batch_size))) | Given number of loaded days in and batch size, calculate steps
per epoc.
Parameters
----------
batch_size: int
Size of each batch in days
date_list : array like
list of days (can vary depending on outliers) | 625941c810dbd63aa1bd2c07 |
def json_encode(value, ensure_ascii=True, default=as_json): <NEW_LINE> <INDENT> return json.dumps(value, default=default, ensure_ascii=ensure_ascii) | Returns the json serialize stream | 625941c87b25080760e394bd |
def closestKValues(self, root, target, k): <NEW_LINE> <INDENT> stack = [] <NEW_LINE> def inorder(root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> inorder(root.left) <NEW_LINE> stack.append(root.val) <NEW_LINE> inorder(root.right) <NEW_LINE> <DEDENT> inorder(root) <NEW_LINE> left, r... | :type root: TreeNode
:type target: float
:type k: int
:rtype: List[int] | 625941c87b180e01f3dc4862 |
def test06a_removeGroup(self): <NEW_LINE> <INDENT> self._reopen(mode="r+", node_cache_slots=self.node_cache_slots) <NEW_LINE> self.h5file.remove_node(self.h5file.root, 'agroup2') <NEW_LINE> self._reopen(node_cache_slots=self.node_cache_slots) <NEW_LINE> with self.assertRaises(LookupError): <NEW_LINE> <INDENT> self.h5fi... | Checking removing a lonely group from an existing file. | 625941c8046cf37aa974cdac |
def get_queryset(self): <NEW_LINE> <INDENT> palabra = self.request.query_params.get('palabra', None) <NEW_LINE> if not palabra: <NEW_LINE> <INDENT> return self.queryset.none() <NEW_LINE> <DEDENT> return self.queryset.filter(palabra__icontains=palabra) | This view should return a list of all the purchases for
the user as determined by the username portion of the URL. | 625941c88a43f66fc4b540c9 |
def read_mask(): <NEW_LINE> <INDENT> filen = get_datafile_name() <NEW_LINE> mask_str = [] <NEW_LINE> with open(filen, "r") as f: <NEW_LINE> <INDENT> for l in f: <NEW_LINE> <INDENT> result = l.find('Mask') <NEW_LINE> if result != -1: <NEW_LINE> <INDENT> mask_str.append(l.rstrip()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> r... | Internal function to read mask from data file | 625941c866673b3332b920f4 |
def __init__(self, name, base_domain, storage_dir, **kwargs): <NEW_LINE> <INDENT> super(LibvirtNode, self).__init__(name, **kwargs) <NEW_LINE> self.base_domain = base_domain <NEW_LINE> self.storage_dir = storage_dir <NEW_LINE> self.mem = kwargs.get('mem', None) <NEW_LINE> self.cpu = kwargs.get('cpu', None) <NEW_LINE> s... | Instanciate a libvirt node | 625941c83cc13d1c6d3c73de |
def test_create(self): <NEW_LINE> <INDENT> Template = self.env['product.template'] <NEW_LINE> product = Template.create({'name': 'Test create product'}) <NEW_LINE> self.assertEqual(product.name, 'Test create product') | Create a simple product template | 625941c8004d5f362079a397 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you sure i... | Run administrative tasks. | 625941c863b5f9789fde7149 |
def intersect(self, spec): <NEW_LINE> <INDENT> ncell = self.shape <NEW_LINE> index = self.getIndex() <NEW_LINE> latspec = spec[CoordTypeToLoc[LatitudeType]] <NEW_LINE> lonspec = spec[CoordTypeToLoc[LongitudeType]] <NEW_LINE> latlin = numpy.ma.filled(self._lataxis_) <NEW_LINE> lonlin = numpy.ma.filled(self._lonaxis_) <N... | Intersect with the region specification.
Parameters
----------
'spec' : region specification of the form defined in the grid module.
Returns
-------
(mask, indexspecs) where'mask' is the mask of the result grid AFTER self
and region spec are interested.
'indexspecs' is a dictionary of index specifications sui... | 625941c855399d3f05588717 |
def vote(self, vote, user_email): <NEW_LINE> <INDENT> pass | This method should take a users vote.
If the vote is one of the options list, record the vote and return a string saying so.
If the vote is not one of the stored options return a fail string.
If the user passes a blank vote i.e. "<bot_name> vote " return a fail string.
If the user tries to vote and there is no vote in ... | 625941c85510c4643540f44a |
def pArchiveDateFormat( date_format=None ): <NEW_LINE> <INDENT> global g_archive_date_format <NEW_LINE> if ( date_format ): <NEW_LINE> <INDENT> g_archive_date_format = date_format <NEW_LINE> <DEDENT> rc = g_archive_date_format <NEW_LINE> return rc | pArchiveDateFormat:
Set or get archive date format.
Input: archive date format (if setting it)
Output: original archive date format | 625941c8f8510a7c17cf975f |
@pytest.fixture(scope="function") <NEW_LINE> def add_users(request, topo): <NEW_LINE> <INDENT> users_num = 200 <NEW_LINE> users = UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn=None) <NEW_LINE> for num in range(users_num): <NEW_LINE> <INDENT> USER_NAME = "test_{:0>3d}".format( num ) <NEW_LINE> user = users.create(pr... | Add users | 625941c84428ac0f6e5ba855 |
def alternate(v): <NEW_LINE> <INDENT> path = alternating_path(v) <NEW_LINE> path.reverse() <NEW_LINE> for i in range(0, len(path) - 1, 2): <NEW_LINE> <INDENT> a_matching[path[i]] = path[i + 1] <NEW_LINE> a_matching[path[i + 1]] = path[i] | Make v unmatched by alternating the path to the root of its structure tree. | 625941c89b70327d1c4e0e38 |
def as_matrix(self): <NEW_LINE> <INDENT> return self.platemap.as_matrix() | Return PS as numpy array
:return: numpy array | 625941c816aa5153ce3624dc |
def sos2zpk(sos): <NEW_LINE> <INDENT> sos = np.asarray(sos) <NEW_LINE> n_sections = sos.shape[0] <NEW_LINE> z = np.empty(n_sections*2, np.complex128) <NEW_LINE> p = np.empty(n_sections*2, np.complex128) <NEW_LINE> k = 1. <NEW_LINE> for section in range(n_sections): <NEW_LINE> <INDENT> print(sos[section]) <NEW_LINE> zpk... | - Taken from scipy/signal/filter_design.py - edit to eliminate first
order section
Return zeros, poles, and gain of a series of second-order sections
Parameters
----------
sos : array_like
Array of second-order filter coefficients, must have shape
``(n_sections, 6)``. See `sosfilt` for the SOS filter format
... | 625941c8498bea3a759b9b13 |
def delete(self, event): <NEW_LINE> <INDENT> linklist = list(self.links) <NEW_LINE> for link in linklist: link.delete(event) <NEW_LINE> CanvasObject.delete(self, event) | Delete the CanvasPort *and* all the links that go to or from it. | 625941c896565a6dacc8f72f |
def get_businesses_tree(parm): <NEW_LINE> <INDENT> businesses = Business.get_businesses() <NEW_LINE> for business in businesses: <NEW_LINE> <INDENT> business['show'] = True <NEW_LINE> <DEDENT> return {'datas': tools.listToTree(businesses, 'parent_business_code', 'business_code')} | 获取业务树 | 625941c8dd821e528d63b20d |
def __init__(self, problem, number_optimizated_parameters=0): <NEW_LINE> <INDENT> self.problem = problem <NEW_LINE> self.number_optimizated_parameters = number_optimizated_parameters | Instantiate DOF_Analysis
:ivar Problem problem:
Problem which need to be analyzed
:ivar int number_optimizated_parameters:
Number of parameters which are being optimized. Thus, those are not acounted as specified parameters in DOF analysis. | 625941c88da39b475bd64fd7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.