code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __init__(self, name, mode, cron_string, command_ipynb, job_id): <NEW_LINE> <INDENT> self.id = job_id <NEW_LINE> self.command_ipynb = command_ipynb <NEW_LINE> self.name = name <NEW_LINE> self.mode = mode <NEW_LINE> self.job_dir = f'{BASE_DIR}/jobs/{self.id}' <NEW_LINE> self.pid = self.get_pid_name() <NEW_LINE> if no... | The Job class is responsible for all operations necessary to create, delete, start and stop a Job.
Create the necessary Job directory if it doesnt exist.
Create an instance of CronTab if the Job is a Cron-Job.
Additional attributes:
*self.job_dir*: specifies the directory of the Job.
*self.job_file*: stores the nam... | 625941cb5166f23b2e1a5225 |
def fit(self, imgs, y=None, confounds=None): <NEW_LINE> <INDENT> BaseDecomposition.fit(self, imgs) <NEW_LINE> data = mask_and_reduce(self.masker_, imgs, confounds=confounds, n_components=self.n_components, random_state=self.random_state, memory=self.memory, memory_level=max(0, self.memory_level - 1), n_jobs=self.n_jobs... | Compute the mask and the components
Parameters
----------
imgs: list of Niimg-like objects
See http://nilearn.github.io/manipulating_visualizing/manipulating_images.html#niimg.
Data on which the PCA must be calculated. If this is a list,
the affine is considered the same for all.
confounds: CSV file path ... | 625941cb5510c4643540f4b1 |
def save_guesses(self): <NEW_LINE> <INDENT> out = util.getString('name your guesses file', default='guess_save') <NEW_LINE> if out == '': <NEW_LINE> <INDENT> out = 'guessed_params' <NEW_LINE> <DEDENT> self.set_guess_dict_from_entries() <NEW_LINE> spl.guess_saver(self.wd.get(), out, self.guess_dict) | save guesses parameters to a file | 625941cb4428ac0f6e5ba8be |
def gcd(m, n): <NEW_LINE> <INDENT> if m == n: <NEW_LINE> <INDENT> return m <NEW_LINE> <DEDENT> elif m < n: <NEW_LINE> <INDENT> return gcd(n, m) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return gcd(m-n, n) | Return the largest k that evenly divides both m and n.
k, m, and n are all positive integers.
>>> gcd(12, 8)
4
>>> gcd(16, 12)
4
>>> gcd(16, 8)
8
>>> gcd(2, 16)
2
>>> gcd(24, 42)
6
>>> gcd(5, 5)
5 | 625941cbd7e4931a7ee9dfea |
def fprop(self, y, cell, inputs, tau): <NEW_LINE> <INDENT> be = self.backend <NEW_LINE> self.cell_fprop(inputs, y, tau, 'i', self.gate_activation) <NEW_LINE> self.cell_fprop(inputs, y, tau, 'f', self.gate_activation) <NEW_LINE> self.cell_fprop(inputs, y, tau, 'o', self.gate_activation) <NEW_LINE> self.cell_fprop(inputs... | Forward pass for the google-style LSTM cell with forget gates, no
peepholes. cell (``self.c_t``) and hidden (``self.output_list``)
activity variables will be updated as a result.
Arguments:
y: input from prev. time step (eg. one batch of (64, 50) size)
cell: state of memory cell from prev. time step (s... | 625941cb5510c4643540f4b2 |
def on_report(self, *args): <NEW_LINE> <INDENT> warning = ReportWarning() <NEW_LINE> warning.text = ('Warning. Some web browsers doesn\'t post the full' ' traceback error. \n\nPlease, check if the last line' ' of your report is "End of Traceback". \n\n' 'If not, use the "Copy to clipboard" button the get' 'the full rep... | Event handler to "Report Bug" button
| 625941cb91f36d47f21ac5bf |
def get_user(login): <NEW_LINE> <INDENT> return instance().get_user(login=login) | get user | 625941cb23e79379d52ee631 |
def testBlendModes(self): <NEW_LINE> <INDENT> self.mComposerRect2.setBlendMode(QPainter.CompositionMode_Multiply) <NEW_LINE> checker = QgsCompositionChecker('composereffects_blend', self.mComposition) <NEW_LINE> checker.setControlPathPrefix("composer_effects") <NEW_LINE> myTestResult, myMessage = checker.testCompositio... | Test that blend modes work for composer items. | 625941cb796e427e537b0692 |
def get_cst_node_type(cst): <NEW_LINE> <INDENT> if type(cst) == list: <NEW_LINE> <INDENT> if len(cst) == 0: <NEW_LINE> <INDENT> return 'const' <NEW_LINE> <DEDENT> if type(cst[0]) in (str, six.text_type): <NEW_LINE> <INDENT> if cst[0] in GNN_NODE_CLASS: <NEW_LINE> <INDENT> return cst[0] <NEW_LINE> <DEDENT> if cst[0] in ... | Return the constraint tree node type of cst. | 625941cb498bea3a759b9b7b |
def _convert_to_example(image_data, labels, labels_text, bboxes, shape, difficult, truncated): <NEW_LINE> <INDENT> xmin = [] <NEW_LINE> ymin = [] <NEW_LINE> xmax = [] <NEW_LINE> ymax = [] <NEW_LINE> for b in bboxes: <NEW_LINE> <INDENT> assert len(b) == 4 <NEW_LINE> [l.append(point) for l, point in zip([ymin, xmin, ymax... | Build an Example proto for an image example.
Args:
image_data: string, JPEG encoding of RGB image;
labels: list of integers, identifier for the ground truth;
labels_text: list of strings, human-readable labels;
bboxes: list of bounding boxes; each box is a list of integers;
specifying [xmin, ymin, xmax, y... | 625941cb2ae34c7f2600d1fe |
def test_registeredUserCanLogIn(self): <NEW_LINE> <INDENT> registerAndLogin(self, username=validUsername, password=validPassword, email=validEmail) <NEW_LINE> user = auth.get_user(self.client) <NEW_LINE> self.assertTrue(user.is_authenticated(), "Registered user could not log in") | Users should be able to register and log in | 625941cb3eb6a72ae02ec5a9 |
def add_edge(self, e): <NEW_LINE> <INDENT> v, w = e <NEW_LINE> self[v][w] = e <NEW_LINE> self[w][v] = e | Adds and edge to the graph by adding an entry in both directions.
If there is already an edge connecting these Vertices, the
new edge replaces it. | 625941cb2c8b7c6e89b3588d |
def generate_news_list(): <NEW_LINE> <INDENT> html_source = urllib2.urlopen(NEWS_SITE) <NEW_LINE> soup = BeautifulSoup(html_source.read()) <NEW_LINE> newslist = [] <NEW_LINE> for i in range (2, 32): <NEW_LINE> <INDENT> htmltext = soup('li')[i] <NEW_LINE> weblink = htmltext('a')[0]['href'] <NEW_LINE> info = htmltext.fin... | generate news list | 625941cb6aa9bd52df036e71 |
def setUp(self): <NEW_LINE> <INDENT> super(ProjectAPITests, self).setUp() <NEW_LINE> self.pending_user = milkman.deliver( PendingUser, email="pendingu@example.com") <NEW_LINE> self.project = milkman.deliver(Project) <NEW_LINE> self.project.set_owner(self.admin) <NEW_LINE> self.project.add_admin(self.user, pending=False... | Bootstrap with project data | 625941cba8ecb033257d319a |
def dock_control_for ( self, info, parent, object ): <NEW_LINE> <INDENT> from enthought.pyface.dock.core import IDockable, DockControl <NEW_LINE> from view import View <NEW_LINE> from dockable_view_element import DockableViewElement <NEW_LINE> try: <NEW_LINE> <INDENT> name = object.name <NEW_... | Returns the DockControl object for a specified object.
| 625941cba219f33f34628a37 |
def at_cmdset_creation(self): <NEW_LINE> <INDENT> super(AccountCmdSet, self).at_cmdset_creation() | Populates the cmdset | 625941cbd10714528d5ffdaf |
def reconnect( self, port: str = None, baudrate: int = None, timeout: float = None, ): <NEW_LINE> <INDENT> self.disconnect() <NEW_LINE> baudrate = self.interface.baudrate if baudrate is None else baudrate <NEW_LINE> port = self.interface.port if port is None else port <NEW_LINE> timeout = self.interface.timeout if time... | Reconnect to PSLab.
Will reuse previous settings (port, baudrate, timeout) unless new ones are
provided.
Parameters
----------
See :meth:`connect`. | 625941cb63d6d428bbe445bc |
def sample_detail_size(location=(0, 0)): <NEW_LINE> <INDENT> pass | Sample the mesh detail on clicked point
Arguments:
@location (int): Screen Coordinates of sampling
array of 2 items in [0, 32767], (optional) | 625941cbd6c5a10208144117 |
def get(handler, endpoint): <NEW_LINE> <INDENT> do_endpoint("get", handler, endpoint, None) | GET method | 625941cb15fb5d323cde0bdc |
@pytest.mark.parametrize("interval", (1, 2, 3, 4, 10, 50, 100, 5000)) <NEW_LINE> def test_interval_limit_succ(runner, interval): <NEW_LINE> <INDENT> flexmock(twitter, parse_configuration=lambda path: exit(100)) <NEW_LINE> result = runner.invoke(twitter.cli, ["console", "--interval", interval, "--search", "python"]) <NE... | Test whether interval succeeds when greater or equal 1 | 625941cba79ad161976cc212 |
def add_error(self, title, details): <NEW_LINE> <INDENT> self["@error"] = { "@title": title, "@messages": [details], } | Adds an error element to the object. Should only be used for the root
object, and only in error scenarios.
Note: Mason allows more than one string in the @messages property (it's
in fact an array). However we are being lazy and supporting just one
message.
: param str title: Short title for the error
: param str deta... | 625941cb498bea3a759b9b7c |
def showSignatureVariances(mode_ensemble, **kwargs): <NEW_LINE> <INDENT> from matplotlib.pyplot import xlabel <NEW_LINE> fract = kwargs.pop('fraction', True) <NEW_LINE> if fract: <NEW_LINE> <INDENT> sig = calcSignatureFractVariance(mode_ensemble) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sig = mode_ensemble.getVari... | Show the distribution of signature variances using
:func:`showSignatureDistribution`. | 625941cbf9cc0f698b1406c9 |
def test_query(self): <NEW_LINE> <INDENT> self.assertRaisesRegexp(ValueError, "is not", wikipedia.queryGenerator, None) <NEW_LINE> useragents = bingCommon.UserAgents().generate(self.config.accounts) <NEW_LINE> b = BingRewards(bingCommon.HEADERS, useragents, self.config) <NEW_LINE> self.config.login = None <NEW_LINE> b ... | test queryGenerator
:return: | 625941cb3346ee7daa2b2e38 |
def save_to_file(onset_times, beat_times): <NEW_LINE> <INDENT> file_name = "mapping_" + time.strftime("%b_%d__%H_%M_%S") + ".txt" <NEW_LINE> text_file = open(file_name, "w") <NEW_LINE> text_file.write("beat_times = [") <NEW_LINE> text_file.write(", ".join([str(a) for a in beat_times])) <NEW_LINE> text_file.write("]") <... | Save the arrays in a txt file
| 625941cb66656f66f7cbc277 |
def retrieve_daily_tmc_data_file(antenna, device, monitorpoint, date, verbose = True, outpath='./'): <NEW_LINE> <INDENT> isodate = get_datetime_from_isodatetime(date).date().strftime('%Y-%m-%d') <NEW_LINE> inputdate = datetime.datetime.strptime(date, '%Y-%m-%d') <NEW_LINE> rooturl = get_root_url_for_curl(date) <NEW_LIN... | Retrieve TMC monitor data via HTTP.
Parameters are something like:
antenna = 'DV01'
device = 'LLC'
monitorpoint = 'CNTR_0'
date = '2010-04-24' # ISO-8601 date or datetime string
outpath = set this if you don't want to write the result to the working directory
Return the name of the file if succeeded, otherwise '_CU... | 625941cb67a9b606de4a7f87 |
def _apply_holdout(self, _mode="sequential", train_size=0, train_prop=0): <NEW_LINE> <INDENT> train = None <NEW_LINE> valid = None <NEW_LINE> if train_size !=0: <NEW_LINE> <INDENT> dataset_iter = self.iterator(mode=_mode, batch_size=(self.num_examples - train_size), num_batches=2) <NEW_LINE> train = dataset_iter.next()... | This function splits the dataset according to the number of
train_size if defined by the user with respect to the mode provided
by the user. Otherwise it will use the
train_prop to divide the dataset into a training and holdout
validation set. This function returns the training and validation
dataset.
Parameters
-----... | 625941cb57b8e32f52483567 |
def combineExpression(self, connector, subExpressions): <NEW_LINE> <INDENT> conn = ' %s ' % connector <NEW_LINE> return conn.join(subExpressions) | Combine a list of subexpressions into a single expression, using
the provided connecting operator. This is required because operators
can vary between backends (e.g., Oracle with %% and &) and between
subexpression types (e.g., date expressions) | 625941cbeab8aa0e5d26dc25 |
def get_pivot(arr, low, high): <NEW_LINE> <INDENT> mid = (high + low) // 2 <NEW_LINE> pivot = high <NEW_LINE> if arr[low] < arr[high]: <NEW_LINE> <INDENT> if arr[mid] < arr[high]: <NEW_LINE> <INDENT> pivot = mid <NEW_LINE> <DEDENT> elif arr[low] < arr[high]: <NEW_LINE> <INDENT> pivot = low <NEW_LINE> <DEDENT> <DEDENT> ... | We have a low index, high index and a middle index. We conpare all
three and choose the middle | 625941cb92d797404e304257 |
def get_track_path(self): <NEW_LINE> <INDENT> self.track_path = str(self.__unquote(self.request("path ?"))) <NEW_LINE> return self.track_path | Get Players Current Track Path | 625941cb21a7993f00bc7dbc |
def create_tables(self, schema=None): <NEW_LINE> <INDENT> con = sqlite3.connect(self.db_path) <NEW_LINE> if schema is None: <NEW_LINE> <INDENT> schema = DEFAULT_SCHEMA <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> with open(schema, encoding="utf-8") as f: <NEW_LINE> <INDENT> sql = f.read() <NEW_LINE> cur = con.cursor() ... | Create programmatically the tables from a schema file.
:param schema: path to the .sql schema file. If this parmeter is
None, then *db/critique_schema_dump.sql* is utilized.
:references:
:[1]: Exercise1, forum.database.py | 625941cbfb3f5b602dac3760 |
def test_get_fuction_returns_value_with_multiple_possibilites(ht_fixture): <NEW_LINE> <INDENT> ht_fixture.set('rowd', 'this is my first value') <NEW_LINE> ht_fixture.set('word', 'this is my second value') <NEW_LINE> assert ht_fixture.get('word') == 'this is my second value' | Test get function returns correct value when multiple keys are stored
at same index in table. | 625941cbde87d2750b85fe60 |
def team_event_key(team_key_val, event_id): <NEW_LINE> <INDENT> return ndb.Key(TeamEvent, event_id, parent=team_key_val) | Constructs a Datastore key for a team_event entity with a team_key as parent and event_id as id | 625941cb96565a6dacc8f799 |
def delete_translations(self, language=None): <NEW_LINE> <INDENT> from .models import Translation <NEW_LINE> return Translation.objects.delete_translations(obj=self, language=language) | Deletes related translations. | 625941cba79ad161976cc213 |
def test03_diff_in_out_maindims(self): <NEW_LINE> <INDENT> shape = list(self.shape) <NEW_LINE> a = np.arange(np.prod(shape), dtype="i4").reshape(shape) <NEW_LINE> b = a.copy() <NEW_LINE> c = a.copy() <NEW_LINE> root = self.h5file.root <NEW_LINE> shape2 = shape[:] <NEW_LINE> shape[self.maindim] = 0 <NEW_LINE> shape2[0] ... | Checking different maindims in inputs and output. | 625941cbcb5e8a47e48b7b78 |
def post(self): <NEW_LINE> <INDENT> name = self.request.get('name', default_value=None) <NEW_LINE> rssUrl = self.request.get('rssUrl', default_value=None) <NEW_LINE> quality = self.request.get('quality', default_value=None) <NEW_LINE> zipped = self.request.get('zipped', default_value=False) == "true" <NEW_LINE> authori... | name -- string: The name of this file source
slug -- stirng: URL friendly version of the name
rssUrl -- string: The rss feed url
quality -- string: The quality of the files in this source
zipped -- boolean: Are the files from this source zip files?
authorizationRequired -- boolean: When d... | 625941cb76e4537e8c351740 |
@logger <NEW_LINE> def extract_date(data_set): <NEW_LINE> <INDENT> sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME <NEW_LINE> try: <NEW_LINE> <INDENT> variable_name = None <NEW_LINE> variable_value = None <NEW_LINE> date_format = None <NEW_LINE> for row in data_set: <NEW_LINE> <INDENT> if "act... | Parse date from a given string and save it into a variable
Action format:
parse date common action variable_name = %|string_containing_date|% | 625941cb009cb60464c6347f |
def update_available_contacts(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.socket.request_user_list() <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOGGER.debug( 'Запрос списка пользователей выполнен успешно.' ) <NEW_LINE> self.show_available_cont... | Update the list of available contacts from the database. | 625941cb8a349b6b435e8240 |
def paste_object(): <NEW_LINE> <INDENT> payload = pyperclip.paste() <NEW_LINE> if payload[0] != 'b': <NEW_LINE> <INDENT> raise Exception("Clipboard does not seem to contain valid hex string") <NEW_LINE> <DEDENT> hex_str = payload[2:-1] <NEW_LINE> hex_obj = binascii.unhexlify(hex_str) <NEW_LINE> return pickle.loads(hex_... | Paste an object copied to the clipboard with `copy_object`.
Returns:
A Python object previously copied to the clipboard | 625941cbd4950a0f3b08c41d |
def __init__(self, center, radius, myid = None, figure=None, axes_object=None): <NEW_LINE> <INDENT> self.center = center <NEW_LINE> self.radius = radius <NEW_LINE> self.fig = figure <NEW_LINE> self.ax = axes_object <NEW_LINE> self.myid = myid <NEW_LINE> self.mypatch = None | @ARGS
CENTER : Tuple of floats
RADIUS : Float | 625941cb4a966d76dd5510dc |
def show_dictionary_differences(self, show_matching=True, show_changed=True, show_removed=True, show_added=True): <NEW_LINE> <INDENT> removed_key_and_value = {} <NEW_LINE> added_key_and_value = {} <NEW_LINE> changed_values = {} <NEW_LINE> matching_keys_and_values = {} <NEW_LINE> for key, value in self.old_dictionary.it... | Shows the matching, changed, removed, and added dictionary keys and values
:return: None | 625941cb379a373c97cfac12 |
def update_policies_with_http_info(self, policy_patch, **kwargs): <NEW_LINE> <INDENT> all_params = ['policy_patch', 'names'] <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_params.append('_request_timeout') <... | Update an existing policy.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_policies_with_http_info(polic... | 625941cb656771135c3eb93c |
def test_min_python_3_6(): <NEW_LINE> <INDENT> assert sys.version_info.major >= 3 <NEW_LINE> if sys.version_info.major == 3: <NEW_LINE> <INDENT> assert sys.version_info.minor >= 6 | This package depends on PEP 468, introduced in Python 3.6 | 625941cb167d2b6e31218c63 |
def nextPermutation(self, nums): <NEW_LINE> <INDENT> if len(nums) <= 1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for i in range(len(nums) - 2, -1, -1): <NEW_LINE> <INDENT> if nums[i + 1] > nums[i]: <NEW_LINE> <INDENT> for j in range(len(nums) - 1, i, -1): <NEW_LINE> <INDENT> if nums[j] > nums[i]: <NEW_LINE> <INDE... | :type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead. | 625941cb63d6d428bbe445bd |
def is_older_than(self, age_in_seconds): <NEW_LINE> <INDENT> if time() - self.__last_usage_time > age_in_seconds: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Check if this view config is older than some time in secs.
Args:
age_in_seconds (float): time in seconds
Returns:
bool: True if older, False otherwise | 625941cbd99f1b3c44c6765c |
def login(request): <NEW_LINE> <INDENT> form = request.form() <NEW_LINE> u, result = User.login(form) <NEW_LINE> session_id = random_string() <NEW_LINE> form = dict( session_id=session_id, user_id=u.id, ) <NEW_LINE> Session.new(form) <NEW_LINE> headers = { 'Set-Cookie': 'session_id={}; path=/'.format( session_id ) } <N... | 登录页面的路由函数 | 625941cb5fc7496912cc3a4b |
def get_push_location(self): <NEW_LINE> <INDENT> push_loc = self.get_config_stack().get('push_location') <NEW_LINE> if push_loc is not None: <NEW_LINE> <INDENT> return push_loc <NEW_LINE> <DEDENT> cs = self.repository._git.get_config_stack() <NEW_LINE> return self._get_related_push_branch(cs) | See Branch.get_push_location. | 625941cb004d5f362079a401 |
def dict_update(src, target, append=False): <NEW_LINE> <INDENT> for k,v in src.iteritems(): <NEW_LINE> <INDENT> if k in target: <NEW_LINE> <INDENT> if v: <NEW_LINE> <INDENT> target[k] = v <NEW_LINE> <DEDENT> <DEDENT> elif append: <NEW_LINE> <INDENT> target[k] = v | better than the dict.update(), in that None or '' won't overwrite values
@param: append variable will append new source into target (regardless of value)
@return: nothing ... will update / append values to 'target' parameter | 625941cb99fddb7c1c9de45f |
def require(self, typename, predicate=None): <NEW_LINE> <INDENT> if predicate: <NEW_LINE> <INDENT> self.predicates_for_type[typename].append(predicate) <NEW_LINE> <DEDENT> return self.products.setdefault(typename, Products.ProductMapping(typename)) | Registers a requirement that file products of the given type by mapped. If a target predicate is
supplied, only targets matching the predicate are mapped. | 625941cb507cdc57c6306da8 |
def parseEnvironmentString(s): <NEW_LINE> <INDENT> rx = QRegExp(r"""\s(\w+\+?=[^\s]+|\w+="[^"]+"|\w+='[^']+')""") <NEW_LINE> return parseString(s, rx) | Function used to convert an environment string into a list of environment settings.
@param s environment string (string or QString)
@return list of environment settings (list of strings) | 625941cb97e22403b379d067 |
def lgm_logits(feat, num_classes, labels=None, alpha=0.1, lambda_=0.01): <NEW_LINE> <INDENT> N = feat.get_shape().as_list()[0] <NEW_LINE> feat_len = feat.get_shape()[1] <NEW_LINE> means = tf.get_variable('rbf_centers', [num_classes, feat_len], dtype=tf.float32, initializer=tf.contrib.layers.xavier_initializer()) <NEW_L... | The 3 input hyper-params are explained in the paper.
Support 2 modes: Train, Validation
(1)Train:
return logits, likelihood_reg_loss
(2)Validation:
Set labels=None
return logits | 625941cbd164cc6175782e1b |
def serialize(self): <NEW_LINE> <INDENT> return { "system": self.system, "value": self.value, "use" : self.use } | Serializes a patient telecom into a dictionary | 625941cb29b78933be1e577a |
def _time_str_to_unix(timestring): <NEW_LINE> <INDENT> if isinstance(timestring, (int, float)): <NEW_LINE> <INDENT> return timestring <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> t = int(time.mktime(datetime.strptime(timestring, '%a, %d %b %Y %H:%M:%S %Z').timetuple())) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> t... | :type timestring: Union[str, int]
:rtype: Union[int, None] | 625941cb5f7d997b87174b65 |
def getTables(self): <NEW_LINE> <INDENT> self.logger.info('Retrieving the names of all the tables in') <NEW_LINE> self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") <NEW_LINE> return [table[0] for table in self.cursor.fetchall()] | Returns a list of tables in the database | 625941cb38b623060ff0aebb |
def render(data, template, filepath): <NEW_LINE> <INDENT> assert(os.path.exists(template)) <NEW_LINE> template = jinjaenv.get_template(template) <NEW_LINE> if not filepath: <NEW_LINE> <INDENT> raise Exception("No target filepath provided") <NEW_LINE> <DEDENT> dirpath = os.path.dirname(filepath) <NEW_LINE> if not os.pat... | Render the given class data using the given Jinja2 template, writing
the output into 'Models'. | 625941cb3317a56b86939d27 |
def configurarEscenario1(self): <NEW_LINE> <INDENT> global punto1 <NEW_LINE> global punto2 <NEW_LINE> global punto3 <NEW_LINE> punto1 = Punto(69, 69) <NEW_LINE> punto2 = Punto(69, 69) <NEW_LINE> punto3 = Punto(69, 36) | Configuramos el escenario 1. | 625941cbec188e330fd5a86d |
def open_webbrowser(self, url): <NEW_LINE> <INDENT> if self.config.parser.get('settings', 'browser_cmd') == "__default__": <NEW_LINE> <INDENT> python_bin = sys.executable <NEW_LINE> browser_output = subprocess.Popen( [python_bin, '-m', 'webbrowser', '-t', url], stdout=subprocess.PIPE, stderr=subprocess.PIPE) <NEW_LINE>... | Handle url and open sub process with web browser | 625941cbd99f1b3c44c6765d |
def CollectedAllCopies(g): <NEW_LINE> <INDENT> accumed_per_player = g.cards_accumalated_per_player() <NEW_LINE> gain_map = collections.defaultdict(list) <NEW_LINE> game_size = len(g.get_player_decks()) <NEW_LINE> for player, card_dict in accumed_per_player.iteritems(): <NEW_LINE> <INDENT> for card, quant in card_dict.i... | Return a dict mapping a player to a list of all the card
names that the player gained all the copies of | 625941cbad47b63b2c50a04d |
def get_day_only(ss): <NEW_LINE> <INDENT> (y, m, d) = ss.split('-') <NEW_LINE> return "%02d" % (int(d)) | # accepts YYYY-MM-DD, returns DD | 625941cb82261d6c526ab56d |
def paintGL(self): <NEW_LINE> <INDENT> super().paintGL() <NEW_LINE> self.render_frame() | This function will be internally called by Qt when a redraw is
needed. To schedule a redraw, call `update` instead. | 625941cb187af65679ca51ed |
def __init__(self, ctype, name, direction=Parameter.DIRECTION_IN, is_const=False, default_value=None): <NEW_LINE> <INDENT> if ctype == self.container_type.name: <NEW_LINE> <INDENT> ctype = self.container_type.full_name <NEW_LINE> <DEDENT> super(ContainerParameterBase, self).__init__( ctype, name, direction, is_const, d... | ctype -- C type, normally 'MyClass*'
name -- parameter name | 625941cba8370b771705296e |
def delete(self, event_id): <NEW_LINE> <INDENT> logger.warning("Removing event, event_id: %s", event_id) <NEW_LINE> event = Event.query.get(event_id) <NEW_LINE> if not event: <NEW_LINE> <INDENT> logger.warning("Removing event, event_id: %s. Event not found.", event_id, request.get_json()) <NEW_LINE> return {'id': ['eve... | Returns specific event data
:param event_id: | 625941cb4e4d5625662d44a6 |
def _um_ats(ats: "generator", y: int) -> [int]: <NEW_LINE> <INDENT> return sorted( set(bc.months_abv(m) for a in ats for m in a.get_budgets(y)), key=lambda x: bc.months_to_int[x]) + [-1] | Returns integers represnting unique months of an Account collection
and breakout integer | 625941cb45492302aab5e391 |
def test_stop(self): <NEW_LINE> <INDENT> minio = Minio('minio', data=self.valid_data) <NEW_LINE> minio.state.set('actions', 'install', 'ok') <NEW_LINE> minio.state.delete = MagicMock() <NEW_LINE> minio._get_zdbs = MagicMock() <NEW_LINE> minio.stop() <NEW_LINE> minio.minio_sal.stop.assert_called_once_with() <NEW_LINE> m... | Test stop action | 625941cb67a9b606de4a7f88 |
def call_end(self, line): <NEW_LINE> <INDENT> temp = line.strip().split(' ') <NEW_LINE> self.state = CALL_END_STATE <NEW_LINE> self.call_end_time = self.get_date(temp.pop(0), False) <NEW_LINE> self.get_loss_peek_range() <NEW_LINE> self.cal_enc_statistics() | update the state, when the call is end | 625941cbb545ff76a8913ee5 |
def mse(target, pred): <NEW_LINE> <INDENT> tmp = pred - target <NEW_LINE> return np.mean(np.power(tmp, 2)) | Mean Squared Error. | 625941cb5fc7496912cc3a4c |
def classify(self, x): <NEW_LINE> <INDENT> rt = None <NEW_LINE> for clsf, C in self.classifiers: <NEW_LINE> <INDENT> rt = clsf.classify(x) <NEW_LINE> if (rt == 0 and C[1,0] == 0) or (rt == 1 and C[0,1] == 0): <NEW_LINE> <INDENT> return rt <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDEN... | Run down the sequence, could return horrible horrible things if
not linearly seperable. This is sadly NOT array-native, also only takes a
SINGLE vector | 625941cbcad5886f8bd270a8 |
def decimal_2_degrees(decimal, latitude=True, add_direction=False): <NEW_LINE> <INDENT> decimal = float(decimal) <NEW_LINE> degrees = int(decimal) <NEW_LINE> submin = abs((decimal - degrees) * 60) <NEW_LINE> minutes = int(submin) <NEW_LINE> subseconds = abs((submin - minutes) * 60) <NEW_LINE> result = str(degrees) + ":... | Converts a value in decimal degrees into a string with the format:
DD:MM.SS (degrees:minutes.seconds).
:param decimal: Decimal value to be converted.
:param latitude: Determines whether the decimal degrees are for the
latitude or for the longitude. This parameter is only necessary when it
is required to add the directi... | 625941cb0c0af96317bb82b6 |
def get_middle_content(self): <NEW_LINE> <INDENT> tag = 'div' <NEW_LINE> attrs = {'class': 'media-body media-middle'} <NEW_LINE> content = '' <NEW_LINE> for itm in self.content_middle: <NEW_LINE> <INDENT> content = text_concat(content, mark_safe(itm.as_html())) <NEW_LINE> <DEDENT> return render_tag(tag, attrs=attrs, co... | Returns middle content of card header as html | 625941cbd53ae8145f87a33f |
def validate_password(authentication, password): <NEW_LINE> <INDENT> method, payload = parse_authentication(authentication) <NEW_LINE> if method == "bcrypt": <NEW_LINE> <INDENT> password = password.encode('utf-8') <NEW_LINE> payload = payload.encode('utf-8') <NEW_LINE> try: <NEW_LINE> <INDENT> return bcrypt.hashpw(pass... | Validate the given password for the required authentication.
authentication (str): an authentication string as stored in the db,
for example "plaintext:password".
password (str): the password provided by the user.
return (bool): whether password is correct.
raise (ValueError): when the authentication string is n... | 625941cbd18da76e235325a4 |
def frequency(word, histogram): <NEW_LINE> <INDENT> for key, value in histogram.items(): <NEW_LINE> <INDENT> if key == word: <NEW_LINE> <INDENT> return value | returns the number of times that word appears in the text | 625941cb26068e7796caedad |
def findOrder(self, numCourses, prerequisites): <NEW_LINE> <INDENT> pre = collections.defaultdict(list) <NEW_LINE> for a,b in prerequisites: <NEW_LINE> <INDENT> pre[b].append(a) <NEW_LINE> <DEDENT> status = [0] * numCourses <NEW_LINE> res = [] <NEW_LINE> def helper(node,check): <NEW_LINE> <INDENT> if status[node] == 1:... | :type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int] | 625941cb56ac1b37e626429e |
def top(self): <NEW_LINE> <INDENT> return self.stack[self.top_] | :rtype: int | 625941cbd7e4931a7ee9dfec |
def destroy(self): <NEW_LINE> <INDENT> if not self.id: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> client.delete('/classes/{0}/{1}'.format(self._class_name, self.id)) | 从服务器上删除这个对象
:rtype: None | 625941cb6aa9bd52df036e72 |
def show_tooltip(self, view, tooltip, content, fallback): <NEW_LINE> <INDENT> st_ver = int(sublime.version()) <NEW_LINE> if st_ver < 3070: <NEW_LINE> <INDENT> return fallback() <NEW_LINE> <DEDENT> width = get_settings(view, 'font_size', 8) * 75 <NEW_LINE> kwargs = {'location': -1, 'max_width': width if width < 900 else... | Generates and display a tooltip or pass execution to fallback
| 625941cb3617ad0b5ed67fc6 |
def freezeEnvironment(self): <NEW_LINE> <INDENT> self.graph.freeze() <NEW_LINE> for module in self.collectorModules: <NEW_LINE> <INDENT> self.timers[module].pause() <NEW_LINE> <DEDENT> for worker in self.workers: <NEW_LINE> <INDENT> worker.stop() <NEW_LINE> <DEDENT> for worker in self.workers: <NEW_LINE> <INDENT> worke... | Freeze the environment by pausing all module timers and stopping the running collectors. | 625941cb91f36d47f21ac5c1 |
def updateMoveText(self): <NEW_LINE> <INDENT> self.chesscomMoveText = '' <NEW_LINE> self.moveText = '' <NEW_LINE> self.moveDict.clear() <NEW_LINE> self.index = 0 <NEW_LINE> self.getMoveText(self.currentMove.getRoot(), self.fenMoveNumber) <NEW_LINE> self.inverseMoveDict = {value: key for key, value in self.moveDict.item... | Updates movetext and dictionary. | 625941cb3d592f4c4ed1d13d |
def test_schema_valid(self): <NEW_LINE> <INDENT> Draft3Validator.check_schema(group_schemas.policy) | The schema itself is a valid Draft 3 schema | 625941cb091ae3566866702d |
def prepare_middleware_test(self): <NEW_LINE> <INDENT> data = create_ancestry() <NEW_LINE> args = { 'name': 'AncestrySample', 'metadata': {'foobar': 'baz'}, TOOL_MODULE_NAME: data, } <NEW_LINE> sample = Sample(**args).save() <NEW_LINE> db.session.commit() <NEW_LINE> return sample | Prepare database forsample middleware test. | 625941cb0a50d4780f666f60 |
def parse_groups(text): <NEW_LINE> <INDENT> counter = 1 <NEW_LINE> scores = [] <NEW_LINE> garbage_scores = [] <NEW_LINE> i = 1 <NEW_LINE> while i < len(text): <NEW_LINE> <INDENT> if text[i] == "{": <NEW_LINE> <INDENT> i += 1 <NEW_LINE> counter += 1 <NEW_LINE> continue <NEW_LINE> <DEDENT> if text[i] == "<": <NEW_LINE> <... | This does the 'normal' scanning for groups. It defers to
parse_garbage() to skip over garbage.
Returns a 3-tuple: the brace counter (should be zero for correct input),
the scores array (for part 1) and the garbage scores array (for part 2). | 625941cbfff4ab517eb2f50b |
def close(self): <NEW_LINE> <INDENT> pass | Optional cleanup logic when component loop is stopped. | 625941cb5e10d32532c5eff5 |
def sigmoid(x, y, alpha=None, c=-E): <NEW_LINE> <INDENT> if alpha is None: <NEW_LINE> <INDENT> alpha = 1 / len(x) <NEW_LINE> <DEDENT> return tanh(alpha*dot(x, y) + c) | Compute a hyperbolic tanget (or sigmoid) kernel.
The Hyperbolic Tangent Kernel is also known as the Sigmoid Kernel and as
the Multilayer Perceptron (MLP) kernel. The Sigmoid Kernel comes from the
Neural Networks field, where the bipolar sigmoid function is often used
as an activation function for artificial neurons:
... | 625941cb0a50d4780f666f61 |
def test_scenario1(self): <NEW_LINE> <INDENT> print(self.test_scenario1.__doc__) <NEW_LINE> examples = [ ['data/iris.csv', '10', '10', '20', '50', 'my new association name']] <NEW_LINE> for example in examples: <NEW_LINE> <INDENT> print("\nTesting with:\n", example) <NEW_LINE> source_create.i_upload_a_file(self, exampl... | Scenario: Successfully creating associations from a dataset:
Given I create a data source uploading a "<data>" file
And I wait until the source is ready less than <time_1> secs
And I create a dataset
And I wait until the dataset is ready less than <time_2> secs
And I create associations from a datas... | 625941cb8e71fb1e9831d878 |
def getRegInfo(disp,host,info={},sync=True): <NEW_LINE> <INDENT> iq=Iq('get',NS_REGISTER,to=host) <NEW_LINE> for i in list(info.keys()): iq.setTagData(i,info[i]) <NEW_LINE> if sync: <NEW_LINE> <INDENT> resp=disp.SendAndWaitForResponse(iq) <NEW_LINE> _ReceivedRegInfo(disp.Dispatcher,resp, host) <NEW_LINE> return resp <N... | Gets registration form from remote host.
You can pre-fill the info dictionary.
F.e. if you are requesting info on registering user joey than specify
info as {'username':'joey'}. See XEP-0077 for details.
'disp' must be connected dispatcher instance. | 625941cb30bbd722463cbe94 |
def build(parent, imagesPath, iconSize = 25, height = 20, marginSize = 5): <NEW_LINE> <INDENT> cmds.rowLayout(numberOfColumns = 1, parent = parent) <NEW_LINE> cmds.iconTextButton(style = 'iconOnly', image1 = os.path.join(imagesPath, 'snapit.png'), hi = os.path.join(imagesPath, 'snapit_hi.png'), width = iconSize, mw = m... | build widget
@param parent : parent layout in maya
@imagesPath : str path | 625941cbf7d966606f6aa0d2 |
def create_track_goal_events_impression( settings_file, user_id, goal_identifier, campaign_goal_revenue_prop_list, revenue=None ): <NEW_LINE> <INDENT> logger = VWOLogger.getInstance() <NEW_LINE> impression = get_events_common_properties(settings_file, user_id, goal_identifier) <NEW_LINE> impression["d"]["event"]["props... | Creates the event impression for track goal call from the arguments passed accordingly
Args:
settings_file (dict): Settings file object
user_id (string): User identifier
goal_identifier (string): campaign(s)'s goal identifier
campaign_goal_revenue_prop_list (list): list of campaign_id, goal_id & goal's... | 625941cb6fece00bbac2d80d |
def jump(self, nums): <NEW_LINE> <INDENT> last_max_reach = 0 <NEW_LINE> current_max_reach = 0 <NEW_LINE> count = 0 <NEW_LINE> for i in range(len(nums)-1): <NEW_LINE> <INDENT> current_max_reach = max(current_max_reach, i + nums[i]) <NEW_LINE> if i == last_max_reach: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> last_max_rea... | :type nums: List[int]
:rtype: int | 625941cb66656f66f7cbc279 |
def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse): <NEW_LINE> <INDENT> _lists = self._lists <NEW_LINE> if min_pos > max_pos: <NEW_LINE> <INDENT> return iter(()) <NEW_LINE> <DEDENT> if min_pos == max_pos: <NEW_LINE> <INDENT> if reverse: <NEW_LINE> <INDENT> indices = reversed(range(min_idx, max_idx)) <NEW_LI... | Return an iterator that slices sorted list using two index pairs.
The index pairs are (min_pos, min_idx) and (max_pos, max_idx), the
first inclusive and the latter exclusive. See `_pos` for details on how
an index is converted to an index pair.
When `reverse` is `True`, values are yielded from the iterator in
reverse... | 625941cb656771135c3eb93d |
def on_train_end(self, logs=None): <NEW_LINE> <INDENT> self.save_checkpoint() <NEW_LINE> Path(self.prev_model_fname).unlink(missing_ok=True) <NEW_LINE> pickle_filepath = make_pickle_file_name(self.prev_model_fname) <NEW_LINE> Path(pickle_filepath).unlink(missing_ok=True) <NEW_LINE> Path(self.prev_vars_fname).unlink(mis... | Save the state of the computation at the end of its last epoch, and remove temporary files that are not needed
anymore. | 625941cb30bbd722463cbe95 |
def show_schema(self, *params): <NEW_LINE> <INDENT> tables = self.get_tables() <NEW_LINE> for table in tables: <NEW_LINE> <INDENT> columns = self.get_columns(table) <NEW_LINE> self.table(columns, title=table) | Displays the database schema | 625941cb090684286d50edb4 |
def tunable_switch(target_seq, tuning_strategy=''): <NEW_LINE> <INDENT> if not tuning_strategy: <NEW_LINE> <INDENT> return complementary_switch(target_seq) <NEW_LINE> <DEDENT> if tuning_strategy[0] not in 'wmb': <NEW_LINE> <INDENT> raise ValueError("Tuning strategy must be one of 'wmb', not '{}'.".format(tuning_strateg... | Return three domains that comprise a switch. The first domain ("switch")
is a sequence that can base pair with either of the two following domains,
the second domain ("on") is what the first should bind in the "on" state,
and the third domain ("off") is what the first should bind in the "off"
state.
By default,... | 625941cb377c676e91272278 |
def __init__(self, t, x , y , radius, vx, vy, color): <NEW_LINE> <INDENT> self.turtle = t <NEW_LINE> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.radius = radius <NEW_LINE> self.velocity = [vx, vy] <NEW_LINE> self.color = color | Parameters
----------
t : turtle
A turtle type object from the module turtle
radius : float
The radius of the ball
x : float
The x coordinate of the ball
y : float
The y coordinate of the ball
vx : float
The x component of the ball velocity
vy : float
The y component of the ball velocity
velocit... | 625941cb92d797404e304259 |
def collapsed_spike_trains(trains): <NEW_LINE> <INDENT> if not trains: <NEW_LINE> <INDENT> return neo.SpikeTrain([] * pq.s, 0 * pq.s) <NEW_LINE> <DEDENT> start = min((t.t_start for t in trains)) <NEW_LINE> stop = max((t.t_stop for t in trains)) <NEW_LINE> collapsed = [] <NEW_LINE> for t in trains: <NEW_LINE> <INDENT> c... | Return a superposition of a list of spike trains.
:param iterable trains: A list of :class:`neo.core.SpikeTrain` objects
:returns: A spike train object containing all spikes of the given
spike trains.
:rtype: :class:`neo.core.SpikeTrain` | 625941cbbe7bc26dc91cd6cf |
def run(self, state: State, package_version: PackageVersion) -> None: <NEW_LINE> <INDENT> if not self._index_url_check(self._index_url, package_version.index.url): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if self._specifier and package_version.locked_version not in self._specifier: <NEW_LINE> <INDENT> return... | Run main entry-point for steps to skip packages. | 625941cb7d43ff24873a2d6f |
def generate_json_for_datagrid(obj, success=True, error_message="Saved Successfully", form_errors=None): <NEW_LINE> <INDENT> json_data = [] <NEW_LINE> try: <NEW_LINE> <INDENT> iterable = iter(obj) <NEW_LINE> if iterable: <NEW_LINE> <INDENT> for element in obj: <NEW_LINE> <INDENT> data = {'success': success, 'error_mess... | Returns the JSON formatted Values of a specific Django Model Instance
for use with Dojo Grid. A few default DOJO Grid Values are specified, rest
are instance specific and are generated on the fly. It assumes the presence
of get_edit_url and get_del_url in the model instances passed to it via
obj.
ARGUMENTS: obj ... | 625941cb7b180e01f3dc48cd |
def add(self, item): <NEW_LINE> <INDENT> self.items.append(item.model) | Add a `Standard` based object to the package.
:param item: a `Standard`-based object to add
:returns: `None` | 625941cb8da39b475bd65042 |
def input_value(): <NEW_LINE> <INDENT> float_value = None <NEW_LINE> while float_value is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> chosen_value = input() <NEW_LINE> if chosen_value == '': <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> elif ',' in chosen_value: <NEW_LINE> <INDENT> chosen_value = chos... | This function check if user input is correct , and change ',' to '.' | 625941cb31939e2706e4cf3a |
def test_dea_c3_naming_conventions(tmp_path: Path): <NEW_LINE> <INDENT> p = DatasetAssembler(tmp_path, naming_conventions="dea_c3") <NEW_LINE> p.platform = "landsat-7" <NEW_LINE> p.datetime = datetime(1998, 7, 30) <NEW_LINE> p.product_family = "wo" <NEW_LINE> p.processed = "1998-07-30T12:23:23" <NEW_LINE> p.maturity = ... | A sample scene for Alchemist C3 processing that tests the naming conventions. | 625941cbd6c5a1020814411a |
def get_age(self): <NEW_LINE> <INDENT> if self.birthday is None: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> return (datetime.date.today() - self.birthday).days | Returns self's current age in days | 625941cb8e7ae83300e4b09b |
def send_one_not_recognize_message(client): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> message_name = "abc" <NEW_LINE> message_name_size = len(message_name) <NEW_LINE> message_data = "virus" <NEW_LINE> message_data_size = len(message_data) <NEW_LINE> message_total_size = 5 + message_name_size + message_data_size <NEW... | func | 625941cb9c8ee82313fbb844 |
def render(self, **kwargs): <NEW_LINE> <INDENT> figure = self._parent <NEW_LINE> assert isinstance(figure, Figure), ('You cannot render this Element ' 'if it is not in a Figure.') <NEW_LINE> for name, element in self._children.items(): <NEW_LINE> <INDENT> element.render(**kwargs) <NEW_LINE> <DEDENT> for name, element i... | Renders the HTML representation of the element. | 625941cbbe8e80087fb20d12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.