code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def testNaiveCentroid(self): <NEW_LINE> <INDENT> schema = self.dataset.makeMinimalSchema() <NEW_LINE> config = self.makeConfig("base_NaiveCentroid") <NEW_LINE> config.plugins["base_NaiveCentroid"].maxDistToPeak = .0001 <NEW_LINE> task = lsst.meas.base.SingleFrameMeasurementTask(schema=schema, config=config) <NEW_LINE> ...
Test the `NaiveCentroid` works with the ``maxDistance`` check.
625941e73c8af77a43ae3c1a
def learn_geometric(t, start=0.5, end=0.1, *args, **kwargs): <NEW_LINE> <INDENT> ln_rate = (1. - t) * np.log(start) + t * np.log(end) <NEW_LINE> return np.exp(ln_rate)
The geometric learning rate between `start` and `end` at time `t`.
625941e732920d7e50b28648
def OnPaint(self, event): <NEW_LINE> <INDENT> if self._buffered: <NEW_LINE> <INDENT> dc = wx.BufferedPaintDC(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dc = wx.PaintDC(self) <NEW_LINE> <DEDENT> self.AdjustDC(dc) <NEW_LINE> x = 0 <NEW_LINE> w, h = self.GetClientSize() <NEW_LINE> w, dummy = self._owner.CalcUnscr...
Handles the ``wx.EVT_PAINT`` event for :class:`TreeListHeaderWindow`. :param `event`: a :class:`PaintEvent` event to be processed.
625941e7fbf16365ca6f6642
def put(self): <NEW_LINE> <INDENT> key = super(I18nableModel, self).put() <NEW_LINE> if hasattr(self, 'i18n'): <NEW_LINE> <INDENT> for lang_id, lang_fields in self.i18n.items(): <NEW_LINE> <INDENT> for field, value in lang_fields.items(): <NEW_LINE> <INDENT> translation = self.translations .filte...
Overrides the default put method, and saves translations also
625941e7435de62698dfe0c1
def test_decrement_activity_populates_store_for_new_kernel(self): <NEW_LINE> <INDENT> self.activity.decrement_activity(self.kernel_id, CONNECTIONS) <NEW_LINE> self.assertTrue(self.activity.get()[self.kernel_id] is not None, 'Kernel activity object was not created')
decrement_activity should initialize an activity object for a new kernel
625941e7a8ecb033257d353f
def tuple(opencv_rect): <NEW_LINE> <INDENT> left, top, right, bottom = opencv_rect <NEW_LINE> return Region(left, top, right - left, bottom - top)
creates a region from an opencv (left, top, right, bottom) tuple
625941e799cbb53fe6793059
def get_yaml_regex(): <NEW_LINE> <INDENT> return r"^---(\r|\n|.)+\.\.\.$"
Get Regex to find YAML section in text
625941e7090684286d50f160
def _get_new_content(self): <NEW_LINE> <INDENT> url = 'http://ftp-master.debian.org/new.822' <NEW_LINE> cache = HttpCache(settings.PTS_CACHE_DIRECTORY) <NEW_LINE> if not cache.is_expired(url): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> response, updated = cache.update(url, force=self.force_update) <NEW_LINE> if not...
:returns: The content of the deb822 formatted file giving the list of packages found in NEW. ``None`` if the cached resource is up to date.
625941e782261d6c526ab91b
def get_header(self): <NEW_LINE> <INDENT> return self.__header
Return the header of the message.
625941e7d58c6744b42580d2
def set(self, value): <NEW_LINE> <INDENT> with self as old_value: <NEW_LINE> <INDENT> self.box = value <NEW_LINE> return old_value
Safely set the box to a new value. Useful for immutable value types
625941e79f2886367277acfe
def _on_keyboard_event(self, widget, event): <NEW_LINE> <INDENT> if event.keyval == 65535: <NEW_LINE> <INDENT> path, column = self.__view.get_cursor() <NEW_LINE> self.__show_infobar(path)
Delete item if Delete was pressed @param widget unused, Gdk.Event
625941e767a9b606de4a832b
def encode(self, longUrl): <NEW_LINE> <INDENT> self.id = len(self.longURLs) <NEW_LINE> self.longURLs.append(longUrl) <NEW_LINE> shortUrl = self.get_shortUrl(self.id) <NEW_LINE> return 'http://' + shortUrl
Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
625941e76aa9bd52df03721b
def get_absolute_pathname_from_list(path_as_list): <NEW_LINE> <INDENT> pathname = os.path.join(*path_as_list) <NEW_LINE> pathname = os.path.sep + pathname <NEW_LINE> return pathname
Returns the absolute pathname from a list :param path_as_list: List of path and file name eg ["syscore","fileutils.py"] :type path_as_list: :returns: full pathname of package
625941e7a4f1c619b28b04a3
def insert(path): <NEW_LINE> <INDENT> new = [] <NEW_LINE> for pp in os.getenv('PYTHONPATH','').split(os.pathsep): <NEW_LINE> <INDENT> if not pp: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if pp in sys.path: <NEW_LINE> <INDENT> sys.path.remove(pp) <NEW_LINE> <DEDENT> pp = os.path.abspath(pp) <NEW_LINE> if pp in sy...
Insert C{path} at the front of sys.path, but after $PYTHONPATH. The goal is to override installed system packages and virtualenv packages but not anything specified via environment like the command wrappers you get running e.g. ./bin/conary
625941e7097d151d1a2232cc
def keys(self): <NEW_LINE> <INDENT> return [x for x in self.__iter__()]
The set of keys in the dictionary.
625941e763d6d428bbe44965
def get_music_as_notename_list(self, lessonfile_ref): <NEW_LINE> <INDENT> assert isinstance(lessonfile_ref, LessonfileCommon) <NEW_LINE> notenames = [self.strip_trailing_digits(n) for n in self.m_musicdata.split()] <NEW_LINE> try: <NEW_LINE> <INDENT> if not lessonfile_ref.header.random_transpose[0]: <NEW_LINE> <INDENT>...
This method will validate the notenames, and raise a mpd.musicalpitch.InvalidNotenameException with the m_linepos1, m_linepos2 og m_lineno.
625941e744b2445a33932507
def solve(brd, empties=9): <NEW_LINE> <INDENT> if empties == 0: <NEW_LINE> <INDENT> return is_valid(brd) <NEW_LINE> <DEDENT> for row, col in product(range(3), repeat=2): <NEW_LINE> <INDENT> cell = brd[row][col] <NEW_LINE> if cell != 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> brd2 = copy(brd) <NEW_LINE> for tes...
solve a mini sudoku brd is the board empty is the number of empty cells
625941e78c0ade5d55d3ee33
def onto(m, n)->int: <NEW_LINE> <INDENT> r = pow(n, m) <NEW_LINE> num = fact(n) <NEW_LINE> for i in range(1, n): <NEW_LINE> <INDENT> den_a = fact(i) <NEW_LINE> den_b = fact(n - i) <NEW_LINE> temp = num // (den_a * den_b) <NEW_LINE> temp = temp * pow(n-i, m) <NEW_LINE> if i & 1 == 1: <NEW_LINE> <INDENT> r -= temp <NEW_L...
distribute m elements to n formula for onto function is R = n^m - C(n, 1)(n-1)^m + C(n, 2)(n-2)^m - ... + (-1)^n-1 C(n, n-1).1^m
625941e7498bea3a759b9f22
def random_so3(): <NEW_LINE> <INDENT> return tr.random_rotation_matrix()[:3, :3]
:return: a random SO(3) matrix (for debugging)
625941e799cbb53fe679305a
def _handle_dependencies(self, dependencies): <NEW_LINE> <INDENT> if not dependencies: <NEW_LINE> <INDENT> logger.debug("No dependencies found, skipping...") <NEW_LINE> return <NEW_LINE> <DEDENT> for dependency in dependencies.keys(): <NEW_LINE> <INDENT> current_dependency = dependencies[dependency] <NEW_LINE> package ...
The dependencies provided is expected to be a dict in following format: { PACKAGE_ID: { 'package': PACKAGE_NAME, 'command': COMMAND_TO_TEST_FOR_PACKACGE_EXISTENCE }, } Additionally every package can contain platform specific information, for example: { 'git': { 'package': 'git', 'executable':...
625941e7711fe17d825427d6
def validate_range(func: Callable[[int], int]) -> Callable[[int], int]: <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def wrapper(number: int) -> int: <NEW_LINE> <INDENT> if number > 64 or number < 1: <NEW_LINE> <INDENT> raise ValueError("Invalid input. Must be in the range 1-64.") <NEW_LINE> <DEDENT> return func(number)...
Raise an exception if a given number is outside of the valid range.
625941e7eab8aa0e5d26dfce
def testGenerateKeyForASinglePPA(self): <NEW_LINE> <INDENT> cprov = getUtility(IPersonSet).getByName('cprov') <NEW_LINE> self._fixArchiveForKeyGeneration(cprov.archive) <NEW_LINE> self.assertTrue(cprov.archive.signing_key is None) <NEW_LINE> txn = FakeTransaction() <NEW_LINE> key_generator = self._getKeyGenerator(ppa_o...
Signing key generation for a single PPA. The 'signing_key' for the specified PPA is generated and the transaction is committed once.
625941e7236d856c2ad44c55
def a_func(x, n_act): <NEW_LINE> <INDENT> beta_a = [-2.5, 3, 0, 1, 1, 0, 0] <NEW_LINE> z = np.matmul(x, np.array(beta_a).reshape(-1, 1)) <NEW_LINE> p = 1 / (1 + np.exp(-z)) <NEW_LINE> a = np.random.binomial(n_act - 1, p) + 1 <NEW_LINE> return a.reshape(-1, 1)
Users define the function of A here. The example below uses a linear function: A = -2.5 + 3*X0 + 0*X1 + 1*X2 + 1*X3 + 0*X4 + 0*X5 :param x: the input X matrix for the a_function :param n_act: the number of possible responses, i.e. treatment options :return: a n x 1 matrix of A (starging from 1)
625941e70383005118ecfa56
def run(self): <NEW_LINE> <INDENT> log.debug('Running source detection') <NEW_LINE> for _ in range(self.max_sources): <NEW_LINE> <INDENT> log.debug('Starting iteration number {0}'.format(_)) <NEW_LINE> debug_folder = self.debug_output_folder + '/' + str(_) <NEW_LINE> if self.debug_output_folder: <NEW_LINE> <INDENT> Pat...
Run source detection.
625941e74428ac0f6e5bac6b
def release_lease(self, lease_id, client_id, epoch): <NEW_LINE> <INDENT> return db_locks.release_lease(lease_id, client_id, epoch)
Release the lease identified by the id, client, and epoch :param lease_id: :param client_id: :param epoch: :return:
625941e78e71fb1e9831dc1c
def batchnorm_forward(x, gamma, beta, bn_param): <NEW_LINE> <INDENT> mode = bn_param['mode'] <NEW_LINE> eps = bn_param.get('eps', 1e-5) <NEW_LINE> momentum = bn_param.get('momentum', 0.9) <NEW_LINE> N, D = x.shape <NEW_LINE> running_mean = bn_param.get('running_mean', np.zeros(D, dtype=x.dtype)) <NEW_LINE> running_var ...
Forward pass for batch normalization. During training the sample mean and (uncorrected) sample variance are computed from minibatch statistics and used to normalize the incoming data. During training we also keep an exponentially decaying running mean of the mean and variance of each feature, and these averages are us...
625941e77c178a314d6ef8db
def new_group(gid: str, description: str) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> Group.objects.create(id=gid, description=description) <NEW_LINE> <DEDENT> except Group.DoesNotExist: <NEW_LINE> <INDENT> raise click.BadParameter('No group was found with id ' + gid)
Creates new group :param gid: Group's symbolic code :type gid: str :param description: Short description (optional) :type description: str :raise click.BadParameter: if wrong `id` has been passed
625941e760cbc95b062c69b8
def p_parameter_2(p): <NEW_LINE> <INDENT> pass
parameter : ID COMMA parameter
625941e77b180e01f3dc4c69
def visitor(n_grams, word, best_words): <NEW_LINE> <INDENT> word = tuple(' ' + word + ' ') <NEW_LINE> word_prob = self.get_word_log_likelihood(word) <NEW_LINE> try_to_store(best_words, word, word_prob, MAX_WORDS_TO_STORE)
Check if this word has a high likelihood and, if so, store it.
625941e799fddb7c1c9de803
def get_dictionary_for_doc(self, document_string): <NEW_LINE> <INDENT> X = self.model.transform([document_string]) <NEW_LINE> doc_tokens = self.tokenize(document_string) <NEW_LINE> candidate_word_dict = defaultdict(lambda:0) <NEW_LINE> for word in doc_tokens: <NEW_LINE> <INDENT> word_score = X[0, self.model.vocabulary_...
" Get the final word=score dictionary for the candidate words for computed index. :param model tv_id model_obj
625941e74527f215b584c8c7
def load(self, settings_path="settings.json"): <NEW_LINE> <INDENT> with open(settings_path) as settings: <NEW_LINE> <INDENT> self.data = json.load(settings)
Loads settings from json
625941e74d74a7450ccd463a
def __init__(self, id=None, name=None, organisationid=None, groupids=None, public=None): <NEW_LINE> <INDENT> self._id = None <NEW_LINE> self._name = None <NEW_LINE> self._organisationid = None <NEW_LINE> self._groupids = None <NEW_LINE> self._public = None <NEW_LINE> self.id = id <NEW_LINE> self.name = name <NEW_LINE> ...
CollectionPut - a model defined in Swagger
625941e7925a0f43d254a2f0
def isNumber(self, s): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> f = float(s) <NEW_LINE> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False
:type s: str :rtype: bool
625941e78c3a873295158835
def status(): <NEW_LINE> <INDENT> status_code, urls = get_urls() <NEW_LINE> if status_code == STATUS_RUNNING: <NEW_LINE> <INDENT> sys.stderr.write("{msg:s} (0)\n".format(msg=status.codes[0])) <NEW_LINE> sys.stderr.write("KA Lite running on:\n\n") <NEW_LINE> for addr in urls: <NEW_LINE> <INDENT> sys.stderr.write("\t{}\n...
Check the server's status. For possible statuses, see the status dictionary status.codes Status *always* outputs the current status in the first line if stderr. The following lines contain optional information such as the addresses where the server is listening. :returns: status_code, key has description in status.co...
625941e73eb6a72ae02ec95e
def uninstall_sonar(args): <NEW_LINE> <INDENT> x('echo "uninstall"') <NEW_LINE> x('/opt/sonarqube/bin/linux-x86-64/sonar.sh stop') <NEW_LINE> x('rm -rf /opt/sonarqube/')
Uninstall sonar
625941e7046cf37aa974d1b8
def parse_setting_time(self, setting_value, setting_name): <NEW_LINE> <INDENT> time_symbols = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400} <NEW_LINE> try: <NEW_LINE> <INDENT> values = setting_value.split('-') <NEW_LINE> multiple = values[0] <NEW_LINE> symbol = values[1] <NEW_LINE> duration = int(time_symbols[symbol] * int(...
This expects a format like "24-h"
625941e716aa5153ce3628ed
def is_fastq(in_file): <NEW_LINE> <INDENT> fastq_ends = [".txt", ".fq", ".fastq"] <NEW_LINE> zip_ends = [".gzip", ".gz"] <NEW_LINE> base, first_ext = os.path.splitext(in_file) <NEW_LINE> second_ext = os.path.splitext(base)[1] <NEW_LINE> if first_ext in fastq_ends: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> eli...
copy from bcbio package
625941e771ff763f4b549b08
def get_or_404(self, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.get(**kwargs) <NEW_LINE> <DEDENT> except DoesNotExist: <NEW_LINE> <INDENT> raise pulp_exceptions.MissingResource(**kwargs)
Generally allow querysets to raise a MissingResource exception if getting an object that does not exist. :param kwargs: keyword arguments that specify field of the document and value it should be :raise pulp_exceptions.MissingResource: if no objects are found
625941e7dc8b845886cb59ac
def route(self, request): <NEW_LINE> <INDENT> url = request.url <NEW_LINE> logging.debug("http: router received url: %s", url) <NEW_LINE> index = url.find("?") <NEW_LINE> if index >= 0: <NEW_LINE> <INDENT> url = url[:index] <NEW_LINE> logging.debug("http: router url without query: %s", url) <NEW_LINE> <DEDENT> if url i...
Route request
625941e78da39b475bd653ee
def batch_normalization_layer(input_layer, dimension): <NEW_LINE> <INDENT> mean, variance = tf.nn.moments(input_layer, axes=[0, 1, 2]) <NEW_LINE> beta = tf.Variable( tf.constant(0.0, shape=[dimension], dtype=tf.float32), name='beta') <NEW_LINE> gamma = tf.Variable( tf.constant(1.0, shape=[dimension], dtype=tf.float32),...
Helper function to do batch normalziation :param input_layer: 4D tensor :param dimension: input_layer.get_shape().as_list()[-1]. The depth of the 4D tensor :return: the 4D tensor after being normalized
625941e707d97122c4178d0b
def clean_tmp_files(self): <NEW_LINE> <INDENT> options = self.options <NEW_LINE> if not options: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> tmp_dir = options.all_tasks[self.rank]['tmp_dir'] <NEW_LINE> logging.debug('clean temp files') <NEW_LINE> rm_cmd = 'rm -rf %s/%s %s/%s %s/%s %s/*.pyc' %( tmp_dir, options.remot...
Remove tmp files
625941e7e76e3b2f99f3ac7a
def spatial_batchnorm_forward(x, gamma, beta, bn_param): <NEW_LINE> <INDENT> out, cache = None, None <NEW_LINE> N, C, H, W = x.shape <NEW_LINE> x = np.swapaxes(x, 0, 1) <NEW_LINE> out, cache = batchnorm_forward( x.reshape(C, N*H*W).T, gamma, beta, bn_param) <NEW_LINE> return out.T.reshape(C, N, H, W).swapaxes(0, 1), ca...
Computes the forward pass for spatial batch normalization. Inputs: - x: Input data of shape (N, C, H, W) - gamma: Scale parameter, of shape (C,) - beta: Shift parameter, of shape (C,) - bn_param: Dictionary with the following keys: - mode: 'train' or 'test'; required - eps: Constant for numeric stability - momen...
625941e7be7bc26dc91cda6d
def run(self, args=(), with_chroot=False, blocking=True, setsid=False, **kw): <NEW_LINE> <INDENT> self.clean_environment(forking=True) <NEW_LINE> cmdline = self.cmdline(args) <NEW_LINE> TRACER.log('PEX.run invoking %s' % ' '.join(cmdline)) <NEW_LINE> process = subprocess.Popen(cmdline, cwd=self._pex if with_chroot else...
Run the PythonEnvironment in an interpreter in a subprocess. :keyword args: Additional arguments to be passed to the application being invoked by the environment. :keyword with_chroot: Run with cwd set to the environment's working directory. :keyword blocking: If true, return the return code of the subprocess. If ...
625941e744b2445a33932508
def big_endian_to_int(b): <NEW_LINE> <INDENT> return int.from_bytes(b, 'big')
big_endian_to_int takes byte sequence as a big-endian number. Returns an integer
625941e78e7ae83300e4b443
def recv_send(self, local, remote, process): <NEW_LINE> <INDENT> packet = local.recv() <NEW_LINE> log_sapni.debug("SAPNIProxyHandler: Received %d bytes", len(packet)) <NEW_LINE> packet = process(packet) <NEW_LINE> remote.send(packet.payload) <NEW_LINE> log_sapni.debug("SAPNIProxyHandler: Sent %d bytes", len(packet))
Receives data from one socket connection, process it and send to the remote connection. @param local: the local socket @type local: L{SAPNIStreamSocket} @param remote: the remote socket @type remote: L{SAPNIStreamSocket} @param process: the function that process the incoming data @type process: function
625941e7460517430c3945ee
def compute_logistic_gradient(y, tx, w): <NEW_LINE> <INDENT> return tx.T.dot(sigmoid(tx.dot(w)) - y)
Computes the gradient of the loss function used in logistic regression. Args: y: labels tx: features w: weight vector Returns: logistic_gradient: the gradient of the loss function used in logistic regression.
625941e792d797404e304601
def connect(self): <NEW_LINE> <INDENT> url = '%s:%s' % (self.host, self.port) <NEW_LINE> if getattr(self, '_username', None): <NEW_LINE> <INDENT> url = '%s@%s' % (self._username, url) <NEW_LINE> <DEDENT> self.logger.debug("Connecting to WinRM: %s" % url) <NEW_LINE> shellid = self.wsman_create() <NEW_LINE> self.shellid ...
Set up a connection to the WinRM server. TODO: should we handle reconnects? Shells could be running on the server, and we could get list of active shell through wsman_enumerate. @rtype: string @return: The ShellId of the shell that got created on the server. This is also put in L{self.shellid}.
625941e7cc40096d61595dc4
def unsqueeze(input, dim): <NEW_LINE> <INDENT> pass
Add the given dimension of size 1. Parameters ---------- input : Tensor The input tensor. dim : int The dimension to be unsqueezed. Returns ------- Tensor The result tensor.
625941e75f7d997b87174f11
def all_products(request): <NEW_LINE> <INDENT> products = Products.objects.all() <NEW_LINE> context = { "products": products, } <NEW_LINE> return render(request, "products/products.html", context)
A view to show all products
625941e7293b9510aa2c3707
def simplex(self, dim=3, project=False, base_ring=None, backend=None): <NEW_LINE> <INDENT> verts = list((ZZ**(dim + 1)).basis()) <NEW_LINE> if project: <NEW_LINE> <INDENT> verts = project_points(*verts, base_ring=base_ring) <NEW_LINE> <DEDENT> return Polyhedron(vertices=verts, base_ring=base_ring, backend=backend)
Return the ``dim`` dimensional simplex. The `d`-simplex is the convex hull in `\RR^{d+1}` of the standard basis `(1,0,\ldots,0)`, `(0,1,\ldots,0)`, \ldots, `(0,0,\ldots,1)`. For more information, see the :wikipedia:`Simplex`. INPUT: - ``dim`` -- The dimension of the simplex, a positive integer. - ``project`` -- (...
625941e7cad5886f8bd2744e
def specifies_app_version_name(self, package): <NEW_LINE> <INDENT> for package in self.shell( 'dumpsys package %s' % package).stdout.readlines(): <NEW_LINE> <INDENT> if 'versionName' in package: <NEW_LINE> <INDENT> return package.split('=', 2)[1].strip()
获取指定应用的versionName :param package:应用包名 :return: 包名,versionName
625941e7435de62698dfe0c2
def __init__(self, at: int, change: int) -> None: <NEW_LINE> <INDENT> self.at = at <NEW_LINE> self.change = change
Constructor. Args: at (int): 何日目に、 change (int): 値段がどれくらい変動するか。
625941e75fcc89381b1e1b37
def test_root_end(self): <NEW_LINE> <INDENT> error_message = 'Fail - Ending the root' <NEW_LINE> assert(gparser.root_end(),error_message)
Raise an assertion if can't find the end root. Used to parse end root elements in the XML representation. Raises ------ AssertionError If can't set the value.
625941e763b5f9789fde755b
def is_str(string): <NEW_LINE> <INDENT> if sys.version_info >= (3, 0): <NEW_LINE> <INDENT> return isinstance(string, str) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return isinstance(string, basestring)
Python 2 and 3 compatible string checker. Args: string (str | basestring): the string to check Returns: bool: True or False
625941e7fb3f5b602dac3b0d
def plot_images(self, save2file=False, samples=16, step=0): <NEW_LINE> <INDENT> if not os.path.exists("./images"): <NEW_LINE> <INDENT> os.makedirs("./images") <NEW_LINE> <DEDENT> filename = "./images/mnist_%d.png" % step <NEW_LINE> noise = np.random.normal(0, 1, (samples, 100)) <NEW_LINE> images = self.G.predict(noise)...
Plot and generated images
625941e7baa26c4b54cb1591
def get_distance(self, robot_id): <NEW_LINE> <INDENT> if (robot_id in self.distance): <NEW_LINE> <INDENT> return self.distance[robot_id] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return(0)
gets the filtered distance between the anchor and the given robot
625941e7de87d2750b86020d
def parse(self, response): <NEW_LINE> <INDENT> sel = Selector(response) <NEW_LINE> links = sel.xpath('//select[@class="acad"]/option').extract() <NEW_LINE> for link in links: <NEW_LINE> <INDENT> p_link = 'http://www.bard.edu%s' % link <NEW_LINE> request = Request(p_link, callback=self.parse_profile_page) <NEW_LINE> yie...
Getting links to profiles
625941e79c8ee82313fbbbec
def set_redirect_found(self, url): <NEW_LINE> <INDENT> self.set_status_code(SC.REDIRECT_FOUND) <NEW_LINE> self.put_header("Location", url)
Set the response to redirect client to specified url Arguments: url (str): redirection location url
625941e796565a6dacc8fb3f
def setOffsetInMilliSeconds(self, milliSeconds): <NEW_LINE> <INDENT> if milliSeconds.isdigit(): <NEW_LINE> <INDENT> milliSeconds = int(milliSeconds) <NEW_LINE> self.data['audioItem']['stream']['offsetInMilliSeconds'] = milliSeconds <NEW_LINE> <DEDENT> return self
设置directive的属性。从指定的offset开始进行播放 :param milliSeconds: 毫秒数。比如5分钟的歌曲,播放的长度是5*60*1000毫秒,选择起始的播放位置 :return:
625941e75fc7496912cc3df3
def test_add_nonexistant_group(self): <NEW_LINE> <INDENT> result = add_group(self._groups_collection, "Fake University") <NEW_LINE> assert self._groups_collection.find_one(({"group_name": "Fake University"}))["_id"]
Asserts add_group returns ObjectID of a group that doesn't already exist in the collection
625941e7b830903b967e9d7c
def ship_as_dict(ship): <NEW_LINE> <INDENT> correct_ship = dict() <NEW_LINE> correct_ship['stern_x'] = ship.stern[0] <NEW_LINE> correct_ship['stern_y'] = ship.stern[1] <NEW_LINE> correct_ship['bow_x'] = ship.bow[0] <NEW_LINE> correct_ship['bow_y'] = ship.bow[1] <NEW_LINE> correct_ship['ship_type'] = ship.type <NEW_LINE...
Convert namedtuple Ship items into correct from, so that they can be sent to the server.
625941e7167d2b6e3121900a
@contextmanager <NEW_LINE> def compressor(path, level=None, append=False): <NEW_LINE> <INDENT> level = LZ4F_COMPRESSION_MAX if level is None else level <NEW_LINE> with open(path, "ab" if append else "wb") as writer: <NEW_LINE> <INDENT> with _WritableCompressor(writer, level=level) as context: <NEW_LINE> <INDENT> yield ...
Create a data compressing context manager for file writing. When 'level' is None, a default LZ4F_COMPRESSION_MAX level is used. When 'append' is True, the open mode is set for appending data.
625941e7aad79263cf390ebd
def clear_jacobi(self) -> None: <NEW_LINE> <INDENT> self.jacobi = None
clear jacobi value
625941e79f2886367277acff
def testRMGSeedEdgeLibraryCreation(self): <NEW_LINE> <INDENT> self.assertTrue(os.path.exists(self.seedThermo)) <NEW_LINE> self.assertTrue(os.path.exists(self.seedKinetics))
Test that edge seed mechanisms are created in the correct database locations.
625941e75510c4643540f84e
def _get_bridge_name(self): <NEW_LINE> <INDENT> command = ovs_vsctl.VSCtlCommand( 'find', ('Bridge', 'datapath_id=%s' % dpid_lib.dpid_to_str(self.datapath_id))) <NEW_LINE> self.run_command([command]) <NEW_LINE> if not isinstance(command.result, list) or len(command.result) != 1: <NEW_LINE> <INDENT> raise OVSBridgeNotFo...
get Bridge name of a given 'datapath_id'
625941e7d53ae8145f87a6dd
@csrf_exempt <NEW_LINE> def checkAddAuthority(year, courseName, majorName): <NEW_LINE> <INDENT> courseSubjectList = CoursesInDisciplines.objects.filter(course=courseName).all() <NEW_LINE> courseSpecialSubjectList = CoreCoursesInSpecializedSubject.objects.filter(course=courseName).all() <NEW_LINE> for cs in courseSubjec...
educList = EducationCourses.objects.filter(year=year, majorName=majorName).all() for e in educList: if e.courseName == courseName: result = "sorry,不能修改该课程。 该课程已存在于该年度该专业中!" return result
625941e792d797404e304602
def do_comparison_to_overflow(gate, comparand_reg, target_bit, controls): <NEW_LINE> <INDENT> if gate.comparand <= 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> overflow_val = 1 << len(comparand_reg) <NEW_LINE> if gate.comparand >= overflow_val: <NEW_LINE> <INDENT> X & controls | target_bit <NEW_LINE> return <NEW_L...
N: len(query_reg) C: len(controls) Size: O(N + C) Depth: O(N + C) Args: gate (LessThanConstantGate): The gate to decompose, containing the constant to compare against. comparand_reg (projectq.types.Qureg): The register that we want to compare against a constant. target_bit (projectq.types.Qu...
625941e78e7ae83300e4b444
def _check_param(self, request, raml_param): <NEW_LINE> <INDENT> param = request.get_param(raml_param.name) <NEW_LINE> if raml_param.required and param is None: <NEW_LINE> <INDENT> raise falcon.HTTPMissingParam(raml_param.name) <NEW_LINE> <DEDENT> if raml_param.type and param is not None: <NEW_LINE> <INDENT> self.check...
Check if the request parameters are valid. The behavior of this function is like _check_header, but for query parameters and body form parameters.
625941e7009cb60464c63823
def lengthOfLIS(self, nums: List[int]) -> int: <NEW_LINE> <INDENT> mem = [1] * len(nums) <NEW_LINE> res = 1 <NEW_LINE> for i, num in enumerate(nums): <NEW_LINE> <INDENT> for j in range(0, i): <NEW_LINE> <INDENT> if nums[j] < num: <NEW_LINE> <INDENT> mem[i] = max(mem[i], mem[j]+1) <NEW_LINE> <DEDENT> <DEDENT> res = max(...
Args: - nums: list of integers, [1, 2500], [-10^4, 10^4] Returns: - int: longest increasing sequence Analysis: - sequential problem: order matters - longest increasing sequence - 9, 10, 1, 12, 13 -> 1 is not important in this case - 10, 1, 2, 12, 13 -> 1 is important in this case - mem_list: record c...
625941e721a7993f00bc816d
def shutdown(self): <NEW_LINE> <INDENT> self.lcr.clear() <NEW_LINE> self.lcr.close() <NEW_LINE> self.timeOut = np.zeros((self.cfg['NUM_SAMPLES'])) <NEW_LINE> self.output = np.zeros((self.cfg['NUM_SAMPLES'], self.numChannels * 2)) <NEW_LINE> print('LCR shutting down...') <NEW_LINE> return 0
@brief: close connection to the LCR, clear arrays
625941e77d43ff24873a3119
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941e7b545ff76a891428b
def create_shop(date): <NEW_LINE> <INDENT> request = aiofnbr.Shop(api_key) <NEW_LINE> response = loop.run_until_complete(request.send()) <NEW_LINE> daily_shop = [] <NEW_LINE> featured_shop = [] <NEW_LINE> if response.status == 200 and response.type == aiofnbr.constants.SHOP_TYPE: <NEW_LINE> <INDENT> shop = response.dat...
Make today's shop image (produces a .png) date - the date that appears at the top of the image This function performs the following steps: 1. Gets the daily shop information using fnbr.co's API 2. Creates icons for each item and saves them in two arrays 3. Creates a blank canvas for the shop image 4. For each icon cr...
625941e78a349b6b435e85e8
def get_readonly_fields(self, request, obj=None): <NEW_LINE> <INDENT> if obj: <NEW_LINE> <INDENT> return self.readonly_fields + ('id_sup', 'id_ref', 'change_taxon',) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.readonly_fields + ('info',)
Return a list of readonly fields when a taxon is valid or not :param request: an request object (see Django doc) :param obj: an Taxon object (see models.py) :return: the readonly field
625941e7287bf620b61d3ed7
def testNotFoundErrors(self): <NEW_LINE> <INDENT> pass
Test NotFoundErrors
625941e7d8ef3951e32439b4
def policy_create(request, args): <NEW_LINE> <INDENT> client = congressclient(request) <NEW_LINE> policy = client.create_policy(args) <NEW_LINE> return policy
Create a policy with the given properties.
625941e70c0af96317bb865e
def test_import_author(self): <NEW_LINE> <INDENT> response = self.do_import( author_name="Testing User", author_email="john@example.com" ) <NEW_LINE> self.assertRedirects(response, self.translation_url) <NEW_LINE> translation = self.get_translation() <NEW_LINE> self.assertEqual(translation.stats.translated, 1) <NEW_LIN...
Test importing normally.
625941e7046cf37aa974d1b9
def validate_unique(schema, data, model): <NEW_LINE> <INDENT> unique_columns = [c.key for c in model.__table__.columns if c.unique] <NEW_LINE> conditions = [getattr(model, column) == data.get(column) for column in unique_columns if data.get(column)] <NEW_LINE> update_id = schema.context.get('update_id', None) <NEW_LINE...
Check whether a row already exists in the database with one or more key(column), value pairs from the provided data dictionary. :param schema: The schema instance that is calling the validator. :param data: the dictionary with data to validate. :param model: the model to validate against. It assumes the model has an ...
625941e7236d856c2ad44c56
def _connect_layer(self, Layer) -> None: <NEW_LINE> <INDENT> if (Layer != None): <NEW_LINE> <INDENT> self._preLayer = Layer <NEW_LINE> Layer._nextLayers.append(self) <NEW_LINE> self._layerNo = Layer._layerNo + 1
Connecting layers. If Layer arguments in `__call__` method is None, it means it it input layer of model. Others are previous layer of current layer. Thus, it should be connected
625941e73c8af77a43ae3c1c
def print_log(self): <NEW_LINE> <INDENT> f = open(self.log_file) <NEW_LINE> print(f.read()) <NEW_LINE> f.close()
Print log file
625941e7f7d966606f6aa480
def pagan_sossounov(prices, window=8, censor=6, cycle=16, phase=4, threshold=0.2): <NEW_LINE> <INDENT> pass
Pagan and Sossounov's labeling method. Sourced from `Pagan, Adrian R., and Kirill A. Sossounov. "A simple framework for analysing bull and bear markets." Journal of applied econometrics 18.1 (2003): 23-46. <https://onlinelibrary.wiley.com/doi/pdf/10.1002/jae.664>`__ Returns a DataFrame with labels of 1 for Bull and -1...
625941e7b5575c28eb68e47a
def onVariableChanged(self, variablename: str, newvalue: Any, previousvalue: Any): <NEW_LINE> <INDENT> row = [i for i, v in enumerate(self._variables) if v.name == variablename][0] <NEW_LINE> self.dataChanged.emit( self.index(row, 0, QtCore.QModelIndex()), self.index(row, self.columnCount(), QtCore.QModelIndex()), ) <N...
This method is called before the variableChanged signal is emitted.
625941e7435de62698dfe0c3
def main() -> None: <NEW_LINE> <INDENT> sources = sys.argv[1:] <NEW_LINE> report_dir = "/reports/coverage/api" <NEW_LINE> dest_dir = "/tmp/coverage/api" <NEW_LINE> shutil.rmtree(dest_dir, ignore_errors=True) <NEW_LINE> shutil.copytree(report_dir, dest_dir) <NEW_LINE> cov = coverage.Coverage( data_file=os.path.join(dest...
Run the command.
625941e70383005118ecfa57
def make_plot(datas, free_var_topics, log_var_topics, free_sam_topics, log_sam_topics, labels, outputdir, filename, colors): <NEW_LINE> <INDENT> new_plot = plot.Plotter(colors) <NEW_LINE> min_y = float('inf') <NEW_LINE> max_y = float('-inf') <NEW_LINE> for key, data in datas.items(): <NEW_LINE> <INDENT> topics = None <...
Makes a single plot with multiple lines datas: {['free' or 'log']: [float]} num_topics: [int] labels: {'xlabel': string, 'ylabel': string} outputdir: string filename: string colors: returned by plot.get_separate_colors(int)
625941e7507cdc57c630715c
def __init__(self, py_dict=None): <NEW_LINE> <INDENT> super(ServiceProfileAttributeSchema, self).__init__() <NEW_LINE> self.set_data_type('xml') <NEW_LINE> self.key = None <NEW_LINE> self.name = None <NEW_LINE> self.value = None <NEW_LINE> if py_dict is not None: <NEW_LINE> <INDENT> self.get_object_from_py_dict(py_dict...
Constructor to create ServiceProfileAttributeSchema object @param py_dict : python dictionary to construct this object
625941e756ac1b37e626463d
def test_no_sm_clause_for_op(self): <NEW_LINE> <INDENT> record = 'AGR0000123400000023C1234567890123D1234567890123OP201201022013020320140304D20100405D201605062017060701234 YY0123456789012A'
Tests that am exception is thrown when the Sales/Manufacture Clause is not set for an Agreement which requires it.
625941e7d99f1b3c44c679fd
def shake(self): <NEW_LINE> <INDENT> if self.sizexyz[2] is not None: <NEW_LINE> <INDENT> self.pos[:,2] = self.bound[2, 1] - (self.pos[:,2] - self.bound[2, 0]) <NEW_LINE> self.vel = (np.random.rand(self.n, 3) - 0.5) * 10
Inverts the z position and gives all the balls random velocity.
625941e730bbd722463cc23f
def patch_site(self): <NEW_LINE> <INDENT> conf_path = os.path.join(self.target_dir, "conf.py") <NEW_LINE> with codecs.open(conf_path, "ab", "utf8") as outf: <NEW_LINE> <INDENT> outf.write('\nPOSTS = (("posts/*.txt", "posts", "post.tmpl"),("posts/*.txt", "posts", "post.tmpl"))\n')
Set the SITE_URL to have a path
625941e7e5267d203edce10d
def fill_chromosomes_table(): <NEW_LINE> <INDENT> database = sqlite3.connect(DATABASE_PATH) <NEW_LINE> in_table_ids = database.cursor().execute('SELECT chromosome_id FROM chromosomes').fetchall() <NEW_LINE> if not len(in_table_ids): <NEW_LINE> <INDENT> chromosome_names_found = {} <NEW_LINE> reference_fasta = pysam.Fast...
Fill the chromosomes table get bam file headers for each sample
625941e77b25080760e398cd
def friendly_serial(serial): <NEW_LINE> <INDENT> result = '' <NEW_LINE> length = min(len(serial), 10) <NEW_LINE> start = len(serial) - length <NEW_LINE> for i, char in enumerate(serial[start:]): <NEW_LINE> <INDENT> result += char <NEW_LINE> if i % 2 == 1: <NEW_LINE> <INDENT> result += ':' <NEW_LINE> <DEDENT> <DEDENT> r...
Returns a more user-friendly rendering of the passed cert serial.
625941e76aa9bd52df03721d
def unpack_bytes(data, pointer=0, length=-1): <NEW_LINE> <INDENT> if length < 0: <NEW_LINE> <INDENT> pointer, length = unpack_length(data, pointer) <NEW_LINE> <DEDENT> return pointer + length, data[pointer:pointer + length]
Unpacks Bytes.
625941e7851cf427c661a981
def _add_stub(self, session, scenario, body): <NEW_LINE> <INDENT> headers = {'session': session} <NEW_LINE> self.http_client.fetch(self.get_url('/api/v2/scenarios/objects/%s/stubs' % scenario), self.stop, method="PUT", headers=headers, body=json.dumps(body)) <NEW_LINE> response = self.wait() <NEW_LINE> return response
Adds stub for specified scenario :param session: session name :param scenario: scenario name :return: returns a response from Stubo
625941e76aa9bd52df03721e
def shopItemList(self, shopid, pagecount): <NEW_LINE> <INDENT> iteminfolist = [] <NEW_LINE> for i in range(0, pagecount): <NEW_LINE> <INDENT> url, headers = apis.xpMyShopItemByid(shopid=shopid, page=i) <NEW_LINE> response = requests.get(url=url, headers=headers) <NEW_LINE> body = response.text <NEW_LINE> try: <NEW_LINE...
获取店铺的所有商品信息 :param shopid: :param page: :return:
625941e7a4f1c619b28b04a5
def linked_list_has_cycle(head): <NEW_LINE> <INDENT> if head is None or head.next is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> slow = head <NEW_LINE> fast = head <NEW_LINE> while fast.next is not None and fast.next.next is not None: <NEW_LINE> <INDENT> slow = slow.next <NEW_LINE> fast = fast.next.next ...
检查链表是否是环链表 :param head: :return:
625941e7cdde0d52a9e534ad
@nose.tools.with_setup(common.create_singleversion_table, common.cleanup) <NEW_LINE> def test_table_snapshot_relaunch(): <NEW_LINE> <INDENT> table_name = 'test' <NEW_LINE> dump_file1 = 'dump1.out' <NEW_LINE> dump_file2 = 'dump2.out' <NEW_LINE> scan_file1 = 'scan1.out' <NEW_LINE> scan_file2 = 'scan2.out' <NEW_LINE> comm...
table cluster relaunch 1. write data set 1 2. create snapshot 3. write data set 2 4. scan w/snapshot, scan w/o snapshot & compare 5. kill & launch cluster 6. repeat 4 :return: None
625941e7596a897236089f31
def fibonacci_recursive(nth: int) -> int: <NEW_LINE> <INDENT> if nth < 0: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> if nth == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if nth == 1: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return fibonacci_recursive(nth-1) + fibonacci_recursive(nth-2)
nth Fibonacci number, with recursive logic
625941e78c0ade5d55d3ee35
def aa_frequencies(seq, gap_chars='-.'): <NEW_LINE> <INDENT> aa_counts = Counter(seq) <NEW_LINE> for gap_char in gap_chars: <NEW_LINE> <INDENT> if gap_char in aa_counts: <NEW_LINE> <INDENT> del aa_counts[gap_char] <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> scale = 1.0 / sum(aa_counts.values()) <NEW_LINE> <DE...
Calculate the amino acid frequencies in a sequence set.
625941e75fdd1c0f98dc06ac
def parse_releasedata(self): <NEW_LINE> <INDENT> df = pd.read_html(self.raw_html_resolution, flavor="bs4") <NEW_LINE> list_of_release_df = [] <NEW_LINE> for table_id in range(len(df)): <NEW_LINE> <INDENT> if table_id == 0: <NEW_LINE> <INDENT> df_header = df[table_id][:1] <NEW_LINE> current_df = df[table_id][1:] <NEW_LI...
Accepts the html data for product releases from the KB article for parsing with pandas.
625941e766656f66f7cbc623
def set_state_action_spaces(self, state_space, action_space): <NEW_LINE> <INDENT> raise NotImplemented()
Set state/action space descriptors Params: state_space: gym.spaces.Box (tested) or Discrete (not tested) action_space: gym.spaces.Box (not tested) or Discrete (tested)
625941e7d268445f265b52e5
def toList(self): <NEW_LINE> <INDENT> return [self.v_tcp, self.v_ori, self.v_leax, self.v_reax]
converts to list
625941e776e4537e8c351aec
def __init__(self, status, user, _raw=None): <NEW_LINE> <INDENT> super(ChatMemberMember, self).__init__() <NEW_LINE> assert_type_or_raise(status, unicode_type, parameter_name="status") <NEW_LINE> self.status = status <NEW_LINE> assert_type_or_raise(user, User, parameter_name="user") <NEW_LINE> self.user = user <NEW_LIN...
Represents a chat member that has no additional privileges or restrictions. https://core.telegram.org/bots/api#chatmembermember Parameters: :param status: The member's status in the chat, always "member" :type status: str|unicode :param user: Information about the user :type user: pytgbot.api_types.receivable.pe...
625941e7eab8aa0e5d26dfd0