code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def warm_reset(): <NEW_LINE> <INDENT> _pcsc_lib.WarmReset.restype = c_bool <NEW_LINE> return _pcsc_lib.WarmReset() | 热复位 | 625941e6099cdd3c635f10a0 |
def __matrix_padding_multi_size_soft(src_mat, out_size=[[64, 64], [128, 128]], dtype=np.float32): <NEW_LINE> <INDENT> num_outsize = np.array(out_size).shape[0] <NEW_LINE> img_c = None <NEW_LINE> if len(src_mat.shape) == 2: <NEW_LINE> <INDENT> img_h, img_w = src_mat.shape <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> im... | padding zero to src matrix to get larger size matrix
if and only if source image's width and height are both small than out's, do padding
:param src_mat: source matrix
:param out_size: every row represent one of the images' out size :[height, width],
and the row's index bigger, the size bigger.
:param ... | 625941e61d351010ab855f62 |
def last_d_softmax(self, x): <NEW_LINE> <INDENT> e_x = T.exp(x - x.max(axis=-1, keepdims=True)) <NEW_LINE> out = e_x / e_x.sum(axis=-1, keepdims=True) <NEW_LINE> return out | Utility function for getting the transition table from canvas | 625941e66fece00bbac2db8b |
def check_if_screen_correct(screen): <NEW_LINE> <INDENT> if screen is not None: <NEW_LINE> <INDENT> check_if_colour_correct(screen.get(cm.FG_COLOUR)) <NEW_LINE> check_if_colour_correct(screen.get(cm.BG_COLOUR)) | Checks if whole screen is correct written in json.
:param screen:
:return: | 625941e67cff6e4e81117dcd |
def create(self, main_bug, extra_bugs, packages, maintainer=None): <NEW_LINE> <INDENT> response = self.request( 'eventSubmit_doStartBugzillaIssue/true/' 'action/workflows.MaintenanceTracker.MaintenanceActions', bugid=main_bug, ) <NEW_LINE> data = response.read() <NEW_LINE> if 'Success' not in data: <NEW_LINE> <INDENT> ... | Creates new maintenance workflow. | 625941e650485f2cf553d1e3 |
def prepare_fabric_fw(self, tenant_id, fw_dict, is_fw_virt, result): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with self.mutex_lock: <NEW_LINE> <INDENT> ret = self._prepare_fabric_fw_internal(tenant_id, fw_dict, is_fw_virt, result) <NEW_LINE> <DEDENT> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> LOG.error("... | Top level routine to prepare the fabric. | 625941e64e696a04525c9895 |
def _parse_raw(self, raw): <NEW_LINE> <INDENT> self.data = raw <NEW_LINE> if not raw: <NEW_LINE> <INDENT> raise NotImplementedError("We cannot instantiate empty resources: %s" % raw) <NEW_LINE> <DEDENT> raw2resource(raw, self, self.tfs) | Parse a raw dictionary to create a resource.
:type raw: Dict[str, Any] | 625941e607d97122c4178cdc |
@pytest.mark.parametrize('tag,message', [ ('vapor/foo:bar', api.V3Tag(namespace='vapor', annotation='foo', label='bar')), ('foo:bar', api.V3Tag(annotation='foo', label='bar')), ('vapor/bar', api.V3Tag(namespace='vapor', label='bar')), ('bar', api.V3Tag(label='bar')), ('', api.V3Tag()), ]) <NEW_LINE> def test_tag_to_mes... | Convert a tag string to the V3Tag message. | 625941e6bd1bec0571d90a76 |
def add_hosts(self, hosts): <NEW_LINE> <INDENT> for line in hosts.strip().splitlines(): <NEW_LINE> <INDENT> ip, host = line.split() <NEW_LINE> self.add_host(host, ip) | 添加多条host记录
:param hosts: `host ip`格式的多行hosts记录
:type hosts: string | 625941e663d6d428bbe44938 |
def sessions(self): <NEW_LINE> <INDENT> sessions = () <NEW_LINE> for session in self.__sessions: <NEW_LINE> <INDENT> sessions += (repr(session),) <NEW_LINE> <DEDENT> return sessions | Get all the session ids that are running | 625941e615fb5d323cde0f5d |
def migrate(belstr: str) -> str: <NEW_LINE> <INDENT> bo.parse(belstr) <NEW_LINE> return migrate_ast(bo.ast).to_string() | Migrate BEL 1 to 2.0.0
Args:
bel: BEL 1
Returns:
bel: BEL 2 | 625941e6c432627299f05091 |
def parse_dota_poly(filename): <NEW_LINE> <INDENT> objects = [] <NEW_LINE> f = [] <NEW_LINE> if sys.version_info >= (3, 5): <NEW_LINE> <INDENT> fd = open(filename, 'r') <NEW_LINE> f = fd <NEW_LINE> <DEDENT> elif sys.version_info >= 2.7: <NEW_LINE> <INDENT> fd = codecs.open(filename, 'r') <NEW_LINE> f = fd <NEW_LINE> <D... | Parse DOTA gound truth in the format:
[(x1, y1), (x2, y2), (x3, y3), (x4, y4)] | 625941e6287bf620b61d3ea8 |
def doctest_typestats_long_type_names(): <NEW_LINE> <INDENT> pass | Test for typestats
>>> _ = gc.collect()
>>> x = type('MyClass', (), {'__module__': 'mymodule'})()
>>> from objgraph import typestats
>>> stats = typestats(shortnames=False)
>>> stats['mymodule.MyClass']
1 | 625941e6442bda511e8be85a |
def set_es_url(self, url): <NEW_LINE> <INDENT> o = urlparse(url) <NEW_LINE> self.es_scheme = o.scheme <NEW_LINE> self.es_host = o.hostname <NEW_LINE> self.es_port = o.port <NEW_LINE> p = o.path.split('/') <NEW_LINE> if len(p) == 2: <NEW_LINE> <INDENT> self.es_index = p[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r... | Parse ES url to extract index name etc. | 625941e6dd821e528d63b5ed |
def proc_every_turn(self, game, start=True): <NEW_LINE> <INDENT> if start: <NEW_LINE> <INDENT> self.statistics.reset_turn() <NEW_LINE> for event in self.every_turn_start: <NEW_LINE> <INDENT> eval(event) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.is_player: <NEW_LINE> <INDENT> self.actionplan.process... | Things that should every proper turn (after player has done an action that prompts an enemy turn.) | 625941e6627d3e7fe0d69299 |
def parse_detail(self, response): <NEW_LINE> <INDENT> node_list = response.xpath("//div[@id='J_goodsList']/ul/li") <NEW_LINE> cnt = 0 <NEW_LINE> print(len(node_list)) <NEW_LINE> for node in node_list: <NEW_LINE> <INDENT> item = JdItem() <NEW_LINE> item['spu_id'] = node.xpath("./@data-spu").extract_first() <NEW_LINE> it... | 提取内容 | 625941e65f7d997b87174ee3 |
def calculate_cell_division_time(current_CDT,alpha): <NEW_LINE> <INDENT> cell_division_max = 180 <NEW_LINE> cell_division_min = 90 <NEW_LINE> CDT_change = 0 <NEW_LINE> if alpha > 0: <NEW_LINE> <INDENT> CDT_change = (current_CDT - cell_division_min)/(cell_division_max - cell_division_min) <NEW_LINE> CDT_change *= alpha ... | Input:
current cell division time of a cell
Fitness effect of the new mutation
Output:
New cell division time calculated based on exisiting cell division time
and fitness effect of the new mutation | 625941e6b57a9660fec33cd2 |
def get_honeypot_ip(self, name): <NEW_LINE> <INDENT> container_details = self._client.inspect_container(name) <NEW_LINE> target_ip = container_details['NetworkSettings']['IPAddress'] <NEW_LINE> return target_ip | Gets the IP address of a running container
:param name: container name
:return: container ip address | 625941e6656771135c3ebcbb |
def vote(self, user, obj, value): <NEW_LINE> <INDENT> if value not in Vote.valid_values: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> vote = self.get(content_object=obj, voted_by=user) <NEW_LINE> if vote.value == value: <NEW_LINE> <INDENT> return vote <NEW_LINE> <DEDENT> <DEDENT> except... | 投票
@param user: 投票人
@param obj: 被投票对象
@param value: 0 为取消投票 | 625941e623e79379d52ee9a6 |
def make_label_combos(label_groups: Dict[str, List[str]]) -> List[str]: <NEW_LINE> <INDENT> copy_label_groups = copy.deepcopy(label_groups) <NEW_LINE> if len(copy_label_groups) == 1: <NEW_LINE> <INDENT> return [item for sublist in copy_label_groups.values() for item in sublist] <NEW_LINE> <DEDENT> anchor_group = sorted... | Make combinations of all possible labels for a supplied dictionary of label groups
:param dict label_groups: Dictionary containing an entry for each label group, where key is the name of the grouping,
e.g. "sex" or "pop", and value is a list of all possible values for that grouping (e.g. ["male", "female"] or ["afr... | 625941e6d7e4931a7ee9e367 |
def _get_node_type_low(self): <NEW_LINE> <INDENT> return (self.node_type & defaults.WLAN_EXP_LOW_MASK) | Get the node type of CPU Low
See defaults.py for a list of CPU Low node types | 625941e68da39b475bd653c1 |
def _broadcast(self): <NEW_LINE> <INDENT> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> try: <NEW_LINE> <INDENT> s.bind((self._ip, self._port)) <NEW_LINE> s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) <NEW_LINE> s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) <NEW_LINE> s.sendto(byte... | Broadcast on udp
| 625941e6fb3f5b602dac3adf |
def ReLU(x): <NEW_LINE> <INDENT> raise NotImplementedError | Computes the threshold of an input using a rectified linear unit. | 625941e62ae34c7f2600d578 |
def sentences(a, b): <NEW_LINE> <INDENT> a = set(sent_tokenize(a, language='english')) <NEW_LINE> b = set(sent_tokenize(b, language='english')) <NEW_LINE> sim_sentences = list(a & b) <NEW_LINE> return sim_sentences | Return sentences in both a and b | 625941e6656771135c3ebcbc |
@register.filter <NEW_LINE> def ListToTableRow(list_items): <NEW_LINE> <INDENT> list_items = [u'<td>%s</td>' % unicode(item) for item in list_items] <NEW_LINE> return u'<tr>%s</tr>' % u''.join(list_items) | Convert a list of items into an HTML table row string. | 625941e6d58c6744b42580a6 |
def getAction(self, gameState): <NEW_LINE> <INDENT> def nextAgent(agent): <NEW_LINE> <INDENT> if agent+1 <= gameState.getNumAgents()-1: <NEW_LINE> <INDENT> return agent+1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> def maxval(state,agent,alpha,beta,depth): <NEW_LINE> <INDENT> if ... | Returns the minimax action using self.depth and self.evaluationFunction | 625941e6a4f1c619b28b0477 |
def libvirt_creds(): <NEW_LINE> <INDENT> g_cmd = 'grep group /etc/libvirt/qemu.conf' <NEW_LINE> u_cmd = 'grep user /etc/libvirt/qemu.conf' <NEW_LINE> group = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0].split('"')[1] <NEW_LINE> user = subprocess.Popen(u_cmd, shell=True, stdout=subprocess... | Returns the user and group that the disk images should be owned by | 625941e6851cf427c661a953 |
def iteritems(self): <NEW_LINE> <INDENT> return six.iteritems(self._as_dict()) | 模拟dict方法. | 625941e656b00c62f0f14aa4 |
def add_requests(self, requests): <NEW_LINE> <INDENT> for request in requests: <NEW_LINE> <INDENT> self.add_request(request) | Add a series of :class:`~chisel.Request` objects to the application.
:param ~collections.abc.Iterable(~chisel.Request) requests: A list of :class:`~chisel.Request` objects. | 625941e68a43f66fc4b544a9 |
def __init__(self, dbconfig=None): <NEW_LINE> <INDENT> if not dbconfig: <NEW_LINE> <INDENT> dbconfig = SafeConfigParser() <NEW_LINE> dbconfig.read("config.ini") <NEW_LINE> <DEDENT> self.connection = sqlalchemy.create_engine( "{type}://{user}:{passwd}@{host}:{port}/{dbname}".format( type=dbconfig.get("database", "type")... | Connect to the database using a config object containing the database
credentials.
If no `configdb` argument is given we use the credentials from the file
`db.ini`
Keyword arguments:
configdb -- a `SafeConfigParser` containing database credentials
(default None) | 625941e6379a373c97cfaf8f |
def is_truetype(self) -> bool: <NEW_LINE> <INDENT> is_tt = wintypes.BOOL() <NEW_LINE> cb = wintypes.DWORD() <NEW_LINE> cb.value = ctypes.sizeof(is_tt) <NEW_LINE> self.gdi32.GetFontResourceInfoW(self.font_path.name, ctypes.byref(cb), ctypes.byref(is_tt), self.GFRI_ISTRUETYPE) <NEW_LINE> return bool(is_tt) | Determines if the installed font is a TrueType font. | 625941e65fdd1c0f98dc067d |
def get_rides(self): <NEW_LINE> <INDENT> connection = self.create_db_connection() <NEW_LINE> ride = Ride() <NEW_LINE> res = ride.get_rides(connection) <NEW_LINE> if res.get('Status'): <NEW_LINE> <INDENT> return {'Status': True, 'Message': res.get('Message')} <NEW_LINE> <DEDENT> return {'Status': False, 'Message': res.g... | Fetch rides from the model. | 625941e69f2886367277acd2 |
def __str__(self): <NEW_LINE> <INDENT> return ( "\n\nThe following column name uses XPath " + "but no query was supplied: " + str(self.value) ) | When the error is raised, print the problematic column name. | 625941e65e10d32532c5f36d |
def __isub__(self, y): <NEW_LINE> <INDENT> pass | x.__isub__(y) <==> x-=y
Returns
-------
out : ndarray | 625941e6a8ecb033257d3514 |
def return_only_one_hour_penalty(pos, event): <NEW_LINE> <INDENT> penalty = 0 <NEW_LINE> curricula = event.curricula <NEW_LINE> for curriculum_id in curricula: <NEW_LINE> <INDENT> curriculum = gi.curricula_dict[curriculum_id] <NEW_LINE> time_slot_list = curriculum.occupied_time_slots <NEW_LINE> current_time_slot = pos[... | This function will look if the specific event is the only one on the day from position
:param pos: This is the specific position
:param event: the specific event
:return: return a penalty if it is the only event in a day for that curriculum | 625941e6283ffb24f3c55d45 |
def detect_test(self, img, waitkey): <NEW_LINE> <INDENT> prediction = self.detect(img) <NEW_LINE> for prediction_ in prediction: <NEW_LINE> <INDENT> coord1 = tuple(map(int, prediction_[:2])) <NEW_LINE> coord2 = tuple(map(int, prediction_[2:4])) <NEW_LINE> cv2.rectangle(img, coord1, coord2, (0, 255, 0), 2) <NEW_LINE> <D... | Args:
img : (ndarray) img matrix from cv2.imread(),
If you want to use plt.imread() or other
RGB format method, ensure to transform
from RGB to BGR, HWC to CHW
waitkey : (int) input for cv2.waitKey()
Returns:
Prediction bounding-boxes | 625941e6711fe17d825427aa |
def __init__(self): <NEW_LINE> <INDENT> self._plugin_cache = collections.defaultdict(dict) <NEW_LINE> self._plugin_config = self._load_config() | Init the caching objects. | 625941e6b7558d58953c5353 |
def make_background_image (self): <NEW_LINE> <INDENT> print ("\n* ** Creating background image...") <NEW_LINE> filename = self.current_path + 'Background.avi' <NEW_LINE> p = util.record_video (filename, 1, 1, self.config.crop_left, self.config.crop_right, self.config.crop_top, self.config.crop_bottom) <NEW_LINE> p.wait... | Create the background video and image.
These are used by the bee
aggregation functions to compute how bees are stopped. The
background video and images are created at start of an experiment
and everytime we change bees. Whenever we change bees, we may
disturb the arena. The bee aggregation is sensitive to changes b... | 625941e65f7d997b87174ee4 |
def link_products(self, request): <NEW_LINE> <INDENT> shopkz_task.delay() <NEW_LINE> return HttpResponseRedirect("../") | Link products | 625941e6187af65679ca5569 |
def test_initialized(self): <NEW_LINE> <INDENT> project_dir = DATACOIN_PATH <NEW_LINE> project = Project(project_dir, create_config_file=True) <NEW_LINE> with project.get_chain('tester') as chain: <NEW_LINE> <INDENT> beneficiary = chain.web3.eth.accounts[3] <NEW_LINE> multisig = chain.web3.eth.accounts[4] <NEW_LINE> ar... | Crowdsale is properly initialized with given parameters. | 625941e67b180e01f3dc4c3d |
def __init__(self, menuHandler): <NEW_LINE> <INDENT> QtWidgets.QWidget.__init__(self) <NEW_LINE> self.MenuR = QtWidgets.QRadioButton(trans.string('PrefsDlg', 12)) <NEW_LINE> self.MenuM = QtWidgets.QRadioButton(trans.string('PrefsDlg', 13)) <NEW_LINE> self.MenuG = QtWidgets.QButtonGroup() <NEW_LINE> self.MenuG.setExclus... | Initializes the General Tab | 625941e699fddb7c1c9de7d7 |
def update_record(values): <NEW_LINE> <INDENT> cursor = db.cursor() <NEW_LINE> row = get_record_by_name(values[0]) <NEW_LINE> row_list = list(row) <NEW_LINE> for i in range(1, 5): <NEW_LINE> <INDENT> row_list[i] += values[i] <NEW_LINE> <DEDENT> row_list.pop(0) <NEW_LINE> row_list.append(values[0]) <NEW_LINE> data = tup... | Updates an existing record, from a tuple (name, w, d, l, pts) | 625941e663f4b57ef0001555 |
def conv_backward_naive(dout, cache): <NEW_LINE> <INDENT> x, w, b, conv_param = cache <NEW_LINE> pad = conv_param['pad'] <NEW_LINE> stride = conv_param['stride'] <NEW_LINE> F, C, HH, WW = w.shape <NEW_LINE> N, C, H, W = x.shape <NEW_LINE> Hp = 1 + (H + 2 * pad - HH) // stride <NEW_LINE> Wp = 1 + (W + 2 * pad - WW) // s... | A naive implementation of the backward pass for a convolutional layer.
Inputs:
- dout: Upstream derivatives.
- cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive
Returns a tuple of:
- dx: Gradient with respect to x
- dw: Gradient with respect to w
- db: Gradient with respect to b | 625941e6be383301e01b58c6 |
def shutdown_server(): <NEW_LINE> <INDENT> func = request.environ.get('werkzeug.server.shutdown') <NEW_LINE> if func is None: <NEW_LINE> <INDENT> raise RuntimeError(logging.error('Not running with the Werkzeug Server')) <NEW_LINE> <DEDENT> func() | shutdown server call
Expects nothing
Returns nothing | 625941e623e79379d52ee9a7 |
def tcl_findprd_safescan(safes, center, session, export=False, noprefix=False, key2mode=False): <NEW_LINE> <INDENT> for j in safes: <NEW_LINE> <INDENT> curef = tcl_findprd_prepcuref(center, j, noprefix, key2mode) <NEW_LINE> print("NOW SCANNING: {0}".format(curef), end="\r") <NEW_LINE> checktext = networkutilstcl.tcl_ch... | Scan for PRDs known not to be in database.
:param safes: List of ends within given range that aren't in database.
:type safes: list(int)
:param center: PRD-center-end.
:type center: str
:param session: Session object.
:type session: requests.Session
:param export: Whether to export XML response to file. Default is ... | 625941e64c3428357757c76e |
def get_connection_string(self, ): <NEW_LINE> <INDENT> raise NotImplementedError() | rief return connection string
| 625941e6cc40096d61595d97 |
def ModGetParty_(self, *args): <NEW_LINE> <INDENT> return _x64dbgapi64.DBGFUNCTIONS_ModGetParty_(self, *args) | ModGetParty_(DBGFUNCTIONS self, duint base) -> int | 625941e6ab23a570cc2505ce |
def __del__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.finalize() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass | Finalize before deletion | 625941e6bde94217f3683235 |
def validate_fields_are_not_empty_in_product(product): <NEW_LINE> <INDENT> fields = { 'product_name', 'generic_name', 'nutriscore_grade', 'url', 'image_url', 'image_nutrition_url', 'categories' } <NEW_LINE> for field in fields: <NEW_LINE> <INDENT> if isinstance(product[field], str) and not product[field].strip(): <NEW_... | Return True if fields wanted are not empty.
If it is return False. | 625941e667a9b606de4a82ff |
def getWatches(self): <NEW_LINE> <INDENT> active = {} <NEW_LINE> cancel = {} <NEW_LINE> vtecTable = self.vtecActiveTable() <NEW_LINE> vtecTable = self._hazUtils._filterVTECBasedOnGFEMode(vtecTable) <NEW_LINE> for v in vtecTable: <NEW_LINE> <INDENT> phenSig = v['phen'] + "." + v['sig'] <NEW_LINE> if not v['phen'] in ['H... | getWatches returns ({activeWatches}, {cancelledWatches}).
The returned records are dictionaries with keys of (phen, sig)
and values of [zoneida, zoneidb,...]. | 625941e6cdde0d52a9e5347e |
def _serialize(self): <NEW_LINE> <INDENT> data, errors = self.__schema__().dump(self) <NEW_LINE> for e in errors: <NEW_LINE> <INDENT> logger.warning("Error serializing for sending to the server: {}".format(str(e))) <NEW_LINE> <DEDENT> return data | The instance validates & serializes itself, returning a dict suitible for json.dumps().
Called from to_server, and from collections to create new server-side entities.
May or may not already have an `id` or __url. | 625941e6e1aae11d1e74a104 |
def GetHandColour(self): <NEW_LINE> <INDENT> return self._handcolour | Gets the hand (arrow indicator) colour. | 625941e682261d6c526ab8ef |
def AlignmentScores(Seq1,Seq2,MatchScore=DEF_MATCH,MismatchScore=DEF_MISMATCH, GapOpen=DEF_GAP,GapExtend=DEF_GAP,SanitizeSeqs=True, **kwargs): <NEW_LINE> <INDENT> if (SanitizeSeqs): <NEW_LINE> <INDENT> Seq1 = Sanitize(Seq1) <NEW_LINE> Seq2 = Sanitize(Seq2) <NEW_LINE> <DEDENT> alignments = pairwise2.align.localms(Seq1,... | Align two sequences locally.
Unit tested implicitly by
TestUtil.TestAlignments.TestReverseComplementAlignment
Args:
Seq1: First Sequence
Seq2: Second Sequence
MatchScore: Amount to add per match
MismatchScore: Amount to add per mismatch. Usually <0
GapOpen : Amount to add per gap Open. Usually <0... | 625941e6be7bc26dc91cda41 |
def get_postal_address(self, nin): <NEW_LINE> <INDENT> rtask = self._get_postal_address.apply_async(args=[nin]) <NEW_LINE> try: <NEW_LINE> <INDENT> rtask.wait() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise self.TaskFailed('Something goes wrong') <NEW_LINE> <DEDENT> if rtask.successful(): <NEW_LINE> <INDENT> re... | The expected address format is:
OrderedDict([
(u'Name', OrderedDict([
(u'@xmlns:xsi', u'http://www.w3.org/2001/XMLSchema-instance'),
(u'GivenNameMarking', u'20'),
(u'GivenName', u'personal name'),
(u'SurName', u'thesurname')
])),
(u'OfficialAd... | 625941e6cdde0d52a9e5347f |
def get_ndbno(self): <NEW_LINE> <INDENT> return self._ndbno | :return: the NDBno of the SearchResult | 625941e63d592f4c4ed1d4aa |
def send_mail(sender, to, subject, message_text): <NEW_LINE> <INDENT> credentials = get_credentials() <NEW_LINE> http = credentials.authorize(httplib2.Http()) <NEW_LINE> service = discovery.build('gmail', 'v1', http=http) <NEW_LINE> message = create_message(sender, to, subject, message_text) <NEW_LINE> response = send_... | Sends an Email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message. | 625941e630bbd722463cc211 |
def _calc_streak(order_numbers, max_order_num): <NEW_LINE> <INDENT> streak = 0 <NEW_LINE> idx = max_order_num <NEW_LINE> for i in reversed(order_numbers): <NEW_LINE> <INDENT> if idx == i: <NEW_LINE> <INDENT> idx -= 1 <NEW_LINE> streak += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT>... | >>> _calc_streak([], 5)
0
>>> _calc_streak([1, 2, 6, 7, 8], 8)
3 | 625941e6b5575c28eb68e44d |
def get_collection_version(): <NEW_LINE> <INDENT> import importlib.util <NEW_LINE> collection_detail_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'tools', 'collection_detail.py') <NEW_LINE> collection_detail_spec = importlib.util.spec_from_file_location('collection_detail', collectio... | Return current collection version, or None if it is not available | 625941e64527f215b584c89b |
def relu(x, alpha=0., max_value=None): <NEW_LINE> <INDENT> negative_part = tf.nn.relu(-x) <NEW_LINE> x = tf.nn.relu(x) <NEW_LINE> if max_value is not None: <NEW_LINE> <INDENT> x = tf.clip_by_value(x, tf.cast(0., dtype=tf.float32), tf.cast(max_value, dtype=tf.float32)) <NEW_LINE> <DEDENT> x -= tf.constant(alpha, dtype=t... | ReLU.
alpha: slope of negative section. | 625941e6a05bb46b383ecc66 |
def encode(self, longUrl): <NEW_LINE> <INDENT> while longUrl not in self.url2code: <NEW_LINE> <INDENT> code = ''.join(random.choice(Codec.alphabet) for _ in xrange(6)) <NEW_LINE> if code not in self.code2url: <NEW_LINE> <INDENT> self.url2code[longUrl] = code <NEW_LINE> self.code2url[code] = longUrl <NEW_LINE> <DEDENT> ... | Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str | 625941e69c8ee82313fbbbbf |
def hex_value(color): <NEW_LINE> <INDENT> return "{:02X}{:02X}{:02X}".format( int(color.redComponent() * 0xFF), int(color.greenComponent() * 0xFF), int(color.blueComponent() * 0xFF), ) | Get hex value of ak.NSColor object | 625941e65510c4643540f822 |
def revoke_all(self, orbit, user_name): <NEW_LINE> <INDENT> table_name = self._services_table(orbit) <NEW_LINE> scan_filter = {'admins': { 'AttributeValueList': [{'S': user_name}], 'ComparisonOperator': 'CONTAINS' }} <NEW_LINE> for region in orbit.regions: <NEW_LINE> <INDENT> dynamodb = self._clients.dynamodb(region) <... | Revoke all access to applications for a user.
:param orbit: Orbit.
:param user_name: User name.
:return: | 625941e68c0ade5d55d3ee07 |
def harvest(self, posx, posy, player): <NEW_LINE> <INDENT> farmtile = self.get_farmtile(posx, posy) <NEW_LINE> if not farmtile["object"]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not farmtile["object"].type == "seed": <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not farmtile['object'].growing ... | Harvest growed seed from farmtile | 625941e63317a56b8693a097 |
@app.route('/api/v1/auth/signup', methods=['POST']) <NEW_LINE> @swag_from('docs/register.yml') <NEW_LINE> def register_a_user(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_data = request.get_json() <NEW_LINE> users_model.register_user(user_data) <NEW_LINE> return jsonify({'message': 'you were successfully regist... | Creates a new user account | 625941e626068e7796caf12e |
def upload_dataset(bucket_name, directory, num_threads=20): <NEW_LINE> <INDENT> s3 = boto3.resource('s3') <NEW_LINE> def upload_file(queue): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> obj = queue.get() <NEW_LINE> if obj is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> abspath, s3_path = obj <NEW_LINE> s3... | Recursively uploads a directory to S3
Args:
bucket_name (str): the name of the S3 bucket to upload to
directory (str): the absolute path of a directory whose contents
should be uploaded to S3; the directory name is used as the S3
prefix for all uploaded files
num_threads (int, optional): De... | 625941e6cc40096d61595d98 |
def setup_bot_data(bot_name, logger): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not isdir(BOT_FOLDER): <NEW_LINE> <INDENT> logger("Setting up root bot folder") <NEW_LINE> mkdir(BOT_FOLDER) <NEW_LINE> <DEDENT> if not isdir(join(BOT_FOLDER, bot_name)): <NEW_LINE> <INDENT> logger("Setting up {} data folder".format(b... | Set up the bot data folder in the root location
If it can't create the folders, return False
else return True (so our bot can continue) | 625941e6bde94217f3683236 |
def write(self, cr, uid, ids, vals, context=None): <NEW_LINE> <INDENT> not_main_ids = self.search( cr, uid, [('is_main', '=', False), ('id', 'in', ids)], context=context) <NEW_LINE> res = super(postal_coordinate, self).write( cr, uid, ids, vals, not_main_ids=not_main_ids, context=context) <NEW_LINE> if vals.get('is_mai... | call `_update_partner_int_instance` if `is_main` is True | 625941e6a79ad161976cc58e |
def u(a, t): <NEW_LINE> <INDENT> a = np.atleast_1d(a) <NEW_LINE> t = np.atleast_1d(t) <NEW_LINE> return self.u_PTPB(a,t)[0, 0] | wrapper for self.u_PTPB for scalar args | 625941e663b5f9789fde752f |
def glGetProgramiv(*argv): <NEW_LINE> <INDENT> pass | no string
| 625941e631939e2706e4d2ad |
def map_to_lengths_for(words): <NEW_LINE> <INDENT> lengths = [ ] <NEW_LINE> for word in words: <NEW_LINE> <INDENT> lengths. append (len(word)) <NEW_LINE> return lengths | Write a program that maps a list of words into a list of integers
representing the lengths of the corresponding words. | 625941e6a219f33f34628dad |
def inverse(self): <NEW_LINE> <INDENT> real = self.real/self.magnitude() <NEW_LINE> pure = -self.pure/self.magnitude() <NEW_LINE> return Quaternion((real,pure)) | Get the multiplicative inverse of a quaternion | 625941e61d351010ab855f64 |
def _int0oo(g1, g2, x): <NEW_LINE> <INDENT> eta, _ = _get_coeff_exp(g1.argument, x) <NEW_LINE> omega, _ = _get_coeff_exp(g2.argument, x) <NEW_LINE> def neg(l): <NEW_LINE> <INDENT> return [-x for x in l] <NEW_LINE> <DEDENT> a1 = neg(g1.bm) + list(g2.an) <NEW_LINE> a2 = list(g2.aother) + neg(g1.bother) <NEW_LINE> b1 = ne... | Express integral from zero to infinity g1*g2 using a G function,
assuming the necessary conditions are fulfilled.
Examples
========
>>> from sympy.integrals.meijerint import _int0oo
>>> from sympy.abc import s, t, m
>>> from sympy import meijerg, S
>>> g1 = meijerg([], [], [-S(1)/2, 0], [], s**2*t/4)
>>> g2 = meijerg... | 625941e62eb69b55b151ccfe |
def tr(self, message): <NEW_LINE> <INDENT> return QCoreApplication.translate('IDECanarias', message) | Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString | 625941e645492302aab5e711 |
def get_body_fields(self): <NEW_LINE> <INDENT> return [self.FIELD_SENDER_ID] | Get which fields should be packed in body | 625941e66fece00bbac2db8d |
def __init__(self, driver, comp_name): <NEW_LINE> <INDENT> self.driver = driver <NEW_LINE> self.comp_name = comp_name <NEW_LINE> self.element = self.get_component() | 类初始化执行 | 625941e68da39b475bd653c2 |
def deallocate_for_instance(self, context, **kwargs): <NEW_LINE> <INDENT> read_deleted_context = context.elevated(read_deleted='yes') <NEW_LINE> if 'instance' in kwargs: <NEW_LINE> <INDENT> instance = kwargs['instance'] <NEW_LINE> instance_uuid = instance.uuid <NEW_LINE> host = instance.host <NEW_LINE> <DEDENT> else: <... | Handles deallocating various network resources for an instance.
rpc.called by network_api
kwargs can contain fixed_ips to circumvent another db lookup | 625941e650485f2cf553d1e5 |
def FormatColour(colour): <NEW_LINE> <INDENT> if isinstance(colour, (list, tuple)): <NEW_LINE> <INDENT> colour = wx.Colour(*colour) <NEW_LINE> <DEDENT> elif isinstance(colour, basestring): <NEW_LINE> <INDENT> colour = wx.NamedColour(colour) <NEW_LINE> <DEDENT> return colour | Convert the input `colour` into a valid :class:`Colour` instance, using whatever typemap
accepted by wxWidgets/wxPython.
:param `colour`: can be an instance of :class:`Colour`, a 3 or 4 integer tuple, a hex
string, a string representing the colour name or ``None``.
:returns: a valid instance of :class:`Colour` or ``... | 625941e6f9cc0f698b140a41 |
def __init__(self, url, connection, initialize=False): <NEW_LINE> <INDENT> super(UsageReports, self).__init__(url, connection, initialize) <NEW_LINE> if url.lower().endswith('/usagereports'): <NEW_LINE> <INDENT> self._url = url <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._url = url + "/usagereports" <NEW_LINE> <... | Constructor | 625941e676e4537e8c351abf |
def test_many_parens_invalid(self): <NEW_LINE> <INDENT> assert not it_parses('(force (field)') <NEW_LINE> assert not it_parses('((') <NEW_LINE> assert not it_parses('())()(()(()())())))(') <NEW_LINE> assert not it_parses('(laser AND (beams OR tractor:beams) NOT (field:one field:two)') <NEW_LINE> assert not it_parses('w... | When there are many ( and ) in an invalid query. | 625941e6a05bb46b383ecc67 |
def _add_output_pin(self, output_pin): <NEW_LINE> <INDENT> pin_name = output_pin.pin_name <NEW_LINE> self._output_pins[pin_name] = output_pin | Add an output pin to the collection
:param output_pin: A reference to the output pin to be added
:return: None | 625941e6a4f1c619b28b0478 |
def setup_init(self): <NEW_LINE> <INDENT> if self.pipeline: del(self.pipeline) <NEW_LINE> self.pipeline = Gst.Pipeline() <NEW_LINE> file = Gst.ElementFactory.make("filesrc", "espeak") <NEW_LINE> wavparse = Gst.ElementFactory.make("wavparse", "wavparse") <NEW_LINE> audioconvert = Gst.ElementFactory.make("audioconvert", ... | Construye el pipe Gst. | 625941e6be8e80087fb21086 |
def set_installed_apps(self, apps): <NEW_LINE> <INDENT> apps = list(apps) <NEW_LINE> if apps: <NEW_LINE> <INDENT> assert isinstance(apps[0], basestring), "The argument to set_installed_apps must be a list of strings." <NEW_LINE> <DEDENT> settings.INSTALLED_APPS, settings.OLD_INSTALLED_APPS = ( apps, settings.INSTALLED_... | Sets Django's INSTALLED_APPS setting to be effectively the list passed in. | 625941e655399d3f05588b00 |
def create_index(self, *fields): <NEW_LINE> <INDENT> reset = False <NEW_LINE> for f in fields: <NEW_LINE> <INDENT> if f not in self.fields: <NEW_LINE> <INDENT> raise NameError("%s is not a field name %s" % (f, self.fields)) <NEW_LINE> <DEDENT> if self.mode == "open" and f in self.indices: <NEW_LINE> <INDENT> continue <... | Create an index on the specified field names
An index on a field is a mapping between the values taken by the field
and the sorted list of the ids of the records whose field is equal to
this value
For each indexed field, an attribute of self is created, an instance
of the class Index (see above). Its name it the fiel... | 625941e6460517430c3945c3 |
def mse(mask_output, output, get_sigmoid=False): <NEW_LINE> <INDENT> if get_sigmoid: <NEW_LINE> <INDENT> mask_output = torch.sigmoid(mask_output) <NEW_LINE> output = torch.sigmoid(output) <NEW_LINE> <DEDENT> return (mask_output - output).pow(2).sum(dim=1) | Function that measures mse-loss divergence between target and output logits: | 625941e6de87d2750b8601e0 |
def login(self, environ, start_response, success_to=None, fail_to=None, msg=''): <NEW_LINE> <INDENT> self.title = "OpenID Login" <NEW_LINE> self.heading = "Login" <NEW_LINE> self.success_to = success_to or self.urls['url_mainpage'] <NEW_LINE> self.fail_to = fail_to or self.urls['url_mainpage'] <NEW_LINE> self.xml = msg... | Set-up template for OpenID Provider Login | 625941e607d97122c4178cdf |
def __init__( self, infile ): <NEW_LINE> <INDENT> f=open(infile,"rb",buffering=81920) <NEW_LINE> self.filename=infile <NEW_LINE> self.f=f <NEW_LINE> l=[] <NEW_LINE> for b in f: <NEW_LINE> <INDENT> l.append(b) <NEW_LINE> s=b.decode() <NEW_LINE> if "[LISTDATA]" in s: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT>... | initialise class instance
infile: path to lst file | 625941e63eb6a72ae02ec932 |
def test_labels(self): <NEW_LINE> <INDENT> i = self.instance.labels() <NEW_LINE> self.get_next(i) <NEW_LINE> self.session.get.assert_called_once_with( url_for("labels"), params={"per_page": 100}, headers={ "Accept": "application/vnd.github.symmetra-preview+json" }, ) | Test the ability to iterate over a repository's labels. | 625941e6566aa707497f49ac |
def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> request = self._init_req(request) <NEW_LINE> self.headers = self.default_response_headers <NEW_LINE> try: <NEW_LINE> <INDENT> self.initial(request, *args, **kwargs) <NEW_LINE> handler = getattr(self, self._req_method, self.http_method_not_allowed) ... | `.dispatch()` is pretty much the same as Django_Rest's regular dispatch,
but with extra hooks for filtering, extracting, and pagination. | 625941e6627d3e7fe0d6929b |
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, CreateCartResponse): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | Returns true if both objects are not equal | 625941e6b830903b967e9d50 |
def _on_manual_install_clicked(self): <NEW_LINE> <INDENT> self._set_current_state_to_searching() <NEW_LINE> exiftoolinst.browser_launches_exiftool_homepage() <NEW_LINE> self._detect_current_state() | Send the user to the exiftool website for manual download.
They will have to set the path manually afterward. | 625941e65f7d997b87174ee5 |
def run_exe(exe_path, args): <NEW_LINE> <INDENT> popen_cmd = [exe_path] + args <NEW_LINE> proc = subprocess.Popen(popen_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) <NEW_LINE> proc_stdout, _ = proc.communicate() <NEW_LINE> return proc.returncode, proc_stdout | Runs the given executable as a subprocess, given the
list of arguments. Captures its return code (rc) and stdout and
returns a pair: rc, stdout_str | 625941e671ff763f4b549add |
def computeQValueFromValues(self, state, action): <NEW_LINE> <INDENT> Q_value = self.values[state] <NEW_LINE> for trans_state, prob in self.mdp.getTransitionStatesAndProbs(state,action): <NEW_LINE> <INDENT> Q_value += self.discount * prob * self.values[trans_state] <NEW_LINE> <DEDENT> return Q_value <NEW_LINE> util.rai... | Compute the Q-value of action in state from the
value function stored in self.values. | 625941e6fff4ab517eb2f888 |
def removeRecent(self, server): <NEW_LINE> <INDENT> Log.log.debug('[GuiController] removeRecent called for server with ' + 'adress ' + server.getaddress()) <NEW_LINE> fm = FileManager() <NEW_LINE> fm.removeRecentServer(server) | Removes a server from the list of recent servers
@param server - server to be removed | 625941e6aad79263cf390e91 |
def check_valid(self): <NEW_LINE> <INDENT> pattern = '^(?:4\d{3}|5\d{3}|6\d{3})\-(?:\d{4})\-(?:\d{4})\-(?:\d{4})|^(?:4\d{15}|5\d{15}|6\d{15})' <NEW_LINE> p = re.compile(pattern) <NEW_LINE> if len(self.number) > 1: <NEW_LINE> <INDENT> if p.match(self.number): <NEW_LINE> <INDENT> self.number = self.number.replace('-', ''... | Check if the number is valid following patterns.
► It must start with a 4, 5 or 6.
► It must contain exactly 16 digits.
► It must only consist of digits (0-9).
► It may have digits in groups of 4, separated by one hyphen "-".
► It must NOT use any other separator like ' ' , '_', etc.
► It must NOT have 4 or more consec... | 625941e607f4c71912b118ce |
def define_table(self): <NEW_LINE> <INDENT> raise NotImplementedError() | Subclasses must implement this and define the database table | 625941e60c0af96317bb8631 |
def get_altitude(latitude_deg, longitude_deg, when, elevation = 0, temperature = constants.standard_temperature, pressure = constants.standard_pressure): <NEW_LINE> <INDENT> projected_radial_distance = get_projected_radial_distance(elevation, latitude_deg) <NEW_LINE> projected_axial_distance = get_projected_axial_dista... | See also the faster, but less accurate, get_altitude_fast() | 625941e63617ad0b5ed68340 |
def mdefs_c(Kp, K, chiL, chiS, z, *cparams): <NEW_LINE> <INDENT> L = 24 - Nbar - Sbar <NEW_LINE> d = 2*np.arctan(phi*Sbar+xi)/np.pi <NEW_LINE> b = kappa*Sbar**eta <NEW_LINE> Y = A*np.exp(z)*K**alpha*(b*Nbar)**(1-alpha) <NEW_LINE> w = (1-alpha)*Y/(b*Nbar) <NEW_LINE> r = alpha*Y/K <NEW_LINE> C = w*b*Nbar + (1+r-delta)*K ... | This function calculates definitions given the state and jump
variables along with the model parameters.
Parallel to mdefs, but takes chiL and chiS as variables and treats
Nbar and Sbar as parameters. | 625941e62c8b7c6e89b35c07 |
def can_preview(file): <NEW_LINE> <INDENT> return file.is_local() and file.has_extensions( *[f".{ext}" for ext in previewable_extensions] ) | Determine if file can be previewed. | 625941e6656771135c3ebcbe |
def redraw(self): <NEW_LINE> <INDENT> turtle.clear() <NEW_LINE> self.setworldcoordinates() <NEW_LINE> self.draw_grid() <NEW_LINE> for tables, kwargs in self.tables: <NEW_LINE> <INDENT> self.plot_table(*tables, draw_speed=1024, **kwargs) | Clear plot and draw grid lines | 625941e601c39578d7e75285 |
def _report(self, r, widget, **attr): <NEW_LINE> <INDENT> s3db = current.s3db <NEW_LINE> context = widget.get("context", None) <NEW_LINE> tablename = widget.get("tablename", None) <NEW_LINE> resource, context = self._resolve_context(r, tablename, context) <NEW_LINE> table = resource.table <NEW_LINE> get_config = resour... | Generate a Report widget
@param r: the S3Request instance
@param widget: the widget as a tuple: (label, type, icon)
@param attr: controller attributes for the request | 625941e638b623060ff0b237 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.