prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
""" mbed SDK Copyright (c) 2011-2016 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writin...
PC11U37H_401', ] def generate(self): libraries = [] for lib in self.resources.libraries: l, _ = splitext(basename(lib)) libraries.append(l[3:]) c
tx = { 'name': self.project_name, 'include_paths': self.resources.inc_dirs, 'linker_script': self.resources.linker_script, 'object_files': self.resources.objects, 'libraries': libraries, 'symbols': self.toolchain.get_symbols() } ctx...
#!/usr/bin/python # # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
erties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. Tags: AdGroupAdService.mutate Api: A
dWordsOnly """ __author__ = 'Joseph DiLallo' from googleads import adwords AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' def main(client, ad_group_id): # Initialize appropriate service. ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') # Create the template elements for the ad. You ...
""" Launcher functionality for the Google Compute Engine (GCE) """ import json import logging import os from dcos_launch import onprem, util from dcos_launch.platforms import gcp from dcos_test_utils.helpers import Host from googleapiclient.errors import HttpError log = logging.getLogger(__name__) def get_credentia...
te_key'] = private_key.decode() self.config['ssh_public_key'] = public_key.decode() def get_cluster_hosts(self) -> [Host]: return list(self.deployment.hosts)[1:] def get_bootstrap_host(self) -> Host: return list(self.deployment.hosts)[0] def wait(self): """ Waits for t...
t to complete: first, the network that will contain the cluster is deployed. Once the network is deployed, a firewall for the network and an instance template are deployed. Finally, once the instance template is deployed, an instance group manager and all its instances are deployed. """ ...
# Copyright (c) 2010-2013 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
:param contdevice: device name that the container is on :param headers_out: dictionary of headers to send in the container
request :param objdevice: device name that the object is in :param policy_idx: the associated storage policy index """ headers_out['user-agent'] = 'obj-server %s' % os.getpid() full_path = '/%s/%s/%s' % (account, container, obj) if all([host, p...
#!/usr/bin/env python # Copyright (c) 2008-14 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 2 of the License, or # version 3 of the Lic...
nse for more details. from __future__ import division from __future__ import print_function from __future__ import unicode_literals from future_builtins import * from PyQt4.QtCore import (QRegExp, Qt) from PyQt4.QtCore
import pyqtSignal as Signal from PyQt4.QtGui import (QCheckBox, QDialog, QDialogButtonBox, QGridLayout, QLabel, QLineEdit, QMessageBox, QRegExpValidator, QSpinBox) class NumberFormatDlg(QDialog): changed = Signal() def __init__(self, format, parent=None): super(NumberFormatDlg, self...
"""Test loading historical builds and jobs.""" from __future__ import absolute_import, unicode_literals from travis_log_fetch.config import _get_travispy from travis_log_fetch._target import Target from travis_log_fetch.get import ( get_travis_repo, get_historical_builds, get_historical_build, get_his...
repo = get_travis_repo(_travis, 'travispy/on_pypy') builds
= get_historical_builds(_travis, repo) ids = [] for build in builds: assert build.repository_id == 2598880 ids.append(build.id) assert ids == [53686685, 37521698, 28881355] def test_multiple_batches_menegazzo(self): """Test using a repository that has great...
e = None ale_lib.act.argtypes = [c_void_p, c_int] ale_lib.act.restype = c_int ale_lib.game_over.argtypes = [c_void_p] ale_lib.game_over.restype = c_bool ale_lib.reset_game.argtypes = [c_void_p] ale_lib.reset_game.restype = None ale_lib.getLegalActionSet.argtypes = [c_void_p, c_void_p] ale_lib.getLegalActionSet.restype ...
State.restype = None ale_lib.loadState.argtypes = [c_void_p] ale_lib.loadState.restype = None ale_lib.cloneState.argtypes = [c_void_p] ale_lib.cloneState.restype = c_void_p ale_lib.restoreState.argtypes = [c_void_p, c_void_p] ale_lib.restoreState.re
stype = None ale_lib.cloneSystemState.argtypes = [c_void_p] ale_lib.cloneSystemState.restype = c_void_p ale_lib.restoreSystemState.argtypes = [c_void_p, c_void_p] ale_lib.restoreSystemState.restype = None ale_lib.deleteState.argtypes = [c_void_p] ale_lib.deleteState.restype = None ale_lib.saveScreenPNG.argtypes = [c_vo...
# Bu kod calismay
acak, mantigi anlamak icin yazildi. from gittigidiyor.applicationservice import * from gittigidiyor.auth i
mport * if __name__ == "__main__": # HTTP Basic authentication credentials.. It blows up for the wrong credentials.. auth = Auth("testuser", "testpassword", None, None) api = ApplicationService(auth) result = api.createApplication("testdeveloper", "Test Application", "This is the test application", ...
from django.db.models.expressions import F, Func from rest_framework import serializers from .models import PdfStorage class PdfStorageListSerializer(serializers.ModelSerializer): author = serializers.SerializerM
ethodField("full_name") class Meta: model = PdfStorage fields = [ "id", "name", "topic", "author", "created", ] def full_name(self, pdf): return pdf.author.person_name() class PaidPdfDownloadLinkSerializer(serializer...
class Meta: model = PdfStorage fields = ["download_url"] def get_download_url(self, obj): return obj.pdf_file.url class AllRelatedIdsSerializer(serializers.Serializer): ids = serializers.SerializerMethodField() class Meta: fields = ["ids"] def get_ids(self, obj): ...
ef setUp(self): self.setup_beets() def tearDown(self): self.teardown_beets() @patch('beetsplug.thumbnails.util') def test_write_metadata_im(self, mock_util): metadata = {"a": u"A", "b": u"B"} write_metadata_im("foo", metadata) try: command = u"convert fo...
_uri.__self__.__class__, PathlibURI) @patch('beetsplug.thumbnails.ThumbnailsPlugin._check_local_ok') @patch('beetsplug.thumbnails.ArtResizer') @patch('beetsplug.thumbnails.util') @patch('beetsplug.thumbnails.os') @patch('beetsplug.thumbnails.shutil') def test_make_cover...
rmpath(b"/thumbnail/dir") md5_file = os.path.join(thumbnail_dir, b"md5") path_to_art = os.path.normpath(b"/path/to/art") mock_os.path.join = os.path.join # don't mock that function plugin = ThumbnailsPlugin() plugin.add_tags = Mock() album = Mock(artpath=path_to_art) ...
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from flask import request from indico.modules.admin.views import...
profile_breadcrumb = _('My Profile') return render_breadcrumbs(profile_breadcrumb) def _get_body(self, params): return self._get
_page_content(params) class WPUserDashboard(WPUser): bundles = ('module_users.dashboard.js',) class WPUsersAdmin(WPAdmin): template_prefix = 'users/' bundles = ('module_users.js',)
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-06-02 07:44 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): depen
dencies = [ ('distances', '0010_auto_20170519_1604'), ] operations = [
migrations.AlterField( model_name='dates', name='startDate', field=models.DateField(default=datetime.datetime(2017, 5, 26, 10, 44, 7, 194576)), ), ]
import re import shutil import time import os import os.path from pyquery.pyquery import PyQuery import requests import requests.utils from WhatManager2.settings import MEDIA_ROOT from bibliotik import manage_bibliotik from bibliotik.models import BibliotikTorrent, BibliotikFulltext from bibliotik.settings import BIB...
}) for tag in row('td:eq(1) > span.taglist > a').items(): href = tag.attr('href') data['tags'].append({ 'id': href[href.rfind('/') + 1:], 'name': tag.text() }) result.append(data) return result class BibliotikClient(objec...
ts.Session() requests.utils.add_dict_to_cookiejar(self.session.cookies, { 'id': session_id }) self.auth_key = None def get_auth_key(self): if self.auth_key: return self.auth_key for i in xrange(3): try: response = self.sess...
# Copyright (C) 2007, 2009, 2010 Canonical Ltd # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Thi
s program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public Licens
e for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA import sys from bzrlib.builtins import cmd_cat from bzrlib.tests import StringIOWrapper...
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file import os all_modifs={} def fixdir(dir): global all_modifs for k in all_modifs: for v in all_modifs[k]: modif(os.path.join(dir,'waflib'),k,v) def modif(dir,name,fun): ...
def r1(code): code=code.replace(',e:',',e:') code=code.replace("",'') code=code.replace('','') return code @subst('Runner.py') def r4(code): code=code.replace('next(self.biter)','self.biter.nex
t()') return code
import time from torba.server import util def sessions_lines(data): """A generator returning lines for a list of sessions. data is the return value of rpc_sessions().""" fmt = ('{:<6} {:<5} {:>17} {:>5} {:>5} {:>5} ' '{:>7} {:>7} {:>7} {:>7} {:>7} {:>9} {:>21}') yield fmt.format('ID', 'Fl...
or '', time_fmt(item['last_good']), time_fmt(item['last_try']), item['try_count'],
item['source'][:20], item['ip_addr'] or '')
list[ind] elif event.key == 'L': print(self.sources[self.sources.sourceid==self.sources['sourceid'][self.index]]) elif event.key == 'T': sdiff = self.accelerator*(self.smax - self.smin)/255.0 self.smax += sdiff sel...
gument("mapdir", help="top-level map
directory")
# --- BEGIN COPYRIGHT BLOCK --- # Copyright (C) 2016 Red Hat, Inc. # All rights reserved. # # License: GPL (version 3 or any later version). # See LICENSE for details. # --- END COPYRIGHT BLOCK --- from lib389.plugins import Plugin, Plugins import argparse from lib389.cli_base import ( _generic_list, _generic...
t_dn(inst, basedn, log, args): dn = _get_arg( args.dn, msg="Enter dn to retrieve") _generic_get_dn(inst, basedn, log.getChild('plugin_get_dn'), MANY, dn) # Plugin enable def plugin_enable(inst, basedn, log, args): dn = _get_arg( args.dn, msg="Enter plugin dn to enable") mc = MANY(inst, basedn) o = ...
enable() o_str = o.display() log.info('Enabled %s', o_str) # Plugin disable def plugin_disable(inst, basedn, log, args, warn=True): dn = _get_arg( args.dn, msg="Enter plugin dn to disable") if warn: _warn(dn, msg="Disabling %s %s" % (SINGULAR.__name__, dn)) mc = MANY(inst, basedn) o = m...
, or # at https://www.sourcefabric.org/superdesk/license import logging import superdesk from flask import current_app as app from settings import DAYS_TO_KEEP from datetime import timedelta from werkzeug.exceptions import HTTPException from superdesk.notification import push_notification from superdesk.io import p...
').get(req=None, lookup={}): if is_valid_type(provider, provider_type) and is_scheduled(provider) and not is_closed(provider): kwargs = { 'provider': provider, 'rule_set': get_provider_rule_set(provider)
} update_provider.apply_async( task_id=get_task_id(provider), expires=get_task_ttl(provider), kwargs=kwargs) @celery.task def update_provider(provider, rule_set=None): """ Fetches items from ingest provider as per the configurat...
""" Contains a function to generate and upload a LaTeX-rendered math image. """ import subprocess import sys import typing def uploadLatex(math: typing.List[str], slackAPI: object, channel: object, users: list) -> str: """ Generates a LaTeX math image from the LaTeX source contained in `math`, and posts it to the a...
: %s: %s" slackAPI.chat.post_message(channel['name'],
msg % ("`%s` because" % toParse, "`%s`" % response.stderr.decode())) return "EE: latex: " + msg % ("'%s'" % toParse, "'%s'" % response.stderr.decode()) # If all went well, upload then delete the file slackAPI.files.upload(latexdir+"/latex_output.png", channels=channel['id']) retstr = "II: l...
# -*- coding: utf-8 -*- from __future__ im
port unicode_literals from django.db import migrations class Migration(migrations.Migration)
: dependencies = [ ('ngw', '0009_config_eventdefaultperms'), ] operations = [ migrations.DeleteModel( name='ChoiceContactField', ), migrations.DeleteModel( name='DateContactField', ), migrations.DeleteModel( name='DateTime...
from temboo
.Library.Google.Drive.Changes.Get import Get, GetInputSet, GetResultSet, GetChoreographyExecution from temboo.Library.Google.Drive.Changes.List import List, ListInputSet, ListResultSet, ListChoreographyExecution
# -*- coding: utf-8 -*- # Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net> # This program is free software: you can r...
om django.apps import AppConfig from django.apps import apps from django.db.models import signals def connect_issues_signals(): from taiga.projects.tagging import signals as tagging_handlers from . import signals as handlers # Finished date signals.pre_save.connect(handlers.set_finished_date_when_edi...
issues", "Issue"), dispatch_uid="set_finished_date_when_edit_issue") # Tags signals.pre_save.connect(tagging_handlers.tags_normalization, sender=apps.get_model("issues", "Issue"), dispatch_uid="tags_normalization_issue") d...
from biokbase.workspace.client import Workspace import requests import json import sys from time import time from fix_workspace_info import fix_all_workspace_info from pprint import pprint kb_port = 9999 mini_ws_url = f"http://localhost:{kb_port}/services/ws" mini_auth_url = f"http://localhost:{kb_port}/services/auth/...
-mongo_1 /bin/bash # b. start mongo (just "mongo" at the prompt) # c. Run the following to use gridFS: # > use workspace # > db.settings.findAndModify({ query: {backend: "shock"}, update: { $set: {"backend": "gridFS"} } }) # d. Exit that container, and restart the workspace container # > docker-com...
cript should do the job of creating accounts, importing the Narrative type, # loading test data, etc. def create_user(user_id): """ Returns a token for that user. """ headers = { "Content-Type": "application/json" } r = requests.post(mini_auth_url + '/api/V2/testmodeonly/user', headers...
from pythonforandroid.toolchain import Bootstrap, current_directory, info, info_main, shprint from pythonforandroid.util import ensure_dir from os.path import join import sh class WebViewBootstrap(Bootstrap): name = 'webview' recipe_depends = list( set(Bootstrap.recipe_depends).union({'genericndkbuil...
tribute_javaclasses(self.ctx.javaclass_dir,
dest_dir=join("src", "main", "java")) python_bundle_dir = join('_python_bundle', '_python_bundle') ensure_dir(python_bundle_dir) site_packages_dir = self.ctx.python_recipe.create_python_bundle( join(self.dist_dir, python_bundle_dir), arch) if 'sql...
from uber.tests import * @pytest.fixture def attendee_id(): with Session() as session: return session.query(Attendee).filter_by(first_name='Regular', last_name='Attendee').one().id @pytest.fixture(autouse=True) def mock_apply(monkeypatch): monkeypatch.setattr(Attendee, 'apply', Mock()) return Atte...
eption, session.attendee, '') pytest.raises(Exception, session.attendee, []) pytest.raises(Exception, session.attendee, None) pytest.raises(Exception, session.attendee, str(uuid4())) pytest.raises(Exception, session.attendee, {'id': str(uuid4())}) def test_basic_get(attendee_id, mock_ap...
.first_name == 'Regular' assert not mock_apply.called assert session.attendee(id=attendee_id).first_name == 'Regular' assert not mock_apply.called assert session.attendee({'id': attendee_id}).first_name == 'Regular' assert mock_apply.called def test_empty_get(mock_apply): wi...
onfig.v3r205;DecFiles.v27r37 #-- Visible : Y from Gaudi.Configuration import * from GaudiConf import IOHelper IOHelper('ROOT').inputFiles(['LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000001_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000002_1.allstreams.dst', 'LFN:/...
N:/lhcb
/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000077_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000078_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000079_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000080_1.allstre...
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLE
S from swgpy.object import * def create(kernel): result = Mission() result.template = "object/mission/base/shared_base_mission.iff" result.attribute_
template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
#!/usr/bin/python # -*- coding: utf-8 -*- # vim: expandtab:tabstop=4:shiftwidth=4 ''' modify_yaml ansible module ''' import yaml DOCUMENTATION = ''' --- module: modify_yaml short_description: Modify yaml key value pairs author: Andrew Butcher requirements: [ ] ''' EXAMPLES = ''' - modify_yaml: dest: /etc/origin/...
ey in ptr and module.safe_eval(ptr[key]) != yaml_value) or (key not in ptr):
ptr[key] = yaml_value changes.append((yaml_key, yaml_value)) else: ptr = ptr[key] return changes def main(): ''' Modify key (supplied in jinja2 dot notation) in yaml file, setting the key to the desired value. ''' # disabling pylint errors for glo...
""" desispec.fiberflat ================== Utility functions to compute a fiber flat correction and apply it We try to keep all the (fits) io separated. """ from __future__ import absolute_import, division import numpy as np from desispec.io import read_frame from desispec.io import write_fiberflat from desispec.fibe...
e from desispec.io import write_qa_frame from desispec.qa import qa_plots import argparse def parse(options=None): parser = argparse.ArgumentParser(description="Compute the fiber flat field correction from a DESI continuum lamp frame") parser.add_argument('--infile', type = str, default = None, required=True,...
help = 'path of DESI frame fits file corresponding to a continuum lamp exposure') parser.add_argument('--outfile', type = str, default = None, required=True, help = 'path of DESI fiberflat fits file') parser.add_argument('--qafile', type=str, default=None, required=False, ...
class Solution(object): def isSelfCrossing(self, x): """ :type x: List[int] :rtype: bool """ inf = float('inf') n = len(x) if n < 3: return False ruld = [0, 0, 0, 0] # right, up, left, down next_max = inf current = [-x[1], ...
if pn * new > pn * ruld[i - 3]: next_max = inf else: if next_max is inf and pn * new >= pn * ruld[i - 1]: ruld[i - 2] = ruld[i] next_max = abs(ruld[i - 2] - current[xy ^ 1])
ruld[i - 1], current[xy] = current[xy], new return False assert Solution().isSelfCrossing([2, 1, 1, 2]) assert not Solution().isSelfCrossing([1, 2, 3, 4]) assert Solution().isSelfCrossing([1, 1, 1, 1]) assert not Solution().isSelfCrossing([3,3,4,2,2]) assert Solution().isSelfCrossing([1,1,2,1,1]) asser...
PROJECT_PATH = __path__[0] TI
EMPO_REGISTRY = {} REDIS_GROUP_NAMESPACE = 'tiempogroup' RECENT_KEY = 'tiempo:recent_tasks' RESULT_PREFIX = 'tiemp
o:task_result' __version__ = "1.2.3"
er): contents = input_api.ReadFile(f, 'rb') # Check that the file ends in one and only one newline character. if len(contents) > 1 and (contents[-1:] != '\n' or contents[-2:-1] == '\n'): eof_files.append(f.LocalPath()) if eof_files: return [output_api.PresubmitPromptWarning( 'These files ...
_file_filter): # For speed, we do two
passes, checking first the full file. Shelling out # to the SCM to determine the changed region can be quite expensive on # Win32. Assuming that most files will be kept problem-free, we can # skip the SCM operations most of the time. extension = str(f.LocalPath()).rsplit('.', 1)[-1] if all(callab...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # encfs.py # # Copyright 2013 Antergos # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your opti...
") system_auth.write("auth optional\tpam_mount.so\n") # Setup finished # Move user home dir out of the way mounted_dir = os.path.join(self.dest_dir, "home/", use
rname) backup_dir = os.path.join(self.dest_dir, "var/tmp/", username) subprocess.check_call(['mv', src_dir, backup_dir]) # Create necessary dirs, encrypted and mounted(unecrypted) encrypted_dir = os.path.join(self.dest_dir, "home/.encfs/", username) subprocess.check_call(['mkdir', '-p', encrypted_d...
import jmri.jmrit.jython.Jynstrument as Jynstrument import jmri.jmrit.catalog.Named
Icon as NamedIcon import jmri.jmrit.symbolicprog.tabbedframe.PaneOpsProgAction as PaneOpsProgAction import javax.swing.JButton as JButton class DecoderPro(Jynstrument): def getExpectedContextClassName(self): return "javax.swing.JComponent" def init(self): jbNew = JButton( PaneOpsProgAction...
the popupmenu on the button too jbNew.setToolTipText( jbNew.getText() ) jbNew.setText( None ) self.add(jbNew) def quit(self): pass
"""Applic
ation base, containing global templates.""" default_app_config = 'pontoon.base.apps.BaseConfig' MOZILLA_REPOS = ( 'ssh://hg.mozilla.org/users/m_owca.info/firefox-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/firefox-for-android-aurora/', 'ssh://hg.mozilla.org/users/m_owca.info/thunderbird-aurora/', ...
lass SyncError(RuntimeError): """Error class for errors relating to the project sync process."""
from Estructura import
espaceado class Arbol_Sintactico_Abstracto: def __init__(self,alcance,hijos): self.hijos = hijos self.alcance = alcance self.cont = 1 def imprimir(self,tabulacion): if (len(self.hijos) > 1): print tabulacion + "SECUENCIA" for hijo in self.hijos: hijo.nivel = 1 hijo.imprimir(
espaceado(tabulacion)) def ejecutar(self): for hijo in self.hijos: hijo.nivel = 1 hijo.ejecutar()
import glob from subprocess import call test_failures = {} test_successes = {} files = [file for file in glob.glob('../**/build.gradle', recursive=True)] for f in files: if f.startswith('../test'): continue # clean all projects in the platform before executing build print("Cleaning all
projects first...") call(['../gradlew', '-p', '../', 'clean']) print("Executing " + f + "...") rc = call(['../gradlew', '-b', f, 'build']) if rc == 0: test
_successes[f] = rc else: test_failures[f] = rc print("Return code: " + str(rc)) print("FAILURES:") for key in test_failures: print(key + ": " + "FAILED(rc=" + str(test_failures[key]) + ")!") print("\n\n") print("SUCCESSES:") for key in test_successes: print(key + ": PASS")
(Filter): """ Highlight special code tags in comments and docstrings. Options accepted: `codetags` : list of strings A list of strings that are flagged as code tags. The default is to highlight ``XXX``, ``TODO``, ``BUG`` and ``NOTE``. """ def __init__(self, **options): ...
nctions. `Name.Function` is the default token type. Options accepted: `name
s` : list of strings A list of names that should be given the different token type. There is no default. `tokentype` : TokenType or string A token type or a string containing a token type name that is used for highlighting the strings in `names`. The default is `Name.Function`. ""...
class BasePlugin(object): """ Extend this/copy its structure to create plugins. Your plugin class must be `Plugin` to be loaded. Can include commands (command_*), admin commands (admin_). Additionally, yaib will look functions for many of the connection events. Any commands with a docstr...
lled during initialization. Use self.settings.setMulti({...}, initial=True) """ pass def getDbSession(self): return self.yaib.persistence.getDbSession() def formatDoc(self, message): """Formats the given message with the {nick} and {command_prefix}.""" ...
age) def callLater(self, delay, func, *args, **kwargs): """ Wait for the delay (in seconds) then call the function with the given arguments.""" return self.yaib.callLater(delay, func, *args, **kwargs) def onShutdown(self): """Called when yaib is shutting down. ...
# -*- coding: utf-8 -*- # Generated by D
jango 1.9.7 on 2016-11-01 22:55 from __future__ import unicode_literals from django.db import migrations from django.db import mod
els class Migration(migrations.Migration): dependencies = [ ('contentcuration', '0038_contentnode_author'), ] operations = [ migrations.AlterField( model_name='formatpreset', name='id', field=models.CharField(choices=[('high_res_video', 'High Resolutio...
# Copyright (C) 2014-2015 Andrey Antukh <niwi@niwi.be> # Copyright (C
) 2014-2015 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2015 David Barragán <bameda@dbarragan.com> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # Lic...
nse, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have recei...
#!/usr/local/bin/python import sys import urllib import urllib2 import json import datetime YAHOO_URL = 'http://query.yahooapis.com/v1/public/yql?env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json&diagnostics=true&q=' def getJSON(fileName): f = open(fileName) jsonData = json.load(f) f.close() ...
' + article['text'] returns[key] = articleReturn if progress % 100 == 0: print progress / size, progress, 'out of', size progress += 1 return returns inputFile = sys.argv[2] outputFile = sys.argv[3] days = int(sys.argv[4]) jsonData = getJSON(inputFile) if sys.argv[1] == 'snip...
jsonToWrite = returnsJSONFull(jsonData, days) writeJSON(jsonToWrite, outputFile)
#!/usr/bin/
env python # coding=utf-8 import json import sys dat
a = { 'g1': { 'hosts': [ '172.17.0.2' ] } } with open('w.log', 'w') as f: f.write(str(sys.argv)) print json.dumps(data)
import random import Image import ImageFont import ImageDraw import ImageFilter import hashlib from random_words import RandomWords def gen_captcha(text, fnt, fnt_sz, file_name, fmt='JPEG'): """Generate a captcha image""" # randomly select the foreground color fgcolor = random.randint(0,0xffff00) # make the backg...
(file_name, format=fmt) def new_word(): rw = RandomWords() word = rw.random_word() return word, hashlib.sh
a224(word).hexdigest() if __name__ == '__main__': """Example: This grabs a random word from the dictionary 'words' (one word per line) and generates a jpeg image named 'test.jpg' using the truetype font 'porkys.ttf' with a font size of 25. """ words = open('static/words').readlines() word = words[random.randint(...
TION="none", ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME) def test_registration_email_verification_neccessary_username(self): """ Tests you can log in without email verification """ self.common_test_registration_email_verification_not_necessary_username() @override_...
ail.outbox), mail_count + 1)
new_user = get_user_model().objects.latest('id') login_response = self.client.post(self.login_url, login_data, format='json') self.assertEquals(login_response.status_code, status.HTTP_400_BAD_REQUEST) # verify email email_confirmation = new_user.emailaddress_set.get(email=self.reusable...
import web import base import local def orNone(a, b): if a is None: return b return a class Field(object): def __init__(self, name, description, primary=False, validator=None): self.name = name self.primary = primary self.description = description if validator == ...
ocus_on = input.errfield else: focus_on = metaself.fields[0].full_name() return local.render.add_form( input=web.input(), action='/%s/add' % (metaself.record_name,), description=metaself.add_title, ...
fields=metaself.fields, default_values=default_values, focus=focus_on ) return C def class_add(self, parent_class=base.Action): metaself = self class C(parent_class): role_required = self.role def request...
# -*- coding: utf-8 -*- # Licensed under the MIT license # http://opensource.org/licenses/mit-license.php # Copyright 2014, Hartmut Goebel <h.goebel@goebel-consult.de> """ Test cases for L{backends.ampache_storage} """ from lxml import etree from twisted.trial import unittest from coherence.backends import ampache...
ore, song) self.assertEqual(track.get_id(), 'song.3180') self.assertEqual(track.parent_id, 'album.2910') self.assertEqual(track.duration, '0:03:54') self.assertEqual(track.get_url(), 'http://localhost/play/index.php?oid=123908...') self.assertEqual(track....
ack.album, 'Back in Black') self.assertEqual(track.genre, None) self.assertEqual(track.track_nr, '4') self.assertEqual(track.cover, 'http://localhost/image.php?id=129348') self.assertEqual(track.mimetype, 'audio/mpeg') # guessed self.assertEqual(track.size, 654321) self.a...
from pygame import K_UP, K_DOWN, K_LEFT, K_RIGHT from Caracter import Caracter class CommandHandler(object): #0 1 2 3 4 5 6 7 8 9 10 11 12 13 _automata_transitions= [[11,11,0, 4, 0, 0, 11,11,0, 11,0, 11,13,0],#up [9, 2, 0, 0, 0, 0, 9, 9, 0, 0, 0, 1...
# The final states final_list = [3,7,9,11,13] final_state = 0 def __init__(self, caracter): self.caracter = caracter self.actual_state = 0 def refresh_state(self, in_key): self.final_state = 0 input_code = -1 if in_key == K
_UP: input_code = 0 elif in_key == K_DOWN: input_code = 1 elif in_key == K_LEFT: input_code = 2 elif in_key == K_RIGHT: input_code = 3 self.actual_state = self._automata_transitions[input_code][self.actual_state] if self.actual_state == 3: if self.caracter.onGround ...
""" CRISPR_db_parser Madeleine Bonsma March 7, 2015 Updated May 3, 2016 This script takes a list of spacers downloaded from the CRISPRdb website and splits them into individual files, one file per organism. Result files are saved in "data/spacers". """ import linecache import os # CRISPR db parser # MB Mar 07 2015 ...
# if more than one bacteria contain spacer i = line.index("|")
# include in header the locus identifier and spacer # position identifier writeline = line[10:i] writeline2 = writeline.replace('_', '.') else: # if it's only one bacteria writeline = ...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
e. from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import Table from sqlalchemy import text def upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine consumers = Table("consumers", meta, autoload=True) if not hasattr(
consumers.c, "generation"): # This is adding a column to an existing table, so the server_default # bit will make existing rows 0 for that column. consumers.create_column(Column("generation", Integer, default=0, server_default=text("0"), nullable=False))
_rate:", x[2] #print "modulation:", x[3] #print "fec_inner:", x[4] #print "inversion:", 2 tlist.append(parm) def getInitialTerrestrialTransponderList(tlist, region): list = nimmanager.getTranspondersTerrestrial(region) #self.transponders[self.parsedTer].append((2,freq,bw,const,crh,crl,guard,transm,hiera...
in list: if x[0] == 2: #TERRESTRIAL parm = buildTerTransponder(x[1], x[9], x[2], x[4], x[5], x[3], x[7], x[6], x[8]) tlist.append(parm) cable_bands = { "DVBC_BAND_EU_VHF_I" : 1 << 0, "DVBC_BAND_EU_MID" : 1 << 1, "DVBC_BAND_EU_VHF_III" : 1 << 2, "DVBC_BAND_EU_SUPER" : 1 << 3, "DVBC_BAND_EU_HYPER" : 1 << 4...
_UHF_IV" : 1 << 5, "DVBC_BAND_EU_UHF_V" : 1 << 6, "DVBC_BAND_US_LO" : 1 << 7, "DVBC_BAND_US_MID" : 1 << 8, "DVBC_BAND_US_HI" : 1 << 9, "DVBC_BAND_US_SUPER" : 1 << 10, "DVBC_BAND_US_HYPER" : 1 << 11, } class CableTransponderSearchSupport: # def setCableTransponderSearchResult(self, tlist): # pass # def cableTra...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli
ance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, ...
under the License. def get_connector_properties(root_helper, my_ip, multipath, enforce_multipath, host=None): """Fake os-brick.""" props = {} props['ip'] = my_ip props['host'] = host iscsi = ISCSIConnector('') props['initiator'] = iscsi.get_initiator() props['...
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
features of gRPC. """ # The scopes needed to make gRPC calls to all of the methods defined # in this service. _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) def __init__( self, channel=None, credentials=None, address="cloudasset.googleapis.com:443" ): """...
make calls. This argument is mutually exclusive with ``credentials``; providing both will raise an exception. credentials (google.auth.credentials.Credentials): The authorization credentials to attach to requests. These credentials identify this application to...
domain="www.example.com", account_key=account_key), achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.chall_to_challb( challenges.HTTP01( token=b"\xba\xa9\xda?<m\xaewmx\xea\xad\xadv\xf4\x02\xc9y" b"\x80\xe2_X\t\xe7\xc...
til.chall_to_challb( challenges.HTTP01( token=b"\x8c\x8a\xbf_-f\\cw\xee\xd6\xf8/\xa5\xe3\xfd" b"\xeb9\xf1\xf5\xb9\xefVM\xc9w\xa4u\x9c\xe1\x87\xb4" ), "pending"), domain="www.example.org", account_key=account_key), achallen...
eX0I_A8DXt9Msmg"), "pending"), domain="migration.com", account_key=account_key), achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.chall_to_challb( challenges.HTTP01(token=b"kNdwjxOeX0I_A8DXt9Msmg"), "pending"), domain="ipv6ssl.com", account_key...
def grade(tid, answer): if answer.find("'twas_sum_EZ_programming,_am_I_rite?")
!= -1: return { "correct": True, "message": "Nice job!" } return { "corre
ct": False, "message": "If you're confused, read some tutorials :)" }
#################################################################################################### # Copyright (C) 2016 by Ingo Keller, Katrin Lohan # # <brutusthetschiepel@gmail.com> # # ...
dest = 'port', default = str(EZModule.TCP_PORT), help = 'Port for the JD robot') parser.add_argument( '-n', '--name',
dest = 'name', default = '', help = 'Name prefix for Yarp port names') return parser.parse_args() def main(module_cls): """ This is a main method to run a module from command line. @param module_cls - an EZModule based class t...
from sys import argv script, user_name = argv # Decalare text or prompt to be seen by the user # for all request for inout prompt = '> ' print "Hi %s, I'm the %s script." % (user_name, script) print "I'd like to ask you a few questions." print "Do you like me %s?" % user_name # The 'prompt = >' is seen by user as the...
ives = raw_input(prompt) print "What kind of computer do you have?" # The 'prompt = >' is seen by user as they are asked for some input computer = raw_input(prompt) print """ Alright, so you said %r about
liking me. You live in %r. Not sure where that is. And you have a %r computer. Nice. """ % (likes, lives, computer)
ain'].vocab self._data_dict['valid'] = Text(self.timesteps, valid_path, vocab=vocab) return self._data_dict class PTB(Dataset): """ Penn Treebank data set from http://arxiv.org/pdf/1409.2329v5.pdf Arguments: timesteps (int): number of timesteps to embed the data onehot_inp...
r(X_test, y_test, nclass=2) return self._data_dict class SICK(Dataset): """ Semantic Similarity dataset from qcri.org (Semeval 2014).
Arguments: path (str): path to SICK_data directory """ def __init__(self, path='SICK_data/'): url = 'http://alt.qcri.org/semeval2014/task1/data/uploads/' self.filemap = {'train': 87341, 'test_annotated': 93443, 'trial': 16446} ...
# Playlist.py # # reads all available playlists, adjusts song paths, removes not copied songs, # writes resulting playlist to destination import mlsSong as sng import config import glob import os import sys import codecs def
Playlist(): # get a list of all playlists playlists = glob.glob(config.SOURCE_PLAYLISTFOLDER + "\\*.m3u*") # keep only the file name for (i, playlist) in enumerate(playlists): (filepath, filename) = os.path.split(playlist) playlists[i] = filename # Winamp fail: playlists are saved...
are not found # won't be copied. for oldPlaylist in playlists: newPlaylist = "" for lutPlaylist in config.PLAYLIST_LUT: print oldPlaylist print lutPlaylist[0] if lutPlaylist[0] == oldPlaylist: newPlaylist = lutPlaylist[1] print ...
# -*- coding: utf-8 -*- """ celery.utils.mail ~~~~~~~~~~~~~~~~~ How task error emails are formatted and sent. """ from __future__ import absolute_import import sys import smtplib import socket import traceback import warnings from email.mime.text import MIMEText from .functional import maybe_list from ...
nd(message, timeout=self.timeout) else:
import socket old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(self.timeout) try: self._send(message) finally: socket.setdefaulttimeout(old_timeout) except Exception, exc: ...
from unidown.tools import unlink_dir_rec class TestD
eleteDirRec: def test_non_existence(self, tmp_path): no_folder = tmp_path.joinpath("./donotexist/")
assert not no_folder.exists() unlink_dir_rec(no_folder) assert not no_folder.exists() def test_recursive(self, tmp_path): for number in range(1, 4): with tmp_path.joinpath(str(number)).open('w'): pass sub_folder = tmp_path.joinpath("sub") s...
"""Validators class.""" # -*- coding: utf-8 -*- from wtforms import ValidationError class Uni
queValidator(object): """Validador para chequear variables unicas.""" def __init__(self, model, field, message=None): s
elf.model = model self.field = field if not message: message = u'Existe otro Elemento con el mismo valor.' self.message = message def __call__(self, form, field): _id = None params = {self.field: field.data, 'deleted': False} existing = ...
questPayer='requester') assert (response['Grants'][1]['Permission'] == 'READ') and ( response['Grants'][0]['Permission'] == 'FULL_CONTROL' ) def test_load_fileobj(self, s3_bucket): hook = S3Hook() with tempfile.TemporaryFile() as temp_file: temp_file.write(b"...
te_bucket(bucket_name=s3_bucket, force_delete=True) assert ctx.value.response['Error']['Code'] == 'NoSuchBucket' @mock.patch.object(S3Hook, 'get_connection', return_value=Connection(schema='test_bucket')) def test_provide_bucket_name(self, mock_get_co
nnection): class FakeS3Hook(S3Hook): @provide_bucket_name def test_function(self, bucket_name=None): return bucket_name fake_s3_hook = FakeS3Hook() test_bucket_name = fake_s3_hook.test_function() assert test_bucket_name == mock_get_connection.ret...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-10-02 21:26 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("order", "0004_auto_20160111_1108"), ("wellsfargo", ...
auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ),
), ( "screen_type", models.CharField(max_length=25, verbose_name="Fraud Screen Type"), ), ( "decision", models.CharField( choices=[ ...
#-*- coding: utf-8 -*- import os, re from traceback import format_exc as fme from exprParser import Parser, ParserContext class Shell: echo = False echoStrs = { 'on': True, 'off': False, 'true': True, 'false': False, } commands = {} history = [] values = [] ops = [] def processEchoCommand(self, args): ...
msg(op) def msg(self, txt): print txt def error(self, msg): print msg def installCommands(self): c = self.commands c[':echo'] = self.processEchoCommand c[':exit'] = self.processExitCommand c[':history'] = self.processHistoryCommand c[':ops'] = self.processOps def inputOperation(self, userInput): ...
arser.ret self.values.append(d) self.msg('$%d=' % (len(self.values), )) self.msg(str(d)) #self.printDeterminant(self.values[-1]) return True def isValidDeterminant(self, d): rl = -1 for r in d: if rl == -1: rl = len(r) elif len(r) != rl: self.msg('invalid determinant') return False r...
##################################################################### # u1.py # # (c) Copyright 2021, Benjamin Parzella. All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Softwa
re Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public Lic...
type.""" from .base_number import BaseNumber class U1(BaseNumber): """ Secs type for 1 byte unsigned data. :param value: initial value :type value: list/integer :param count: number of items this value :type count: integer """ format_code = 0o51 text_code = "U1" _base_type ...
# -*- coding: utf-8 -*- # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from django.db import models from django.utils.translation import ugettext_lazy as _ from django.template import Library from treemenus.models import MenuItem register = Library() class ...
=False) css = models.CharField(_(u'CSS style'), null=True, blank=True, max_length=300)
# $Id: icmp.py,v 1.1.1.1 2005/10/29 18:20:48 provos Exp $ from dpkt import Packet, in_cksum as _icmp_cksum import ip # Types (icmp_type) and codes (icmp_code) - # http://www.iana.org/assignments/icmp-parameters ICMP_CODE_NONE = 0 # for types without codes ICMP_ECHOREPLY = 0 # echo reply ICMP_UNREACH = 3 # dest u...
D_REASS = 1 # ttl==0 in reass ICMP_PARAMPROB = 12 # ip header bad ICMP_PARAMPROB_ERRATPTR = 0 # req. opt. absent ICMP_PARAMPROB_OPTABSENT = 1 # req. opt. absent ICMP_PARAMPROB_LENGTH = 2 # bad length ICMP_TSTAMP = 13 # timestamp request ICMP_TSTAMPREPLY = 14 # timestamp reply ICMP_INFO = 15
# information request ICMP_INFOREPLY = 16 # information reply ICMP_MASK = 17 # address mask request ICMP_MASKREPLY = 18 # address mask reply ICMP_TRACEROUTE = 30 # traceroute ICMP_DATACONVERR = 31 # data conversion error ICMP_MOBILE_REDIRECT = 32 # mobile host redirect ICMP_IP6_WHEREAREYOU = 33 # IPv6 where-are-yo...
import sys ROBOT_LISTENER_API_VERSION = 2 def start_keyword(name, attrs): sys.stdout.wri
te('start keyword %s\n' % name) sys.stderr.write('start keyword %s\n' % name) def end_keyword(name, attrs): sys.stdout.write('
end keyword %s\n' % name) sys.stderr.write('end keyword %s\n' % name)
from elasticsearch import TransportError import olympi
a.core.logger from olympia.amo.utils import render log = olympia.core.logger.getLogger('z.es') class ElasticsearchExceptionMiddleware(object): def process_exception(self, request, exception): if issubclass(exception.__class__, TransportError): log.exception(u'Elasticsearch error') ...
equest, 'search/down.html', status=503)
class Egg(object): def __init__(self, xpos, ypos, t, s): self.x = xpos # x-coordinate self.y = ypos # y-coordinate self.tilt = t # Left and right angle offset self.angle = 0 # Used to define the tilt self.scalar = s / 100.0 # Height of the egg def wobble(self): ...
ith pushMatrix(): translate(self.x, self.y) rotate(self.tilt) scale(self.scalar) with beginShape(): vertex(0, -100)
bezierVertex(25, -100, 40, -65, 40, -40) bezierVertex(40, -15, 25, 0, 0, 0) bezierVertex(-25, 0, -40, -15, -40, -40) bezierVertex(-40, -65, -25, -100, 0, -100)
import numpy as np def CG(A, X, B, maxiter=20, tolerance=1.0e-10, verbose=False): """Solve X*A=B using conjugate gradient method. ``X`` and ``B`` are ``ndarrays```of shape ``(m
, nx, ny, nz)`` coresponding to matrices of size ``m*n`` (``n=nx*ny*nz``) and ``A`` is a callable representing an ``n*n`` matrix:: A(X, Y) will store ``X*A`` in the output array ``Y``. On return ``X`` will be the solution to ``X*A=B`` within ``tolerance``."
"" m = len(X) shape = (m, 1, 1, 1) R = np.empty(X.shape, X.dtype.char) Q = np.empty(X.shape, X.dtype.char) A(X, R) R -= B P = R.copy() c1 = A.sum(np.reshape([abs(np.vdot(r, r)) for r in R], shape)) for i in range(maxiter): error = sum(c1.ravel()) if verbose: ...
""" Grade API v1 URL specification """ from django.conf.urls import url, patterns import views urlpatterns = patterns( '', url(r'^g
rades/courses/$', views.CourseGradeList.as_view()), url(r'^grades/courses/(?P<org>[A-Za-z0-9_.-]+)[+](?P<name>[A-Za-z0-9_.-]+)[+](?P<run
>[A-Za-z0-9_.-]+)/$', views.CourseGradeDetail.as_view()), url(r'^grades/students/$', views.StudentList.as_view()), url(r'^grades/students/(?P<student_id>[0-9]+)/$', views.StudentGradeDetail.as_view()), )
urlencoded_get_query_multivalued_param(self): r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz'])) assert r.status_code == 200 assert r.url == httpbin('get?test=foo&test=baz') def test_different_encodings_dont_break_post(self): r = requests.post(httpbin('post'), ...
e.secure == secure assert cookie.domain == domain assert cookie._rest['HttpOnly'] == rest['HttpOnly'] def test_cookie_as_dict_keeps_len(self): key = 'some_cookie' value = 'some_value' key1 = 'some_cookie1' value1 = 'some_value1' jar = requests.cookies.Reque...
(jar.items()) assert len(jar) == 2 assert len(d1) == 2 assert len(d2) == 2 assert len(d3) == 2 def test_cookie_as_dict_keeps_items(self): key = 'some_cookie' value = 'some_value' key1 = 'some_cookie1' value1 = 'some_value1' jar = requests.c...
int), ('gyroscope', int), ('accelerometer', int), ('magnetometer', int), ], # ID_RECHARGE_POWERDOWN: [], ID_BATTERY_CHARGE_RATIO: [('charge', int)], # ID_GO_TO_SLEEP: [('duration', int)], # ID_SHUTDOWN: [], # ID_MOTOR_ACCEL: [('acceleration', float)], ID_STATUS_BUTTO...
PERCENT_ERROR = 25 CPU_CLOCK_SPEED_PERCENT_WARN = 50 # Disk limits. DISK_USAGE_PERCENT_ERROR = 95 DISK_USAGE_PERCENT_WARN = 90 # Memory limits. MEMORY_USAGE_PERCENT_ERROR = 95 MEMORY_USAGE_PERCENT_WARN = 90 # Links BASE_FOOTPRINT = 'base_footprint' BASE_LINK = 'base_link' NECK = 'neck' HE
AD = 'head' ODOM = 'odom' # Joints FOOTPRINT_TO_TORSO_JOINT = 'footprint_to_base_link_joint' TORSO_TO_NECK_JOINT = 'base_link_to_neck_joint' NECK_TO_HEAD_JOINT = 'neck_to_head_joint' HEAD_TO_CAMERA_JOINT = 'head_to_camera_joint' # Battery limits. BATTERY_CHARGE_RATIO_ERROR = 0.8 BATTERY_CHARGE_RATIO_WARN = 0.85 # ...
_key_id, aws_secret_access_key, region=None, ): """Query STS for a users' account_id""" client = get_client( "sts", profile_name, aws_access_key_id, aws_secret_access_key, region, ) return client.get_caller_identity().get("Account") def get_client( client, profile_name, aws_access_...
ler": cfg.get("handler"), "Description": cfg.get("description", ""), "Timeout": cfg.get("timeout", 15),
"MemorySize": cfg.get("memory_size", 512), } if preserve_vpc: kwargs["VpcConfig"] = existing_cfg.get("Configuration", {}).get( "VpcConfig" ) if kwargs["VpcConfig"] is None: kwargs["VpcConfig"] = { "SubnetIds": cfg.get("subnet_ids", []), ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008 Zuza Software Foundation # # This file is part of translate. # # translate is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of t...
# 'short-namespace:tag'
if tag is None: try: namespace_shortcut, tag = namespace_shortcut.split(':') except ValueError: # If there is no namespace in namespace_shortcut. tag = namespace_shortcut.lstrip("{}") return tag return "{%s}%s" % (self.n...
# Django settings for temp project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': {'ENGINE': 'django.db.backends.sqlite3'} } # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://do...
g protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'test_urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'temp.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django...
o use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: # 'django.contr...
# -*- coding: utf-8 -*- """ Plugins related to folders and paths """ from hyde.plugin import Plugin from hyde.fs import Folder class FlattenerPlugin(Plugin): """ The plugin class for flattening nested folders. """ def __init__(self, site): super(FlattenerPlugin, self).__init__(site) def b...
node = self.site.content.node_from_relative_path(item.source) target = Folder(item.target)
except AttributeError: continue if node: for resource in node.walk_resources(): target_path = target.child(resource.name) self.logger.debug( 'Flattening resource path [%s] to [%s]' % (...
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-06-25 15:19 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('shipping', '0005_auto_20170616_1351'), ('teamstore'...
s = [ migrations.AddField( model_name='teamstore', name='shipping_method', field=models.Fore
ignKey(default=2, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='shipping.ShippingMethod', verbose_name='team shipping method'), ), ]
""" A sub-package for efficiently dealing with polynomials. Within the documentation for this sub-pac
kage, a "finite power series," i.e., a polynomial (also referred to simply as a "series") is represented by a 1-D numpy array of the polynomial's coefficients, ordered from lowest order term to highest. For example, array([1,2,3]) represents ``P_0 + 2*P_1 + 3*P_2``, where P_n is the n-th order basis polynomial applica...
n polynomials, including evaluation at an argument, are implemented as operations on the coefficients. Additional (module-specific) information can be found in the docstring for the module of interest. """ from polynomial import * from chebyshev import * from polyutils import * from numpy.testing import Tester test ...
''' This is the library for getting DotA2 insight information. Problem: there was no way to get dota internal data about heroes, their abilities... in suitable for further work form. Solution: this library allows you to get access to all the data in the in-game files. But information abo
ut single hero does not have much use, so there is a way to get stats of selected heroes or get information about certain match. ''' from atod.meta import meta_info from atod.models.interfaces import Member, Group from atod.models.ability import Ability from atod.models.abilities import Ab
ilities from atod.models.hero import Hero from atod.models.heroes import Heroes from atod.models.match import Match from atod.utils.pick import get_recommendations # from atod.utils import dota_api
from django.conf import settings from django.conf.urls import url from plans.views import CreateOrderView, OrderListView, InvoiceDetailView, AccountActivationView, \ OrderPaymentReturnView, CurrentPlanView, UpgradePlanView, OrderView, BillingInfoRedirectView, \ BillingInfoCreateView, BillingInfoUpdateView, Bil...
OrderPaymentReturnView.as_view(status='failure'), name='order_payment_failure'), url(r'^billing/$', BillingInfoRedirectView.as_view(), name='billing_info'), url(r'^billing/create/$', BillingInfoCreateView.as_view(
), name='billing_info_create'), url(r'^billing/update/$', BillingInfoUpdateView.as_view(), name='billing_info_update'), url(r'^billing/delete/$', BillingInfoDeleteView.as_view(), name='billing_info_delete'), url(r'^invoice/(?P<pk>\d+)/preview/html/$', InvoiceDetailView.as_view(), name='invoice_preview_html'...
""" Tests for foe.command.interpret._set
up_readline
""" from foe.command.interpret import _get_input def test_no_config(): assert not _get_input()
.async_register( DOMAIN, "{}_{}".format(p_type, SERVICE_SAY), async_say_handle, descriptions.get(SERVICE_SAY), schema=SCHEMA_SERVICE_SAY) setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN)] if setup_tasks...
"""Load a speech from filesystem.""" with open(voice_file, 'rb') as speech: return speech.read() try: data = yield from self.hass.loop.run_in_executor(None, load_speech) except OSError: del self.file_cache[key]
raise HomeAssistantError("Can't read {}".format(voice_file)) self._async_store_to_memcache(key, filename, data) @callback def _async_store_to_memcache(self, key, filename, data): """Store data to
terms=[['P(-1,1)','P(-1,2)','Metric(1,2003)','Metric(2,1003)'], # from C term ['P(-1,1)','P(-1,2)','Metric(1,1003)','Metric(2,2003)'], # from C term ['P(-1,1)','P(-1,2)','Metric(1,2)','Metric(1003,2003)'], # from C term ['P(1,2)','P(2,1)','Metric(1003,2003)'], # from D ...
) ' % (new_couplings[icoup],all_couplings[icoup]) elif(new_couplings[icoup]) : all_couplings[icoup] = new_couplings[icoup] # return the results return (ordering,all_couplings) def processTensorCouplings(lorentztag,vertex,model,parmsubs,all_couplings,order) : # check for fermion ...
nknown"]*3 value = ["Unknown"]*3 # loop over the colours for icolor in range(0,len(all_couplings)) : lmax = len(all_couplings[icolor]) if(fermions) : lmax //=3 # loop over the different terms for ix in range(0,lmax) : test = [False]*3 imax=3 ...
''' Copyright (C) 2012 mental
smash.org <contact@mentalsmash.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the...
Y; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Custom managers for the Division model. """ from __future__ import unicode_literals from calaccess_processed.managers import BulkLoadSQLManager class OCDAssemblyDivisionManager(BulkLoadSQLManager): """ Custom manager for state as
sembly OCD Divisions. """ def get_queryset(self): """ Filters down to state assembly divisions. """ qs = super(OCDAssemblyDivisionManager, self).get_queryset()
return qs.filter(subid1='ca', subtype2='sldl') class OCDSenateDivisionManager(BulkLoadSQLManager): """ Custom manager for state senate OCD Divisions. """ def get_queryset(self): """ Filters down to state senate divisions. """ qs = super(OCDSenateDivisionManager, sel...
ture, osmTableData['polygons'], workspace, UPPER=None ) for cls in alOut: if cls not in mergeOut: mergeOut[cls] = [alOut[cls]] else: mergeOut[cls].append(alOut[cls]) # ************************************************************************ # # 5 - Get data f...
osmTableData['lines'], osmTableData['polygons'], workspace ) for cls in roads: if cls not in mergeOut: mergeOut[cls] = [roads[cls]] else: mergeOut[cls].append(roads[cls]) # ***************************************************************
********* # # 3 - Area Upper than # # ************************************************************************ # """ auOut = { cls_code : rst_name, ... } """ auOut = area(osm_db, nomenclature, osmTableData['polygons'], workspace, UPPER=True) for cls in auOut: ...
# -*- coding: utf-8 -*- from django.db import models, migrations class Migration(migrations.Migra
tion): dependencies = [ ('entries', '0005_resultsmode_json'), ] operations = [ migrations.AlterField( model_name='resultsmode', name='json
', field=models.TextField(default='', blank=True), ), ]
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ictions_tensor = constant_op.constant( prediction_logits, dtype=dtypes.float32) loss_for_positives, _ = losses.per_example_exp_loss( labels_positive, weights, predictions_tensor, eps=eps) loss_for_negatives, _ = losses.per_example_exp_loss( labels_negative, weights, prediction...
s = loss_for_negatives.eval() # For positive labels, points <= 0.3 get max loss of e. # For negative labels, these points have minimum loss of 1/e. for i in range(2): self.assertEqual(math.exp(1), pos_loss[i]) self.assertEqual(math.exp(-1), neg_loss[i]) # For positive lables, p...
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import pytest from ...
self): Goal.clear() TaskRegistrar(name=self._LIST_GOALS_NAME, action=ListGoals)\ .install().with_description(self._LIST_GOALS_DESC) Ta
skRegistrar(name=self._LLAMA_NAME, action=ListGoalsTest.LlamaTask)\ .install().with_description(self._LLAMA_DESC) TaskRegistrar(name=self._ALPACA_NAME, action=ListGoalsTest.AlpacaTask, dependencies=[self._LLAMA_NAME])\ .install() self.assert_console_output( self._INSTALLED_HEADER, ' {0...
import json import argparse import os from listener.config import MIN_TIME, MAX_TIME, PRESSURE_AV
ERAGE_AM
OUNT from listener.replayer import Replayer from listener.utilities import convert_time, average from listener.calculate import (calculate_temp_NTC, calculate_press, calculate_height, calculate_gyr) from collections import deque from io import StringIO parser = argparse.ArgumentParser(...
## Automatically adapted for numpy.oldnumeric Apr 14, 2008 by -c from builtins import range def writeMeshMatlabFormat(mesh,meshFileBase): """ build array data structures for matlab finite element mesh representation and write to a file to view and play with in matlatb in matlab can then print mesh wi...
e parameterization, should be 1 row 5 = global edge id, base 1 row 6 = subdomain on left? always 1 for now row 7 = subdomain on right? always 0 for now element matrix is [4 x num elements] row 1 = vertex 1 global number row 2 = vertex 2 global number row 3 = vertex 3 global number row 4...
f vertices in triangle """ import numpy as numpy matlabBase = 1 p = numpy.zeros((2,mesh['nNodes_global']),numpy.float_) e = numpy.zeros((7,mesh['nElementBoundaries_global']),numpy.float_) t = numpy.zeros((4,mesh['nElements_global']),numpy.float_) #load p,e,t and write file mfile = ...
import sys import vtk from vtk.test import Testing class TestGhostPoints(Testing.vtkTest): def testLinear(self): pts = vtk.vtkPoints() pts.SetNumberOfPoints(4) pts.InsertPoint(0, (0, 0, 0)) pts.InsertPoint(1, (1, 0, 0)) pts.InsertPoint(2, (0.5, 1, 0)) pts....
id.InsertNextCell(te.GetCellType(), te.GetPointIds()) grid.SetPoints(pts) grid.GetPointData().AddArray(ghosts) dss = vtk.vtkDataSetSurfaceFilter() dss.SetInputData(grid) dss.
Update() self.assertEqual(dss.GetOutput().GetNumberOfCells(), 3) def testNonLinear(self): pts = vtk.vtkPoints() pts.SetNumberOfPoints(10) pts.InsertPoint(0, (0, 0, 0)) pts.InsertPoint(1, (1, 0, 0)) pts.InsertPoint(2, (0.5, 1, 0)) pts.InsertPoint(3, (...
signature unknown pass def connect_after(self, *args, **kwargs): # real signature unknown pass def connect_object(self, *args, **kwargs): # real signature unknown pass def connect_object_after(self, *args, **kwargs): # real signature unknown pass def disconnect(self,...
""" x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass __gtype__ = None # (!) real value is '' class GType(object): # no doc def from_name(self, *args, **kwargs): # real signature unk...
al signature unknown pass def is_abstract(self, *args, **kwargs): # real signature unknown pass def is_classed(self, *args, **kwargs): # real signature unknown pass def is_deep_derivable(self, *args, **kwargs): # real signature unknown pass def is_derivable(self, *arg...
in range(self.n_restarts_optimizer): theta_initial = \ self._rng.uniform(bounds[:, 0], bounds[:, 1]) optima.append( self._constrained_optimization(obj_func, theta_initial, bound...
viation of the predictive distribution at the
query points is returned along with the mean. return_cov : bool, default=False If True, the covariance of the joint predictive distribution at the query points is returned along with the mean. Returns ------- y_mean : ndarray of shape (n_samples,) or (n_samples...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2014, Brian Coca <briancoca+ansible@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module...
[question]} else: prev[question] = '' if module._diff: after = prev.copy() after.update(curr) diff_
dict = {'before': prev, 'after': after} else: diff_dict = {} module.exit_json(changed=changed, msg=msg, current=curr, previous=prev, diff=diff_dict) module.exit_json(changed=changed, msg=msg, current=prev) if __name__ == '__main__': main()
"endorsed_at": None, "abuse_flagged": False, "voted": True, "vote_count": 4, "children": [], "editable_fields": ["abuse_flagged", "voted"], }] self.register_get_thread_response({ "id": self.thread_id, "cours...
ent"}) self.comment_id = "test_comment" def test_basic(self): self.register_get_user_response(self.user) cs_thread = make_minimal_cs_thread({ "id": "test_thread", "course_id": unicode(self.course.id), }) self.register_get_thread_response(cs_thread) ...
hread["id"], "username": self.user.username, "user_id": str(self.user.id), }) self.register_get_comment_response(cs_comment) self.register_delete_comment_response(self.comment_id) response = self.client.delete(self.url) self.assertEqual(response.status_cod...