code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_method(method, testspecs, testfunc): <NEW_LINE> <INDENT> log("testing %s ...", method) <NEW_LINE> stat = defaultdict(int) <NEW_LINE> for spec in testspecs: <NEW_LINE> <INDENT> if 'samples' in spec: <NEW_LINE> <INDENT> spec['prec'] = sorted(random.sample(range(1, 101), spec['samples'])) <NEW_LINE> <DEDENT> for ...
Iterate a test function through many context settings.
625941f1fb3f5b602dac3c41
def size(self, w = None, h = None): <NEW_LINE> <INDENT> if not w: <NEW_LINE> <INDENT> w = self._canvas.width <NEW_LINE> <DEDENT> if not h: <NEW_LINE> <INDENT> h = self._canvas.height <NEW_LINE> <DEDENT> if not w and not h: <NEW_LINE> <INDENT> return (self._canvas.width, self._canvas.height) <NEW_LINE> <DEDENT> w, h = s...
Sets the size of the canvas, and creates a Cairo surface and context. Only the first call will actually be effective.
625941f14f6381625f114fe3
def initialize_parameters_deep(layer_dims): <NEW_LINE> <INDENT> np.random.seed(3) <NEW_LINE> parameters = {} <NEW_LINE> L = len(layer_dims) <NEW_LINE> for l in range(1, L): <NEW_LINE> <INDENT> parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l - 1]) * 0.01 <NEW_LINE> parameters['b' + str(l)] = np.ze...
Arguments: layer_dims -- python array (list) containing the dimensions of each layer in our network Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1]) bl -- bias vector of shape (...
625941f1dc8b845886cb5adf
def depth_limited_search(problem, limit=50): <NEW_LINE> <INDENT> def recursive_dls(node, problem, limit): <NEW_LINE> <INDENT> if problem.goal_test(node.state): <NEW_LINE> <INDENT> return node <NEW_LINE> <DEDENT> elif node.depth == limit: <NEW_LINE> <INDENT> return 'cutoff' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ...
[Fig. 3.17]
625941f1d99f1b3c44c67b2c
@register.filter <NEW_LINE> def check_favorite(user, obj): <NEW_LINE> <INDENT> return get_fav(obj, user)
check if the user has already favorited ( user|check_favorite:item )
625941f182261d6c526aba50
def moveChildNodes(db, olddn, newdn): <NEW_LINE> <INDENT> reslist = db.conn.search_s(olddn,ldap.SCOPE_ONELEVEL) <NEW_LINE> for dn,att in reslist: <NEW_LINE> <INDENT> child = db.norm_dn(dn).split(',',1)[0] <NEW_LINE> modlist = ldap.modlist.addModlist(att) <NEW_LINE> db.conn.add_s(child + ',' + newdn,modlist) <NEW_LINE> ...
recursively move all childs from olddn to newdn.
625941f1596a89723608a060
def close_serial_port(self): <NEW_LINE> <INDENT> print("Closing Serial Port") <NEW_LINE> try: <NEW_LINE> <INDENT> if self._serial.isOpen(): <NEW_LINE> <INDENT> self._serial.close() <NEW_LINE> print("Serial Port closed...") <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> print("Error: Unable to close the Serial...
Closes the serial port attached to the modem.
625941f191f36d47f21acaa1
def start_nodes(self, extra_args=None, *args, **kwargs): <NEW_LINE> <INDENT> if extra_args is None: <NEW_LINE> <INDENT> extra_args = [None] * self.num_nodes <NEW_LINE> <DEDENT> assert_equal(len(extra_args), self.num_nodes) <NEW_LINE> try: <NEW_LINE> <INDENT> for i, node in enumerate(self.nodes): <NEW_LINE> <INDENT> nod...
Start multiple Actiniumds
625941f13317a56b8693a1f2
def get_cpu_temperature(): <NEW_LINE> <INDENT> t_file = open('/sys/class/thermal/thermal_zone0/temp') <NEW_LINE> temp = float(t_file.read()) <NEW_LINE> return temp / 1000
Read the temperature of the CPU returned in degrees Celsius
625941f1656771135c3ebe1e
def generate_phrase(n): <NEW_LINE> <INDENT> with open('/usr/share/dict/words') as f: <NEW_LINE> <INDENT> words = [word.strip() for word in f] <NEW_LINE> return ' '.join(choice(words) for i in range(n))
Generates an n word passphrase a la XKCD
625941f1baa26c4b54cb16c1
def get_named_ref(commit: git.Commit) -> str: <NEW_LINE> <INDENT> _hexsha, name = commit.name_rev.split(" ") <NEW_LINE> return remove_prefix(name, "remotes/")
Get a user-friendly named ref for the commit.
625941f199cbb53fe679318c
def suspended(self, job): <NEW_LINE> <INDENT> pass
void KUiServerJobTracker.suspended(KJob job)
625941f1ab23a570cc25072f
def PublicObject_Find(publicID): <NEW_LINE> <INDENT> return _DataModel.PublicObject_Find(publicID)
PublicObject_Find(std::string const & publicID) -> PublicObject
625941f18e71fb1e9831dd4f
def test_cur_timestamp(self): <NEW_LINE> <INDENT> dropall_and_create() <NEW_LINE> ins_doc = Document(type='article') <NEW_LINE> insert(ins_doc) <NEW_LINE> ins_doc_id = ins_doc.doc_id <NEW_LINE> sel_timestamp = select(Document.created, Document.doc_id == ins_doc_id).fetchone()[0] <NEW_LINE> self.assertLess(math.fabs(dat...
working with timestamp
625941f1cad5886f8bd27580
def _decrease_indent(self): <NEW_LINE> <INDENT> if self._indent == 0: <NEW_LINE> <INDENT> raise AssertionError("Cannot decrease indentation any more") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._indent -= 1
Decreases the current indentation of self :return: None
625941f1dd821e528d63b74c
def __init__(self, matrix): <NEW_LINE> <INDENT> if not matrix or not matrix[0]: <NEW_LINE> <INDENT> self.sum = None <NEW_LINE> return <NEW_LINE> <DEDENT> h, w = len(matrix), len(matrix[0]) <NEW_LINE> self.sum = [[0] * w for i in range(h)] <NEW_LINE> for i in range(h): <NEW_LINE> <INDENT> tmp = 0 <NEW_LINE> for j in ran...
:type matrix: List[List[int]]
625941f1bde94217f3683394
def do_log(self, line): <NEW_LINE> <INDENT> if self.logger != None: <NEW_LINE> <INDENT> nhandlers = len(logging.getLogger("RepTate").handlers) <NEW_LINE> logfilename = "" <NEW_LINE> if nhandlers > 0: <NEW_LINE> <INDENT> print(Fore.RED + "%15s %10s" % ("Log Handler", "Level")) <NEW_LINE> print(26 * "=" + Fore.RESET) <NE...
Info about the logger
625941f1e1aae11d1e74a265
def setup(app): <NEW_LINE> <INDENT> app.add_config_value('collections', {}, 'html') <NEW_LINE> app.add_config_value('collections_target', '_collections', 'html') <NEW_LINE> app.add_config_value('collections_clean', True, 'html') <NEW_LINE> app.add_config_value('collections_final_clean', True, 'html') <NEW_LINE> app.con...
Configures Sphinx Registers: * config values * receivers for events * directives
625941f1fb3f5b602dac3c42
def _submit_to_queue(self, script_file): <NEW_LINE> <INDENT> if sys.version_info[0] < 3: <NEW_LINE> <INDENT> process = Popen(['qsub', script_file], stdout=PIPE, stderr=PIPE) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> process = Popen(['qsub', script_file], stdout=PIPE, stderr=PIPE, universal_newlines=True) <NEW_LINE>...
Submit a job script to the queue.
625941f18a43f66fc4b54607
def bandwidth_resources_transition(G, u, r): <NEW_LINE> <INDENT> sum_bt = 0 <NEW_LINE> for v in G.neighbors(u): <NEW_LINE> <INDENT> sum_bt = sum_bt + bandwidth_resource(G, u, v)*1.00 / adjacent_bandwidth_resources(G, v)* r[v] <NEW_LINE> <DEDENT> return sum_bt
Bandwidth resource transition in numberal form *** Warning *** This function should multiple r(v) in order to calculate r(u) in numberal form. This is only used in numberal case, not in matrix case Calculate and sum each path adjacent node u 's weight among u's neighbour's adjacent paths Input: G: the graph u...
625941f1adb09d7d5db6cd34
def __init__(self, **kwargs): <NEW_LINE> <INDENT> top.Service.__init__(self, db=kwargs.get('db'), comms_dir=kwargs.get('comms_dir')) <NEW_LINE> if kwargs.get('notification_delay') is not None: <NEW_LINE> <INDENT> self.set_notification_delay(kwargs.get('notification_delay')) <NEW_LINE> <DEDENT> if kwargs.get('hold_perio...
:class:`top.Reminder` initialisation.
625941f123e79379d52eeb04
def DJANGO_WE_USERINFO_COOKIE_FUNC(code, state, access_info=None, userinfo=None): <NEW_LINE> <INDENT> from django.conf import settings <NEW_LINE> from utils.user.userinfo_save import userinfo_save <NEW_LINE> user = userinfo_save(userinfo) <NEW_LINE> token_check_key = getattr(user, settings.TOKEN_CHECK_KEY) <NEW_LINE> r...
WeChat Userinfo Set Cookie Redirect Callback Func
625941f1d268445f265b5417
def read(self, num_bytes): <NEW_LINE> <INDENT> while len(self.decoded) < num_bytes: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tag, data = next(self.chunks) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> raise EOFError() <NEW_LINE> <DEDENT> if tag != b'IDAT': <NEW_LINE> <INDENT> continue <NEW_LINE> <DE...
Read `num_bytes` from the compressed data chunks. Data is returned as `bytes` of length `num_bytes` Will raise an EOFError if data is unavailable. Note: Will always return `num_bytes` of data (unlike the file read method).
625941f1956e5f7376d71414
def Paulson_m(x): <NEW_LINE> <INDENT> return np.pi/2 - 2*np.arctan(x) + np.log((1+x)**2 * (1 + x**2) / 8)
Momentum similarity function for unstable conditions Ref: Paulson, C.A., 1970: The mathematical representation of wind speed and temperature in the unstable atmospheric surface layer. J. Appl. Meteor., 9, 857-861.
625941f107d97122c4178e42
@app.route("/nsi/connections", methods=['DELETE']) <NEW_LINE> def delete_last_connection(): <NEW_LINE> <INDENT> app.logger.debug(LOGGER_INTRO) <NEW_LINE> app.logger.info("Deleting last connection") <NEW_LINE> try: <NEW_LINE> <INDENT> nsi.release(LAST_RESERVATION) <NEW_LINE> nsi.terminate(LAST_RESERVATION) <NEW_LINE> <D...
Delete lastly created connection or its reservation (for testing purposes only)
625941f15f7d997b87175045
def __getattr__(self, name): <NEW_LINE> <INDENT> from .transformations import master_transform_graph <NEW_LINE> nmsys = master_transform_graph.lookup_name(name) <NEW_LINE> if self.__class__ is nmsys: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> if nmsys is not None and self.is_transformable_to(nmsys): <NEW_LINE>...
Overrides getattr to return coordinates that this can be transformed to, based on the alias name in the master transform graph.
625941f1d6c5a102081445f8
def combine_dicts(a, b, op=operator.add): <NEW_LINE> <INDENT> return dict(a.items() + b.items() + [(k, op(a[k], b[k])) for k in set(b) & set(a)])
Helper:Combines dictionaries that will enable us to flatten data structure appropriately :param dict a: first of the dictionaries we want to merge :param dict a: second of the dictionaries we want to merge
625941f1a8370b7717052e46
def onCloseWindow(self, evt): <NEW_LINE> <INDENT> self.Destroy()
Close the window and reset the gv parameters.
625941f1507cdc57c6307291
def _set_strand(self, value): <NEW_LINE> <INDENT> if value not in [+1, -1, 0, None]: <NEW_LINE> <INDENT> raise ValueError(f"Strand should be +1, -1, 0 or None, not {value!r}") <NEW_LINE> <DEDENT> self._strand = value
Set function for the strand property (PRIVATE).
625941f1287bf620b61d4008
def get_catalogue(): <NEW_LINE> <INDENT> input_txt = input('Enter the path to directory:\n').strip() <NEW_LINE> input_lst = input_txt.split() <NEW_LINE> two_flag = False <NEW_LINE> if len(input_lst) == 2 and input_lst[1] == '--two': <NEW_LINE> <INDENT> two_flag = True <NEW_LINE> <DEDENT> dir_path = os.path.abspath(inpu...
Reades fit-files and *._cat.csv in the folder dir_path. Produces astrometric calibration over the fit-files. Produces photometry over the fits-files in the SExtractor software. Produces a compilation catalogue of objects from data received after processing in the SExtractor software. Produces a correlation analysis of ...
625941f1377c676e9127274f
def process(self) -> bool: <NEW_LINE> <INDENT> self._post.comment_sort = "top" <NEW_LINE> self._post.comments.replace_more(limit=None) <NEW_LINE> return self.browse_comments(self._post, [self._post])
Check for answers in the comments and delete wrong comments
625941f1fbf16365ca6f6779
def get_design_data_coh_vs_all(coh_name: str) -> pd.DataFrame: <NEW_LINE> <INDENT> dsn_cohs = pickle.load(open(design_data_root+'dsn_cohs_%s.obj' % time_to_use, 'rb')) <NEW_LINE> dsn_docs = pickle.load(open(design_data_root+'dsn_docs_%s.obj' % time_to_use, 'rb')) <NEW_LINE> coh_seq = dsn_cohs[coh_name] <NEW_LINE> df_ =...
:return: goes over all designed coh-doc pairs and returns a DF similar to the one used to create the decision tree
625941f1283ffb24f3c55ea3
def splitDataPerYear_sat( data , year ): <NEW_LINE> <INDENT> globals()['data_satisfied'+str(year)] = data[data["Ano"] == str(year)].where(data['Código Resposta'] == 1, inplace = False) <NEW_LINE> globals()['data_satisfied'+str(year)].dropna(inplace = True) <NEW_LINE> globals()['data_satisfied'+str(year)].where(globals(...
Function to split the data per year and filter for unsatisfied and where the comments did not have "NAO SE APLICA". Input: a dataframe with unfiltered data a list of years Output: Datasets per year
625941f11d351010ab8560c3
def setProgress(self, progress): <NEW_LINE> <INDENT> self.progress = progress
Set the progress instance to use. Usually one of rios.cuiprogress.* Default is silent progress
625941f107f4c71912b11a2d
def buscar_avatar(usuario): <NEW_LINE> <INDENT> url = f'https://api.github.com/users/{usuario}' <NEW_LINE> resp = requests.get(url) <NEW_LINE> return resp.json()['avatar_url']
Busca o avatar de um usuário no Github :param usuario: str com o nome de usuário no github :return: str com o link do avatar
625941f176d4e153a657f0db
def __init__(self): <NEW_LINE> <INDENT> self.elements = deque()
Init queue.
625941f1a79ad161976cc6ee
def test_valid_docs(self): <NEW_LINE> <INDENT> docs = self.run_function('sys.doc') <NEW_LINE> nodoc = set() <NEW_LINE> noexample = set() <NEW_LINE> allow_failure = ( 'cp.recv', 'pkg.expand_repo_def', 'runtests_decorators.depends', 'runtests_decorators.depends_will_fallback', 'runtests_decorators.missing_depends', 'runt...
Make sure no functions are exposed that don't have valid docstrings
625941f166656f66f7cbc755
def delete_block(self, name): <NEW_LINE> <INDENT> if name in self.saved_pulse_blocks: <NEW_LINE> <INDENT> del(self._saved_pulse_blocks[name]) <NEW_LINE> <DEDENT> filepath = os.path.join(self._assets_storage_dir, '{0}.block'.format(name)) <NEW_LINE> if os.path.exists(filepath): <NEW_LINE> <INDENT> os.remove(filepath) <N...
Remove the serialized object "name" from the block list and HDD. @param name: string, name of the PulseBlock object to be removed.
625941f1ad47b63b2c50a528
def QFT(Qcircuit, inverse=False): <NEW_LINE> <INDENT> qc = Qcircuit[0] <NEW_LINE> qr = Qcircuit[1] <NEW_LINE> cr = Qcircuit[2] <NEW_LINE> n_qubits = Qcircuit[3] <NEW_LINE> if not inverse: <NEW_LINE> <INDENT> for i in range(n_qubits): <NEW_LINE> <INDENT> qc.h(qr[i]) <NEW_LINE> for j in range(i+1,n_...
_________________________ Quantum Fourier Transform _________________________ Input: Qcircuit = [qc,qr,cr,n] - qc -> Quantum circuit object - qr -> Quantum register object - cr -> Classical register object - n -> Number of qubits inverse: True,False Output:...
625941f12eb69b55b151ce60
def do_GET(self): <NEW_LINE> <INDENT> termcolor.cprint(self.requestline, 'green') <NEW_LINE> contents = "I am the happy server! :-)" <NEW_LINE> self.send_response(200) <NEW_LINE> self.send_header('Content-Type', 'text/plain') <NEW_LINE> self.send_header('Content-Length', len(contents.encode())) <NEW_LINE> self.end_head...
This method is called whenever the client invokes the GET method in the HTTP protocol request
625941f126238365f5f0f41e
def test_tools_json(self): <NEW_LINE> <INDENT> self.base_test_json(dumps(SAMPLE_TOOL_HASH))
Test the hash portion using base object method.
625941f1cb5e8a47e48b8049
def do_GET(self): <NEW_LINE> <INDENT> if self.path == '/': <NEW_LINE> <INDENT> self.send_response(200) <NEW_LINE> self.send_header("Content-type", "text/html") <NEW_LINE> self.end_headers() <NEW_LINE> self.wfile.write("<html><head>" "<title>Escher map</title>" "</head><body>\n") <NEW_LINE> self.wfile.write(html) <NEW_L...
Respond to a GET request.
625941f11f037a2d8b9467a5
def first_word(text: str) -> str: <NEW_LINE> <INDENT> return text.replace(".", " ").replace(",", " ").strip().split()[0]
returns the first word in a given text.
625941f14428ac0f6e5bada0
def _instrument(self, **kwargs): <NEW_LINE> <INDENT> tracer_provider = kwargs.get("tracer_provider") <NEW_LINE> dbapi.wrap_connect( __name__, psycopg2, "connect", self._DATABASE_COMPONENT, self._DATABASE_TYPE, self._CONNECTION_ATTRIBUTES, version=__version__, tracer_provider=tracer_provider, )
Integrate with PostgreSQL Psycopg library. Psycopg: http://initd.org/psycopg/
625941f18a349b6b435e871b
@pytest.fixture <NEW_LINE> def register_all_plain(scope="module"): <NEW_LINE> <INDENT> pylatest.xdocutils.core.register_all(use_plain=True)
Register pylatest docutils extensions (nodes, directives ... but no transforms).
625941f199fddb7c1c9de936
def printMatrix(matrix): <NEW_LINE> <INDENT> if matrix is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> ret = [] <NEW_LINE> while matrix: <NEW_LINE> <INDENT> ret.extend(matrix.pop(0)) <NEW_LINE> if matrix and matrix[0]: <NEW_LINE> <INDENT> for row in matrix: <NEW_LINE> <INDENT> ret.append(row.pop()) <NEW_LI...
matrix是一个二维的list,是一个矩阵,需要返回逆时针遍历这个矩阵的数值 例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. 这个方法会将原始的matrix消解掉
625941f1c432627299f051f3
def separateCSV(smhi, frm, wid): <NEW_LINE> <INDENT> to = frm + wid <NEW_LINE> smhi_a = smhiCSV() <NEW_LINE> smhi_b = smhiCSV() <NEW_LINE> length = len(smhi.data) <NEW_LINE> smhi_a.header = smhi.header[0:frm] <NEW_LINE> for row in smhi.data: <NEW_LINE> <INDENT> smhi_a.data.append(row[0:frm]) <NEW_LINE> <DEDENT> end = l...
separateCSV : Separates the columns in a SMHI object into two separate SMHI objects. smhi : the original object. frm : the start splice index to : the end splice index
625941f1baa26c4b54cb16c2
def read_raw(self, timeout=1.0): <NEW_LINE> <INDENT> sleep_step_s = timeout/self.retry_cnt <NEW_LINE> timeout= max(timeout, sleep_step_s) <NEW_LINE> packet_type = None <NEW_LINE> result = None <NEW_LINE> wait_time_s = 0 <NEW_LINE> while wait_time_s < timeout: <NEW_LINE> <INDENT> new_data = b'' <NEW_LINE> while self.__p...
Read data form the communication interface
625941f1d8ef3951e3243ae6
def vector_matrix_mul(v, M): <NEW_LINE> <INDENT> assert M.D[0] == v.D <NEW_LINE> tempMat = Mat(M.D, {(y,x):z*val for (y,x),z in M.f.items() for key,val in v.f.items() if y == key}) <NEW_LINE> return Vec(M.D[1], {key:sum(z for (y,x),z in tempMat.f.items() if x == key) for key in M.D[1]})
Returns the product of vector v and matrix M
625941f1be383301e01b5a23
def get_traj(self): <NEW_LINE> <INDENT> parcel = self.mupcl <NEW_LINE> slinky = params.parcelTraj(self, parcel) <NEW_LINE> if slinky == None: <NEW_LINE> <INDENT> self.slinky_traj = ma.masked <NEW_LINE> self.updraft_tilt = ma.masked <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.slinky_traj = slinky[0] <NEW_LINE> se...
Function to compute the storm slinky profile using the trajectory model. self.slinky_traj - the list containing the position vector for the updraft self.updraft_tilt - the updraft tilt (an angle) with respect to the horizon Parameters ---------- None Returns ------- None
625941f115fb5d323cde10c1
@app.route('/greet') <NEW_LINE> def greet_person(): <NEW_LINE> <INDENT> player = request.args.get("person") <NEW_LINE> compliment = request.args.get("compliment") <NEW_LINE> return render_template("compliment.html", player, compliment)
Get user by name and ask if they want to play a game.
625941f1d7e4931a7ee9e4c8
def set_author(self, user): <NEW_LINE> <INDENT> self.author = user <NEW_LINE> self.save()
Добавление автора вопроса
625941f1287bf620b61d4009
def medicalnet(images, num_classes=10, is_training=False, dropout_keep_prob=0.5, prediction_fn=slim.softmax, scope='CifarNet'): <NEW_LINE> <INDENT> end_points = {} <NEW_LINE> with tf.variable_scope(scope, 'MedicalNet', [images, num_classes]): <NEW_LINE> <INDENT> net = slim.conv2d(images, 64, [5, 5], scope='conv1') <NEW...
Creates a variant of the CifarNet model. Note that since the output is a set of 'logits', the values fall in the interval of (-infinity, infinity). Consequently, to convert the outputs to a probability distribution over the characters, one will need to convert them using the softmax function: logits = cifarnet....
625941f15166f23b2e1a5702
def get_max_summary_len(articles): <NEW_LINE> <INDENT> return max([ max(map(lambda s: len(s.split()), art.gold_summaries)) for art in articles ])
Get the maximum length of a summary within the articles list. Args: articles (list<DucArticle>) Returns: int length
625941f1091ae356686674fe
def conj(P): <NEW_LINE> <INDENT> Pc = P.coefficients() <NEW_LINE> x = P.parent().gen() <NEW_LINE> return sum([Pc[p] * generic_power(x,p) for p in range(0,len(Pc)) if Pc[p].imag() == 0]) - sum([Pc[p] * generic_power(x,p) for p in range(0,len(Pc)) if Pc[p].imag() !=...
Conjugate of a polynomial P.
625941f1b57a9660fec33e35
def to_json(self): <NEW_LINE> <INDENT> return { 'file_id' : self.file_id, 'file_location': self.file_location, 'file_exists' : self.file_exists, 'expiration_date' : self.expiration_date, 'local_location' : self.local_location, 'remote_location' : self.remote_location, 'download_count' : self.download_count, 'is_expired...
Return a json object of this instance.
625941f1460517430c39471e
def query(string, service=GOOGLE, **kwargs): <NEW_LINE> <INDENT> service = service.lower() <NEW_LINE> if service in (GOOGLE, "google", "g"): <NEW_LINE> <INDENT> engine = Google <NEW_LINE> <DEDENT> elif service in (YAHOO, "yahoo", "y!"): <NEW_LINE> <INDENT> engine = Yahoo <NEW_LINE> <DEDENT> elif service in (BING, "bing...
Returns the list of search query results from the given service. For service=WIKIPEDIA, this is a single WikipediaArticle or None.
625941f17cff6e4e81117f2e
@app.route('/crashcallback') <NEW_LINE> def crashcallback(): <NEW_LINE> <INDENT> raise(Exception('SomethingBad'))
Deliberately raises an unhandled error which will have diagnostic data attached by the global callback function, and crash the app.
625941f191af0d3eaac9bfc7
def create_test_suite_with_http_info(self, project_id, body, **kwargs): <NEW_LINE> <INDENT> all_params = ['project_id', 'body', 'parent_id', 'parent_type'] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_para...
Creates a Test Suite To create a new Test Suite <strong>qTest Manager version:</strong> 6+ 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(re...
625941f1cc40096d61595ef7
def generate(cam_data, plate_data, frame_range): <NEW_LINE> <INDENT> data = const.MM_CAMERA_HEADER_VERSION_1.copy() <NEW_LINE> plate_path = plate_data.get('file_path') <NEW_LINE> if plate_path is not None: <NEW_LINE> <INDENT> plate_path = os.path.normpath(plate_path) <NEW_LINE> <DEDENT> data.update( { 'data': { 'name':...
Generate a JSON formatted string from the input data. The generated string is then able to be saved to a file.
625941f1090684286d50f299
def find_services_more_availability(self, known=None, min_score=1, **_kwargs): <NEW_LINE> <INDENT> if known is None: <NEW_LINE> <INDENT> known = list() <NEW_LINE> <DEDENT> filtered = [x for x in self.services.values() if self.get_score(x) >= min_score] <NEW_LINE> filtered.sort(key=(lambda svc: svc['upper_limit'] - len(...
Find `replicas` services, including the ones of `known`
625941f1aad79263cf390ff3
def fill_in_expiration_years(select): <NEW_LINE> <INDENT> for child in select.getchildren(): <NEW_LINE> <INDENT> select.remove(child) <NEW_LINE> <DEDENT> e = Element('option', value='', selected='selected') <NEW_LINE> e.text = '(select)' <NEW_LINE> select.append(e) <NEW_LINE> this_year = datetime.date.today().year <NEW...
Fill in expiration date year values in the given `select` element.
625941f1566aa707497f4b0a
def _check_to_open_playlist(self, a_url=None): <NEW_LINE> <INDENT> if self._cnf.dirty_playlist: <NEW_LINE> <INDENT> if self._cnf.auto_save_playlist: <NEW_LINE> <INDENT> ret = self.saveCurrentPlaylist() <NEW_LINE> if ret == 0: <NEW_LINE> <INDENT> self._open_playlist(a_url) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i...
Open a playlist after saving current playlist (if needed) Parameters a_url: An online service url
625941f1925a0f43d254a426
def get_average(root: Node) -> float: <NEW_LINE> <INDENT> return -1
Please implement this method to return the average of all node values (Node.getValue()) in the tree. :param root the root node of a tree from which to determine the average value :return the average of all node values in the tree
625941f115fb5d323cde10c2
def hsps_plots(dates, domains, dates2, domains2, filename='plot'): <NEW_LINE> <INDENT> dates = list(filter(None, dates)) <NEW_LINE> dates = filter_hackerspaces_dates(dates) <NEW_LINE> xdata = mat.dates.date2num(dates) <NEW_LINE> xdata2 = mat.dates.date2num(dates2) <NEW_LINE> ydata,ydata2 = range(len(xdata)), range(len...
Accept two lists of dates and domains, return a scatterplot.
625941f18a43f66fc4b54608
def warn(self, warning): <NEW_LINE> <INDENT> print >>sys.stderr, u"Warning: %s" % warning
Print warning. Separate function for easy testing.
625941f1a17c0f6771cbe5f8
def sort_seqids_by_uniprot(seqids, uniprot_data): <NEW_LINE> <INDENT> def cmp_longer_protein_is_first(seqid1, seqid2): <NEW_LINE> <INDENT> return uniprot_data[seqid2]['length'] - uniprot_data[seqid1]['length'] <NEW_LINE> <DEDENT> def diff_list(orig_list, other_list): <NEW_LINE> <INDENT> return [v for v in orig_l...
Returns a sorted list of seqids such that longest proteins that are reviewed appear first in the list.
625941f10c0af96317bb8790
def changer_type(self, nouveau_type): <NEW_LINE> <INDENT> classe = importeur.objet.get_type(nouveau_type) <NEW_LINE> self.__class__ = classe <NEW_LINE> del self._extensions_editeur <NEW_LINE> self.__setstate__(self.__dict__.copy()) <NEW_LINE> for objet in self.objets: <NEW_LINE> <INDENT> for nom, val in self._attributs...
Cette méthode force le changement de type du prototype. ATTENTION : cette méthode change le type en changeant '__class__' et performent certaines opérations automatiques. Il y a des conséquences à changer une instance de classe comme cela, et cela ne devrait pas se produire fréquemment ni automatiquement.
625941f17c178a314d6efa13
def invrmat(self): <NEW_LINE> <INDENT> return np.array(cho_solve(self.crmat, np.eye(self.m), check_finite=False), order="C")
inv(R)
625941f150812a4eaa59c8c5
def process_exception(self, request, exception): <NEW_LINE> <INDENT> if type(exception) == PermissionDenied and exception.allow_redirect: <NEW_LINE> <INDENT> target_type = ContentType.objects.get_for_model(exception.target) <NEW_LINE> target = exception.target <NEW_LINE> view = ExpedientPermission.objects.filter( name=...
Redirect to the denied permission's URL if it exists.
625941f1236d856c2ad44d8c
def testCountLoc(self): <NEW_LINE> <INDENT> empty_script = PythonScript.PythonScript(fileName= "../public/not_missing.py") <NEW_LINE> self.assertEqual(empty_script.countLoc(), 0) <NEW_LINE> comments_script = PythonScript.PythonScript(fileName= "../public/comments.py") <NEW_LINE> self.assertEqual(comments_script.countLo...
Test countLoc method.
625941f160cbc95b062c6aed
def upload(self,*args): <NEW_LINE> <INDENT> cmd_dict = args[0] <NEW_LINE> filename = cmd_dict['filename'] <NEW_LINE> filesize = cmd_dict['filesize'] <NEW_LINE> if filesize > self.private_info_dict['disc_space']: <NEW_LINE> <INDENT> self.request.send(b'101') <NEW_LINE> space = int(self.private_info_dict['disc_space']/(1...
The function is used to receive and store the file which is uploaded by client in current directory :param args: :return:
625941f121a7993f00bc82a4
def test_have_key(): <NEW_LINE> <INDENT> jay = {'name': "John Doe"} <NEW_LINE> assert this(jay).should.have.key("name") <NEW_LINE> assert this(jay).should_not.have.key("age") <NEW_LINE> def opposite(): <NEW_LINE> <INDENT> assert this(jay).should_not.have.key("name") <NEW_LINE> <DEDENT> def opposite_not(): <NEW_LINE> <I...
this(dictionary).should.have.key(key_name)
625941f16fb2d068a760f650
def startUp(self): <NEW_LINE> <INDENT> log.debug("Sending pretest NULL") <NEW_LINE> self.c1.null() <NEW_LINE> log.debug("Got pretest NULL response")
Run before each test
625941f14e696a04525c99f7
def softmax(self, x): <NEW_LINE> <INDENT> return np.exp(x) / np.sum(np.exp(x) , axis = -1 , keepdims = True)
Compute softmax values for each sets of scores in x.
625941f124f1403a9260110b
def _remove(self, id_p, name, id_, force=False): <NEW_LINE> <INDENT> log.debug('_remove(%d, %s): start', id_p, name) <NEW_LINE> timestamp = time.time() <NEW_LINE> if self.db.has_val("SELECT 1 FROM contents WHERE parent_inode=?", (id_,)): <NEW_LINE> <INDENT> log.debug("Attempted to remove entry with children: %s", get_p...
Remove entry `name` with parent inode `id_p` `id_` must be the inode of `name`. If `force` is True, then the `locked` attribute is ignored. This method releases the global lock.
625941f1d18da76e23532a87
def finish_dir(self, name: str, collapse: bool = False): <NEW_LINE> <INDENT> self.dirs[name].style = 'bold green' <NEW_LINE> self.dirs[name].guide_style = 'dark_green' <NEW_LINE> self.dirs[name].label = '✔️ ' + self.dirs[name].label.split(':open_file_folder:')[-1] <NEW_LINE> self.dirs[name].expanded = not collapse
Finish a directory, change text to green + give a check (and collapse if requested, to minimize terminal bloat.) Args: name: Full path to the file collapse: Whether or not to collapse the folder. Defaults to False.
625941f18e05c05ec3eea923
def test_multiple_yyyymm_range_single(self): <NEW_LINE> <INDENT> test_range = [['201203', '201301']] <NEW_LINE> valid_result = {2012:range(3, 13), 2013:range(1, 2)} <NEW_LINE> self.assertEqual(valid_result,validate_multiple_yyyymm_range(test_range, 'month'))
Test if a single range produces the right result
625941f110dbd63aa1bd314c
def runAll(): <NEW_LINE> <INDENT> suite = unittest.TestSuite() <NEW_LINE> suite.addTest(unittest.TestLoader().loadTestsFromTestCase(PresenterTestCase)) <NEW_LINE> unittest.TextTestRunner(verbosity=2).run(suite)
Unittest runner
625941f1be7bc26dc91cdb9e
def scores(l, s): <NEW_LINE> <INDENT> global landings <NEW_LINE> out, land = [], landings[:bisect(landings, l)] <NEW_LINE> for i in [3, 2, 1]: <NEW_LINE> <INDENT> out += [(i, land[j]) for j in reversed(range(bisect(land, s/i)))] <NEW_LINE> <DEDENT> return out
Return a list of multiplier-score pairs that one dart can acquire when it can only land on the values less than or equal to l and the score must be less than or equal to s. The list is also returned in reverse sorted order.
625941f1462c4b4f79d1dc79
def test_kh_addkh_edit1(self): <NEW_LINE> <INDENT> self.app.waitActivity(".ui.activity.index.IndexActivity", 50) <NEW_LINE> self.app.index().goto_kh().goto_addkh().send_name().send_phone()
已登录,点击客户->点击添加客户,输入手机号和姓名 :return:
625941f14f6381625f114fe5
def _bin_op(self, arg1, arg2): <NEW_LINE> <INDENT> if not isinstance(arg1[0], (int, float)) or not isinstance(arg2[0], (int, float)): <NEW_LINE> <INDENT> raise Exception("Can only compare numbers.") <NEW_LINE> <DEDENT> return arg1[0] <= arg2[0]
@see Operator#_op
625941f156ac1b37e626476d
def exclude(self, data=None, wcs=None, view=()): <NEW_LINE> <INDENT> self._validate_wcs(data, wcs) <NEW_LINE> return self._exclude(data=data, wcs=wcs, view=view)
Return a boolean array indicating which values should be excluded. If ``view`` is passed, only the sliced mask will be returned, which avoids having to load the whole mask in memory. Otherwise, the whole mask is returned in-memory.
625941f166673b3332b9263b
def is_running(name): <NEW_LINE> <INDENT> if _job_pid(name) is not None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Test whether task ``name`` is currently running. :param name: name of task :type name: unicode :returns: ``True`` if task with name ``name`` is running, else ``False`` :rtype: bool
625941f1dc8b845886cb5ae1
def read_struct_conn(self): <NEW_LINE> <INDENT> for loop in self.loops: <NEW_LINE> <INDENT> if self.read_struct_conn_(loop): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
Create bonds from STRUCT_CONN category
625941f1b5575c28eb68e5af
def __init__(self, argv=None): <NEW_LINE> <INDENT> self.argv = argv or sys.argv[:]
AUTHORS: -------- :author: Alix Leroy DESCRIPTION: ------------ Initialize the ManagementUtility and keep the args in memory PARAMETERS: ----------- None RETURN: ------- :return: None
625941f1097d151d1a223400
def tree_build_from_dict(containers=None, root='Tenant', debug=False): <NEW_LINE> <INDENT> tree = Tree() <NEW_LINE> previously_created = list() <NEW_LINE> MODULE_LOGGER.debug('containers list is %s', str(containers)) <NEW_LINE> tree.create_node(root, root) <NEW_LINE> for container_name, container_info in containers.ite...
Build a tree based on a unsorted dictConfig(config). Build a tree of containers based on an unsorted dict of containers. Example: -------- >>> containers = {'Fabric': {'parent_container': 'Tenant'}, 'Leaves': {'configlets': ['container_configlet'], 'devices': ['veos01'], ...
625941f163d6d428bbe44a9b
def validate_block(self, block_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> block = next(self._block_manager.get([block_id])) <NEW_LINE> <DEDENT> except StopIteration as stop_iteration: <NEW_LINE> <INDENT> raise UnknownBlock(stop_iteration.args[0]) <NEW_LINE> <DEDENT> self._chain_controller.validate_block(block)
Instruct the chain controller to validate the given block.
625941f131939e2706e4d40b
def verify_code(self): <NEW_LINE> <INDENT> num = random.choice(['0.']) + "".join(random.choice("0123456789") for i in range(17)) <NEW_LINE> img_url = self.login_url + num <NEW_LINE> image_path = r'D:\潘泽—工作文件\项目代码\createBQcredit\testImages\1.jpg' <NEW_LINE> ul.urlretrieve(img_url, image_path) <NEW_LINE> img_str = pytess...
获取验证码 :return: 验证码求和后的值
625941f10a50d4780f667441
def list_blobs(storage_conn=None, **kwargs): <NEW_LINE> <INDENT> if not storage_conn: <NEW_LINE> <INDENT> storage_conn = get_storage_conn(opts=kwargs) <NEW_LINE> <DEDENT> if 'container' not in kwargs: <NEW_LINE> <INDENT> raise SaltSystemExit( code=42, msg='An storage container name must be specified as "container"' ) <...
.. versionadded:: 2015.8.0 List blobs associated with the container
625941f199cbb53fe679318e
def test_make_timestamp(self): <NEW_LINE> <INDENT> for dt, fmt, target in ( (datetime.now(tz=timezone.utc), r"%d%HZ", False), (datetime.now(tz=timezone.utc), r"%d%H%MZ", False), (datetime(2010, 2, 2, 2, 2, tzinfo=timezone.utc), r"%d%HZ", True), (datetime(2010, 2, 2, 2, 2, tzinfo=timezone.utc), r"%d%H%MZ", True), ): <NE...
Tests that a report timestamp is converted into a Timestamp dataclass
625941f1ab23a570cc250731
def test_non_version_response(self): <NEW_LINE> <INDENT> async def _non_version_response(self): <NEW_LINE> <INDENT> packet = await SFTPHandler.recv_packet(self) <NEW_LINE> self.send_packet(FXP_STATUS, None) <NEW_LINE> return packet <NEW_LINE> <DEDENT> with patch('asyncssh.sftp.SFTPServerHandler.recv_packet', _non_versi...
Test sending a non-version message in response to init
625941f15fdd1c0f98dc07e0
def LNAHPSU_thri2(ip_addr='192.168.0.1', thri=''): <NEW_LINE> <INDENT> return telnet(ip_addr, 'thri2 %s' % thri)
Чтение/задание порога по току 2 @param ip_addr - ip-адрес устройства @param thri - порог по току @return 1 - порог по току
625941f1f548e778e58cdb2a
def get_text(obj) -> Tuple[int, str]: <NEW_LINE> <INDENT> from bioc.bioc import BioCDocument, BioCPassage, BioCSentence <NEW_LINE> if isinstance(obj, BioCSentence): <NEW_LINE> <INDENT> return obj.offset, obj.text <NEW_LINE> <DEDENT> elif isinstance(obj, BioCPassage): <NEW_LINE> <INDENT> if obj.text: <NEW_LINE> <INDENT>...
Return text with its offset in the document Args: obj: BioCDocument, BioCPassage, or BioCSentence Returns: offset, text
625941f163f4b57ef00016b2
def check(reaction, user): <NEW_LINE> <INDENT> print('checking reaction') <NEW_LINE> result = reaction.message.id == bot_answer.id and str(reaction.emoji) in emojis.numbers.values() and user.id != bot_answer.author.id <NEW_LINE> return result
Check if the reactions match the same lobby as the latest rendered one. And if the reacted emoji only is part of the ones the bot added. Returns a boolean.
625941f192d797404e304737
def get_article_sections(self, index): <NEW_LINE> <INDENT> article = self.get_article(index) <NEW_LINE> return (article.get("title"), article.get("published"), article.get("summary"))
Returns an article at the given index
625941f13eb6a72ae02eca97
def jsonify(obj_type, action, result, args): <NEW_LINE> <INDENT> response = {} <NEW_LINE> response['type'] = obj_type <NEW_LINE> response['action'] = action <NEW_LINE> response['result'] = result <NEW_LINE> response['args'] = args <NEW_LINE> response = JSONEncoder().encode(response) <NEW_LINE> return response
JSONify response
625941f19f2886367277ae32
@permissionverify() <NEW_LINE> @login_required <NEW_LINE> def project_show_vm(request, num): <NEW_LINE> <INDENT> pj = Project.objects.get(id=num) <NEW_LINE> mlist = pj.vm_set.all() <NEW_LINE> lst = selfpaginator(request, mlist, 20) <NEW_LINE> kwvars = { 'lPage': lst, 'request': request, } <NEW_LINE> return render_to_re...
通过项目num查询所属虚拟机
625941f1fff4ab517eb2f9ea
def addAtTail(self, val): <NEW_LINE> <INDENT> self.llist.append(val)
Append a node of value val to the last element of the linked list. :type val: int :rtype: void
625941f1a219f33f34628f0b
def condition_8(self, df): <NEW_LINE> <INDENT> if repairSubstructureFeasible(self, df) == False: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Notes:
625941f1fbf16365ca6f677a