code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_ellp(): <NEW_LINE> <INDENT> f = Fuselage() <NEW_LINE> fs = FlightState() <NEW_LINE> faero = f.flight_model(f, fs) <NEW_LINE> f.substitutions[f.Vol] = 1.33 <NEW_LINE> m = Model(f.W*faero.Cd, [f, fs, faero]) <NEW_LINE> m.solve() | elliptical fuselage test | 625941be4f6381625f11495a |
def font_color(self): <NEW_LINE> <INDENT> return self.get_color(self.font.colour_index) | Get cell foreground-color as 3-tuple. | 625941be24f1403a92600a85 |
def get_user_name(): <NEW_LINE> <INDENT> return name | Returns current user name | 625941be57b8e32f524833b6 |
def getPlayListInfo(playListItem, myRow, playListType, level=None): <NEW_LINE> <INDENT> if not level: <NEW_LINE> <INDENT> level = Prefs['PlayList_Level'] <NEW_LINE> <DEDENT> if playListType == 'video': <NEW_LINE> <INDENT> myRow = getPlayListSimpleVideo(playListItem, myRow) <NEW_LINE> if level in [ 'Basic', "Extended", "Extreme", "Extreme 2", "Extreme 3"]: <NEW_LINE> <INDENT> myRow = getPlayListBasicVideo(playListItem, myRow) <NEW_LINE> <DEDENT> <DEDENT> elif playListType == 'audio': <NEW_LINE> <INDENT> myRow = getPlayListSimpleAudio(playListItem, myRow) <NEW_LINE> if level in [ 'Basic', "Extended", "Extreme", "Extreme 2", "Extreme 3"]: <NEW_LINE> <INDENT> myRow = getPlayListBasicAudio(playListItem, myRow) <NEW_LINE> <DEDENT> <DEDENT> elif playListType == 'photo': <NEW_LINE> <INDENT> myRow = getPlayListSimplePhoto(playListItem, myRow) <NEW_LINE> if level in [ 'Basic', "Extended", "Extreme", "Extreme 2", "Extreme 3"]: <NEW_LINE> <INDENT> myRow = getPlayListBasicPhoto(playListItem, myRow) <NEW_LINE> <DEDENT> <DEDENT> return myRow | This function will export and return the info for the Playlist | 625941be7c178a314d6ef378 |
def shift_vert(image): <NEW_LINE> <INDENT> i = numpy.roll(numpy.identity(len(image)), 100, axis=0) <NEW_LINE> shifted = numpy.dot(i, image) <NEW_LINE> return shifted | Shift an image horizontally
1) Create rolled identity matrix:
| 0 0 1 |
| 1 0 0 |
| 0 1 0 |
2) Dot with image | 625941be0fa83653e4656ed9 |
def get_cache(self, cache_type, cache_name): <NEW_LINE> <INDENT> return self.worker_store.cache_api.get_cache(cache_type, cache_name) | Returns a cache object of given type and name.
| 625941bee8904600ed9f1e46 |
def setupShipDesign(self, compDict, weapDict, name): <NEW_LINE> <INDENT> self.clearMyText() <NEW_LINE> self.componentdata = self.mode.game.componentdata <NEW_LINE> self.weapondata = self.mode.game.weapondata <NEW_LINE> self.myShipDesign = self.mode.game.getDroneDesign('1', self.id, compDict, weapDict, name) <NEW_LINE> self.mode.designName = self.getShipDesignName() <NEW_LINE> self.createQuads() <NEW_LINE> self.createWeaponList() <NEW_LINE> self.createComponentList() <NEW_LINE> self.createDesignInfo() <NEW_LINE> self.createDesignNameEntry() <NEW_LINE> self.createDesignSubmit() | Setup the Ship design based on compDict and weapDict | 625941bebe7bc26dc91cd522 |
def make_auth_req(self, entity_id, nameid_format=None, relay_state="relay_state", request_binding=BINDING_HTTP_REDIRECT, response_binding=BINDING_HTTP_REDIRECT, subject=None): <NEW_LINE> <INDENT> _binding, destination = self.pick_binding( 'single_sign_on_service', [request_binding], 'idpsso', entity_id=entity_id) <NEW_LINE> kwargs = {} <NEW_LINE> if subject: <NEW_LINE> <INDENT> kwargs['subject'] = subject <NEW_LINE> <DEDENT> req_id, req = self.create_authn_request( destination, binding=response_binding, nameid_format=nameid_format, **kwargs ) <NEW_LINE> ht_args = self.apply_binding(_binding, '%s' % req, destination, relay_state=relay_state) <NEW_LINE> if _binding == BINDING_HTTP_POST: <NEW_LINE> <INDENT> form_post_html = "\n".join(ht_args["data"]) <NEW_LINE> doctree = BeautifulSoup(form_post_html, "html.parser") <NEW_LINE> saml_request = doctree.find("input", {"name": "SAMLRequest"})["value"] <NEW_LINE> resp = {"SAMLRequest": saml_request, "RelayState": relay_state} <NEW_LINE> <DEDENT> elif _binding == BINDING_HTTP_REDIRECT: <NEW_LINE> <INDENT> resp = dict(parse_qsl(urlparse(dict(ht_args["headers"])["Location"]).query)) <NEW_LINE> <DEDENT> return destination, resp | :type entity_id: str
:rtype: str
:param entity_id: SAML entity id
:return: Authentication URL. | 625941befbf16365ca6f60db |
def reset_stats(self): <NEW_LINE> <INDENT> self.ships_left = self.settings.ship_limit <NEW_LINE> self.score = 0 <NEW_LINE> self.level = 1 | Initialize statistics that will change during the game | 625941be7d847024c06be1d6 |
def test_messages_invitation(self): <NEW_LINE> <INDENT> self.members_tab.log_in(self.team_owner.username, 'password') <NEW_LINE> self.messages_tab.open_messages_tab(self.team.slug) <NEW_LINE> self.members_tab.open_members_page(self.team.slug) <NEW_LINE> self.members_tab.invite_user_via_form( username = self.non_member.username, message = 'Join my team', role = 'Contributor') <NEW_LINE> self.user_message_pg.log_in(self.non_member.username, 'password') <NEW_LINE> self.user_message_pg.open_messages() <NEW_LINE> self.assertTrue(self._TEST_MESSAGES['INVITATION'] in self.user_message_pg.message_text()) | Invited user see the custom message. | 625941be67a9b606de4a7dd8 |
def cmpname(name1, name2): <NEW_LINE> <INDENT> if name1 is None and name2 is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if name1 is None: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> if name2 is None: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> lower_name1 = name1.lower() <NEW_LINE> lower_name2 = name2.lower() <NEW_LINE> return cmp(lower_name1, lower_name2) | Compare two CIM names. The comparison is done
case-insensitively, and one or both of the names may be `None`. | 625941be7cff6e4e811178a2 |
def __get_zs_integration_limits(zs): <NEW_LINE> <INDENT> ranges = [] <NEW_LINE> for zsi in zs: <NEW_LINE> <INDENT> pdftype = get_standard_soft_pdf_type(zsi[0]) <NEW_LINE> if pdftype in [1, 2]: <NEW_LINE> <INDENT> nl = zsi[1] <NEW_LINE> limi = zsi[2] <NEW_LINE> ranges.append((limi[0], limi[nl[0]-1])) <NEW_LINE> <DEDENT> elif pdftype in [10]: <NEW_LINE> <INDENT> zm = zsi[1] <NEW_LINE> zstd = np.sqrt(zsi[2]) <NEW_LINE> ranges.append((zm-3*zstd, zm+3*zstd)) <NEW_LINE> <DEDENT> <DEDENT> ranges = np.array(ranges) <NEW_LINE> return ranges.copy() | get soft data integration limit | 625941be23849d37ff7b2fad |
def predict(self, Xs : np.ndarray): <NEW_LINE> <INDENT> raise NotImplementedError | The predictive probabilities
:param Xs: numpy array, of shape N, Dx
:return: p, of shape (N, K) | 625941bed99f1b3c44c674b2 |
def record(self, identity, action, props=None): <NEW_LINE> <INDENT> props = props or {} <NEW_LINE> if isinstance(action, dict): <NEW_LINE> <INDENT> self.set(action) <NEW_LINE> <DEDENT> props.update({'_n': action}) <NEW_LINE> return self.request('e', props, identity=identity) | Record `action` with the KISSmetrics API.
:param str identity: User identity
:param str action: Action to record
:param dict props: Additional information to include | 625941becb5e8a47e48b79ca |
@login_required <NEW_LINE> def all_galleries(request, page): <NEW_LINE> <INDENT> user_galleries = {'queryset': Gallery.objects.filter(is_public=True, author=request.user), 'page': page, 'allow_empty': True, 'paginate_by': 2, 'extra_context':{'sample_size':SAMPLE_SIZE} } <NEW_LINE> return object_list(request, **user_galleries) | Displays current user's galleries paginated.
Extended to support users. | 625941bee8904600ed9f1e47 |
def create_correspondence( self): <NEW_LINE> <INDENT> conll_words = [] <NEW_LINE> onto_words = [] <NEW_LINE> for bundle in self.conll_doc.bundles: <NEW_LINE> <INDENT> for root in bundle.trees: <NEW_LINE> <INDENT> sent_ID = root.sent_id <NEW_LINE> for node in root.descendants: <NEW_LINE> <INDENT> word_ID = node.ord <NEW_LINE> form = node.form <NEW_LINE> conll_ID = ( sent_ID, word_ID ) <NEW_LINE> conll_words.append( ( conll_ID, form, node )) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> sent_ID = -1 <NEW_LINE> for onto_line in self.onto_input: <NEW_LINE> <INDENT> if ( "Leaves:" in onto_line ): <NEW_LINE> <INDENT> self.are_leaves = True <NEW_LINE> sent_ID += 1 <NEW_LINE> <DEDENT> elif ( self.are_leaves and onto_line == "\n" ): <NEW_LINE> <INDENT> self.are_leaves = False <NEW_LINE> <DEDENT> elif ( self.are_leaves ): <NEW_LINE> <INDENT> split_line = onto_line.split( ' ') <NEW_LINE> word_ID = None <NEW_LINE> form = None <NEW_LINE> try: <NEW_LINE> <INDENT> word_ID = int( split_line[4]) <NEW_LINE> was_number = True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> form = split_line[-1][:-1] <NEW_LINE> if ( len( form) == 0 or form[0] == '*' ): <NEW_LINE> <INDENT> form = None <NEW_LINE> <DEDENT> if ( word_ID != None and form != None ): <NEW_LINE> <INDENT> onto_ID = ( sent_ID, word_ID ) <NEW_LINE> onto_words.append( ( onto_ID, form )) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> list_of_corresponding_words = [] <NEW_LINE> conll_index = 0 <NEW_LINE> onto_index = 0 <NEW_LINE> while ( conll_index < len( conll_words) and onto_index < len( onto_words) ): <NEW_LINE> <INDENT> conll_word = conll_words[ conll_index ] <NEW_LINE> onto_word = onto_words[ onto_index ] <NEW_LINE> if ( conll_word[1] == onto_word[1] ): <NEW_LINE> <INDENT> list_of_corresponding_words.append( ( onto_word[0], conll_word[2] )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i = 1 <NEW_LINE> limit = 12 <NEW_LINE> while ( i < limit and conll_index + i < len( conll_words) and onto_index + i < len( onto_words) ): <NEW_LINE> <INDENT> conll_sec_word = conll_words[ conll_index + i ] <NEW_LINE> onto_sec_word = onto_words[ onto_index + i ] <NEW_LINE> if ( conll_word[1] == onto_sec_word[1] ): <NEW_LINE> <INDENT> onto_index += i <NEW_LINE> onto_word = onto_sec_word <NEW_LINE> break <NEW_LINE> <DEDENT> if ( conll_sec_word[1] == onto_word[1] ): <NEW_LINE> <INDENT> conll_index += i <NEW_LINE> conll_word = conll_sec_word <NEW_LINE> break <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> list_of_corresponding_words.append( ( onto_word[0], conll_word[2] )) <NEW_LINE> <DEDENT> conll_index += 1 <NEW_LINE> onto_index += 1 <NEW_LINE> <DEDENT> return list_of_corresponding_words | main method, called from outside
it creates two lists of words (for conll file and for onf file) and then builds a bijection based on comparing of forms | 625941be67a9b606de4a7dd9 |
def mergeTwoLists(self, l1, l2): <NEW_LINE> <INDENT> temp_l1 = [] <NEW_LINE> while l1 != None: <NEW_LINE> <INDENT> temp_l1.append(l1.val) <NEW_LINE> l1 = l1.next <NEW_LINE> <DEDENT> temp_l2 = [] <NEW_LINE> while l2 != None: <NEW_LINE> <INDENT> temp_l2.append(l2.val) <NEW_LINE> l2 = l2.next <NEW_LINE> <DEDENT> result = list() <NEW_LINE> result.extend(list(temp_l1)) <NEW_LINE> result.extend(list(temp_l2)) <NEW_LINE> result = sorted(result) <NEW_LINE> return result | :type l1: ListNode
:type l2: ListNode
:rtype: ListNode | 625941be2eb69b55b151c7c9 |
def add(self, rule): <NEW_LINE> <INDENT> self._rules.append(rule) | Add a rule to the chain
Parameters:
rule (Rule): a rule to add to _rules | 625941beb545ff76a8913d33 |
def print_first_word(words): <NEW_LINE> <INDENT> word = words.pop(0) <NEW_LINE> print(word) | Prints the first word after popping off | 625941be5510c4643540f308 |
def read_seqs(filepath,randomize=False): <NEW_LINE> <INDENT> seqs = [] <NEW_LINE> with open(filepath,"r") as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> seqs.append(line.strip().upper()) <NEW_LINE> <DEDENT> <DEDENT> if randomize == True: <NEW_LINE> <INDENT> np.random.shuffle(seqs) <NEW_LINE> <DEDENT> return seqs | Read in sequences from a text file of newline-delimited sequences
Input: file path as string
Output: 1D array of sequences as strings, all uppercase | 625941befff4ab517eb2f357 |
def _find_instance_or_cluster(cs, instance_or_cluster): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return _find_instance(cs, instance_or_cluster), 'instance' <NEW_LINE> <DEDENT> except exceptions.CommandError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return _find_cluster(cs, instance_or_cluster), 'cluster' <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise exceptions.CommandError( "No instance or cluster with a name or ID of '%s' exists." % instance_or_cluster) | Returns an instance or cluster, found by id, along with the type of
resource, instance or cluster, that was found.
Raises CommandError if none is found. | 625941bed7e4931a7ee9de3a |
def get_normalized_entrys(self, curls): <NEW_LINE> <INDENT> result = set() <NEW_LINE> for url in set(curls): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result.add(self.get_normalized_entry(url)) <NEW_LINE> <DEDENT> except NoMatchAnalyzer as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return result | Return all of the urls to a new url list.
This returned url list make sure the following things:
1. all urls are be normalized
2. no duplicated
3. all urls match at least one analyzers. | 625941beec188e330fd5a6c1 |
def initGui(self): <NEW_LINE> <INDENT> icon_path = ':/plugins/cartolinegen/icon.png' <NEW_LINE> self.add_action( icon_path, text=self.tr(u'Cartographic Line Generalization'), callback=self.run, parent=self.iface.mainWindow()) | Create the menu entries and toolbar icons inside the QGIS GUI. | 625941be29b78933be1e55ce |
def data(self, index, role = None): <NEW_LINE> <INDENT> return QVariant() | QVariant KDirModel.data(QModelIndex index, int role = Qt.DisplayRole) | 625941be236d856c2ad446f3 |
def __init__(self, query_id: int, cache_time: int, alert: Optional[bool]=None, message: Optional[str]=None, url: Optional[str]=None): <NEW_LINE> <INDENT> self.query_id = query_id <NEW_LINE> self.cache_time = cache_time <NEW_LINE> self.alert = alert <NEW_LINE> self.message = message <NEW_LINE> self.url = url | :returns Bool: This type has no constructors. | 625941be379a373c97cfaa61 |
def zip_with_m_(monad_t, zip_function, left, right): <NEW_LINE> <INDENT> return sequence_(monad_t, func.zip_with(zip_function, left, right)) | Same as zip_with_m, but ignores the result. | 625941be3eb6a72ae02ec3f3 |
def check_events(settings, screen, stats, play_button, sb, survivor, zombies, bullets): <NEW_LINE> <INDENT> for event in pygame.event.get(): <NEW_LINE> <INDENT> if event.type == pygame.QUIT: <NEW_LINE> <INDENT> sys.exit() <NEW_LINE> <DEDENT> elif event.type == pygame.KEYDOWN: <NEW_LINE> <INDENT> check_keydown_events(event, settings, screen, survivor, bullets) <NEW_LINE> <DEDENT> elif event.type == pygame.KEYUP: <NEW_LINE> <INDENT> check_keyup_events(event, survivor) <NEW_LINE> <DEDENT> elif event.type == pygame.MOUSEBUTTONDOWN: <NEW_LINE> <INDENT> mouse_x, mouse_y = pygame.mouse.get_pos() <NEW_LINE> check_play_button(settings, screen, stats, play_button, sb, survivor, zombies, bullets, mouse_x, mouse_y) | Respond to keypresses and mouse events. | 625941be32920d7e50b280eb |
def rand_port(): <NEW_LINE> <INDENT> return random.randint(10311, 12311) | Picks a random port number.
This is potentially unsafe, but shouldn't generally be a problem. | 625941be1d351010ab855a3a |
def is_valid(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.validate() <NEW_LINE> <DEDENT> except ValidationException: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | Convenience wrapper for validate() to return True or False. | 625941be3539df3088e2e268 |
def list_supported_commands(self, data): <NEW_LINE> <INDENT> self.host.reply(self.PUBLIC_API_METHODS) | Get a list of all the commands this api supports
:param data: Message data {} (no data expected) | 625941be046cf37aa974cc67 |
def DeleteEdgeNodes(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("DeleteEdgeNodes", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.DeleteEdgeNodesResponse() <NEW_LINE> model._deserialize(response["Response"]) <NEW_LINE> return model <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> code = response["Response"]["Error"]["Code"] <NEW_LINE> message = response["Response"]["Error"]["Message"] <NEW_LINE> reqid = response["Response"]["RequestId"] <NEW_LINE> raise TencentCloudSDKException(code, message, reqid) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> if isinstance(e, TencentCloudSDKException): <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TencentCloudSDKException(e.message, e.message) | 批量删除边缘节点
:param request: Request instance for DeleteEdgeNodes.
:type request: :class:`tencentcloud.iecp.v20210914.models.DeleteEdgeNodesRequest`
:rtype: :class:`tencentcloud.iecp.v20210914.models.DeleteEdgeNodesResponse` | 625941be009cb60464c632d1 |
def get_engine(self): <NEW_LINE> <INDENT> return self.engine | Get the database engine
| 625941be7d43ff24873a2bbb |
def ssh_check_mic(self, mic_token, session_id, username=None): <NEW_LINE> <INDENT> self._session_id = session_id <NEW_LINE> self._username = username <NEW_LINE> if username is not None: <NEW_LINE> <INDENT> mic_field = self._ssh_build_mic( self._session_id, self._username, self._service, self._auth_method, ) <NEW_LINE> self._gss_srv_ctxt.verify(mic_field, mic_token) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._gss_ctxt.verify(self._session_id, mic_token) | Verify the MIC token for a SSH2 message.
:param str mic_token: The MIC token received from the client
:param str session_id: The SSH session ID
:param str username: The name of the user who attempts to login
:return: None if the MIC check was successful
:raises: ``sspi.error`` -- if the MIC check failed | 625941be2ae34c7f2600d04f |
def save_as_mainfile(filepath: str = "", check_existing: bool = True, filter_blender: bool = True, filter_backup: bool = False, filter_image: bool = False, filter_movie: bool = False, filter_python: bool = False, filter_font: bool = False, filter_sound: bool = False, filter_text: bool = False, filter_btx: bool = False, filter_collada: bool = False, filter_alembic: bool = False, filter_folder: bool = True, filter_blenlib: bool = False, filemode: int = 8, display_type: int = 'DEFAULT', sort_method: int = 'FILE_SORT_ALPHA', compress: bool = False, relative_remap: bool = True, copy: bool = False, use_mesh_compat: bool = False): <NEW_LINE> <INDENT> pass | Save the current file in the desired location
:param filepath: File Path, Path to file
:type filepath: str
:param check_existing: Check Existing, Check and warn on overwriting existing files
:type check_existing: bool
:param filter_blender: Filter .blend files
:type filter_blender: bool
:param filter_backup: Filter .blend files
:type filter_backup: bool
:param filter_image: Filter image files
:type filter_image: bool
:param filter_movie: Filter movie files
:type filter_movie: bool
:param filter_python: Filter python files
:type filter_python: bool
:param filter_font: Filter font files
:type filter_font: bool
:param filter_sound: Filter sound files
:type filter_sound: bool
:param filter_text: Filter text files
:type filter_text: bool
:param filter_btx: Filter btx files
:type filter_btx: bool
:param filter_collada: Filter COLLADA files
:type filter_collada: bool
:param filter_alembic: Filter Alembic files
:type filter_alembic: bool
:param filter_folder: Filter folders
:type filter_folder: bool
:param filter_blenlib: Filter Blender IDs
:type filter_blenlib: bool
:param filemode: File Browser Mode, The setting for the file browser mode to load a .blend file, a library or a special file
:type filemode: int
:param display_type: Display TypeDEFAULT Default, Automatically determine display type for files.LIST_SHORT Short List, Display files as short list.LIST_LONG Long List, Display files as a detailed list.THUMBNAIL Thumbnails, Display files as thumbnails.
:type display_type: int
:param sort_method: File sorting modeFILE_SORT_ALPHA Sort alphabetically, Sort the file list alphabetically.FILE_SORT_EXTENSION Sort by extension, Sort the file list by extension/type.FILE_SORT_TIME Sort by time, Sort files by modification time.FILE_SORT_SIZE Sort by size, Sort files by size.
:type sort_method: int
:param compress: Compress, Write compressed .blend file
:type compress: bool
:param relative_remap: Remap Relative, Remap relative paths when saving in a different directory
:type relative_remap: bool
:param copy: Save Copy, Save a copy of the actual working state but does not make saved file active
:type copy: bool
:param use_mesh_compat: Legacy Mesh Format, Save using legacy mesh format (no ngons) - WARNING: only saves tris and quads, other ngons will be lost (no implicit triangulation)
:type use_mesh_compat: bool | 625941be167d2b6e31218ab3 |
def inverable_unique_two_lists(item1_list, item2_list): <NEW_LINE> <INDENT> import utool as ut <NEW_LINE> unique_list1, inverse1 = np.unique(item1_list, return_inverse=True) <NEW_LINE> unique_list2, inverse2 = np.unique(item2_list, return_inverse=True) <NEW_LINE> flat_stacked, cumsum = ut.invertible_flatten2((unique_list1, unique_list2)) <NEW_LINE> flat_unique, inverse3 = np.unique(flat_stacked, return_inverse=True) <NEW_LINE> reconstruct_tup = (inverse3, cumsum, inverse2, inverse1) <NEW_LINE> return flat_unique, reconstruct_tup | item1_list = aid1_list
item2_list = aid2_list | 625941be5fcc89381b1e15da |
def write_config(): <NEW_LINE> <INDENT> global config <NEW_LINE> config = read_config() <NEW_LINE> print("GDrive_Sync") <NEW_LINE> print("\nPlease look below at the options which you wish to update: ") <NEW_LINE> print("(Enter the number followed by value, eg. \"1 input\")") <NEW_LINE> print("1. Add Upload Folder [full path to folder]") <NEW_LINE> print("2. Remove Upload Folder [full path to folder]") <NEW_LINE> print("3. Change Download Directory [full path to folder]") <NEW_LINE> print("4. Toggle Remove_Post_Upload [Y/N]") <NEW_LINE> print("5. Toggle Save_Share_Link [Y/N]") <NEW_LINE> print("6. Toggle Write_Permission [Y/N]") <NEW_LINE> print("7. List current settings [type \"7 ls\"]") <NEW_LINE> print("\nInput \"0 exit\" at anytime to exit config edit") <NEW_LINE> while True: <NEW_LINE> <INDENT> user_input = str(input()) <NEW_LINE> value = None <NEW_LINE> try: <NEW_LINE> <INDENT> if len(user_input.split()) == 1: <NEW_LINE> <INDENT> opt = int(user_input) <NEW_LINE> <DEDENT> elif len(user_input.split()) > 1: <NEW_LINE> <INDENT> opt, value = list(map(str, user_input.split())) <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print("Error: please adhere to the input format") <NEW_LINE> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if int(opt) == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> elif int(opt) == 7: <NEW_LINE> <INDENT> print("---Current Configuration---") <NEW_LINE> print("Download directory: " + config['Down_Dir']) <NEW_LINE> print("Upload directories: " + str(config['Up_Dir'])) <NEW_LINE> print("Remove post upload: " + str(config['Remove_Post_Upload'])) <NEW_LINE> print("Save share link: " + str(config['Share_Link'])) <NEW_LINE> print("Write permission granted: " + str(config['Write_Permission'])) <NEW_LINE> <DEDENT> elif int(opt) not in list(range(1, 7)): <NEW_LINE> <INDENT> print("Error: Wrong parameters entered") <NEW_LINE> <DEDENT> elif option[int(opt)](value): <NEW_LINE> <INDENT> print("Success") <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print("Error: invalid input") <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> with open(file_add.config_file, "w") as output: <NEW_LINE> <INDENT> json.dump(config, output) <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> print("Permission Denied: please run with sudo") | displays console for editing and manages input | 625941be97e22403b379ceb6 |
def parse_lattice_vectors(file_path): <NEW_LINE> <INDENT> file_name = 'input.xml' <NEW_LINE> treeinput = ET.parse(file_path) <NEW_LINE> if file_path.split('/')[-1] != file_name: <NEW_LINE> <INDENT> file_path = os.path.join(file_path, fileName) <NEW_LINE> <DEDENT> treeinput = ET.parse(file_path) <NEW_LINE> root_input = treeinput.getroot() <NEW_LINE> try: <NEW_LINE> <INDENT> scale = float(root_input.find("structure").find("crystal").attrib["scale"]) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> scale = 1.0 <NEW_LINE> <DEDENT> lat_vec = [np.array(val.text.split(), dtype=float)*scale for val in root_input.find("structure").find("crystal").findall("basevect")] <NEW_LINE> lat_vec = np.array(lat_vec).transpose() <NEW_LINE> return lat_vec | Parse the lattice coordinate from the input.xml. Units are in bohr.
:param file_path: relative path to the input.xml
:return lattvec: matrix that holds the lattice vectors. | 625941be3346ee7daa2b2c87 |
def _on_connection_close(self, connection, reply_code, reply_text): <NEW_LINE> <INDENT> self._channel = None <NEW_LINE> if reply_code == 200: <NEW_LINE> <INDENT> _log.info('Server connection closed (%s), shutting down', reply_text) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _log.warning('Connection to %s closed unexpectedly (%d): %s', connection.params.host, reply_code, reply_text) <NEW_LINE> self._connection.add_timeout(0, self._connection.connect) | Callback invoked when a previously-opened connection is closed.
Args:
connection (pika.connection.SelectConnection): The connection that
was just closed.
reply_code (int): The AMQP code indicating why the connection was closed.
reply_text (str): The human-readable reason the connection was closed. | 625941be30dc7b7665901886 |
def test_node_printing(self): <NEW_LINE> <INDENT> tree = ParentedTree.fromstring("(S (n x) (N x))") <NEW_LINE> self.assertEqual( list(tgrep.tgrep_positions("N", [tree])), list(tgrep.tgrep_positions("'N", [tree])), ) <NEW_LINE> self.assertEqual( list(tgrep.tgrep_positions("/[Nn]/", [tree])), list(tgrep.tgrep_positions("'/[Nn]/", [tree])), ) | Test that the tgrep print operator ' is properly ignored. | 625941beaad79263cf39095a |
def test_fetchSpecific(self): <NEW_LINE> <INDENT> d = self.client.fetchSpecific('7') <NEW_LINE> self.assertEqual( self.transport.value(), b'0001 FETCH 7 BODY[]\r\n') <NEW_LINE> self.client.lineReceived(b'* 7 FETCH (BODY[] "Some body")') <NEW_LINE> self.client.lineReceived(b'0001 OK FETCH completed') <NEW_LINE> self.assertEqual( self.successResultOf(d), {7: [['BODY', [], "Some body"]]}) | L{IMAP4Client.fetchSpecific} sends the I{BODY[]} command if no
parameters beyond the message set to retrieve are given. It returns a
L{Deferred} which fires with a C{dict} mapping message sequence numbers
to C{list}s of corresponding message data given by the server's
response. | 625941be92d797404e3040a7 |
def __init__(self, filename): <NEW_LINE> <INDENT> self.filename = filename | Unlink all datasets associated with filename. | 625941bebaa26c4b54cb1040 |
def test_with_org_and_course_key(self): <NEW_LINE> <INDENT> self._enroll_users(self.course, self.users, 'audit') <NEW_LINE> CourseModeFactory(course_id=self.course.id, mode_slug='no-id-professional') <NEW_LINE> with self.assertRaises(CommandError): <NEW_LINE> <INDENT> call_command( 'bulk_change_enrollment', org=self.org, course=text_type(self.course.id), from_mode='audit', to_mode='no-id-professional', commit=True, ) | Verify that command raises CommandError when `org` and `course_key` both are given. | 625941be9c8ee82313fbb692 |
def read_data(filename): <NEW_LINE> <INDENT> with open('tmp/text8') as f: <NEW_LINE> <INDENT> data = f.readlines() <NEW_LINE> data = data[0].split() <NEW_LINE> <DEDENT> return data | Extract the first file enclosed in a zip file as a list of words. | 625941bedd821e528d63b0c8 |
def get_changed_files(repo: Repo) -> List[str]: <NEW_LINE> <INDENT> untracked_files = repo.untracked_files <NEW_LINE> dirty_files = [item.a_path for item in repo.index.diff(None)] <NEW_LINE> return [*untracked_files, *dirty_files] | Get untracked / dirty files in the given git repo.
:param repo: Git repo to check.
:return: A list of filenames. | 625941be0fa83653e4656eda |
def create_universe(self, name, universe_id): <NEW_LINE> <INDENT> new_universe = { "name": name, "staff": {}, "committees": committee_list } <NEW_LINE> self.universes[universe_id] = new_universe | Ideally universe_id is the channel_id for the public main branch of the committee
and committee_list is the channel_id for the private channels of the branch | 625941beab23a570cc25009e |
def respondent_get(self, research_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.respondent_get_with_http_info(research_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.respondent_get_with_http_info(research_id, **kwargs) <NEW_LINE> return data | Find all Respondents of a Research
<p><strong>Permissions:</strong> ✓ Respondent ✗ Customer ✓ Manager</p>
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.respondent_get(research_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int research_id: Search by research id. (required)
:param int skip: The number of results to skip.
:param int limit: The maximum number of results to return.
:param str where: JSON formatted string.
:param str sort: Attribute used to sort results.
:return: list[Respondent]
If the method is called asynchronously,
returns the request thread. | 625941bed4950a0f3b08c26f |
def main(step=5, max_comparision=-1): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> data = [] <NEW_LINE> title = ('文件名', '协定名', '国家1', '国家2','签署时间','生效时间', '条款','条款数目') <NEW_LINE> data.append(title) <NEW_LINE> for filename in reader.read_path('E:/2018/2018-3-12-论文-BITs/B&R_Country_info/BITs_html', max_comparision): <NEW_LINE> <INDENT> result_tuple = reader.read(filename) <NEW_LINE> filename, name, country1, country2,sign_year,force_year,article,count = result_tuple <NEW_LINE> print('%s %s %s %s %s %s %s %s' % (filename, name, country1, country2,sign_year,force_year,article,count)) <NEW_LINE> data.append((filename, name, country1, country2,sign_year,force_year,article,count)) <NEW_LINE> <DEDENT> end_time = time.time() <NEW_LINE> data.append(('耗时:', '%.2fs' % (end_time - start_time))) <NEW_LINE> print('写入结果') <NEW_LINE> writer.write(data) <NEW_LINE> print('写入xls文件成功') | 使用jaccard算法,计算出xml文件夹下的文本之间的相似度。
:param step: 分词系数
:param max_comparision: 最大需要比较的文件数,默认是所有文件 | 625941be63f4b57ef000103d |
def most_recent(): <NEW_LINE> <INDENT> return VideoCollection.from_feed(yt_service.GetMostRecentVideoFeed()) | :rtype: VideoCollection | 625941bea05bb46b383ec742 |
def zapsat_statistiky(cursor): <NEW_LINE> <INDENT> cursor.execute("select cislo_smlouvy, down, up from elpr") <NEW_LINE> rows = cursor.fetchall() <NEW_LINE> for smlouva,down,up in rows: <NEW_LINE> <INDENT> print("DEBUG smlouva %d: d:%d u:%d" % (smlouva,down,up)) <NEW_LINE> if (not os.path.exists("/raid/elpr/rrd_real/id-%s.rrd" % smlouva)): <NEW_LINE> <INDENT> vytvor_rrd(smlouva) <NEW_LINE> <DEDENT> rrdtool.update("/raid/elpr/rrd_real/id-%s.rrd" % smlouva, "-t","down:up", "N:%s:%s" % (down, up)) | Zaznamenat statistiky do rrd.
@param cursor: databazovy kurzor | 625941be7d43ff24873a2bbc |
def load_expression_tree(self): <NEW_LINE> <INDENT> fp = filedialog.askopenfilename(initialdir = self.last_used_dir, initialfile = 'randomart1.json', defaultextension = 'json', title = "select file", filetypes = (("json","*.json"),("all files","*.*"))) <NEW_LINE> self.last_used_dir = os.path.dirname(fp) <NEW_LINE> try: <NEW_LINE> <INDENT> with open(fp,'r') as f: <NEW_LINE> <INDENT> s = f.read() <NEW_LINE> <DEDENT> self.art = jsonpickle.loads(s) <NEW_LINE> self.draw() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> messagebox.showinfo("error during expressiontree loading", str(e) ) | loads the expressions that define a picture from file, and render corresponding picture
:return: | 625941be76e4537e8c35158e |
def delete(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del self.replacement_map[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self._write_replacement_map() <NEW_LINE> return True | remove item from dict | 625941bed6c5a10208143f66 |
def update(self): <NEW_LINE> <INDENT> direction_radians = math.radians(self.direction) <NEW_LINE> self.x += self.speed * math.sin(direction_radians) <NEW_LINE> self.y -= self.speed * math.cos(direction_radians) <NEW_LINE> self.image.pos = (self.x, self.y) <NEW_LINE> if self.y >= screen_size[1]/2.0: <NEW_LINE> <INDENT> self.bounce(0) <NEW_LINE> <DEDENT> if self.x <= -screen_size[0] / 2.0: <NEW_LINE> <INDENT> self.direction = (360 - self.direction) % 360 <NEW_LINE> self.x = -screen_size[0] / 2.0 + self.radius <NEW_LINE> <DEDENT> if self.x >= screen_size[0] / 2.0: <NEW_LINE> <INDENT> self.direction = (360 - self.direction) % 360 <NEW_LINE> self.x =screen_size[0] / 2.0 - self.radius - 1 <NEW_LINE> <DEDENT> if self.y < - (screen_size[1] / 2.0 + self.radius): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Update the position of the ball. | 625941bead47b63b2c509e9e |
def remove_unused_funcs(self): <NEW_LINE> <INDENT> ir = self.IR <NEW_LINE> inFunction = False <NEW_LINE> to_remove = [] <NEW_LINE> for idx, irLine in enumerate(ir): <NEW_LINE> <INDENT> ir_firstNode = irLine.treeList[0] <NEW_LINE> if inFunction == True: <NEW_LINE> <INDENT> if isinstance(ir_firstNode, irl.IRFunctionDecl): <NEW_LINE> <INDENT> inFunction = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> to_remove.append(idx) <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> if isinstance(ir_firstNode, irl.IRFunctionDecl): <NEW_LINE> <INDENT> func_name = ir_firstNode.name <NEW_LINE> referenceNum = len([x.references for x in self.symTable.symbols if func_name == x.name and x.entry_type == 1][0]) <NEW_LINE> if referenceNum == 0 and func_name != "main": <NEW_LINE> <INDENT> to_remove.append(idx) <NEW_LINE> inFunction = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for i in to_remove[::-1]: <NEW_LINE> <INDENT> del ir[i] <NEW_LINE> <DEDENT> self.IR = ir | Removes function that are not reference in the symbol table. They can be removed if not used. | 625941be26238365f5f0ed89 |
def open(self): <NEW_LINE> <INDENT> file_name = os.path.join(self.current_dir, "out.txt") <NEW_LINE> with recipy.open('out.txt', 'w') as f: <NEW_LINE> <INDENT> f.write("This is a test") <NEW_LINE> <DEDENT> os.remove(file_name) | Use recipy.open to save a file out.txt. | 625941bea219f33f3462888b |
def MEDCouplingPointSet_Rotate3DAlg(*args): <NEW_LINE> <INDENT> return _MEDCoupling.MEDCouplingPointSet_Rotate3DAlg(*args) | Rotate3DAlg(PyObject center, PyObject vect, double angle, int nbNodes,
PyObject coords)
MEDCouplingPointSet_Rotate3DAlg(PyObject center, PyObject vect, double angle, PyObject coords)
1 | 625941bea8ecb033257d2fec |
def debounce(interval_s, keyed_by=None): <NEW_LINE> <INDENT> def wrapper(func): <NEW_LINE> <INDENT> timers = {} <NEW_LINE> lock = threading.Lock() <NEW_LINE> @functools.wraps(func) <NEW_LINE> def debounced(*args, **kwargs): <NEW_LINE> <INDENT> sig = inspect.signature(func) <NEW_LINE> call_args = sig.bind(*args, **kwargs) <NEW_LINE> key = call_args.arguments[keyed_by] if keyed_by else None <NEW_LINE> def run(): <NEW_LINE> <INDENT> with lock: <NEW_LINE> <INDENT> del timers[key] <NEW_LINE> <DEDENT> return func(*args, **kwargs) <NEW_LINE> <DEDENT> with lock: <NEW_LINE> <INDENT> old_timer = timers.get(key) <NEW_LINE> if old_timer: <NEW_LINE> <INDENT> old_timer.cancel() <NEW_LINE> <DEDENT> timer = threading.Timer(interval_s, run) <NEW_LINE> timers[key] = timer <NEW_LINE> timer.start() <NEW_LINE> <DEDENT> <DEDENT> return debounced <NEW_LINE> <DEDENT> return wrapper | Debounce calls to this function until interval_s seconds have passed. | 625941be6aa9bd52df036cc1 |
def coinChange(self, coins, amount): <NEW_LINE> <INDENT> dp=[0]+ [-1]* amount <NEW_LINE> for i in range(amount): <NEW_LINE> <INDENT> if dp[i]< 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for c in coins: <NEW_LINE> <INDENT> if i+c > amount: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if dp[i+c]<0 or dp[i+c]> dp[i]+1: <NEW_LINE> <INDENT> dp[i+c]=dp[i]+1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return dp[amount] | :type coins: List[int]
:type amount: int
:rtype: int | 625941be4428ac0f6e5ba70f |
def testOBMolSeparatePreservesAromaticity(self): <NEW_LINE> <INDENT> smi = "C.c1ccccc1" <NEW_LINE> for N in range(2): <NEW_LINE> <INDENT> obmol = pybel.readstring("smi", smi).OBMol <NEW_LINE> if N == 0: <NEW_LINE> <INDENT> obmol.SetAromaticPerceived(False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assertTrue(obmol.HasAromaticPerceived()) <NEW_LINE> <DEDENT> mols = obmol.Separate() <NEW_LINE> if N == 0: <NEW_LINE> <INDENT> self.assertFalse(mols[1].HasAromaticPerceived()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assertTrue(mols[1].HasAromaticPerceived()) <NEW_LINE> <DEDENT> atom = mols[1].GetAtom(1) <NEW_LINE> atom.SetImplicitHCount(0) <NEW_LINE> if N == 0: <NEW_LINE> <INDENT> self.assertFalse(atom.IsAromatic()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assertTrue(atom.IsAromatic()) | If the original molecule had aromaticity perceived,
then the fragments should also. | 625941be4527f215b584c378 |
def get_best(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return list(self.best_df["Name"])[0] <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self.compare() <NEW_LINE> return list(self.best_df["Name"])[0] | Function that return the name of the best model.
Best here is define be the maximum value of the
feature "Score*Preci"
:rtype: str | 625941beac7a0e7691ed3ff3 |
def active(self, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if kwargs['user']: <NEW_LINE> <INDENT> user = kwargs['user'] <NEW_LINE> return super(ListManager, self).filter(archived=False, user=user) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> return super(ListManager, self).filter(archived=False) | filter archived objs or archived and specific user Lists
:param args:
:param kwargs:
:return: Queryset of lists filtered by archived element or archived and user | 625941be3cc13d1c6d3c7299 |
def bwLim(self, tsampRate, strict = False, uniq = "abcd"): <NEW_LINE> <INDENT> if self.__sampRate < tsampRate: <NEW_LINE> <INDENT> raise ValueError("The target sampling rate must be less than current sampling rate") <NEW_LINE> <DEDENT> if strict: <NEW_LINE> <INDENT> self.__sig = signal.resample(self.signal, int(tsampRate * self.length/self.sampRate)) <NEW_LINE> self.__sampRate = tsampRate <NEW_LINE> self.__len = len(self.signal) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> jumpIndex = int(self.sampRate / tsampRate) <NEW_LINE> offset = 0 <NEW_LINE> if not self.__chunker is None: <NEW_LINE> <INDENT> offset = self.__chunker.get(constants.CHUNK_BWLIM + uniq, 0) <NEW_LINE> nextOff = (jumpIndex - (self.length - offset)%jumpIndex)%jumpIndex <NEW_LINE> self.__chunker.set(constants.CHUNK_BWLIM + uniq, nextOff) <NEW_LINE> <DEDENT> self.__sig = self.signal[offset::jumpIndex] <NEW_LINE> self.__sampRate = int(self.sampRate/jumpIndex) <NEW_LINE> self.__len = len(self.signal) <NEW_LINE> <DEDENT> return self | Limit the bandwidth by downsampling
Args:
tsampRate (:obj:`int`): target sample rate
strict (:obj:`bool`, optional): if true, the target sample rate will be matched exactly
uniq (:obj:`str`, optional): in case chunked signal, uniq is to differentiate different bwLim funcs
Returns:
:obj:`commSignal`: Updated signal (self) | 625941be5fc7496912cc389c |
def restrict_by_tables(self, tables, fill=False): <NEW_LINE> <INDENT> nodes = [n for n in self.nodes() if self.node[n].get('label') in tables] <NEW_LINE> if fill: <NEW_LINE> <INDENT> nodes = self.fill_connection_nodes(nodes) <NEW_LINE> <DEDENT> return self.subgraph(nodes) | Creates a subgraph containing only specified tables.
:param tables: list of tables to keep in the subgraph
:param fill: set True to automatically include nodes connecting two nodes in the specified list
of tables
:return: a subgraph with specified nodes | 625941be66656f66f7cbc0c8 |
def versions(self): <NEW_LINE> <INDENT> out, err, status = self._run_prcs(["info", "-f", self._name]) <NEW_LINE> if status != 0: <NEW_LINE> <INDENT> raise PrcsCommandError(err.decode()) <NEW_LINE> <DEDENT> versions = {} <NEW_LINE> for line in out.splitlines(): <NEW_LINE> <INDENT> match = _INFO_RECORD_PATTERN.match(line.decode()) <NEW_LINE> if match: <NEW_LINE> <INDENT> project, version, date, author, deleted = match.groups() <NEW_LINE> versions[version] = { "project": project, "id": version, "date": datetime(*parsedate(date)[0:6]), "author": author, "deleted": bool(deleted), } <NEW_LINE> <DEDENT> <DEDENT> return versions | Return a dictionary of the summary records for all the versions. | 625941be56ac1b37e62640f2 |
def boolean_graph(): <NEW_LINE> <INDENT> node1 = node(0,'',[],[1, 3]) <NEW_LINE> node2 = node(1,'&',[0,2],[]) <NEW_LINE> node3 = node(2,'',[],[1, 3]) <NEW_LINE> node4 = node(3,'|',[0,2],[4]) <NEW_LINE> node5 = node(4,'~',[3],[]) <NEW_LINE> nodelist = [node1,node2,node3,node4,node5] <NEW_LINE> g = open_digraph([0,2], [1,4], nodelist) <NEW_LINE> return g | create and return a logical well formed graph possibly boolean
with :
2 inputs
2 outputs
max_indegree = 2
max_outdegree = 2
min_indegree = 1
min_outdegree = 1 | 625941bea4f1c619b28aff5d |
def exec_(self): <NEW_LINE> <INDENT> return self._view.exec_() | Run the dialog.
| 625941be5e10d32532c5ee45 |
def fast_all_primes_less_than(n): <NEW_LINE> <INDENT> sieve = [True] * (n // 2) <NEW_LINE> for i in range(3, int(n ** 0.5) + 1, 2): <NEW_LINE> <INDENT> if sieve[i // 2]: <NEW_LINE> <INDENT> sieve[i * i // 2::i] = [False] * ((n - i * i - 1) // (2 * i) + 1) <NEW_LINE> <DEDENT> <DEDENT> return [2] + [2 * i + 1 for i in range(1, n // 2) if sieve[i]] | Returns a list of primes < num | 625941beb7558d58953c4e37 |
def forward(self, *args): <NEW_LINE> <INDENT> images, annotations, *_ = args <NEW_LINE> images, annotations = images.to(self.device), annotations.to(self.device) <NEW_LINE> anchors, regressions, classifications = self.model(images, annotations) <NEW_LINE> del images <NEW_LINE> classification_loss, regression_loss = self.criterion(anchors, regressions, classifications, annotations) <NEW_LINE> del anchors, regressions, classifications, annotations <NEW_LINE> weights = self.hyperparameters['criterion']['weights'] <NEW_LINE> classification_loss = classification_loss * weights['classification'] <NEW_LINE> regression_loss = regression_loss * weights['regression'] <NEW_LINE> loss = classification_loss + regression_loss <NEW_LINE> self.current_log['Class.'] = '{:.3f}'.format(float(classification_loss)) <NEW_LINE> self.current_log['Regr.'] = '{:.3f}'.format(float(regression_loss)) <NEW_LINE> self.current_log['Cl. w'] = '{:.3f}'.format(float(self.model.classification.weight.mean())) <NEW_LINE> self.current_log['Cl. b'] = '{:.3f}'.format(float(self.model.classification.bias.mean())) <NEW_LINE> return loss | Forward pass through the network and loss computation.
Returns:
torch.Tensor: The loss of the batch. | 625941be2c8b7c6e89b356e0 |
def get_visibility_techniques(filename): <NEW_LINE> <INDENT> groups_dict = {} <NEW_LINE> detection_techniques, name, platform = _load_detections(filename) <NEW_LINE> group_id = 'VISIBILITY' <NEW_LINE> groups_dict[group_id] = {} <NEW_LINE> groups_dict[group_id]['group_name'] = 'Visibility' <NEW_LINE> groups_dict[group_id]['techniques'] = set() <NEW_LINE> for t, v in detection_techniques.items(): <NEW_LINE> <INDENT> if 'visibility' in v.keys() and v['visibility']['score'] > 0: <NEW_LINE> <INDENT> groups_dict[group_id]['techniques'].add(t) <NEW_LINE> <DEDENT> <DEDENT> return groups_dict | Get all techniques (in a dict) from the detections administration
:param filename: path to the YAML technique administration file
:return: dictionary | 625941be73bcbd0ca4b2bf95 |
@user_logged_in.connect <NEW_LINE> def combine_cart(sender, user): <NEW_LINE> <INDENT> merge_carts(session_key_from=session.sid, user_id_to=str(user.id)) | 合并购物车
:param sender:
:param user:
:return: | 625941be3eb6a72ae02ec3f4 |
def add(self, command_id, func): <NEW_LINE> <INDENT> func.base = getattr(func, "base", func) <NEW_LINE> func.argspec = getattr(func, "argspec", inspect.getargspec(func)) <NEW_LINE> func.doc = getattr(func.base, "__doc__", "Call function %s with parameters %s" % (func.base.__name__, func.argspec.args)) <NEW_LINE> self.registered[command_id] = func <NEW_LINE> return func | 対象のコマンド名に対して対象の呼び出し可能オブジェクトを登録する
:param command_id: 対象のコマンド名
:param func: 呼び出し可能オブジェクト
:return: 呼び出し可能オブジェクト自体が返却される | 625941be76e4537e8c35158f |
def __init__(self, pid_or_name, debug=False, prefer_lock=False): <NEW_LINE> <INDENT> pid = None <NEW_LINE> name = None <NEW_LINE> if isinstance(pid_or_name, int): <NEW_LINE> <INDENT> pid = pid_or_name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pid = self.pid_from_name(pid_or_name) <NEW_LINE> name = pid_or_name <NEW_LINE> <DEDENT> if pid is None: <NEW_LINE> <INDENT> raise ValueError('Process Id required') <NEW_LINE> <DEDENT> elif pid == os.getpid(): <NEW_LINE> <INDENT> raise ValueError('Must not be current process') <NEW_LINE> <DEDENT> self.pid = pid <NEW_LINE> self.name = name <NEW_LINE> self.debug = debug <NEW_LINE> self.prefer_lock = prefer_lock | Create and Open a process object from its pid or from its name | 625941be8e71fb1e9831d6c9 |
def addxp(self, xp=[], verbose=False): <NEW_LINE> <INDENT> self.addshot(xp=xp, verbose=verbose) | Add all shots for one or more XPx
**Usage**
>>> nstx.addxp(1032)
>>> nstx.addxp(xp=1013)
>>> nstx.addxp([1042, 1016]) | 625941bed10714528d5ffbff |
def format(self, frame): <NEW_LINE> <INDENT> return str(frame) | Return the given frame in timecode format.
frame - Frame number, which can be negative. | 625941be5166f23b2e1a5077 |
def mylinearsvm(beta_init, theta_init, lambduh, eta_init, maxiter, x= x_train, y= y_train): <NEW_LINE> <INDENT> beta = beta_init <NEW_LINE> theta = theta_init <NEW_LINE> grad_theta = grad_obj(theta, lambduh, x=x, y=y) <NEW_LINE> beta_vals = beta <NEW_LINE> theta_vals = theta <NEW_LINE> iterate = 0 <NEW_LINE> while iterate < maxiter: <NEW_LINE> <INDENT> eta = backtrack(theta, lambduh, eta=eta_init, x=x, y=y) <NEW_LINE> beta_new = theta - eta*grad_theta <NEW_LINE> theta = beta_new + iterate/(iterate+3)*(beta_new-beta) <NEW_LINE> beta_vals = np.vstack((beta_vals, beta_new)) <NEW_LINE> theta_vals = np.vstack((theta_vals, theta)) <NEW_LINE> grad_theta = grad_obj(theta, lambduh, x=x, y=y) <NEW_LINE> beta = beta_new <NEW_LINE> iterate += 1 <NEW_LINE> <DEDENT> return beta_vals, theta_vals | This function implements fast gradient algorithm with backtracking rule
to tune the step size.
It calls backtrack and gradient functions. | 625941beff9c53063f47c113 |
def randomize_molecule(molecule, manipulations, nonbond_thresholds, max_tries=1000): <NEW_LINE> <INDENT> for m in xrange(max_tries): <NEW_LINE> <INDENT> random_molecule = randomize_molecule_low(molecule, manipulations) <NEW_LINE> if check_nonbond(random_molecule, nonbond_thresholds): <NEW_LINE> <INDENT> return random_molecule | Return a randomized copy of the molecule.
If no randomized molecule can be generated that survives the nonbond
check after max_tries repetitions, None is returned. In case of success,
the randomized molecule is returned. The original molecule is not
altered. | 625941bed99f1b3c44c674b3 |
def _inner_loop_update(self, loss, weights, use_second_order, current_update_step): <NEW_LINE> <INDENT> self.model.zero_grad(weights) <NEW_LINE> grads = torch.autograd.grad( loss, weights, create_graph=use_second_order, allow_unused=True) <NEW_LINE> updated_weights = list() <NEW_LINE> for idx, (weight, grad) in enumerate(zip(weights, grads)): <NEW_LINE> <INDENT> updated_weight = weight - self.learning_rates[current_update_step, idx // 2] * grad <NEW_LINE> updated_weights.append(updated_weight) <NEW_LINE> <DEDENT> return updated_weights | Applies an inner loop update
Args:
loss: Loss on support set
weights: Network weights
use_second_order: If use second order
current_update_step
Returns:
updated network weights | 625941bede87d2750b85fcae |
def search_by_text(self, query_text: str, max_id: int = None) -> List[int]: <NEW_LINE> <INDENT> id_tweets = [] <NEW_LINE> text_list_include = FilterText.objects.filter(id_status=1).values_list('text') or [] <NEW_LINE> if not text_list_include: <NEW_LINE> <INDENT> logging.error("[e] reply_for_tweet_by_id - Please check filter_text table or fix query") <NEW_LINE> return id_tweets <NEW_LINE> <DEDENT> text_list_exclude = FilterText.objects.filter(id_status=2).values_list('text') or [] <NEW_LINE> from_date = datetime.now() - timedelta(days=1) <NEW_LINE> to_date = datetime.now() + timedelta(days=1) <NEW_LINE> if max_id and max_id > 0: <NEW_LINE> <INDENT> search_results = tweepy.Cursor(self._api.search, q=query_text, since=from_date.strftime("%Y-%m-%d"), until=to_date.strftime("%Y-%m-%d"), since_id=max_id, result_type='recent', lang="en").items() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> search_results = tweepy.Cursor(self._api.search, q=query_text, since=from_date.strftime("%Y-%m-%d"), until=to_date.strftime("%Y-%m-%d"), result_type='recent', lang="en").items() <NEW_LINE> <DEDENT> i = 0 <NEW_LINE> for item in search_results: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tweet_text = filter_printable_char(strip_emoji(item.text)) <NEW_LINE> count_include = 0 <NEW_LINE> count_exclude = 0 <NEW_LINE> for item_text in text_list_include: <NEW_LINE> <INDENT> if str(''.join(item_text)).lower() in tweet_text.lower(): <NEW_LINE> <INDENT> count_include = count_include + 1 <NEW_LINE> <DEDENT> <DEDENT> if len(text_list_include) > count_include: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for item_text in text_list_exclude: <NEW_LINE> <INDENT> if str(''.join(item_text)).lower() not in tweet_text.lower(): <NEW_LINE> <INDENT> count_exclude = count_exclude + 1 <NEW_LINE> <DEDENT> <DEDENT> if len(text_list_exclude) > count_exclude: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if Tweets.objects.filter(id_tweet=item.id).exists(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> dict_record = {"id_tweet": item.id, "id_user": item.user.id, "name_author": filter_printable_char(strip_emoji(item.user.name)), "name_screen": item.user.screen_name, "text_tweet": tweet_text, "create_at": item.created_at if isinstance(item.created_at, datetime) else datetime.now(), "location": filter_printable_char(strip_emoji(item.user.location)), "geo": item.geo, "source": filter_printable_char(item.source), "lang": filter_printable_char(item.lang), "status": StatusTweet.objects.get(id=1)} <NEW_LINE> new_tweet = Tweets.objects.create(**dict_record) <NEW_LINE> new_tweet.save() <NEW_LINE> logging.info("Add {0} row. ID: {1}".format(i, new_tweet.pk)) <NEW_LINE> logging.info("MAX ID: {}".format(str(item.id))) <NEW_LINE> id_tweets.append(item.id) <NEW_LINE> return item.id <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.exception("Error search_by_text. {}".format(e)) <NEW_LINE> i -= 1 <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> return id_tweets | Search tweets by some text
:param query_text: str
Text for search in twitter
:param max_id: int
Max ID tweet for search new tweets
:return: list[dict]
Data for work | 625941bee64d504609d7475e |
def SetObjective(self, cost, ExtraArgs=None): <NEW_LINE> <INDENT> _cost,_raw,_args = self._cost <NEW_LINE> if (cost is None or cost is _raw or cost is _cost) and (ExtraArgs is None or ExtraArgs is _args): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if cost is None: cost = _raw <NEW_LINE> args = _args if ExtraArgs is None else ExtraArgs <NEW_LINE> args = () if args is None else args <NEW_LINE> if not isvalid(cost, [0]*self.nDim, *args): <NEW_LINE> <INDENT> try: name = cost.__name__ <NEW_LINE> except AttributeError: <NEW_LINE> <INDENT> cost(*args) <NEW_LINE> <DEDENT> validate(cost, None, *args) <NEW_LINE> <DEDENT> self._cost = (None, cost, ExtraArgs) <NEW_LINE> self._live = False <NEW_LINE> return | set the cost function for the optimization
input::
- cost is the objective function, of the form y = cost(x, *ExtraArgs),
where x is a candidate solution, and ExtraArgs is the tuple of positional
arguments required to evaluate the objective.
note::
this method decorates the objective with bounds, penalties, monitors, etc | 625941be9c8ee82313fbb693 |
def FileEntryExistsByPath(self, path): <NEW_LINE> <INDENT> if self._file_entries is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return path in self._file_entries | Determines if file entry for a specific path exists.
Returns:
bool: True if the file entry exists. | 625941bee76e3b2f99f3a72f |
def shEpoTrImg(dbe, ver, con, nStn, epo, iBat=1): <NEW_LINE> <INDENT> nm = '{}_{}_{}'.format(dbe, ver, con) <NEW_LINE> tmpFold = os.path.join(os.environ['HOME'], 'save/{}/torch/tmp/{}'.format(dbe, nm)) <NEW_LINE> outFold = os.path.join(os.environ['HOME'], 'save/{}/torch/deb_stn/{}'.format(dbe, nm)) <NEW_LINE> lib.mkDir(outFold) <NEW_LINE> outPath = '{}/tr_{}_{}_img.jpg'.format(outFold, epo, iBat) <NEW_LINE> h5Path = '{}/tr_{}_{}_grid.h5'.format(tmpFold, epo, iBat) <NEW_LINE> ha = lib.hdfRIn(h5Path) <NEW_LINE> gridCorns = lib.cells(nStn) <NEW_LINE> for iStn in range(nStn): <NEW_LINE> <INDENT> gridCorns[iStn] = lib.hdfR(ha, 'gridCorn{}'.format(iStn + 1)) <NEW_LINE> <DEDENT> lib.hdfROut(ha) <NEW_LINE> h5Path = '{}/tr_{}_{}_img_in.h5'.format(tmpFold, epo, iBat) <NEW_LINE> ha = lib.hdfRIn(h5Path) <NEW_LINE> imgIn0 = lib.hdfR(ha, 'imgIn0') <NEW_LINE> imgIns = lib.cells(nStn) <NEW_LINE> for iStn in range(nStn): <NEW_LINE> <INDENT> imgIns[iStn] = lib.hdfR(ha, 'imgIn{}'.format(iStn + 1)) <NEW_LINE> <DEDENT> lib.hdfROut(ha) <NEW_LINE> n, _, h, w = imgIn0.shape <NEW_LINE> nTop = min(n, 7) <NEW_LINE> rows = 2 <NEW_LINE> cols = nTop <NEW_LINE> Ax = lib.iniAx(1, nStn * rows, cols, [3 * nStn * rows, 3 * cols], flat=False) <NEW_LINE> for iStn in range(nStn): <NEW_LINE> <INDENT> grid = gridCorns[iStn] <NEW_LINE> for iTop in range(nTop): <NEW_LINE> <INDENT> col = iTop <NEW_LINE> lib.shImg(imgIn0[iTop].transpose((1, 2, 0)), ax=Ax[iStn * 2, col]) <NEW_LINE> idxYs = [0, 0, 1, 1, 0] <NEW_LINE> idxXs = [0, 1, 1, 0, 0] <NEW_LINE> xs, ys = lib.zeros(5, n=2) <NEW_LINE> for i in range(5): <NEW_LINE> <INDENT> idxY = idxYs[i] <NEW_LINE> idxX = idxXs[i] <NEW_LINE> ys[i] = (grid[iTop, idxY, idxX, 0] + 1) / 2 * h <NEW_LINE> xs[i] = (grid[iTop, idxY, idxX, 1] + 1) / 2 * w <NEW_LINE> <DEDENT> lib.plt.plot(xs, ys, 'r-') <NEW_LINE> lib.shImg(imgIns[iStn][iTop].transpose((1, 2, 0)), ax=Ax[iStn * 2 + 1, col]) <NEW_LINE> <DEDENT> <DEDENT> lib.shSvPath(outPath, type='jpg') | Show the transformation of each epoch.
Input
dbe - database
ver - version
con - configuration
nStn - #stn
epo - epoch id
iBat - batch id | 625941be498bea3a759b99ce |
def test_set_circuit_not_missing(): <NEW_LINE> <INDENT> circuit_filename = os.path.join(SHEEP_HOME,"pysheep","pysheep","tests", "testfiles","simple_add.sheep") <NEW_LINE> r=sheep_client.set_circuit(circuit_filename) <NEW_LINE> check_404_response(r) | check the set_circuit function with a real filename
but no server
- should get status_code 404 | 625941be287bf620b61d3984 |
def list_jobs(self, project_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.list_jobs_with_http_info(project_id, **kwargs) | Returns a collection of Jobs # noqa: E501
Returns a collection of Jobs # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_jobs(project_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str project_id: ID of the Project (required)
:param int page: page number
:param int per_page: number of records per page
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: JobsCollection
If the method is called asynchronously,
returns the request thread. | 625941be29b78933be1e55cf |
def getMetaDataInfo(self): <NEW_LINE> <INDENT> return {'_id':self.channelNumber,'sensorName':self.sensorName, 'sensorReadingType':self.sensorReadingType, 'plotType':self.plotType,'lastSyncTime':time.time(),'signals':1} | Gets the meta data for the sensor
:return: meta data for the sensor
:rtype: dict | 625941be85dfad0860c3ad78 |
def unpackMail(mailString): <NEW_LINE> <INDENT> return unpackMultifile(multifile.MultiFile(StringIO.StringIO(mailString))) | returns body, content-type, html-body and attachments for mail-string.
| 625941becdde0d52a9e52f4f |
def open_file(r_file): <NEW_LINE> <INDENT> with open(r_file,'r') as f: <NEW_LINE> <INDENT> raw_data = f.read().splitlines() <NEW_LINE> <DEDENT> return raw_data | Open and read file into split lines and return
Input: text file (txt/sql)
Output: each line from input file returned | 625941bea934411ee37515b2 |
def conform_mlc_to_rectangle(beam, x, y, center): <NEW_LINE> <INDENT> xy = x,y <NEW_LINE> bld = getblds(beam.BeamLimitingDeviceSequence) <NEW_LINE> mlcdir, jawdir1, jawdir2 = get_mlc_and_jaw_directions(bld) <NEW_LINE> mlcidx = (0,1) if mlcdir == "MLCX" else (1,0) <NEW_LINE> nleaves = len(bld[mlcdir].LeafPositionBoundaries)-1 <NEW_LINE> for cp in beam.ControlPointSequence: <NEW_LINE> <INDENT> if hasattr(cp, 'BeamLimitingDevicePositionSequence') and cp.BeamLimitingDevicePositionSequence != None: <NEW_LINE> <INDENT> bldp = getblds(cp.BeamLimitingDevicePositionSequence) <NEW_LINE> for i in range(nleaves): <NEW_LINE> <INDENT> if bld[mlcdir].LeafPositionBoundaries[i+1] > (center[mlcidx[1]]-xy[mlcidx[1]]/2.0) and bld[mlcdir].LeafPositionBoundaries[i] < (center[mlcidx[1]]+xy[mlcidx[1]]/2.0): <NEW_LINE> <INDENT> bldp[mlcdir].LeafJawPositions[i] = center[mlcidx[0]] - xy[mlcidx[0]]/2.0 <NEW_LINE> bldp[mlcdir].LeafJawPositions[i + nleaves] = center[mlcidx[0]] + xy[mlcidx[0]]/2.0 | Sets MLC to open at least x * y cm | 625941bef7d966606f6a9f20 |
def get_proper_type(typ: Optional[Type]) -> Optional[ProperType]: <NEW_LINE> <INDENT> if typ is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if isinstance(typ, TypeGuardedType): <NEW_LINE> <INDENT> typ = typ.type_guard <NEW_LINE> <DEDENT> while isinstance(typ, TypeAliasType): <NEW_LINE> <INDENT> typ = typ._expand_once() <NEW_LINE> <DEDENT> assert isinstance(typ, ProperType), typ <NEW_LINE> return typ | Get the expansion of a type alias type.
If the type is already a proper type, this is a no-op. Use this function
wherever a decision is made on a call like e.g. 'if isinstance(typ, UnionType): ...',
because 'typ' in this case may be an alias to union. Note: if after making the decision
on the isinstance() call you pass on the original type (and not one of its components)
it is recommended to *always* pass on the unexpanded alias. | 625941be60cbc95b062c6461 |
def extract_xray_structure(self, crystal_symmetry=None, min_distance_sym_equiv=None): <NEW_LINE> <INDENT> if min_distance_sym_equiv is not None: <NEW_LINE> <INDENT> return self.as_pdb_input(crystal_symmetry).xray_structure_simple( min_distance_sym_equiv=min_distance_sym_equiv) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.as_pdb_input(crystal_symmetry).xray_structure_simple() | Generate the equivalent cctbx.xray.structure object. If the crystal
symmetry is not provided, this will be placed in a P1 box. In practice it
is usually best to keep the original xray structure object around, but this
method is helpful in corner cases. | 625941be24f1403a92600a87 |
def quantize_cluster(C,data): <NEW_LINE> <INDENT> qC = [] <NEW_LINE> for i in C: <NEW_LINE> <INDENT> mC = np.mean(data[i,:],axis=0) <NEW_LINE> pos = find_nearest(mC,i,data) <NEW_LINE> qC.append(pos) <NEW_LINE> <DEDENT> return qC | Select Centroid of Each Cluster | 625941be6e29344779a62533 |
def _update_order(self, order_info): <NEW_LINE> <INDENT> if order_info["contract_type"] != self._contract_type or order_info["symbol"] != self._symbol: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> order_no = str(order_info["order_id"]) <NEW_LINE> status = order_info["status"] <NEW_LINE> order = self._orders.get(order_no) <NEW_LINE> if not order: <NEW_LINE> <INDENT> if order_info["direction"] == "buy": <NEW_LINE> <INDENT> if order_info["offset"] == "open": <NEW_LINE> <INDENT> trade_type = TRADE_TYPE_BUY_OPEN <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> trade_type = TRADE_TYPE_BUY_CLOSE <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if order_info["offset"] == "close": <NEW_LINE> <INDENT> trade_type = TRADE_TYPE_SELL_CLOSE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> trade_type = TRADE_TYPE_SELL_OPEN <NEW_LINE> <DEDENT> <DEDENT> info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "client_order_id": order_info.get("client_order_id"), "order_price_type": order_info.get("order_price_type"), "order_type": order_info["order_type"], "action": ORDER_ACTION_BUY if order_info["direction"] == "buy" else ORDER_ACTION_SELL, "symbol": self._symbol + '/' + self._contract_type, "price": order_info["price"], "quantity": order_info["volume"], "trade_type": trade_type } <NEW_LINE> order = Order(**info) <NEW_LINE> self._orders[order_no] = order <NEW_LINE> <DEDENT> order.trade_quantity = None <NEW_LINE> order.trade_price = None <NEW_LINE> if order_info.get("trade"): <NEW_LINE> <INDENT> quantity = 0 <NEW_LINE> price = 0 <NEW_LINE> amount = 0 <NEW_LINE> count = len(order_info.get("trade")) <NEW_LINE> for trade in order_info.get("trade"): <NEW_LINE> <INDENT> order.role = trade.get("role") <NEW_LINE> quantity += float(trade.get("trade_volume")) <NEW_LINE> amount += float(trade.get("trade_volume")*trade.get("trade_price")) <NEW_LINE> <DEDENT> price = amount/quantity <NEW_LINE> order.trade_quantity = int(quantity) <NEW_LINE> order.trade_price = price <NEW_LINE> <DEDENT> if status in [1, 2, 3]: <NEW_LINE> <INDENT> order.status = ORDER_STATUS_SUBMITTED <NEW_LINE> <DEDENT> elif status == 4: <NEW_LINE> <INDENT> order.status = ORDER_STATUS_PARTIAL_FILLED <NEW_LINE> order.remain = int(order.quantity) - int(order_info["trade_volume"]) <NEW_LINE> <DEDENT> elif status == 6: <NEW_LINE> <INDENT> order.status = ORDER_STATUS_FILLED <NEW_LINE> order.remain = 0 <NEW_LINE> <DEDENT> elif status in [5, 7]: <NEW_LINE> <INDENT> order.status = ORDER_STATUS_CANCELED <NEW_LINE> order.remain = int(order.quantity) - int(order_info["trade_volume"]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> order.avg_price = order_info["trade_avg_price"] <NEW_LINE> order.ctime = order_info["created_at"] <NEW_LINE> order.utime = order_info["ts"] <NEW_LINE> SingleTask.run(self._order_update_callback, copy.copy(order)) <NEW_LINE> if order.status in [ORDER_STATUS_FAILED, ORDER_STATUS_CANCELED, ORDER_STATUS_FILLED]: <NEW_LINE> <INDENT> self._orders.pop(order_no) <NEW_LINE> <DEDENT> logger.info("symbol:", order.symbol, "order:", order, caller=self) | Order update.
Args:
order_info: Order information. | 625941be1f037a2d8b94611d |
def twoSum(self, numbers, target): <NEW_LINE> <INDENT> i, j = 0, len(numbers) - 1 <NEW_LINE> s = numbers[i] + numbers[j] <NEW_LINE> while s != target: <NEW_LINE> <INDENT> if s < target: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> j -= 1 <NEW_LINE> <DEDENT> s = numbers[i] + numbers[j] <NEW_LINE> <DEDENT> return [i + 1, j + 1] | :type numbers: List[int]
:type target: int
:rtype: List[int] | 625941be498bea3a759b99cf |
def test_create_pool_with_all_params(self): <NEW_LINE> <INDENT> resource = 'pool' <NEW_LINE> cmd = pool.CreatePool(test_cli20.MyApp(sys.stdout), None) <NEW_LINE> name = 'my-name' <NEW_LINE> description = 'my-desc' <NEW_LINE> lb_method = 'round-robin' <NEW_LINE> protocol = 'http' <NEW_LINE> subnet_id = 'subnet-id' <NEW_LINE> tenant_id = 'my-tenant' <NEW_LINE> my_id = 'my-id' <NEW_LINE> args = ['--admin-state-down', '--description', description, '--lb-method', lb_method, '--name', name, '--protocol', protocol, '--subnet-id', subnet_id, '--tenant-id', tenant_id] <NEW_LINE> position_names = ['admin_state_up', 'description', 'lb_method', 'name', 'protocol', 'subnet_id', 'tenant_id'] <NEW_LINE> position_values = [False, description, lb_method, name, protocol, subnet_id, tenant_id] <NEW_LINE> self._test_create_resource(resource, cmd, name, my_id, args, position_names, position_values) | lb-pool-create with all params set. | 625941be4f88993c3716bf89 |
def _convert(self, batch, output_format, output_batch, **kwargs): <NEW_LINE> <INDENT> if isinstance(output_format, DenseFormat): <NEW_LINE> <INDENT> return self._convert_to_DenseFormat(batch, output_format, output_batch, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError("Conversion from format %s to format %s " "not supported." % (type(self), type(output_format))) | Converts a batch to another format.
Implemented by methods '_convert_to_XXX()' for target format XXX.
See those methods' documentation for details. | 625941be67a9b606de4a7dda |
def test_add_project_info_list(self): <NEW_LINE> <INDENT> self.assertRaises(TypeError, keenio.add_project_info_list) <NEW_LINE> self.assertRaises(TypeError, keenio.add_project_info_list, None) <NEW_LINE> self.assertRaises(TypeError, keenio.add_project_info_list, ["string"]) <NEW_LINE> self.assertListEqual([], keenio.add_project_info_list([])) <NEW_LINE> self.assertListEqual( [{"buildtime_trend": self.project_info}], keenio.add_project_info_list([{}]) ) <NEW_LINE> self.assertListEqual( [{"test": "value", "buildtime_trend": self.project_info}], keenio.add_project_info_list([{"test": "value"}]) ) <NEW_LINE> self.assertListEqual( [ {"test": "value", "buildtime_trend": self.project_info}, {"test2": "value2", "buildtime_trend": self.project_info} ], keenio.add_project_info_list([ {"test": "value"}, {"test2": "value2"}]) ) | Test keenio.add_project_info_list() | 625941be1d351010ab855a3b |
def stream_object_data(self, ref): <NEW_LINE> <INDENT> cmd = self._get_persistent_cmd("cat_file_all", "cat_file", batch=True) <NEW_LINE> hexsha, typename, size = self.__get_object_header(cmd, ref) <NEW_LINE> return (hexsha, typename, size, self.CatFileContentStream(size, cmd.stdout)) | As get_object_header, but returns the data as a stream
:return: (hexsha, type_string, size_as_int, stream)
:note: This method is not threadsafe, you need one independent Command instance
per thread to be safe ! | 625941be7b25080760e39379 |
def __init__(self, filename: str, events=None): <NEW_LINE> <INDENT> self.filename = os.path.abspath(filename) <NEW_LINE> self.stat = os.stat(self.filename) <NEW_LINE> self.start_datetime, self.end_datetime = None, None <NEW_LINE> self._events = [] <NEW_LINE> self._events_by_baseclass = collections.defaultdict(list) <NEW_LINE> if events is not None: <NEW_LINE> <INDENT> for ev in events: <NEW_LINE> <INDENT> self.append(ev) | List of ABINIT events.
Args:
filename: Name of the file
events: List of Event objects | 625941becb5e8a47e48b79cc |
def enqueue(self, value): <NEW_LINE> <INDENT> new_node = SimpleQueueNode(value, self._tail, None) <NEW_LINE> if self.is_empty(): <NEW_LINE> <INDENT> self._head = new_node <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._tail.next_node = new_node <NEW_LINE> <DEDENT> self._tail = new_node <NEW_LINE> self.size += 1 | Add an item to the end of the queue. Creates a new SimpleQueueNode
to accomplish this.
Arguments:
value - the value of the item to be added to the end of the queue. | 625941be67a9b606de4a7ddb |
def move_down(self): <NEW_LINE> <INDENT> if (self.y + 8) <= 700: <NEW_LINE> <INDENT> self.y += 8 | 飞机向下移 | 625941be3d592f4c4ed1cf94 |
def add_model(self, inputs): <NEW_LINE> <INDENT> with tf.variable_scope('InputDropout'): <NEW_LINE> <INDENT> inputs = [tf.nn.dropout(x, self.dropout_placeholder) for x in inputs] <NEW_LINE> <DEDENT> with tf.variable_scope('rnn') as scope: <NEW_LINE> <INDENT> self.initial_state = tf.zeros([self.config.batch_size, self.config.hidden_size]) <NEW_LINE> state = self.initial_state <NEW_LINE> rnn_outputs = [] <NEW_LINE> for step, current_input in enumerate(inputs): <NEW_LINE> <INDENT> if step > 0: <NEW_LINE> <INDENT> scope.reuse_variables() <NEW_LINE> <DEDENT> Whh = tf.get_variable('Whh', [self.config.hidden_size, self.config.hidden_size], initializer=tf.random_normal_initializer(0, 1.)) <NEW_LINE> Whx = tf.get_variable('Whx', [self.config.embed_size, self.config.hidden_size], initializer=tf.random_normal_initializer(0, 1.)) <NEW_LINE> b_1 = tf.get_variable('b_h', [self.config.hidden_size], initializer=tf.constant_initializer(0.)) <NEW_LINE> state = tf.nn.sigmoid(tf.matmul(state, Whh) + tf.matmul(current_input, Whx) + b_1) <NEW_LINE> rnn_outputs.append(state) <NEW_LINE> if step == 0: <NEW_LINE> <INDENT> variable_summaries(Whh, Whh.name) <NEW_LINE> variable_summaries(Whx, Whx.name) <NEW_LINE> variable_summaries(b_1, b_1.name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.final_state = rnn_outputs[-1] <NEW_LINE> with tf.variable_scope('RNNDropout'): <NEW_LINE> <INDENT> rnn_outputs = [tf.nn.dropout(x, self.dropout_placeholder) for x in rnn_outputs] <NEW_LINE> <DEDENT> return rnn_outputs | Creates the RNN LM model.
In the space provided below, you need to implement the equations for the
RNN LM model. Note that you may NOT use built in rnn_cell functions from
tensorflow.
Hint: Use a zeros tensor of shape (batch_size, hidden_size) as
initial state for the RNN. Add this to self as instance variable
self.initial_state
(Don't change variable name)
Hint: Add the last RNN output to self as instance variable
self.final_state
(Don't change variable name)
Hint: Make sure to apply dropout to the inputs and the outputs.
Hint: Use a variable scope (e.g. "RNN") to define RNN variables.
Hint: Perform an explicit for-loop over inputs. You can use
scope.reuse_variables() to ensure that the weights used at each
iteration (each time-step) are the same. (Make sure you don't call
this for iteration 0 though or nothing will be initialized!)
Hint: Here are the dimensions of the various variables you will need to
create:
H: (hidden_size, hidden_size)
I: (embed_size, hidden_size)
b_1: (hidden_size,)
Args:
inputs: List of length num_steps, each of whose elements should be
a tensor of shape (batch_size, embed_size).
Returns:
outputs: List of length num_steps, each of whose elements should be
a tensor of shape (batch_size, hidden_size) | 625941be4d74a7450ccd40e2 |
def pathSum(self, root, sum): <NEW_LINE> <INDENT> self.result = [] <NEW_LINE> self.getpath(root, [], 0, sum) <NEW_LINE> return self.result | :type root: TreeNode
:type sum: int
:rtype: List[List[int]] | 625941be099cdd3c635f0b7b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.