code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@testing.requires_testing_data <NEW_LINE> def test_rap_music_picks(): <NEW_LINE> <INDENT> evoked = mne.read_evokeds(fname_ave, condition='Right Auditory', baseline=(None, 0)) <NEW_LINE> evoked.crop(tmin=0.05, tmax=0.15) <NEW_LINE> evoked.pick_types(meg=True, eeg=False) <NEW_LINE> forward = mne.read_forward_solution(fna... | Test RAP-MUSIC with picking. | 625941e315fb5d323cde0f07 |
def output_signature(self): <NEW_LINE> <INDENT> return _trellis.trellis_pccc_decoder_combined_ci_sptr_output_signature(self) | output_signature(self) -> gr_io_signature_sptr | 625941e38a43f66fc4b54453 |
def stop_adcp_server(self): <NEW_LINE> <INDENT> if self.serial_server is not None: <NEW_LINE> <INDENT> self.serial_server.close() <NEW_LINE> logger.debug("serial server stopped") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.debug('No serial connection') <NEW_LINE> <DEDENT> self.raw_serial_socket.close() <NEW_LI... | Stop the ADCP Serial TCP server | 625941e33d592f4c4ed1d455 |
def nr_of_videos(self): <NEW_LINE> <INDENT> return self.videos.count() | Returns the number of videos | 625941e356ac1b37e62645ba |
def release_logic(buffer, current_node, channel, network): <NEW_LINE> <INDENT> if buffer[0].to_node == current_node.address: <NEW_LINE> <INDENT> check_establish = { 'to_node': buffer[0].from_node, 'from_node': buffer[0].to_node, } <NEW_LINE> try: <NEW_LINE> <INDENT> establish_connections.pop( establish_connections.inde... | if we get response_rel+ message need to release channel
:param buffer:
:param current_node:
:param channel:
:param network:
:return: | 625941e3e8904600ed9f2325 |
def run_effect(): <NEW_LINE> <INDENT> runpy.run_module("effect") | Runs the module effect. Copy any hyperion effect code in this module or create your own.
Note that effects that call hyperion.setColor(r, g, b) or hyperion.setImage(img) are not supported. | 625941e35166f23b2e1a554b |
def resample_nifti_images(images_location, voxel_dimensions, resample_method): <NEW_LINE> <INDENT> image_files = sorted([ f for f in os.listdir(images_location) if os.path.isfile(os.path.join(images_location, f)) ]) <NEW_LINE> voxel_size_str = '_{:.0f}mm'.format(float(voxel_dimensions[0])) <NEW_LINE> new_folder = image... | Resample the NIfTI images in a folder and put them in a new folder
Args:
images_location: Path where the images are stored
voxel_dimension: tuple (dx, dy, dz)
resample_method: NN - Nearest neighbor
Li - Linear interpolation
Returns:
None: | 625941e30a366e3fb873ec10 |
def test_instance(self): <NEW_LINE> <INDENT> def assertIsNotNone(x): <NEW_LINE> <INDENT> self.assertTrue(x is not None) <NEW_LINE> <DEDENT> def assertIsNone(x): <NEW_LINE> <INDENT> self.assertTrue(x is None) <NEW_LINE> <DEDENT> assertIsNotNone(unify.instance(str2form('p(1)'), str2form('p(y)'))) <NEW_LINE> assertIsNotNo... | Test whether the INSTANCE computation is correct. | 625941e38da39b475bd6536b |
def single(self, mask=False): <NEW_LINE> <INDENT> mask = os.urandom(4) if mask else None <NEW_LINE> return Frame(body=self.data or '', opcode=self.opcode, masking_key=mask, fin=1).build() | Returns a frame bytes with the fin bit set and a random mask. | 625941e3442bda511e8be805 |
def random_hexdigits(len=1): <NEW_LINE> <INDENT> return random.sample(string.hexdigits, len) | 生成随机生成数字或字母 | 625941e3c432627299f0503b |
def print_py(self): <NEW_LINE> <INDENT> return libzyre.zyre_print(self._p) | Print zyre node information to stdout | 625941e323e79379d52ee951 |
def set_parameters(self, locations, credentials, app=None): <NEW_LINE> <INDENT> if app is None: <NEW_LINE> <INDENT> app = 'none' <NEW_LINE> <DEDENT> result = self.call(self.MAX_RETRIES, self.server.set_parameters, locations, credentials, [app], self.secret) <NEW_LINE> if result.startswith('Error'): <NEW_LINE> <INDENT> ... | Passes the given parameters to an AppController, allowing it to start
configuring API services in this AppScale deployment.
Args:
locations: A list that contains the first node's IP address.
credentials: A list that contains API service-level configuration info,
as well as a mapping of IPs to the API services ... | 625941e35f7d997b87174e8d |
def get_disk_drives(): <NEW_LINE> <INDENT> drives = [] <NEW_LINE> if env.is_posix(): <NEW_LINE> <INDENT> for folder in _os.listdir('/dev'): <NEW_LINE> <INDENT> if folder.startswith('sd'): <NEW_LINE> <INDENT> drives.append(folder) <NEW_LINE> <DEDENT> <DEDENT> user_media = _os.path.join('/media/', _os.environ['USER']) <N... | Returns a list of drive root paths that are available
on this machine.
Ex. ['CSSS-9928', 'sda', ...] or ['C:\', 'D:\', ...] | 625941e376e4537e8c351a68 |
def read_headers(self, reader, lines): <NEW_LINE> <INDENT> header_dict = defaultdict(str) <NEW_LINE> while True: <NEW_LINE> <INDENT> line = reader.readline() <NEW_LINE> if line is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> line = line.strip() <NEW_LINE> if not line: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT... | :type reader: DataReader
:type lines: list
:return: dict | 625941e371ff763f4b549a85 |
def waveResnet18(pretrained=False, **kwargs): <NEW_LINE> <INDENT> if pretrained == True: <NEW_LINE> <INDENT> resnet = resnet18(pretrained) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resnet = resnet18() <NEW_LINE> <DEDENT> modules = list(resnet.children())[4:8] <NEW_LINE> model = WaveResNet(BasicBlock, modules) <NEW_... | Constructs a waveResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet | 625941e3d6c5a10208144441 |
def is_initial_task(self): <NEW_LINE> <INDENT> return len(self.job.job_state.processed_tasks) == 0 | :returns True: If the task is the first task in a job.
:returns False: If the task is not the first task in a job. | 625941e324f1403a92600f55 |
def _get_restart_timer(self): <NEW_LINE> <INDENT> return self.__restart_timer | Getter method for restart_timer, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/afi_safis/afi_safi/l3vpn_ipv6_multicast/prefix_limit/state/restart_timer (decimal64)
YANG Description: Time interval in seconds after which the BGP session
is re-established after being ... | 625941e3596a897236089eae |
@when(r"i provide (?P<key>[a-zA-Z0-9\-_]+) (?P<value>.+)") <NEW_LINE> def when_i_provide(context, key, value): <NEW_LINE> <INDENT> context.apiRequestData['params'][key] = value | :type key: str
:type value: str
:type context: behave.runner.Context | 625941e33cc13d1c6d3c776b |
def _measure_time(self, launch_test, test_case, iters, print_per_iter): <NEW_LINE> <INDENT> curr_test_total_time = 0 <NEW_LINE> time_trace = [] <NEW_LINE> while True: <NEW_LINE> <INDENT> if self.args.wipe_cache: <NEW_LINE> <INDENT> torch.ops.operator_benchmark._clear_cache() <NEW_LINE> <DEDENT> run_time_sec = launch_te... | This function execute the operator for <iters> iterations then look at the time.
If it's not significant, the number of iterations will be increased before rerun.
The execution stops when the time becomes significant. | 625941e363f4b57ef0001500 |
def unpack_from(fmt, data, offset=0): <NEW_LINE> <INDENT> return CompiledFormat(fmt).unpack_from(data, offset) | Unpack `data` (bytes or bytearray) according to given format string
`fmt`, starting at given bit offset `offset`. The result is a
tuple even if it contains exactly one item. | 625941e350812a4eaa59c710 |
def __init__(self, input_dim, hidden_dim, kernel_size, bias, peepholes): <NEW_LINE> <INDENT> super(ConvLSTMCell, self).__init__() <NEW_LINE> self.input_dim = input_dim <NEW_LINE> self.hidden_dim = hidden_dim <NEW_LINE> self.kernel_size = kernel_size <NEW_LINE> self.padding = kernel_size[0] // 2, kernel_size[1] // 2 <NE... | Initialize ConvLSTM cell.
Parameters
----------
input_dim: int
Number of channels of input tensor.
hidden_dim: int
Number of channels of hidden state.
kernel_size: (int, int)
Size of the convolutional kernel.
bias: bool
Whether or not to add the bias.
peepholes: bool
Use peepholes (state c_cur is d... | 625941e356ac1b37e62645bb |
def generate_schema_documentation(yaml_schema=DOSDP_SCHEMA, md_output=DOSDP_SCHEMA_MD): <NEW_LINE> <INDENT> mapping_definitions = find_mapping_definitions() <NEW_LINE> plain_doc = generate_plain_documentation(yaml_schema, mapping_definitions) <NEW_LINE> config = configparser.ConfigParser() <NEW_LINE> config.read(DOSDP_... | Generates documentation for the given YAML schema. Uses jsonschema2md to generate a plain documentation,
then decorates generated documentation through using the documentation config (.ini file) | 625941e3d164cc6175783142 |
def makeRandomMove(self): <NEW_LINE> <INDENT> randElem = random.randrange(self.planLength + 4) <NEW_LINE> if randElem < self.planLength: <NEW_LINE> <INDENT> opts = self._otherSymbols(self.plan[randElem]) <NEW_LINE> newElem = random.choice(opts) <NEW_LINE> newPlan = self.plan[:randElem] + newElem + self.plan[randElem+1:... | Takes a ruleset and returns a new ruleset identical to the original, but with one random change. | 625941e3851cf427c661a8fe |
def get_axis_label_keys(self): <NEW_LINE> <INDENT> axis_labels = self.data_info.get_meta_data('axis_labels') <NEW_LINE> axis_label_keys = [] <NEW_LINE> for labels in axis_labels: <NEW_LINE> <INDENT> for key in labels.keys(): <NEW_LINE> <INDENT> axis_label_keys.append(key) <NEW_LINE> <DEDENT> <DEDENT> return axis_label_... | Get axis_label names
:returns: A list containing associated axis names for each dimension
:rtype: list(str) | 625941e35166f23b2e1a554c |
def loadConversations(self, dirName): <NEW_LINE> <INDENT> conversations = [] <NEW_LINE> dirList = self.filesInDir(dirName) <NEW_LINE> for filepath in tqdm(dirList, "OpenSubtitles data files"): <NEW_LINE> <INDENT> if filepath.endswith('xml'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> doc = self.getXML(filepath) <NEW_... | Args:
dirName (str): folder to load
Return:
array(question, answer): the extracted QA pairs | 625941e3dc8b845886cb5929 |
def download_glossary(self, glossaryId: int, exportId: str): <NEW_LINE> <INDENT> glossary_export_path = self.get_glossary_export_path( glossaryId=glossaryId, exportId=exportId ) <NEW_LINE> return self.requester.request( method="get", path=f"{glossary_export_path}/download", ) | Download Glossary.
Link to documentation:
https://support.crowdin.com/api/v2/#operation/api.glossaries.exports.download.download | 625941e307d97122c4178c87 |
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.update_date = timezone.now() <NEW_LINE> ''' For "new" content, populate "Add" fields ''' <NEW_LINE> if self._state.adding == True: <NEW_LINE> <INDENT> self.create_date = timezone.now() <NEW_LINE> <DEDENT> return super(AuditModel, self).save(*args, **kwargs) | For all saves, populate "Update" fields | 625941e345492302aab5e6ba |
def had_allergy_attack(self): <NEW_LINE> <INDENT> for food in self.get_dna(): <NEW_LINE> <INDENT> if self.allergy == food.food_type: <NEW_LINE> <INDENT> print(self.get_species(), "from generation", self.get_generation(),"died from allergy after eating", food.get_species()) <NEW_LINE> return(True) | Deletes the animal from the simulation if it has eaten something
that the species is allergic to. | 625941e3fb3f5b602dac3a8a |
def create_stacks(self): <NEW_LINE> <INDENT> stacks = [] <NEW_LINE> for i in range(4): <NEW_LINE> <INDENT> stacks.append([self.deck.pop()]) <NEW_LINE> <DEDENT> return stacks | create 4 new stacks each having 1 card from the deck
at the start of every round
Initialize all players with that stack
:return: [[Tuple] ...] | 625941e3a4f1c619b28b0423 |
def test_help_content(self, url=url): <NEW_LINE> <INDENT> rqt = requests.get(url).json() <NEW_LINE> self.assertEqual({'/': 'Help (This page)', '/patients': 'Redirects to /patients/', '/patients/': 'List all patients', '/patients/<query>': 'List all patients that was queried', '/status': 'Shows APIs status'}, rqt) | This test tests the '/' route, this route should return a dict with all available routes.
Test: route's content | 625941e34a966d76dd551406 |
def AddUserToGroup(group, username=None): <NEW_LINE> <INDENT> if username is None: <NEW_LINE> <INDENT> usertuple = getnormaluser() <NEW_LINE> USERNAMEVAR = usertuple[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> USERNAMEVAR = username <NEW_LINE> <DEDENT> print("Adding {0} to group {1}.".format(USERNAMEVAR, group)) <... | Add a given user to a single given group. | 625941e3d58c6744b4258051 |
def test_success_not_before_time_jwt_token(self): <NEW_LINE> <INDENT> with mock.patch('django.utils.timezone.now') as mock_time: <NEW_LINE> <INDENT> mock_time.return_value = TEST_TIME <NEW_LINE> data = {'test': 1, '2': 'some text'} <NEW_LINE> expected_token = ( b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzM4NCJ9.' b'eyJ0ZXN0IjoxLCI... | Method that tests succeeded `create_token` method with not before time parameter. | 625941e38e05c05ec3eea76b |
def __getitem__(self, key: Union[int, slice, str]) -> Union[Dict, List]: <NEW_LINE> <INDENT> return self._getitem( key, format_type=self._format_type, format_columns=self._format_columns, output_all_columns=self._output_all_columns, ) | Can be used to index columns (by string names) or rows (by integer index)
| 625941e3cc40096d61595d42 |
def delete_policy_target(self, policy_target): <NEW_LINE> <INDENT> return self.delete(self.policy_target_path % (policy_target)) | Deletes the specified policy target. | 625941e330c21e258bdfa894 |
def patch_response_headers(response, cache_timeout=None): <NEW_LINE> <INDENT> if cache_timeout is None: <NEW_LINE> <INDENT> cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS <NEW_LINE> <DEDENT> if cache_timeout < 0: <NEW_LINE> <INDENT> cache_timeout = 0 <NEW_LINE> <DEDENT> if settings.USE_ETAGS and not response.has_hea... | Adds some useful headers to the given HttpResponse object:
ETag, Last-Modified, Expires and Cache-Control
Each header is only added if it isn't already set.
cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used
by default. | 625941e366656f66f7cbc5a0 |
def get_dendrogram_traces(self, X, colorscale, distfun, linkagefun): <NEW_LINE> <INDENT> d = distfun(X) <NEW_LINE> Z = linkagefun(d) <NEW_LINE> P = sch.dendrogram(Z, orientation=self.orientation, labels=self.labels, no_plot=True) <NEW_LINE> icoord = scp.array(P['icoord']) <NEW_LINE> dcoord = scp.array(P['dcoord']) <NEW... | Calculates all the elements needed for plotting a dendrogram.
:param (ndarray) X: Matrix of observations as array of arrays
:param (list) colorscale: Color scale for dendrogram tree clusters
:param (function) distfun: Function to compute the pairwise distance
from the observations
:param (fu... | 625941e3566aa707497f4956 |
def get_page_name(self): <NEW_LINE> <INDENT> return 'webtail' | Return the name of the html page that corresponds to this plugin | 625941e3f8510a7c17cf9af2 |
@click.group(cls=SnapcraftGroup, invoke_without_command=True) <NEW_LINE> @click.version_option(message=SNAPCRAFT_VERSION_TEMPLATE, version=snapcraft.__version__) <NEW_LINE> @click.pass_context <NEW_LINE> @add_build_options(hidden=True) <NEW_LINE> @click.option('--debug', '-d', is_flag=True, envvar='SNAPCRAFT_DEBUG') <N... | Snapcraft is a delightful packaging tool. | 625941e3a8370b7717052c90 |
def process_masks(superdark_dir): <NEW_LINE> <INDENT> superdark = glob.glob(os.path.join(superdark_dir, '*drk.fits'))[0] <NEW_LINE> nnblvs = glob.glob(os.path.join(superdark_dir, 'nn*blv_tmp.fits')) <NEW_LINE> for nnblv in nnblvs: <NEW_LINE> <INDENT> for ext in [3, 6]: <NEW_LINE> <INDENT> logging.info('\tImprinting hot... | Perform the imprinting of the hot pixel mask for the group of
CR-grown ``blv_tmp.fits`` files in the given superdark directory.
Parameters
----------
superdark_dir : str
The path to the superdark directory to process. | 625941e3bde94217f36831e0 |
def lengthOfLastWord(self, s: str) -> int: <NEW_LINE> <INDENT> if len(s.strip()) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return len(s.split()[-1]) | 完全以来 str 的行管方法处理,使用去空格和空格拆分之后得到最后一个单词,计算长度 | 625941e3c432627299f0503c |
def zone_for_name(name, rdclass=dns.rdataclass.IN, tcp=False, resolver=None): <NEW_LINE> <INDENT> if isinstance(name, string_types): <NEW_LINE> <INDENT> name = dns.name.from_text(name, dns.name.root) <NEW_LINE> <DEDENT> if resolver is None: <NEW_LINE> <INDENT> resolver = get_default_resolver() <NEW_LINE> <DEDENT> if no... | Find the name of the zone which contains the specified name.
@param name: the query name
@type name: absolute dns.name.Name object or string
@param rdclass: The query class
@type rdclass: int
@param tcp: use TCP to make the query (default is False).
@type tcp: bool
@param resolver: the resolver to use
@type resolver: ... | 625941e3379a373c97cfaf3a |
def script_to_address(script: bytes, version='P2SH') -> str: <NEW_LINE> <INDENT> converter = script_to_addr_versions[ADDRESS(version.upper())] <NEW_LINE> return converter(script) | Redeem script to address | 625941e3498bea3a759b9ea1 |
def levelOrderBottom(self, root): <NEW_LINE> <INDENT> if root==None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> resultslist=[[root.val]] <NEW_LINE> currootlist=[root] <NEW_LINE> while True: <NEW_LINE> <INDENT> resultstmplist=[] <NEW_LINE> curtmplist=[] <NEW_LINE> for i in range(0,len(currootlist)): <NEW_LINE> <I... | :type root: TreeNode
:rtype: List[List[int]] | 625941e32ae34c7f2600d524 |
def select_all(self, what): <NEW_LINE> <INDENT> if what == 'user': <NEW_LINE> <INDENT> cboxes = self.user_checkboxes.values() <NEW_LINE> <DEDENT> elif what == 'server': <NEW_LINE> <INDENT> cboxes = self.server_checkboxes.values() <NEW_LINE> <DEDENT> elif what == 'query_type': <NEW_LINE> <INDENT> cboxes = self.query_typ... | Set the value property of all checkboxes in the list to True
@what must be one of 'user' or 'server' | 625941e39f2886367277ac7e |
def csv2json(filename, indent=4): <NEW_LINE> <INDENT> if type(filename) != str: raise TypeError('filename must be a str') <NEW_LINE> try: <NEW_LINE> <INDENT> with open(filename, encoding='utf-8') as file: <NEW_LINE> <INDENT> headers = file.readline().strip().split(',') <NEW_LINE> lst = [] <NEW_LINE> for line in file: <... | This method accepts a readable CSV filename as input,
and returns a string representing the data in JSON format | 625941e3e1aae11d1e74a0ae |
def _max_min_avg_sum(self, select='', alias='', type='MAX'): <NEW_LINE> <INDENT> if not isinstance(select, str) or select == '': <NEW_LINE> <INDENT> print('db_invalid_query') <NEW_LINE> <DEDENT> type = type.upper() <NEW_LINE> if type not in ['MAX', 'MIN', 'AVG', 'SUM']: <NEW_LINE> <INDENT> raise ValueError('Invalid fun... | * Processing Function for the four functions above:
*
* select_max()
* select_min()
* select_avg()
* select_sum()
*
* @param string the field
* @param string an alias
* @return object | 625941e3ad47b63b2c50a372 |
def similarity(self, a: FeatureDocument, b: FeatureDocument) -> float: <NEW_LINE> <INDENT> model = self.model <NEW_LINE> vectorizer = model['vectorizer'] <NEW_LINE> lsa = model['lsa'] <NEW_LINE> emb_a = self._transform_doc(a, vectorizer, lsa) <NEW_LINE> emb_b = self._transform_doc(b, vectorizer, lsa) <NEW_LINE> return ... | Return the semantic similarity between two documents.
| 625941e397e22403b379d38f |
def test_dobrowser_children(self): <NEW_LINE> <INDENT> print ("BEGIN test_dobrowser_children") <NEW_LINE> searchbox = self.driver.find_element(By.ID, 'searchToolTextArea') <NEW_LINE> searchbox.send_keys("DOID:12365") <NEW_LINE> searchbox.send_keys(Keys.RETURN) <NEW_LINE> self.driver.find_element(By.LINK_TEXT, 'malaria'... | @status this test verifies the correct Parent Terms, Siblings, and Children are returned for this query. This test example has children | 625941e382261d6c526ab899 |
def panoids_from_response(text, closest=False, disp=False, proxies=None): <NEW_LINE> <INDENT> pans = re.findall('\[[0-9]+,"(.+?)"\].+?\[\[null,null,(-?[0-9]+.[0-9]+),(-?[0-9]+.[0-9]+)', text) <NEW_LINE> pans = [{ "panoid": p[0], "lat": float(p[1]), "lon": float(p[2])} for p in pans] <NEW_LINE> pans = [p for i, p in enu... | Gets panoids from response (gotting asynchronously) | 625941e3097d151d1a22324b |
def change_collision_direction(self, boundary_value): <NEW_LINE> <INDENT> if self.direction < boundary_value: <NEW_LINE> <INDENT> self.direction -= randint(20, 30) <NEW_LINE> <DEDENT> elif boundary_value == 0: <NEW_LINE> <INDENT> if self.direction > 270: <NEW_LINE> <INDENT> self.direction -= randint(20, 30) <NEW_LINE> ... | This responds to when an ant hits a wall by changing its direction | 625941e3656771135c3ebc67 |
def enable_logger(self, logger, log_level=20): <NEW_LINE> <INDENT> self.logger = logger.getLogger("log") <NEW_LINE> self.logger.setLevel(log_level) | Enables library logging provided a logger object.
:param logger: A python logger pacakge.
:param log_level: Numeric value of a logging level, defaults to INFO. | 625941e321bff66bcd684d42 |
def town_label(self, town): <NEW_LINE> <INDENT> pos = self.latlon_to_canvas(town["lat"], town["lon"]) <NEW_LINE> font = self.fonts[town["class"]] <NEW_LINE> msize = self.style["markersizes"][town["class"]] <NEW_LINE> ts = self.canvas.textsize(town["name"], font=font) <NEW_LINE> textpos = [pos[0] - ts[0] / 2, pos[1] - t... | Draw a town label if it is either capital or does not intersect with a previously drawn
:param town: dict with town data, keys used currently: name, lat, lon, class
:return: | 625941e3596a897236089eaf |
def remove_whitespace(string): <NEW_LINE> <INDENT> if not is_list: <NEW_LINE> <INDENT> return '' <NEW_LINE> print ('Error, remove_whitespace() given a list') <NEW_LINE> <DEDENT> if string == '': <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> if string[0] == ' ': <NEW_LINE> <INDENT> return remove_whitespace(string[1:... | Removes white space from the head of a string
str -> str | 625941e3cad5886f8bd273cd |
def valueLeapYear(year, month): <NEW_LINE> <INDENT> if((year%4 == 0 and year%100 !=0 or year%400 == 0) and month == (1 or 2)): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> return 0 | :param year: the year of the date to test
:param month: the month of the date to test
:return: -1 if the year of date is a leap year and if the month is January of February | 625941e3ec188e330fd5ab8b |
def ContentsValidator(self, filepointer): <NEW_LINE> <INDENT> fileSize = os.stat(filepointer.name).st_size <NEW_LINE> Npix = (fileSize-6000)/2 <NEW_LINE> if Npix == 9000000 or Npix == 2250000 or Npix == 36000000: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Test by checking if the file size makes sense.
| 625941e3167d2b6e31218f89 |
def containsVar(self, v, inclusive=True): <NEW_LINE> <INDENT> return _ilwisobjects.ContinuousColorRange_containsVar(self, v, inclusive) | containsVar(ContinuousColorRange self, PyObject const * v, bool inclusive=True) -> bool
containsVar(ContinuousColorRange self, PyObject const * v) -> bool | 625941e321a7993f00bc80ea |
def add_item(self, text, callback, icon_src): <NEW_LINE> <INDENT> def tap_on_item(instance): <NEW_LINE> <INDENT> callback(instance) <NEW_LINE> self.dismiss() <NEW_LINE> <DEDENT> item = GridBottomSheetItem( caption=text, on_release=tap_on_item, source=icon_src ) <NEW_LINE> if len(self._gl_content.children) % 3 == 0: <NE... | :arg text: element text;
:arg callback: function that will be called when clicking on an item;
:arg icon_src: icon item; | 625941e3d7e4931a7ee9e313 |
def to_single_table_scaled(ruleset, openflow=True): <NEW_LINE> <INDENT> tables = sorted({x.table for x in ruleset}) <NEW_LINE> assert 0 in tables <NEW_LINE> for rule in ruleset: <NEW_LINE> <INDENT> if not rule.path: <NEW_LINE> <INDENT> rule.path = (rule,) <NEW_LINE> <DEDENT> <DEDENT> for table in tables: <NEW_LINE> <IN... | Convert a pre-scaled ruleset to an equivalent single table
Path is attached to all rules and records the original rules
combined to create the single table rule.
ruleset: A list of Rules, pre-scaled by scale_ruleset()
openflow: Remain OpenFlow compatible, if not throw
a MergeException. Default True
return: ... | 625941e3090684286d50f0de |
def get_opened_javascript_dialog(self): <NEW_LINE> <INDENT> return ( self._session_manager.event_handlers["JavascriptDialog"].get_opened_javascript_dialog() ) | Gets the opened javascript dialog.
:raises DomainNotEnabledError: If the Page domain isn't enabled
:raises JavascriptDialogNotFoundError: If there is currently no dialog open | 625941e3eab8aa0e5d26df4d |
def t400290_x0(actionbutton1=6000, flag4=1355, flag5=1357, flag6=6000, flag7=6000, flag8=6000): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> assert (not GetOneLineHelpStatus() and not IsTalkingToSomeoneElse() and not IsClientPlayer() and not IsPlayerDead() and not IsCharacterDisabled()) <NEW_LINE> assert (GetEve... | State 0 | 625941e3566aa707497f4957 |
def application(environ, start_response): <NEW_LINE> <INDENT> form = parse_formvars(environ) <NEW_LINE> cb = form.get("callback", None) <NEW_LINE> ts = form.get("valid", "")[:19] <NEW_LINE> fmt = form.get("fmt", "geojson")[:7] <NEW_LINE> if fmt == "geojson": <NEW_LINE> <INDENT> headers = [("Content-type", "application/... | Do Something | 625941e3507cdc57c63070d7 |
def futures_coin_place_batch_order(self, **params): <NEW_LINE> <INDENT> query_string = urlencode(params) <NEW_LINE> query_string = query_string.replace('%27', '%22') <NEW_LINE> params['batchOrders'] = query_string[12:] <NEW_LINE> return self._request_futures_coin_api('post', 'batchOrders', True, data=params) | Send in new orders.
https://binance-docs.github.io/apidocs/delivery/en/#place-multiple-orders-trade
To avoid modifying the existing signature generation and parameter order logic,
the url encoding is done on the special query param, batchOrders, in the early stage. | 625941e307d97122c4178c88 |
def robotInit(self): <NEW_LINE> <INDENT> self.lstick = wpilib.Joystick(0) <NEW_LINE> self.rstick = wpilib.Joystick(1) <NEW_LINE> self.l_motor = wpilib.Jaguar(1) <NEW_LINE> self.r_motor = wpilib.Jaguar(2) <NEW_LINE> self.gyro = wpilib.ADXRS450_Gyro() <NEW_LINE> self.robot_drive = wpilib.RobotDrive(self.l_motor, self.r_m... | Robot-wide initialization code should go here | 625941e3bd1bec0571d90a23 |
def stop_condition1(pi_old, pi_new, r): <NEW_LINE> <INDENT> ranking_old = np.argsort(pi_old) <NEW_LINE> ranking_new = np.argsort(pi_new) <NEW_LINE> if np.where(ranking_new == r)[0] > np.where(ranking_old == r)[0]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | True if ranking of state r has improved, False otherwise. | 625941e3e76e3b2f99f3abf9 |
def load_embeddings_file(file_name, sep=" ",lower=False, normalize=False): <NEW_LINE> <INDENT> emb={} <NEW_LINE> first = True <NEW_LINE> for line in open(file_name, errors='ignore', encoding='utf-8'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fields = re.split(" ", line) <NEW_LINE> if len(fields) < 5 and first: <NEW... | load embeddings file | 625941e3435de62698dfe041 |
def start_service(self, service): <NEW_LINE> <INDENT> timeout = self.task.timeout or Config().timeouts.default <NEW_LINE> timeout += 300 <NEW_LINE> tags = "service,%s" % service <NEW_LINE> return db.add_service(timeout, self.task.owner, tags) | Start a VM containing one or more services. | 625941e37047854f462a17f9 |
def list_courses(name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> student_obj = get_student(name) <NEW_LINE> <DEDENT> except StudentDNE_Error: <NEW_LINE> <INDENT> print ('ERROR: Student', name, 'does not exist.') <NEW_LINE> return <NEW_LINE> <DEDENT> if student_obj.courses == []: <NEW_LINE> <INDENT> print( name, 'is... | (str) -> Nonetype
Lists the courses that a student with name is taking. | 625941e3adb09d7d5db6cb81 |
def update(self, new_account=None, silent=True): <NEW_LINE> <INDENT> errmsg = "" <NEW_LINE> if not new_account: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.id: <NEW_LINE> <INDENT> new_account = self.connection.get_account_by_id(account_id=self.id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_account = sel... | Base update method for updating component service objs
:params new_account: optional new_account object to be used to update this account
:params silent: bool, if True will not raise Exceptions found during lookup, will instead
write errors to self.connection.err_method()
:returns : self upon successful... | 625941e37c178a314d6ef85a |
def ml_loop(): <NEW_LINE> <INDENT> comm.ml_ready() <NEW_LINE> while True: <NEW_LINE> <INDENT> scene_info = comm.get_scene_info() <NEW_LINE> if scene_info.status == GameStatus.GAME_OVER: <NEW_LINE> <INDENT> comm.ml_ready() <NEW_LINE> continue <NEW_LINE> <DEDENT> comm.send_command(scene_info.frame, SnakeAction.RIGHT) | The main loop for the ml process | 625941e371ff763f4b549a86 |
def convolution(insize, filters, kernel_size, stride=1, padding=0): <NEW_LINE> <INDENT> N, c, y, x = insize <NEW_LINE> ky, kx = make_tup(kernel_size) <NEW_LINE> sy, sx = make_tup(stride) <NEW_LINE> py, px = make_tup(padding) <NEW_LINE> py *= 2 <NEW_LINE> px *= 2 <NEW_LINE> y_out = (y + py - ky) // sy + 1 <NEW_LINE> x_o... | this calculates the size of the output tensor when put through a convolution
that has the parameters given. | 625941e31f5feb6acb0c4f3d |
def create(self, *args, **kwargs): <NEW_LINE> <INDENT> language = kwargs.pop("language", settings.DEFAULT_LANGUAGE) <NEW_LINE> country = kwargs.pop("country", None) <NEW_LINE> user = super(UserManager, self).create(language=language, country=country, **kwargs) <NEW_LINE> return user | Override to create user codes model instance and send confirmation email.
:param args: additional args.
:type args: list.
:param kwargs: additional args.
:type kwargs: dict.
:return: created user instance.
:rtype: mk42.apps.user.models.user.User. | 625941e3d164cc6175783143 |
def _check_network_output(output, num_features): <NEW_LINE> <INDENT> shape = output.shape <NEW_LINE> if output.ndim != 2 or shape[1] != num_features: <NEW_LINE> <INDENT> raise ValueError( 'The output shape of the network should be (-1, {}) but got {}' .format(num_features, shape)) | Checks whether the shape of the network output is (-1, num_features).
Args:
output: Numpy array, output of the network.
num_features: Integer, number of output features.
Raises:
ValueError: If the shape of the output is not (-1, num_features). | 625941e392d797404e304580 |
def __call__( self ): <NEW_LINE> <INDENT> failedReplicas = 0 <NEW_LINE> catalog = self.operation.Catalog <NEW_LINE> waitingFiles = self.getWaitingFilesList() <NEW_LINE> registerOperations = {} <NEW_LINE> for opFile in waitingFiles: <NEW_LINE> <INDENT> gMonitor.addMark( "RegisterReplicaAtt", 1 ) <NEW_LINE> lfn = opFile.... | call me maybe | 625941e3009cb60464c637a3 |
def handle_messages(self, messages): <NEW_LINE> <INDENT> for msg, t in messages: <NEW_LINE> <INDENT> pass | re-implement this method to handle the messages | 625941e3e8904600ed9f2327 |
def test_verify_failure_invalid_audience_no_audience_expected(self): <NEW_LINE> <INDENT> easyjwt_creation = EasyJWT(self.key) <NEW_LINE> easyjwt_creation.audience = self.audience <NEW_LINE> token = easyjwt_creation.create() <NEW_LINE> with self.assertRaises(InvalidAudienceError): <NEW_LINE> <INDENT> easyjwt_verificatio... | Test verifying a token with an audience claim, but without expecting one when verifying the token.
Expected Result: An `InvalidAudienceError` is raised. | 625941e366673b3332b92485 |
def test_hide_owned_thread_no_time(self): <NEW_LINE> <INDENT> self.override_acl({ 'can_hide_own_threads': 1, 'can_hide_threads': 0, 'thread_edit_time': 1, }) <NEW_LINE> self.thread.starter = self.user <NEW_LINE> self.thread.started_on = timezone.now() - timedelta(minutes=5) <NEW_LINE> self.thread.save() <NEW_LINE> resp... | api forbids non-moderator from hiding other users threads | 625941e36e29344779a62a04 |
def Value(self, x, y, size, orientation_degree = 0): <NEW_LINE> <INDENT> text_size = pcbnew.wxSize(size, size) <NEW_LINE> self.module.Value().SetPos0(self.TransformPoint(x, y)) <NEW_LINE> self.module.Value().SetTextPosition(self.module.Value().GetPos0()) <NEW_LINE> self.module.Value().SetSize(text_size) <NEW_LINE> self... | As for references, draw the module's value | 625941e332920d7e50b285c8 |
def yearly(date=datetime.date.today()): <NEW_LINE> <INDENT> return datetime.date(date.year, 1, 1) | once a year | 625941e382261d6c526ab89a |
def __init__(self, height=32, **kwargs): <NEW_LINE> <INDENT> WPFWindow.__init__(self, op.join(op.dirname(__file__), self.xaml_source)) <NEW_LINE> self.user_height = height <NEW_LINE> self.update_window() <NEW_LINE> self._setup(**kwargs) | Initialize user prompt window. | 625941e31d351010ab855f0f |
def t_REG(t): <NEW_LINE> <INDENT> t.type = 'REG' <NEW_LINE> return t | \$r[0-9]+ | 625941e38e05c05ec3eea76c |
def implicit_share(self, contacts): <NEW_LINE> <INDENT> if self.author.user: <NEW_LINE> <INDENT> self._send_to_remotes(contacts) | Contacts can see the content because it is public, but it is not
directly shared with them. | 625941e3c432627299f0503d |
def test_get_product(self): <NEW_LINE> <INDENT> response = self.client.open( '/omogollo2/ServerAPI/1.0.0/product/{productId}'.format(product_id=56), method='GET') <NEW_LINE> self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) | Test case for get_product
devuelve la información de un producto | 625941e38a349b6b435e8567 |
def forward(self, state): <NEW_LINE> <INDENT> state = torch.unsqueeze(state,0) <NEW_LINE> x = F.relu(self.fc1(state)) <NEW_LINE> x = self.batchnorm_1(x) <NEW_LINE> x = F.relu(self.fc2(x)) <NEW_LINE> return F.tanh(self.fc3(x)) | Build an actor (policy) network that maps states -> actions. | 625941e30a50d4780f66728a |
def put_vlq(target: bytearray, n: int) -> int: <NEW_LINE> <INDENT> offset = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> high_bit_mask = 0x80 <NEW_LINE> if offset == 0: <NEW_LINE> <INDENT> high_bit_mask = 0x00 <NEW_LINE> <DEDENT> target[offset] = n & 0x7f | high_bit_mask <NEW_LINE> if n <= 0x7f: <NEW_LINE> <INDENT> bre... | Notice, here change the passed target , so target should be bytearray, not bytes | 625941e391af0d3eaac9be11 |
def GetCodepointForCompletionRequest( self, request_data ): <NEW_LINE> <INDENT> return request_data[ 'start_codepoint' ] | Returns the 1-based codepoint offset on the current line at which to make
the completion request | 625941e3627d3e7fe0d69246 |
def __init__(self, mem, know=None, env=None, testlevel=sudoenv.TEST_AILEVEL): <NEW_LINE> <INDENT> assert isinstance(env, sudoenv.SudoEnv) or env is None <NEW_LINE> assert isinstance(testlevel, int) and testlevel>=0 or testlevel is None <NEW_LINE> oldlev = env.testLevel("ai") <NEW_LINE> if... | Initialisation du système de décision. Celui-ci a initialement
un dictionnaire de données avec des valeurs de début de résolution.
Le code qui crée l'instance SudoAI doit appeler <instance>.data pour
récupérer ce dictionnaire et mettre à jour les données au fur et à
mesure de l'avancement de la résolution. | 625941e3091ae3566866734b |
def browserColors(self): <NEW_LINE> <INDENT> return self._browserColors | Get the colors to be displayed in the browser
:rtype: list[studioqt.Color] | 625941e33317a56b8693a043 |
def get_correct_type(section, key, config): <NEW_LINE> <INDENT> def getstring(section, key, config): <NEW_LINE> <INDENT> return config[section][key] <NEW_LINE> <DEDENT> def getinteger(section, key, config): <NEW_LINE> <INDENT> return config[section].getint(key) <NEW_LINE> <DEDENT> def getboolean(section, key, config): ... | Gives e.g. the boolean True for the string 'True' | 625941e373bcbd0ca4b2c46a |
def encode(self, type, value): <NEW_LINE> <INDENT> if isinstance(type, spec08.Struct): <NEW_LINE> <INDENT> self.encode_struct(type, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> getattr(self, "encode_" + type)(value) | calls the appropriate encode function e.g. encode_octet, encode_short etc. | 625941e3004d5f362079a725 |
def convert(code, outfile, outencoding): <NEW_LINE> <INDENT> outfile.write(GENERIC_DEFINITIONS_1) <NEW_LINE> opts = { 'lang' : 'c', 'sty' : 'default', 'linenosep' : '0pt', 'tabsize' : '8', 'encoding' : 'guess', } <NEW_LINE> usedstyles = [ ] <NEW_LINE> styledefs = '' <NEW_LINE> pos = 0 <NEW_LINE> while pos... | Convert ``code`` | 625941e385dfad0860c3b250 |
def set_ip_address(self, ip_address): <NEW_LINE> <INDENT> is_set = None <NEW_LINE> try: <NEW_LINE> <INDENT> self.logger.info('Start: set ip address') <NEW_LINE> self._system_admin_page.set_ip_address(ip_address) <NEW_LINE> is_set = True <NEW_LINE> <DEDENT> except WebDriverException as exp: <NEW_LINE> <INDENT> is_set = ... | Returning set ip address
Implementing logging for set ip address functionality
:param ip_address:
:return: True/False | 625941e3e76e3b2f99f3abfa |
def palpitar(l_jogado): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> print() <NEW_LINE> print('Digite seu palpite: ') <NEW_LINE> palpite = input() <NEW_LINE> palpite = palpite.lower() <NEW_LINE> if len(palpite) != 1: <NEW_LINE> <INDENT> print("Você deve digitar apenas uma letra.") <NEW_LINE> <DEDENT> elif palpit... | Funcao que testa se o jogador usou uma letra e não qualquer outra coisa
e contabiliza letra jogada retornando o valor da letra que foi jogada | 625941e33617ad0b5ed682eb |
def test_create_business_without_authentication(self): <NEW_LINE> <INDENT> response = self.app.post('/api/v2/businesses', content_type = 'application/json', data = json.dumps(self.business)) <NEW_LINE> self.assertEqual(response.status_code, 404) | Tests whether a user can create a business without token | 625941e366656f66f7cbc5a1 |
def run_blastx(fasta,out,database,threads): <NEW_LINE> <INDENT> cmd = home+"Software/ncbi-blast-2.11.1+/bin/blastx -query "+fasta+" -out "+out+" -db "+database <NEW_LINE> cmd = cmd+" -outfmt 6 -evalue 1e-10 -num_threads "+str(threads) <NEW_LINE> os.system(cmd) <NEW_LINE> return(0) | Run blastx.
Threshold of e-value is 1e-10.
INPUT
fasta (string): query file (fasta)
out (string): output file (blast)
database (string): database for search
outfmt (string): output format (6: tabular, no column name;
7: tabular with column name). Default value is 6.
OUTPUT:
blast file | 625941e31f037a2d8b9465f2 |
def get_options_for_model(self, model): <NEW_LINE> <INDENT> opts = self._get_options_for_model(model) <NEW_LINE> if not opts.registered: <NEW_LINE> <INDENT> raise NotRegistered('The model "%s" is not registered for ' 'translation' % model.__name__) <NEW_LINE> <DEDENT> return opts | Thin wrapper around ``_get_options_for_model`` to preserve the
semantic of throwing exception for models not directly registered. | 625941e34f88993c3716c458 |
def wait_on(server, jobid): <NEW_LINE> <INDENT> jobstatus = server.scheduler.job_state(jobid)["job_state"] <NEW_LINE> running = False <NEW_LINE> while jobstatus in ["Submitted", "Scheduling", "Scheduled", "Running"]: <NEW_LINE> <INDENT> if not running and jobstatus == "Running": <NEW_LINE> <INDENT> print("Job started r... | Wait for the completion of the job.
Do not care for result. This is mostly to prevent flooding of lava with
multiple jobs for the same commit hash. Jenkins is responsible for
running only one job for job submissions. | 625941e34428ac0f6e5babea |
def to_dict(self): <NEW_LINE> <INDENT> d = {} <NEW_LINE> for value, key in self.named_entries(): <NEW_LINE> <INDENT> d[key] = value <NEW_LINE> <DEDENT> return d | Represent this vector as a dictionary from labels to values. | 625941e3be7bc26dc91cd9ed |
def change_piece_to_dict(item): <NEW_LINE> <INDENT> piece_dict = {} <NEW_LINE> piece_dict['piece_id'] = item.piece_id <NEW_LINE> piece_dict['img_url'] = item.img_url <NEW_LINE> piece_dict['clothing_type'] = item.clothing_type <NEW_LINE> return piece_dict | Takes in list of piece objects and returns a dictionary. | 625941e35166f23b2e1a554e |
def coarse_grain(real_thing, memo=None, particle_classes=None): <NEW_LINE> <INDENT> if memo is None: <NEW_LINE> <INDENT> memo = OrderedDict() <NEW_LINE> <DEDENT> if particle_classes is None: <NEW_LINE> <INDENT> particle_classes = [] <NEW_LINE> <DEDENT> proxy = _create_proxy_compounds(real_thing, memo, particle_classes)... | Coarse-graining function. | 625941e3851cf427c661a901 |
def subscribe_admins(self): <NEW_LINE> <INDENT> for uid in g.credentials.userids_with_named_role(self.project._id, 'Admin'): <NEW_LINE> <INDENT> model.Mailbox.subscribe( type='direct', user_id=uid, project_id=self.project._id, app_config_id=self.config._id) | Subscribe all project Admins (for this Application's project) to the
:class:`allura.model.notification.Mailbox` for this Application. | 625941e4711fe17d82542757 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.