code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_clear_emtpy_markers(self): <NEW_LINE> <INDENT> dat = self.dat.copy() <NEW_LINE> dat.markers = [] <NEW_LINE> dat2 = clear_markers(dat) <NEW_LINE> self.assertEqual(dat, dat2)
Clearing emtpy markers has no effect.
625941c3596a897236089a78
def _check_description(description: str, starts_with_verb: bool) -> Optional[str]: <NEW_LINE> <INDENT> if description == "": <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if not description[:1].isalpha(): <NEW_LINE> <INDENT> return "description should start with alphanumeric character" <NEW_LINE> <DEDENT> if description[:1].isupper(): <NEW_LINE> <INDENT> return "description should start with lower case character" <NEW_LINE> <DEDENT> words = description.split(' ') <NEW_LINE> if starts_with_verb and not words[0].endswith('s'): <NEW_LINE> <INDENT> return "description should start with verb in present tense (stem + \"-s\")" <NEW_LINE> <DEDENT> lines = description.splitlines() <NEW_LINE> if not lines[0].endswith('.'): <NEW_LINE> <INDENT> return "description's first line should end with a period" <NEW_LINE> <DEDENT> one_empty_line = False <NEW_LINE> for i, line in enumerate(lines): <NEW_LINE> <INDENT> if line.strip() != line: <NEW_LINE> <INDENT> return "no line in the description should contain leading or trailing white space" <NEW_LINE> <DEDENT> if i == 1 and line.strip() != "": <NEW_LINE> <INDENT> return "description's second line should be empty" <NEW_LINE> <DEDENT> if line == "": <NEW_LINE> <INDENT> if one_empty_line: <NEW_LINE> <INDENT> return "description should not contain two empty lines" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> one_empty_line = True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> one_empty_line = False <NEW_LINE> <DEDENT> <DEDENT> if description.strip() != description: <NEW_LINE> <INDENT> return "description should not contain leading or trailing whitespaces" <NEW_LINE> <DEDENT> return None
Check whether a description is well-styled. :param description: the description :param starts_with_verb: if True, check that the description should start with a verb in third person singular (stem -s). :return: the failed check, if any
625941c3d486a94d0b98e0fa
def test_returns_list(self): <NEW_LINE> <INDENT> self.assertIsInstance(self.products, list)
Test returns a list instance.
625941c350812a4eaa59c2d8
def save_as(self): <NEW_LINE> <INDENT> if self.filename: <NEW_LINE> <INDENT> prev_dir = os.path.dirname(self.filename) <NEW_LINE> prev_name = os.path.basename(self.filename) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prev_dir = None <NEW_LINE> prev_name = None <NEW_LINE> <DEDENT> saved = save_dialog(self.save_filename, _('Choose where to save the history'), self.window_main, _('HTML Files'), '*.html', 'html', prev_dir, prev_name) <NEW_LINE> return saved
Show the save dialog. Return True if was saved.
625941c3a8370b7717052855
def __init__(self, name): <NEW_LINE> <INDENT> assert not '/' in name <NEW_LINE> assert not '.java' in name <NEW_LINE> Declaration.__init__(self, name)
The name of the dependency, initially what the user types "com.biicode.Class" The Case is stored as typed by the user, no changes until it is found and managed by biicode
625941c385dfad0860c3ae0f
def peek(self): <NEW_LINE> <INDENT> if not self.heap: <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> item = self.heap[0] <NEW_LINE> return item[1][0], item[1][1]
Returns the first item in the heap (with the highest priority (smallest value)) with popping from the heap Returns: dp_id, pkt
625941c3dc8b845886cb54e9
def get_wait_game(): <NEW_LINE> <INDENT> f = open(DATABASE_FILE, 'r') <NEW_LINE> game_list = json.loads(f.read()) <NEW_LINE> f.close() <NEW_LINE> wait_game_list = [] <NEW_LINE> for cur_game in game_list: <NEW_LINE> <INDENT> if cur_game['status'] == 'wait': <NEW_LINE> <INDENT> wait_game_list.append(cur_game) <NEW_LINE> <DEDENT> <DEDENT> result = '' <NEW_LINE> for x in wait_game_list: <NEW_LINE> <INDENT> result += '创建人ID: ' + x['player1'] + ' 游戏ID: ' + x['game_id'] + '<br>' <NEW_LINE> <DEDENT> return result
获取正在等待中的游戏列表 :return:
625941c3f9cc0f698b1405b2
def _lookup_iocs(self, all_iocs, resource_per_req=25): <NEW_LINE> <INDENT> threat_info = {} <NEW_LINE> cache_file_name = config_get_deep('virustotal.LookupDomainsFilter.cache_file_name', None) <NEW_LINE> vt = VirusTotalApi(self._api_key, resource_per_req, cache_file_name=cache_file_name) <NEW_LINE> iocs = [x for x in all_iocs if not self._whitelist.match_values(x)] <NEW_LINE> reports = vt.get_domain_reports(iocs) <NEW_LINE> for domain in reports: <NEW_LINE> <INDENT> if not reports[domain]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> trimmed_report = self._trim_domain_report(domain, reports[domain]) <NEW_LINE> if self._should_store_ioc_info(trimmed_report): <NEW_LINE> <INDENT> threat_info[domain] = trimmed_report <NEW_LINE> <DEDENT> <DEDENT> return threat_info
Caches the VirusTotal info for a set of domains. Domains on a whitelist will be ignored. Args: all_iocs - a list of domains. Returns: A dict with domain as key and threat info as value
625941c350812a4eaa59c2d9
def insertResource( self, resourceName, resourceType, serviceType, siteName, gridSiteName, meta = None ): <NEW_LINE> <INDENT> return self.__query( 'insert', 'Resource', locals() )
Inserts on Resource a new row with the arguments given. :Parameters: **resourceName** - `string` name of the resource **resourceType** - `string` it has to be a valid resource type, any of the defaults: `CE` | `CREAMCE` ... **serviceType** - `string` type of the service it belongs, defaults are: `Computing` | `Storage` .. **siteName** - `string` name of the site the resource belongs ( if any ) **gridSiteName** - `string` name of the grid site the resource belongs ( if any ) **meta** - `[, dict]` meta-data for the MySQL query. It will be filled automatically with the `table` key and the proper table name. :return: S_OK() || S_ERROR()
625941c37c178a314d6ef411
def _set_param(self, name, value): <NEW_LINE> <INDENT> if name in self.PARAMS: <NEW_LINE> <INDENT> if self._validate_param(name, value): <NEW_LINE> <INDENT> self._params[name] = value <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> return False
set parameter, with validation
625941c3c4546d3d9de729e7
def _on_message(self, sender, message): <NEW_LINE> <INDENT> logger.info("Received message {0} from {1}".format(message, sender)) <NEW_LINE> if len(message) < 3: <NEW_LINE> <INDENT> logger.info('Message is too short to be something!') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if message[:1] == b'\x02': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logger.info('Received ack, deleting message from sent') <NEW_LINE> id = int.from_bytes(message[1:3], 'big') <NEW_LINE> if id in self.__sent_messages.keys(): <NEW_LINE> <INDENT> self.__sent_messages.pop(id) <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> logger.error("Message was already deleted from republish") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logger.info('Received message, sending ack...') <NEW_LINE> ack_message = b'\x02' + message[1:3] <NEW_LINE> self.__connection.publish(b'ack', sender.decode(), ack_message) <NEW_LINE> self.__callback(self.__callback_object, sender, message[3:])
Message receiving callback :param sender: Message sender :param message: The message
625941c3bf627c535bc13184
def test_update_g(): <NEW_LINE> <INDENT> color = Color(100, 142, 438) <NEW_LINE> assert color.get_r() == 100 <NEW_LINE> assert color.get_g() == 142 <NEW_LINE> assert color.get_b() == 438 <NEW_LINE> update_g(color, 239) <NEW_LINE> assert color.get_r() == 100 <NEW_LINE> assert color.get_g() == 239 <NEW_LINE> assert color.get_b() == 438
Test function for update_g function :return: Tests pass if g component is updated properly, false if otherwise.
625941c3b57a9660fec33837
def test_ObjectNotDictError(): <NEW_LINE> <INDENT> assert_equals( 'Try to inialize with a non-dict object: test', str(ObjectNotDictError('test')) )
测试stock_price_crawler.config的ObjectNotDictError异常类 :return:
625941c345492302aab5e277
def _find_obj(self, obj): <NEW_LINE> <INDENT> for _, provider_class in self.providers.items(): <NEW_LINE> <INDENT> if obj == provider_class or obj == provider_class.__class__: <NEW_LINE> <INDENT> return_obj = provider_class <NEW_LINE> self.fire_hook('resolve', obj, return_obj) <NEW_LINE> return return_obj <NEW_LINE> <DEDENT> elif inspect.isclass(provider_class) and issubclass(provider_class, obj) or issubclass(provider_class.__class__, obj): <NEW_LINE> <INDENT> return_obj = provider_class <NEW_LINE> self.fire_hook('resolve', obj, return_obj) <NEW_LINE> return return_obj <NEW_LINE> <DEDENT> <DEDENT> raise MissingContainerBindingNotFound( 'The dependency with the {0} annotation could not be resolved by the container'.format(obj))
Find an object in the container. Arguments: obj {object} -- Any object in the container Raises: MissingContainerBindingNotFound -- Raised when the object cannot be found. Returns: object -- Returns the object in the container
625941c37b25080760e3940f
def calcLikeness(dist1, dist2): <NEW_LINE> <INDENT> likeness = 1-((np.sum(abs(dist1-dist2))/2)) <NEW_LINE> return likeness
Computes the likeness metric on 2 samples. Parameters ---------- dist1, dist2 : Relative probability distributions (e.g., PDP, KDE) Returns ------- sim : float likeness metric Notes ----- dist1 and dist2 must have the same length. Based on Saylor and Sundell, 2016: Geosphere, v. 12, doi:10.1130/GES01237.1
625941c3a17c0f6771cbe007
def list_cmd(self) -> Dict[str, Dict[str, Any]]: <NEW_LINE> <INDENT> data = self.run_cmd("list", "--json") <NEW_LINE> return json.loads(data)
Executes "eden list --json" to list the Eden checkouts and returns the result as a dictionary.
625941c35fdd1c0f98dc01e8
def CrossProduct(self, *args): <NEW_LINE> <INDENT> return _stomp.AngularCoordinate_CrossProduct(self, *args)
CrossProduct(AngularCoordinate self, AngularCoordinate ang, Stomp::AngularCoordinate::Sphere sphere=Equatorial) -> AngularCoordinate CrossProduct(AngularCoordinate self, AngularCoordinate ang) -> AngularCoordinate
625941c397e22403b379cf4e
def test_extract_new_page(soup) -> None: <NEW_LINE> <INDENT> result = extract_next_page(parser=soup) <NEW_LINE> assert result == "?nextpagelink"
Test to check if "extract_new_page" func returns correct next page link
625941c3de87d2750b85fd46
def update_chat_read_count(self, game_id: int, messages_read: int): <NEW_LINE> <INDENT> headers = { "User-Agent": "WebFeudClient/3.0.17 (Android 10)", "Content-Type": "application/json; charset=UTF-8", "Content-Length": "0", "Host": "api.wordfeud.com", "Connection": "Keep-Alive", "Accept-Encoding": "gzip", "Cookie": f"sessionid={self.sessionid}", } <NEW_LINE> data = f"""{{"read_chat_count":{messages_read}}}""" <NEW_LINE> response = requests.post( f"https://api.wordfeud.com/wf/game/{game_id}/read_chat_count/", data=data.encode("utf-8"), headers=headers, verify=VERIFY_SSL, ) <NEW_LINE> parsed = response.json() <NEW_LINE> if not (parsed["status"] == "success"): <NEW_LINE> <INDENT> logging.error( f"Unexpected response from server in {inspect.stack()[0][3]}") <NEW_LINE> <DEDENT> return parsed
Inform the server about the number of messages in chat you have seen (in total, not new) Args: game_id (int): ID of the game with a chat messages_read (int): The amount of messages you have read Returns: dict: Parsed server response
625941c3377c676e9127215e
def checkLanguage(text): <NEW_LINE> <INDENT> global validLanguageList <NEW_LINE> from langdetect import detect <NEW_LINE> wordCaption = getPlainText(text) <NEW_LINE> if detect(wordCaption) not in validLanguageList: <NEW_LINE> <INDENT> print(" foreign: ", detect(wordCaption)); <NEW_LINE> return False <NEW_LINE> <DEDENT> else: return True
check if item is in the english language, prints if foreign
625941c3656771135c3eb822
def __init__(self, json_dict, lt_id): <NEW_LINE> <INDENT> self.book_id = json_dict[lt_id]["book_id"] <NEW_LINE> self.book_title = json_dict[lt_id]["title"] <NEW_LINE> self.book_author_lf = json_dict[lt_id]["author_lf"] <NEW_LINE> self.book_author_fl = json_dict[lt_id]["author_fl"] <NEW_LINE> self.book_author_code = json_dict[lt_id]["author_code"] <NEW_LINE> self.book_ISBN = json_dict[lt_id]["ISBN"] <NEW_LINE> self.book_ISBN_cleaned = json_dict[lt_id]["ISBN_cleaned"] <NEW_LINE> self.book_publication_date = json_dict[ lt_id]["publicationdate"] <NEW_LINE> self.book_language_original = json_dict[ lt_id]["language_original"] <NEW_LINE> self.book_cover_URL = json_dict[lt_id]["cover"] <NEW_LINE> if ("tags" in json_dict[lt_id]): <NEW_LINE> <INDENT> self.user_tags = json_dict[lt_id]["tags"] <NEW_LINE> <DEDENT> if ("collections" in json_dict[lt_id]): <NEW_LINE> <INDENT> self.user_collections = json_dict[lt_id]["collections"]
Collects the individual book data from Library Thing's JSON export Args: json_dict (dictionary): Expects a JSON object lt_id (integer): Key for the JSON object. In the LT import, this is LT's internal book ID. Structure: (curly braces indicate generic explanations) self.{SQLite field name} = json_dict[{Key for the JSON object to be deserialized}][{key for the target value for this field}] self.book_id = json_dict[lt_id]["book_id]
625941c394891a1f4081ba5e
@app.route('/') <NEW_LINE> @app.route('/home') <NEW_LINE> def home(): <NEW_LINE> <INDENT> name = 'Sherline' <NEW_LINE> return render_template( 'index.html', name = name )
Renders the home page.
625941c3cc0a2c11143dce45
def get_prediction(probability_setting, opposite): <NEW_LINE> <INDENT> mu = probability_setting['mu'] <NEW_LINE> if opposite: <NEW_LINE> <INDENT> mu = 1 - mu <NEW_LINE> <DEDENT> return np.random.normal(mu, probability_setting['sigma'])
Returns a normally distributed random number.
625941c33cc13d1c6d3c7330
def setUp(self): <NEW_LINE> <INDENT> pass
_setUp_ Do nothing
625941c3cc0a2c11143dce46
def t_MODULE(self, t): <NEW_LINE> <INDENT> return t
module
625941c3091ae35668666f17
@app.route('/theme/<theme_id:request_theme>/rss.xml') <NEW_LINE> @cache.cached(timeout=CACHE_TTL) <NEW_LINE> def theme(request_theme): <NEW_LINE> <INDENT> items = db.video.select().where(db.video.themes.contains(request_theme.id)) <NEW_LINE> logo_url = '/logo/theme/%s.png' % request_theme.id <NEW_LINE> theme_feed = podcast.Feed(items, title=request_theme.name, logo_url=logo_url) <NEW_LINE> return make_response_rss(theme_feed)
theme feed
625941c3507cdc57c6306c8c
def show_window_commands(self): <NEW_LINE> <INDENT> self.window.show_commands()
print the available commands for the selected display application
625941c3167d2b6e31218b4b
def _serialize_field(self, obj, field_name, parent): <NEW_LINE> <INDENT> self.obj = obj <NEW_LINE> if self.source == '*': <NEW_LINE> <INDENT> return self.serialize(obj) <NEW_LINE> <DEDENT> self.field_name = self.source or field_name <NEW_LINE> return self.serialize_field(obj, self.field_name)
The entry point into a field, as called by it's parent serializer.
625941c3dd821e528d63b160
def _ReadIslandQuality86(): <NEW_LINE> <INDENT> with winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, x86regpath) as qualitystring: <NEW_LINE> <INDENT> quality = winreg.QueryValueEx(qualitystring, "Island Quality") <NEW_LINE> <DEDENT> quality = quality[0] <NEW_LINE> return quality
Read x86 'Island Quality' string
625941c3d7e4931a7ee9ded2
def get_common_word_threshold(fdist): <NEW_LINE> <INDENT> threshold = get_word_frequency_at(fdist, COMMON_THRESH) <NEW_LINE> if threshold: <NEW_LINE> <INDENT> return threshold <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 2
Returns frequency threshold for a common word.
625941c326238365f5f0ee21
def launch_gateway(port=0, jarpath="", classpath="", javaopts=[], die_on_exit=False): <NEW_LINE> <INDENT> if not jarpath: <NEW_LINE> <INDENT> jarpath = find_jar_path() <NEW_LINE> <DEDENT> if not os.path.exists(jarpath): <NEW_LINE> <INDENT> raise Py4JError("Could not find py4j jar at {0}".format(jarpath)) <NEW_LINE> <DEDENT> classpath = os.pathsep.join((jarpath, classpath)) <NEW_LINE> command = ["java", "-classpath", classpath] + javaopts + ["py4j.GatewayServer"] <NEW_LINE> if die_on_exit: <NEW_LINE> <INDENT> command.append("--die-on-broken-pipe") <NEW_LINE> <DEDENT> command.append(str(port)) <NEW_LINE> logger.debug("Launching gateway with command {0}".format(command)) <NEW_LINE> proc = Popen(command, stdout=PIPE, stdin=PIPE) <NEW_LINE> _port = int(proc.stdout.readline()) <NEW_LINE> return _port
Launch a `Gateway` in a new Java process. :param port: the port to launch the Java Gateway on. If no port is specified then an ephemeral port is used. :param jarpath: the path to the Py4J jar. Only necessary if the jar was installed at a non-standard location or if Python is using a different `sys.prefix` than the one that Py4J was installed under. :param classpath: the classpath used to launch the Java Gateway. :param javaopts: an array of extra options to pass to Java (the classpath should be specified using the `classpath` parameter, not `javaopts`.) :param die_on_exit: if `True`, the Java gateway process will die when this Python process exits or is killed. :rtype: the port number of the `Gateway` server.
625941c3a17c0f6771cbe008
def write(row, output, method='a'): <NEW_LINE> <INDENT> if not os.path.isfile(output) and method == 'a': <NEW_LINE> <INDENT> write(['uid','content','source','url','date','author','label'], output, 'w') <NEW_LINE> <DEDENT> with open(output, method) as f: <NEW_LINE> <INDENT> writer = csv.writer(f) <NEW_LINE> writer.writerow(row)
Writes result to file.
625941c3167d2b6e31218b4c
def is_number(var: Any) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> float(var) <NEW_LINE> return True <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return False
Check if variable is a numeric value. Parameters ---------- var : object Returns ------- is_number : bool True if var is numeric, False otherwise.
625941c31d351010ab855ad2
@when('I ask Gremlin to find the package {package:S} version {version} in the ecosystem ' '{ecosystem}') <NEW_LINE> def gremlin_find_package_version(context, package, version, ecosystem): <NEW_LINE> <INDENT> query = Query().has("pecosystem", ecosystem).has("pname", package).has("version", version) <NEW_LINE> post_query(context, query)
Try to find the package with version in the selected ecosystem.
625941c3004d5f362079a2ea
def test_current_func(self): <NEW_LINE> <INDENT> self.assert_selector( self.MARKUP, ":current(p, div, a)", [], flags=util.HTML )
Test the functional form of current (should match nothing).
625941c3be7bc26dc91cd5b9
def load_file(fname): <NEW_LINE> <INDENT> mat = loadmat(fname) <NEW_LINE> mdata = mat['dataStruct'] <NEW_LINE> mtype = mdata.dtype <NEW_LINE> ndata = {n: mdata[n][0,0] for n in mtype.names} <NEW_LINE> data_headline = ndata['channelIndices'][0] <NEW_LINE> data_raw = ndata['data'] <NEW_LINE> pdata = pd.DataFrame(data_raw,columns=data_headline) <NEW_LINE> iEEGsamplingRate = ndata['iEEGsamplingRate'] <NEW_LINE> nSamplesSegment = ndata['nSamplesSegment'] <NEW_LINE> return pdata, iEEGsamplingRate, nSamplesSegment
Load sample from file
625941c34e4d5625662d4390
def _dumpAccessLogs(self) -> None: <NEW_LINE> <INDENT> if len(self._accessLog) > 0: <NEW_LINE> <INDENT> logger.warning('Failed job accessed files:') <NEW_LINE> for item in self._accessLog: <NEW_LINE> <INDENT> if len(item) == 2: <NEW_LINE> <INDENT> logger.warning('Downloaded file \'%s\' to path \'%s\'', *item) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.warning('Streamed file \'%s\'', *item)
When something goes wrong, log a report. Includes the files that were accessed while the file store was open.
625941c399fddb7c1c9de347
def __predict(self, x): <NEW_LINE> <INDENT> labels = np.zeros(x.shape[0]).astype(np.int) <NEW_LINE> distance = np.full(x.shape[0], np.inf) <NEW_LINE> for i in range(self.k): <NEW_LINE> <INDENT> current_distance = np.sum((x - self.means[i]) ** 2, axis=1) <NEW_LINE> mask = distance > current_distance <NEW_LINE> labels[mask] = i <NEW_LINE> distance[mask] = current_distance[mask] <NEW_LINE> <DEDENT> return labels
Predict the labels for input data, by calculating square Euclidean distance. Args: x: Array-like. Contains data to be predicted. Return: Array of size[amount of data,], contains labels of data.
625941c34428ac0f6e5ba7a7
def academic_degree(self): <NEW_LINE> <INDENT> degrees = self.data['academic_degree'] <NEW_LINE> return choice(degrees)
Get a random academic degree. :return: Degree. :Example: Bachelor.
625941c3711fe17d82542325
def sparse_matrix(self): <NEW_LINE> <INDENT> if sparse.issparse(self.matrix): <NEW_LINE> <INDENT> return self.matrix <NEW_LINE> <DEDENT> return sparse.csr_matrix(self.matrix)
return the sparse representation of this matrix, as a scipy matrix
625941c3e8904600ed9f1ee0
def update(self, event=None): <NEW_LINE> <INDENT> user = os.getlogin() <NEW_LINE> date_formatted = time.strftime("%c") <NEW_LINE> classname = self._entity.__class__.__name__ <NEW_LINE> msg = 'Class : ' + classname + 'Name : ' + self._name + 'Date : ' + date_formatted + 'Event : ' + event <NEW_LINE> if event: <NEW_LINE> <INDENT> self._metadata['log'].append(msg)
Logs an activity update.
625941c391af0d3eaac9b9cd
def min(self): <NEW_LINE> <INDENT> if not self.sublocations: <NEW_LINE> <INDENT> return self.start <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> m = reduce(lambda x, y: min(x,y), map(lambda x: x.min(), self.sublocations), sys.maxint) <NEW_LINE> return m
Returns the minimum start value for this location. :returns: int Minimum start value of this location
625941c307d97122c417883d
def my_load_dataset(dataset = 'mnist'): <NEW_LINE> <INDENT> if dataset == 'cifar10': <NEW_LINE> <INDENT> (x_train, y_train), (x_test, y_test) = cifar10.load_data() <NEW_LINE> img_rows, img_cols, img_chns = 32, 32, 3 <NEW_LINE> <DEDENT> elif dataset == 'mnist': <NEW_LINE> <INDENT> (x_train, y_train), (x_test, y_test) = mnist.load_data() <NEW_LINE> img_rows, img_cols, img_chns = 28, 28, 1 <NEW_LINE> <DEDENT> x_train = np.reshape(x_train, (-1 , img_rows, img_cols, img_chns)).astype(np.float32) <NEW_LINE> x_test = np.reshape(x_test, (-1, img_rows, img_cols, img_chns)).astype(np.float32) <NEW_LINE> y_train = np.reshape(y_train, (-1 ,)).astype(np.int32) <NEW_LINE> y_test = np.reshape(y_test, (-1 ,)).astype(np.int32) <NEW_LINE> print('load dataset ' + str(dataset) + ' finished') <NEW_LINE> print('train_size:', x_train.shape) <NEW_LINE> print('test_size:', x_test.shape) <NEW_LINE> print('train_labels_shape:', y_train.shape) <NEW_LINE> print('test_labels_shape:', y_test.shape) <NEW_LINE> return x_train, y_train, x_test, y_test
625941c3e5267d203edcdc55
def create_contributors(): <NEW_LINE> <INDENT> for contributor in repo_data.top_contributors(): <NEW_LINE> <INDENT> add_contributor(contributor)
method to add all current contributors to the database
625941c3ac7a0e7691ed4086
def wait_connect(self) -> bool: <NEW_LINE> <INDENT> self._auth_event.wait() <NEW_LINE> if not self._auth_success: <NEW_LINE> <INDENT> log.error("Invalid credentials for connecting to XMPP server.") <NEW_LINE> return False <NEW_LINE> <DEDENT> self._connect_event.wait() <NEW_LINE> return True
Wait for client to connect. Returns: Success or not.
625941c392d797404e30413f
def __init__(self): <NEW_LINE> <INDENT> self.N = 0 <NEW_LINE> self.x = [] <NEW_LINE> self.y = [] <NEW_LINE> self.z = [] <NEW_LINE> self.a = [] <NEW_LINE> self.materials = []
Creates empty collection of spheres. Use child classes for non-empty!
625941c3be8e80087fb20bfb
def print_upper_words_start(words, must_start_with): <NEW_LINE> <INDENT> for word in words: <NEW_LINE> <INDENT> for letter in must_start_with: <NEW_LINE> <INDENT> if word[0].upper() == letter.upper(): <NEW_LINE> <INDENT> print(word.upper())
print words that start with letter
625941c3009cb60464c63369
def validate(self): <NEW_LINE> <INDENT> return self._validate(self.root)
verify the tree by traversing the nodes and reproduce the hash
625941c35fc7496912cc3934
def test_s_mtp_stat_router_get_all_aggregate_sub_account_provider_smtp_stats(self): <NEW_LINE> <INDENT> pass
Test case for s_mtp_stat_router_get_all_aggregate_sub_account_provider_smtp_stats
625941c33d592f4c4ed1d028
def abort(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.request('ABOR', *args, **kwargs)
Sends a ABOR request. Returns :class:`FTPResponse` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes.
625941c34f6381625f1149f2
def pensize(turtle, width=None): <NEW_LINE> <INDENT> if type(turtle) != _turtle.Turtle: <NEW_LINE> <INDENT> raise(TypeError("turtle argument to pensize is not a valid turtle")) <NEW_LINE> <DEDENT> return turtle.pensize(width)
Set or return the line thickness. Aliases: pensize | width Arguments: turtle -- the turtle width -- positive number Set the line thickness to width or return it. If resizemode is set to "auto" and turtleshape is a polygon, that polygon is drawn with the same line thickness. If no argument is given, current pensize is returned. Example: >>> pensize(turtle) 1 >>> pensize(turtle, 10) # from here on lines of width 10 are drawn
625941c3097d151d1a222e11
def get_volumes(self): <NEW_LINE> <INDENT> self.lv_list = self.get_all_volumes(self.vg_name) <NEW_LINE> return self.lv_list
Get all LV's associated with this instantiation (VG). :returns: List of Dictionaries with LV info
625941c391f36d47f21ac4a7
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(SeqGen, self).__init__(reduce_alignment=False, **kwargs)
Instantiate. Mandatory arguments are a tree and GTR model.
625941c3fbf16365ca6f6176
def update_skill_name_dict(self, message): <NEW_LINE> <INDENT> self.skill_names[message.data['id']] = message.data['name']
Messagebus handler, updates dictionary of if to skill name conversions.
625941c367a9b606de4a7e71
def searchByCritirea(crit1, crit2, crit2value): <NEW_LINE> <INDENT> result = df.loc[df[crit2] == crit2value, crit1].sum() <NEW_LINE> return result
Recieves problem to search for and returns that problem when value of crit2 matches value given to function as crit2value. Returns int.
625941c33eb6a72ae02ec48e
def sign_in(self, username='', password=''): <NEW_LINE> <INDENT> with open(self.DB_CONN, self.READ_MODE) as file: <NEW_LINE> <INDENT> records = file.readlines() <NEW_LINE> for record in records: <NEW_LINE> <INDENT> __username, __password = record.split(',')[:2] <NEW_LINE> if username == __username and password == __password: <NEW_LINE> <INDENT> self.store_logs(content=self.LOGGED_IN_LOG.format( username)) <NEW_LINE> self.current_user = username <NEW_LINE> return self.LOGIN_SUCCESSFUL <NEW_LINE> <DEDENT> <DEDENT> return self.NO_RECORD_FOUND
Provided the username and password the user sign-in Keyword Arguments: username {str} -- [description] (default: {''}) password {str} -- [description] (default: {''}) Returns: Custom msg defined in the constructor
625941c385dfad0860c3ae10
def data_to_message(self, data): <NEW_LINE> <INDENT> return [ self.child.data_to_message(item) for item in data ]
List of protobuf messages <- List of dicts of python primitive datatypes.
625941c323e79379d52ee51c
def get_val_outputs(self, use_one_hot=None): <NEW_LINE> <INDENT> if self._data['val_inds'] is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> out_data = self._data['out_data'][self._data['val_inds'], :] <NEW_LINE> return self._get_outputs(out_data, use_one_hot)
Get the outputs (targets) of all validation samples. See documentation of method "get_train_outputs" for details. Args: use_one_hot: See "get_train_outputs". Returns: A 2D numpy array. Returns None if no validation set exists.
625941c39b70327d1c4e0d8a
def __getattr__(self, name): <NEW_LINE> <INDENT> return self.get_endpoint(name)
Summons endpoints. E.g. api.mailing :returns: EndpointProxy
625941c36aa9bd52df036d59
def _collect_stix2_mappings(): <NEW_LINE> <INDENT> if not STIX2_OBJ_MAPS: <NEW_LINE> <INDENT> top_level_module = importlib.import_module('stix2') <NEW_LINE> path = top_level_module.__path__ <NEW_LINE> prefix = str(top_level_module.__name__) + '.' <NEW_LINE> for module_loader, name, is_pkg in pkgutil.walk_packages(path=path, prefix=prefix): <NEW_LINE> <INDENT> ver = name.split('.')[1] <NEW_LINE> if re.match(r'^stix2\.v2[0-9]$', name) and is_pkg: <NEW_LINE> <INDENT> mod = importlib.import_module(name, str(top_level_module.__name__)) <NEW_LINE> STIX2_OBJ_MAPS[ver] = {} <NEW_LINE> STIX2_OBJ_MAPS[ver]['objects'] = mod.OBJ_MAP <NEW_LINE> STIX2_OBJ_MAPS[ver]['observables'] = mod.OBJ_MAP_OBSERVABLE <NEW_LINE> STIX2_OBJ_MAPS[ver]['observable-extensions'] = mod.EXT_MAP <NEW_LINE> <DEDENT> elif re.match(r'^stix2\.v2[0-9]\.common$', name) and is_pkg is False: <NEW_LINE> <INDENT> mod = importlib.import_module(name, str(top_level_module.__name__)) <NEW_LINE> STIX2_OBJ_MAPS[ver]['markings'] = mod.OBJ_MAP_MARKING
Navigate the package once and retrieve all object mapping dicts for each v2X package. Includes OBJ_MAP, OBJ_MAP_OBSERVABLE, EXT_MAP.
625941c3e76e3b2f99f3a7c5
def test_port_v2(self): <NEW_LINE> <INDENT> conf.properties['main.server.port'] = '1234' <NEW_LINE> conf.properties['main.server.scheme'] = '' <NEW_LINE> self.assertEqual(get_server_url(), 'https://example.com:1234')
Hostname and port set, scheme blank.
625941c35510c4643540f39f
def home(request): <NEW_LINE> <INDENT> qs = Deck.objects.all <NEW_LINE> context = {} <NEW_LINE> return render(request, 'flashcards/home.html')
Render the FLASHCARD app home template
625941c3ec188e330fd5a759
def __init__(self, A, B, pi): <NEW_LINE> <INDENT> self.A = np.array(A) <NEW_LINE> self.B = np.array(B) <NEW_LINE> self.pi = np.array(pi) <NEW_LINE> self.N = self.A.shape[0] <NEW_LINE> self.M = self.B.shape[1]
'' A: 状态转移概率矩阵 B: 输出观察概率矩阵 pi: 初始化状态向量
625941c3bd1bec0571d905e5
def save_monitor_command(self, server, timestamp, command, keyname, argument): <NEW_LINE> <INDENT> epoch = timestamp.strftime('%s') <NEW_LINE> current_date = timestamp.strftime('%y%m%d') <NEW_LINE> pipeline = self.conn.pipeline() <NEW_LINE> command_count_key = server + ":CommandCount:" + epoch <NEW_LINE> pipeline.zincrby(command_count_key, command, 1) <NEW_LINE> command_count_key = server + ":DailyCommandCount:" + current_date <NEW_LINE> pipeline.zincrby(command_count_key, command, 1) <NEW_LINE> key_count_key = server + ":KeyCount:" + epoch <NEW_LINE> pipeline.zincrby(key_count_key, keyname, 1) <NEW_LINE> key_count_key = server + ":DailyKeyCount:" + current_date <NEW_LINE> pipeline.zincrby(key_count_key, keyname, 1) <NEW_LINE> command_count_key = server + ":CommandCountBySecond" <NEW_LINE> pipeline.hincrby(command_count_key, epoch, 1) <NEW_LINE> command_count_key = server + ":CommandCountByMinute" <NEW_LINE> field_name = current_date + ":" + str(timestamp.hour) + ":" <NEW_LINE> field_name += str(timestamp.minute) <NEW_LINE> pipeline.hincrby(command_count_key, field_name, 1) <NEW_LINE> command_count_key = server + ":CommandCountByHour" <NEW_LINE> field_name = current_date + ":" + str(timestamp.hour) <NEW_LINE> pipeline.hincrby(command_count_key, field_name, 1) <NEW_LINE> command_count_key = server + ":CommandCountByDay" <NEW_LINE> field_name = current_date <NEW_LINE> pipeline.hincrby(command_count_key, field_name, 1) <NEW_LINE> pipeline.execute()
save information about every command Args: server (str): Server ID timestamp (datetime): Timestamp. command (str): The Redis command used. keyname (str): The key the command acted on. argument (str): The args sent to the command.
625941c38c0ade5d55d3e96f
def _get_last_pose(self): <NEW_LINE> <INDENT> return pose2tf(self.keyframes[-1].pose.param)
Get last pose
625941c37b180e01f3dc47b8
def solve_row0_tile(self, target_col): <NEW_LINE> <INDENT> self.update_puzzle('l') <NEW_LINE> self.update_puzzle('d') <NEW_LINE> target_tile = self.current_position(0, target_col) <NEW_LINE> if target_tile == (0, target_col): <NEW_LINE> <INDENT> return 'ld' <NEW_LINE> <DEDENT> up_moves = ['u'] * (1 - target_tile[0]) <NEW_LINE> left_moves = ['l'] * (target_col - 1 - target_tile[1]) <NEW_LINE> phase1_moves = up_moves + left_moves <NEW_LINE> phase2_moves = [] <NEW_LINE> if len(up_moves) == 0: <NEW_LINE> <INDENT> phase2_moves = phase2_moves + ['urrdl'] * (len(left_moves) - 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if len(left_moves) == 0: <NEW_LINE> <INDENT> phase2_moves = phase2_moves + ['ld'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> phase2_moves = ['drrul'] * (len(left_moves) - 1) + ['druld'] <NEW_LINE> <DEDENT> <DEDENT> res = ''.join(phase1_moves + phase2_moves + ['urdlurrdluldrruld']) <NEW_LINE> for charr in list(res): <NEW_LINE> <INDENT> self.update_puzzle(charr) <NEW_LINE> <DEDENT> return 'ld' + res
Solve the tile in row zero at the specified column Updates puzzle and returns a move string
625941c31b99ca400220aa68
def __init__(self, name="outputtriggerstep"): <NEW_LINE> <INDENT> OutputTrigger.__init__(self, name) <NEW_LINE> return
Constructor.
625941c399cbb53fe6792b9d
def adjust_group_result(weight_dic, group_list, n_groups): <NEW_LINE> <INDENT> group_dic = dict() <NEW_LINE> group_weight_dic = dict() <NEW_LINE> n = len(weight_dic.keys()) <NEW_LINE> for sub_id in range(1, n + 1): <NEW_LINE> <INDENT> group_id = group_list[sub_id - 1] <NEW_LINE> group_dic.setdefault(group_id, []).append(sub_id) <NEW_LINE> if group_id not in group_weight_dic: <NEW_LINE> <INDENT> group_weight_dic[group_id] = 0 <NEW_LINE> <DEDENT> group_weight_dic[group_id] += weight_dic[sub_id][ImportReaches2Mongo._NUMCELLS] <NEW_LINE> <DEDENT> ave_eight = 0 <NEW_LINE> for tmpid in group_weight_dic: <NEW_LINE> <INDENT> ave_eight += group_weight_dic[tmpid] <NEW_LINE> <DEDENT> ave_eight /= n_groups <NEW_LINE> for iGroup in range(n_groups): <NEW_LINE> <INDENT> if iGroup not in group_dic: <NEW_LINE> <INDENT> max_id, max_weight = get_max_weight(group_weight_dic, group_dic) <NEW_LINE> if max_id < 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> sub_list = group_dic[max_id] <NEW_LINE> sub_id = sub_list[0] <NEW_LINE> group_dic[iGroup] = [sub_id, ] <NEW_LINE> group_list[sub_id - 1] = iGroup <NEW_LINE> group_dic[max_id].remove(sub_id)
Adjust group result
625941c3ab23a570cc250137
def readin_temp(temp_file): <NEW_LINE> <INDENT> with open(temp_file, 'r') as fid: <NEW_LINE> <INDENT> temp = np.loadtxt(fid, skiprows=1, usecols=[2]) <NEW_LINE> <DEDENT> return temp
The temperature file should be in mag-format: header + 3 columns with coordinates and value of temperature. The coordinates have to be the same as from the resistivity data. Such a temperature file can be produced with #############
625941c39c8ee82313fbb72b
def associate_connection_with_lag(connectionId=None, lagId=None): <NEW_LINE> <INDENT> pass
Associates an existing connection with a link aggregation group (LAG). The connection is interrupted and re-established as a member of the LAG (connectivity to AWS will be interrupted). The connection must be hosted on the same AWS Direct Connect endpoint as the LAG, and its bandwidth must match the bandwidth for the LAG. You can reassociate a connection that's currently associated with a different LAG; however, if removing the connection will cause the original LAG to fall below its setting for minimum number of operational connections, the request fails. Any virtual interfaces that are directly associated with the connection are automatically re-associated with the LAG. If the connection was originally associated with a different LAG, the virtual interfaces remain associated with the original LAG. For interconnects, any hosted connections are automatically re-associated with the LAG. If the interconnect was originally associated with a different LAG, the hosted connections remain associated with the original LAG. See also: AWS API Documentation :example: response = client.associate_connection_with_lag( connectionId='string', lagId='string' ) :type connectionId: string :param connectionId: [REQUIRED] The ID of the connection. Example: dxcon-abc123 Default: None :type lagId: string :param lagId: [REQUIRED] The ID of the LAG with which to associate the connection. Example: dxlag-abc123 Default: None :rtype: dict :return: { 'ownerAccount': 'string', 'connectionId': 'string', 'connectionName': 'string', 'connectionState': 'ordering'|'requested'|'pending'|'available'|'down'|'deleting'|'deleted'|'rejected', 'region': 'string', 'location': 'string', 'bandwidth': 'string', 'vlan': 123, 'partnerName': 'string', 'loaIssueTime': datetime(2015, 1, 1), 'lagId': 'string', 'awsDevice': 'string' } :returns: Ordering : The initial state of a hosted connection provisioned on an interconnect. The connection stays in the ordering state until the owner of the hosted connection confirms or declines the connection order. Requested : The initial state of a standard connection. The connection stays in the requested state until the Letter of Authorization (LOA) is sent to the customer. Pending : The connection has been approved, and is being initialized. Available : The network link is up, and the connection is ready for use. Down : The network link is down. Deleting : The connection is in the process of being deleted. Deleted : The connection has been deleted. Rejected : A hosted connection in the 'Ordering' state will enter the 'Rejected' state if it is deleted by the end customer.
625941c356b00c62f0f1460f
def __init__(self, mdp, discount = 0.9, iterations = 100): <NEW_LINE> <INDENT> self.mdp = mdp <NEW_LINE> self.discount = discount <NEW_LINE> self.iterations = iterations <NEW_LINE> self.values = util.Counter() <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> for i in range(0,self.iterations): <NEW_LINE> <INDENT> Vi = util.Counter() <NEW_LINE> state_all=self.mdp.getStates() <NEW_LINE> for state in state_all: <NEW_LINE> <INDENT> actions = self.mdp.getPossibleActions(state) <NEW_LINE> ma=float('-Inf') <NEW_LINE> if not self.mdp.isTerminal(state) or actions: <NEW_LINE> <INDENT> for a in actions: <NEW_LINE> <INDENT> pai_tmp = self.getQValue(state, a) <NEW_LINE> if ma < pai_tmp: <NEW_LINE> <INDENT> ma=pai_tmp <NEW_LINE> pai_star=a <NEW_LINE> <DEDENT> <DEDENT> Vi[state] = ma <NEW_LINE> <DEDENT> elif self.mdp.isTerminal(state) or not actions: <NEW_LINE> <INDENT> Vi[state]=0 <NEW_LINE> <DEDENT> <DEDENT> self.values = Vi
Your value iteration agent should take an mdp on construction, run the indicated number of iterations and then act according to the resulting policy. Some useful mdp methods you will use: mdp.getStates() mdp.getPossibleActions(state) mdp.getTransitionStatesAndProbs(state, action) mdp.getReward(state, action, nextState)
625941c330bbd722463cbd7b
def get_image_plane_shapes_from_camera(cam_tfm, cam_shp): <NEW_LINE> <INDENT> assert isinstance(cam_tfm, (str, unicode, basestring)) <NEW_LINE> assert len(cam_tfm) > 0 <NEW_LINE> assert maya.cmds.objExists(cam_tfm) <NEW_LINE> assert isinstance(cam_shp, (str, unicode, basestring)) <NEW_LINE> assert len(cam_shp) > 0 <NEW_LINE> assert maya.cmds.objExists(cam_shp) <NEW_LINE> assert node_utils.attribute_exists('imagePlane', cam_shp) <NEW_LINE> plug = '{0}.imagePlane'.format(cam_shp) <NEW_LINE> img_pl_shps = maya.cmds.listConnections(plug, type='imagePlane') or [] <NEW_LINE> img_pl_shps = [node_utils.get_long_name(n) for n in img_pl_shps] <NEW_LINE> img_pl_shps = [n for n in img_pl_shps if n is not None] <NEW_LINE> return img_pl_shps
Get the list of image plane shape nodes connected to the given camera. :param cam_tfm: Camera transform node. :type cam_tfm: str :param cam_shp: Camera shape node. :type cam_shp: str :returns: The list of image shape nodes, may be an empty list. :rtype: [str, ..]
625941c330dc7b766590191f
def test_add_floats(self): <NEW_LINE> <INDENT> result = mymath.add(10.5, 2) <NEW_LINE> self.assertEqual(result, 12.5)
Test that the addition of two floats returns the correct result
625941c33317a56b86939c13
def ReqQryDepthMarketData(self, qry_depth_market_data, request_id): <NEW_LINE> <INDENT> return super(TraderApi, self).ReqQryDepthMarketData(qry_depth_market_data, request_id)
请求查询行情 :param qry_depth_market_data: :param request_id: int :return: int
625941c3fff4ab517eb2f3f1
def generate_label(self, label_text: str) -> object: <NEW_LINE> <INDENT> raise NotImplementedError("generate_label not implemented")
Generates a label widget that shows text :param label_text: The text to be displayed by the label :return: the label widget
625941c355399d3f0558866a
def handle(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> meta = self.platform.platformmeta_set.get(key='subject_prepend') <NEW_LINE> subject = '%s: %s' % (meta.value, self.telegram.subject) <NEW_LINE> <DEDENT> except PlatformMeta.DoesNotExist: <NEW_LINE> <INDENT> subject = self.telegram.subject <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> from_address = self.platform.platformmeta_set.get(key='from_address').value <NEW_LINE> <DEDENT> except PlatformMeta.DoesNotExist: <NEW_LINE> <INDENT> from_address = settings.TELEGRAM_EMAIL_HANDLER_FROM <NEW_LINE> <DEDENT> send_mail( subject, self.telegram.content, from_address, [self.subscription.subscriptionmeta_set.get(key='email_address').value])
Will try to use settings.TELEGRAM_EMAIL_HANDLER_FROM, the platformmeta setting "subject_prepend", and the subscriptionmeta setting "email_address".
625941c30a50d4780f666e47
def invertTree(self, root): <NEW_LINE> <INDENT> if root is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if root.left is not None: <NEW_LINE> <INDENT> self.invertTree(root.left) <NEW_LINE> <DEDENT> if root.right is not None: <NEW_LINE> <INDENT> self.invertTree(root.right) <NEW_LINE> <DEDENT> root.left, root.right = root.right, root.left
:type root: TreeNode :rtype: TreeNode
625941c37d847024c06be270
def __virtual__(): <NEW_LINE> <INDENT> disable = [ 'Windows', ] <NEW_LINE> if __grains__['os'] in disable: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return 'locate'
Only work on posix-like systems
625941c32ae34c7f2600d0e8
def _set_override_role_caught_exc(self): <NEW_LINE> <INDENT> self.__override_role_caught_exc = True
Helper for tracking whether exception was thrown inside ``override_role``.
625941c3596a897236089a79
@pytest.fixture <NEW_LINE> def reg_comp(): <NEW_LINE> <INDENT> y_true = np.random.normal(size=100) <NEW_LINE> y_pred = np.random.normal(0.25, 0.3, size=y_true.shape) + y_true <NEW_LINE> eval1 = RegressionEvaluation( y_true=y_true, y_pred=y_pred, value_name='variable', model_name='test', ) <NEW_LINE> y_true = np.random.normal(size=100) <NEW_LINE> y_pred = np.random.normal(0.2, 0.3, size=y_true.shape) + y_true <NEW_LINE> eval2 = RegressionEvaluation( y_true=y_true, y_pred=y_pred, value_name='variable', model_name='train', ) <NEW_LINE> y_true = np.random.normal(size=100) <NEW_LINE> y_pred = np.random.normal(0.3, 0.3, size=y_true.shape) + y_true <NEW_LINE> eval3 = RegressionEvaluation( y_true=y_true, y_pred=y_pred, value_name='variable', model_name='validate', ) <NEW_LINE> return RegressionComparison([eval1, eval2, eval3])
Setup an example RegressionComparison
625941c3ab23a570cc250138
def save_function_effect(module): <NEW_LINE> <INDENT> for intr in module.itervalues(): <NEW_LINE> <INDENT> if isinstance(intr, dict): <NEW_LINE> <INDENT> save_function_effect(intr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fe = FunctionEffects(intr) <NEW_LINE> IntrinsicArgumentEffects[intr] = fe <NEW_LINE> if isinstance(intr, intrinsic.Class): <NEW_LINE> <INDENT> save_function_effect(intr.fields)
Recursively save function effect for pythonic functions.
625941c3498bea3a759b9a66
def get_map(tokens): <NEW_LINE> <INDENT> token_index = enumerate(tokens) <NEW_LINE> token_map = {} <NEW_LINE> for k, v in token_index: <NEW_LINE> <INDENT> if v in token_map.keys(): <NEW_LINE> <INDENT> token_map[v].append(k) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> token_map[v] = [k] <NEW_LINE> <DEDENT> <DEDENT> return token_map
Returns a dictionary with each unique token in @tokens as keys. The values are lists: the index of the position/s in global @TEXT that the token is found.
625941c37d847024c06be271
def angle_features(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return [ "_".join((F_ANGLE, str(n))) for n in range(1, self.ncontrol_points() - 1) ] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logging.error( "Failed to get # of control points from training file. Unknown number of angle measurements", exc_info=True, ) <NEW_LINE> return []
Return a list of angle feature names
625941c3097d151d1a222e12
def decrypt(self, data, client): <NEW_LINE> <INDENT> decryptor = self.CLIENTS[client]['enc-dec'].decryptor() <NEW_LINE> data = decryptor.update(data) + decryptor.finalize() <NEW_LINE> unpadder = padding.PKCS7(128).unpadder() <NEW_LINE> data = unpadder.update(data) + unpadder.finalize() <NEW_LINE> return data
Decrypt a message
625941c3236d856c2ad4478f
def resetPlayers(self): <NEW_LINE> <INDENT> if len(self.spawns) >= 2: <NEW_LINE> <INDENT> self.p1 = self.spawns[int(random.random() * len(self.spawns))] <NEW_LINE> self.p2 = self.spawns[int(random.random() * len(self.spawns))] <NEW_LINE> while self.p1 == self.p2: <NEW_LINE> <INDENT> self.p2 = self.spawns[int(random.random() * len(self.spawns))] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> self.p1 = (int(random.random() * self.size), int(random.random() * self.size)) <NEW_LINE> self.p2 = (int(random.random() * self.size), int(random.random() * self.size)) <NEW_LINE> if self.p1 not in self.allOccupiedSpaces and self.p2 not in self.allOccupiedSpaces and not self.isPlayer1(self.p2): <NEW_LINE> <INDENT> break
Resets players to spawn points. If spawns are invalid, places randomly.
625941c3cb5e8a47e48b7a63
def get_raw_fields(): <NEW_LINE> <INDENT> pass
Returns a list of fields, each represents ticket field dictionary. For example: * name: field name * type: field type * label: the label to display, preferably wrapped with N_() * format: field format * other appropriate field properties
625941c3d6c5a10208144000
def check_duplicate_class_names(class_names): <NEW_LINE> <INDENT> duplicates = get_duplicates(class_names) <NEW_LINE> if duplicates: <NEW_LINE> <INDENT> logger.error(f'Only globally unique class names are allowed. Found duplicates {duplicates}') <NEW_LINE> raise SystemExit(0)
Raises an exception if there are duplicates in the given class names :param class_names: List of class names :type class_names: list
625941c3925a0f43d2549e2c
def send_null_provenance(self, stmt, for_what, reason=''): <NEW_LINE> <INDENT> content_fmt = ('<h4>No supporting evidence found for {statement} from ' '{cause}{reason}.</h4>') <NEW_LINE> content = KQMLList('add-provenance') <NEW_LINE> stmt_txt = EnglishAssembler([stmt]).make_model() <NEW_LINE> content.sets('html', content_fmt.format(statement=stmt_txt, cause=for_what, reason=reason)) <NEW_LINE> return self.tell(content)
Send out that no provenance could be found for a given Statement.
625941c36e29344779a625ca
@receiver(pre_save, sender=RhinitisDetails) <NEW_LINE> def create_related_rhinits_diagnosis( sender, instance, **kwargs ): <NEW_LINE> <INDENT> if not instance.id: <NEW_LINE> <INDENT> Diagnosis.objects.create( episode=instance.episode, category=Diagnosis.RHINITIS, condition=Diagnosis.RHINITIS, date=instance.date ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> existing_instance = instance.__class__.objects.get( id=instance.id ) <NEW_LINE> if not existing_instance.date == instance.date: <NEW_LINE> <INDENT> Diagnosis.objects.filter( episode=instance.episode, category=Diagnosis.RHINITIS, condition=Diagnosis.RHINITIS, date=existing_instance.date ).update( date=instance.date )
If its new create a diagnosis. If its an update that updates the date, update the diagnosis date.
625941c3596a897236089a7a
def test_add_over_existing_vote_to_db(): <NEW_LINE> <INDENT> with mock.patch('annotran.languages.models.Language') as language: <NEW_LINE> <INDENT> language.get_by_public_language_id = MagicMock(return_value=language) <NEW_LINE> with mock.patch('annotran.pages.models.Page') as page: <NEW_LINE> <INDENT> page.get_by_uri = MagicMock(return_value=page) <NEW_LINE> with mock.patch('h.groups.models.Group') as group: <NEW_LINE> <INDENT> group.get_by_pubid = MagicMock(return_value=group) <NEW_LINE> with mock.patch('h.models.User') as user: <NEW_LINE> <INDENT> user.get_by_username = MagicMock(return_value=user) <NEW_LINE> with mock.patch('annotran.votes.models.Vote') as vote: <NEW_LINE> <INDENT> vote.get_vote = MagicMock(return_value=vote) <NEW_LINE> request = _mock_request(matchdict={'page_uri': 'http://www.annotran_test.com', 'public_group_id': "12345", 'public_language_id': "12345", 'score': 5, 'username':"test_username"}, authenticated_user=mock.Mock(id=2, username="test2", uid="test2")) <NEW_LINE> result = views.add_vote(request) <NEW_LINE> request.db.delete.assert_called_once() <NEW_LINE> request.db.add.assert_called_once() <NEW_LINE> assert isinstance(result, httpexceptions.HTTPRedirection)
This should delete an existing vote from the db and add a new one. After successfully adding a new vote it should redirect.
625941c3dd821e528d63b161
def get_sel(self): <NEW_LINE> <INDENT> return self.selected
Return the selected icon or -1 (no selection yet)
625941c3566aa707497f4523
def get_random_position(self): <NEW_LINE> <INDENT> x_max = self._width <NEW_LINE> y_max = self._height <NEW_LINE> pos_x = round(random.uniform(0, x_max), 2) % x_max <NEW_LINE> pos_y = round(random.uniform(0, y_max), 2) % y_max <NEW_LINE> random_pos = Position(pos_x,pos_y) <NEW_LINE> assert self.is_position_in_room(random_pos) <NEW_LINE> return random_pos
Returns: a Position object; a valid random position (inside the room).
625941c3f9cc0f698b1405b4
def __init__(self, tokenized_text: List[str] = None, unk_sample_prob: float = 0.0) -> None: <NEW_LINE> <INDENT> self.word_to_index = {} <NEW_LINE> self.index_to_word = [] <NEW_LINE> self.word_count = {} <NEW_LINE> self.alphabet = {tok for tok in _SPECIAL_TOKENS} <NEW_LINE> self.correct_counts = False <NEW_LINE> self.unk_sample_prob = unk_sample_prob <NEW_LINE> self.add_word(PAD_TOKEN) <NEW_LINE> self.add_word(START_TOKEN) <NEW_LINE> self.add_word(END_TOKEN) <NEW_LINE> self.add_word(UNK_TOKEN) <NEW_LINE> if tokenized_text: <NEW_LINE> <INDENT> self.add_tokenized_text(tokenized_text)
Create a new instance of a vocabulary. Arguments: tokenized_text: The initial list of words to add.
625941c32ae34c7f2600d0e9
def signed_out_message(request): <NEW_LINE> <INDENT> if request.user.is_authenticated(): <NEW_LINE> <INDENT> return HttpResponseRedirect('/') <NEW_LINE> <DEDENT> return render_to_response('registration/logged_out.html', request, request.get_node('Q/Web/myesp'), {})
If the user is indeed logged out, show them a "Goodbye" message.
625941c3498bea3a759b9a67
def choose_file(self, selector, file_path, by=By.CSS_SELECTOR, timeout=None): <NEW_LINE> <INDENT> if not timeout: <NEW_LINE> <INDENT> timeout = settings.LARGE_TIMEOUT <NEW_LINE> <DEDENT> if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: <NEW_LINE> <INDENT> timeout = self.__get_new_timeout(timeout) <NEW_LINE> <DEDENT> selector, by = self.__recalculate_selector(selector, by) <NEW_LINE> abs_path = os.path.abspath(file_path) <NEW_LINE> self.add_text(selector, abs_path, by=by, timeout=timeout)
This method is used to choose a file to upload to a website. It works by populating a file-chooser "input" field of type="file". A relative file_path will get converted into an absolute file_path. Example usage: self.choose_file('input[type="file"]', "my_dir/my_file.txt")
625941c3287bf620b61d3a1c
def get_names (self, themes=None, match_all=False): <NEW_LINE> <INDENT> names = Name.objects.filter(topic__topic_map=self.topic_map) <NEW_LINE> names = self._get_constructs(names, themes, match_all) <NEW_LINE> return names
Returns the `Name`s in the topic map whose scope property contains at least one of the specified `themes`. If `themes` is None, all `Name`s in the unconstrained scope are returned. If `match_all` is True, the scope property of a name must match all `themes`. The return value may be empty but must never be None. :param themes: scope of the `Name`s to be returned :type themes: `Topic` or list of `Topic`s :param match_all: whether a `Name`'s scope property must match all `themes` :type match_all: boolean :rtype: `QuerySet` of `Name`s
625941c34e4d5625662d4391
def map_found(self, map_name): <NEW_LINE> <INDENT> map_list = [] <NEW_LINE> append = map_list.append <NEW_LINE> for maps in self.game.get_all_maps(): <NEW_LINE> <INDENT> if map_name.lower() == maps or ('ut4_%s' % map_name.lower()) == maps: <NEW_LINE> <INDENT> append(maps) <NEW_LINE> break <NEW_LINE> <DEDENT> elif map_name.lower() in maps: <NEW_LINE> <INDENT> append(maps) <NEW_LINE> <DEDENT> <DEDENT> if not map_list: <NEW_LINE> <INDENT> ret_val = False, None, "^3Map not found" <NEW_LINE> <DEDENT> elif len(map_list) > 1: <NEW_LINE> <INDENT> ret_val = False, None, "^7Maps matching %s: ^3%s" % (map_name, ', '.join(map_list)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret_val = True, map_list[0], None <NEW_LINE> <DEDENT> return ret_val
return True and map name or False and message text
625941c33c8af77a43ae3756
def loadCompounds(path=os.path.join(config.confdir, 'compounds.xml'), clear=True): <NEW_LINE> <INDENT> container = {} <NEW_LINE> document = xml.dom.minidom.parse(path) <NEW_LINE> groupTags = document.getElementsByTagName('group') <NEW_LINE> if groupTags: <NEW_LINE> <INDENT> for groupTag in groupTags: <NEW_LINE> <INDENT> groupName = groupTag.getAttribute('name') <NEW_LINE> container[groupName] = {} <NEW_LINE> compoundTags = groupTag.getElementsByTagName('compound') <NEW_LINE> if compoundTags: <NEW_LINE> <INDENT> for compoundTag in compoundTags: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> name = compoundTag.getAttribute('name') <NEW_LINE> compound = mspy.compound(compoundTag.getAttribute('formula')) <NEW_LINE> compound.description = _getNodeText(compoundTag) <NEW_LINE> container[groupName][name] = compound <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if container and clear: <NEW_LINE> <INDENT> compounds.clear() <NEW_LINE> <DEDENT> for group in container: <NEW_LINE> <INDENT> compounds[group] = container[group]
Parse compounds XML and get data.
625941c38e7ae83300e4af83
def match(self, aggressor_side): <NEW_LINE> <INDENT> trades = [] <NEW_LINE> for bid_i in range(len(self.bid) - 1, -1, -1): <NEW_LINE> <INDENT> bid = self.bid[bid_i] <NEW_LINE> size_offer = len(self.offer) <NEW_LINE> offer_i = 0 <NEW_LINE> while offer_i < size_offer: <NEW_LINE> <INDENT> offer = self.offer[offer_i] <NEW_LINE> (crossed, remaining_qty) = OrderBookUtils.cross(bid, offer) <NEW_LINE> if crossed: <NEW_LINE> <INDENT> trade = Trade(price=offer.price, qty=offer.qty, aggressor=aggressor_side) <NEW_LINE> self.last_price = offer.price <NEW_LINE> stop = False <NEW_LINE> if remaining_qty >= 0: <NEW_LINE> <INDENT> offer.qty = remaining_qty <NEW_LINE> trade.qty = bid.qty <NEW_LINE> del self.bid[bid_i] <NEW_LINE> stop = True <NEW_LINE> <DEDENT> if remaining_qty <= 0: <NEW_LINE> <INDENT> bid.qty = abs(remaining_qty) <NEW_LINE> del self.offer[offer_i] <NEW_LINE> size_offer -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> offer_i += 1 <NEW_LINE> <DEDENT> trades += [trade] <NEW_LINE> if stop: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return trades <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return trades
Match orders and return a list of trades
625941c3b545ff76a8913dce
def gen_keypair() -> Tuple[ecdsa.Private_key, ecdsa.Public_key]: <NEW_LINE> <INDENT> g = ecdsa.generator_secp256k1 <NEW_LINE> d = SystemRandom().randrange(1, g.order()) <NEW_LINE> pub = ecdsa.Public_key(g, g * d) <NEW_LINE> priv = ecdsa.Private_key(pub, d) <NEW_LINE> return priv, pub
generate a new ecdsa keypair
625941c3009cb60464c6336a