prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
"""Provides Django-Admin form field.""" # coding=utf-8 from django.utils.translation import ugettext_lazy as _ from django.
forms.fields import Field, ValidationError from tempo.django.widgets import RecurrentEventSetWidget from tempo.recurrenteventset import RecurrentEventSet class RecurrentEventSetField(Field): """Form field, for usage in admin forms. Represents RecurrentEventSet."""
# pylint: disable=no-init widget = RecurrentEventSetWidget def clean(self, value): """Cleans and validates RecurrentEventSet expression.""" # pylint: disable=no-self-use if value is None: return None if not RecurrentEventSet.validate_json(value): rai...
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import print_function, unicode_literals, absolute_import import json import pytest import requests import requests.exception...
try_times=0) ct.build_method = CONTAINER_DOCKERPY_BUILD_METHOD return ct @pytest.fixture(params=[True, False]) def reactor_config_map(request): return request.param @pytest.fixture(params=[True, False]) def inspect_only(request): return request.param @pytest.fixture def user_params(monkeypatch): ...
:class:`DockerBuildWorkflow` requires this fixture. """ monkeypatch.setenv('USER_PARAMS', json.dumps({'image_tag': TEST_IMAGE})) @pytest.fixture def workflow(user_params): return DockerBuildWorkflow(source=MOCK_SOURCE) @pytest.mark.optionalhook def pytest_html_results_table_row(report, cells): if r...
[Line(Point(3, 3), Point(3, 5)), Line(Point(3, 3), Point(5, 3))] assert Circle(Point(5, 5), 2).tangent_lines(Point(5 - 2*sqrt(2), 5)) == \ [Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 - sqrt(2))), Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 + sqrt(2))),] # Properties major = 3 ...
ational(25,2) assert t1.is_right() assert t2.is_right() == False assert t3.is_right() assert p1 in t1 assert t1.sides[0] in t1 assert Segment((0, 0), (1, 0)) in t1 assert Point(5, 5) not in t2 assert t1.is_convex() assert feq(t1.angles[p1].evalf(), pi.evalf()/2) assert t1.is_equ...
assert are_similar(t1, t3) assert are_similar(t2, t3) == False # Bisectors bisectors = t1.bisectors() assert bisectors[p1] == Segment(p1, Point(Rational(5,2), Rational(5,2))) ic = (250 - 125*sqrt(2)) / 50 assert t1.incenter == Point(ic, ic) # Inradius assert t1.inradius == 5 - 5*sqr...
cipher, mode) else: return _CipherContext(self, cipher, mode, _CipherContext._ENCRYPT) def create_symmetric_decryption_ctx(self, cipher, mode): if (isinstance(mode, CTR) and isinstance(cipher, AES) and not self._evp_cipher_supported(cipher, mode)): # This is...
key_size, bn, self._ffi.NULL ) assert res == 1 return _RSAPrivateKey(self, rsa_cdata) def generate_rsa_parameters_supported(self, public_exponent, key_size): return (public_exponent >= 3 and public_exponent & 1 != 0 and key_size >= 512) def load_rsa_private_nu...
numbers.dmp1, numbers.dmq1, numbers.iqmp, numbers.public_numbers.e, numbers.public_numbers.n ) rsa_cdata = self._lib.RSA_new() assert rsa_cdata != self._ffi.NULL rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) rsa_c...
person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, copy, # modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the...
frm, 0, min, sec, frm] serialized_mock_full_toc = [(((13 + 2 * 3) * 11 + 2) >> 8), (((13 + 2 * 3) * 11 + 2) & 0xFF), 1, 2] serialized_mock_full_toc.extend( TRACK_DESCRIPTOR(1, 1, 4, 0xA0, 0, 0, 0, 1, cueify.SESSION_MODE_1, 0)) serialized_mock_full_toc.extend( TRACK_DESCRIPTOR(1, 1, ...
RACK_DESCRIPTOR(1, 1, 4, 1, 0, 0, 0, 0, 2, 0)) serialized_mock_full_toc.extend( TRACK_DESCRIPTOR(1, 1, 4, 2, 0, 0, 0, 4, 47, 70)) serialized_mock_full_toc.extend( TRACK_DESCRIPTOR(1, 1, 4, 3, 0, 0, 0, 7, 42, 57)) serialized_mock_full_toc.extend( TRACK_DESCRIPTOR(1, 1, 4, 4, 0, 0, 0, 13, 47, 28)) serialized_...
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("wagtailcore", "0016_change_page_url_path_to_text_field"), ] operations = [ migrations.AlterField( model_name="grouppagepermission", name="per...
verbose_name="Permission type", ), preserve_default=True, ), ]
from digitalio import DigitalInOut, Direction, Pull import board import time import neopixel led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT pixelPin = board.D2 pixelNumber = 8 strip = neopixel.NeoPixel(pixelPin, pixelNumber, brightness=1, auto_write=False) switch = DigitalInOut(board.D1) switch.dire...
rection.INPUT switch.pull = Pull.UP def wheel(pos): if (pos < 0) or (pos > 255): return (0, 0, 0) if (pos < 85): return (int(pos * 3), int(255 - (pos * 3)), 0) elif (pos < 170): pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170 ret...
index = int((inner * 256 / len(strip)) + outer) strip[inner] = wheel(index & 255) strip.write() time.sleep(wait) while True: if switch.value: led.value = False strip.fill((0, 0, 0)) strip.write() else: led.value = True # strip....
from pandac.PandaModules import * from toontown.toonbase import TTLocalizer from toontown.toonbase import ToontownGlobals ENDLESS_GAME = config.GetBool('endless-ring-game', 0) NUM_RING_GROUPS = 16 MAX_TOONXZ = 15.0 MAX_LAT = 5 MAX_FIELD_SPAN = 135 CollisionRadius = 1.5 CollideMask = ToontownGlobals.CatchGameBitmask TAR...
23, 32], [29, 13, 6.5, 3.2],
[colorRed, colorGreen, colorBlue, colorYellow], [2, 2, 2, 1], ...
import lorun import os import codecs import random import subprocess import config import sys RESULT_MAP = [ 2, 10, 5, 4, 3, 6, 11, 7, 12 ] class Runner: def __init__(self): return def compile(self, judger, srcPath, outPath): cmd = config.langCompile[judger.lang] % {'root': sys.path[0], '...
path.exists(fout_path): os.remove(fout_path)
fin = open(inFile, 'rU') fout = open(fout_path, 'w') runcfg = { 'args': cmd.split(" "), 'fd_in': fin.fileno(), 'fd_out': fout.fileno(), 'timelimit': int(timelimit), 'memorylimit': int(memlimit) } rst = lorun.run(runcfg...
__author__ = 'Dr. Masroor Ehsan' __email__ = 'masroore@gmail.com' __copyright__ = 'Copyright 2013, Dr. Masroor Ehsan' __license__ = 'BSD' __version__ = '0.1.1' from datetime import datetime try: from lxml import etree except ImportError: try: # Python 2.5 import xml.etree.cElementTree as etree...
nd_and_set('title', rootNode, article) _find_and_set('published_at', rootNode, article, _parse_datetime) _find_and_set('link', rootNode, article) _find_and_set('guid', rootNode, article) categories = _parse_category_set(rootNode, tagName='categories') if categories is not None: article['cat...
= categories sourceNode = rootNode.find('source') if sourceNode is not None: source_dict = {} _find_and_set('name', sourceNode, source_dict) _find_and_set('guid', sourceNode, source_dict) if len(source_dict) > 0: article['source'] = source_dict author_set = _pa...
import tak from . import tps import attr import re @attr.s class PTN(object): tags = attr.ib() moves = attr.ib() @classmethod def parse(cls, text): head, tail = text.split("\n\n", 1) tags_ = re.findall(r'^\[(\w+) "([^"]+)"\]$', head, re.M) tags = dict(tags_) tail = re.sub(r'{[^}]+}', ' ', ...
n") if dir and not pickup and not slides: pickup = '1' if pickup and not slides: slides = (int(pickup),) if pickup and int(pickup) != sum(slides): raise BadMove(move, "inconsistent pickup and drop: {0} v {1}".format(pickup, drops)) return tak.Move(x, y, typ, sli
des) def format_move(move): bits = [] bits.append(place_rmap.get(move.type, '')) if move.type.is_slide(): pickup = sum(move.slides) if pickup != 1: bits.append(pickup) bits.append(chr(move.x + ord('a'))) bits.append(chr(move.y + ord('1'))) if move.type.is_slide(): bits.append(slide_rm...
# -*- coding: utf-8 -*- from __future__ import unicode_
literals # do this when > 1.6!!! # from django.db import migrations, models from gazetteer.models import GazSource,GazSourceConfig,LocationTypeField,CodeFieldConfig,NameFieldCon
fig from skosxl.models import Concept, Scheme, MapRelation from gazetteer.settings import TARGET_NAMESPACE_FT def load_base_ft(): (sch,created) = Scheme.objects.get_or_create(uri=TARGET_NAMESPACE_FT[:-1], defaults = { 'pref_label' :"Gaz Feature types" }) try: (ft,created) = Concept.objects.get_or...
a = {"abc":
"d<caret>
ef"}
# Make your image, region, and location changes then change the from-import # to match. from configurables_akeeton_desktop import * import hashlib import java.awt.Toolkit import json import os import shutil import time Settings.ActionLogs = True Settings.InfoLogs = True Settings.DebugLogs = True Set...
ts) HITS_PATH = os.path.join(ATTEMPT_NUM_PATH, HITS_DIR) MISSES_PATH = os.path.join(ATTEMPT_NUM_PATH, MISSES_DIR) print "TEMP_PATH:", TEMP_PATH print "ATTEMPT_NUM_PATH", ATTEMPT_NUM_PATH print "HITS_PATH:", HITS_PATH print "MISSES_PATH:", MISSES_PATH os.mkdir(AT...
card_sent_to_bottom', ZeroValueDict()] card_hash_to_times_card_sent_to_bottom_and_drawn = ['card_hash_to_times_card_sent_to_bottom_and_drawn', ZeroValueDict()] card_hash_to_times_card_drawn = ['card_hash_to_times_card_drawn', ZeroValueDict()] card_hash_to_capture ...
import pyaudio import struct from threading import Thread, Condition import time from logging import thread import socket CHUNK = 2**12 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 class AudioReader(Thread): def __init__(self, raw = False, remote = False, host = 'localhost', port = 9999): Thread._...
elf.active: data = self.stream.read(CHUNK) if not self.raw: count = len(data) / 2 fmt = "%dh" % (count) shorts = struct.unpack(fmt, data) else: shorts = data for l in self.listeners: ...
self.stream.close() def readRemoteData(self): self.condition.acquire() self.condition.wait() self.condition.release() self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((self.host, self.port)) buf = [] wh...
# Tweepy # Copyright 2009-2022 Joshua Roesslein # See LICENSE for details. from collections.abc import Mapping class EqualityComparableID: __slots__ = () def __eq__(self, other): if isinstance(other, self.__class__): return self.id == other.id return NotImplemented class Hasha...
def __getattr__(self, name): try: return self.data[name] except KeyErr
or: raise AttributeError from None def __getitem__(self, key): try: return getattr(self, key) except AttributeError: raise KeyError from None def __iter__(self): return iter(self.data) def __len__(self): return len(self.data)
import sys, os def timeSplit( ETR ): h = int(ETR/3600) m = int(ETR - 3600*h)/60 s = int(ETR - 3600*h - 60*m) return h, m, s def printProgress( current, total, deltaIter, deltaTime ): terminalString = "\rProgress: " if total==0: total+=1 percent = 100.*current/total nDots = int(percent/5) dotsStri...
s - 60*minutes) ETRstring = " ETR= {0}:{1:02}:{2:02} ".format(hours, minutes, seconds) if deltaTime < 0.0001: ETRstring = " ETR= " terminalString += dotsString + percentString + ETRstring sys.stdout. write(terminalString) sys.stdout.flush()
def printProgressTime( current, total, deltaTime ): terminalString = "\rProgress: " if total==0: total+=1 percent = 100.*current/total nDots = int(percent/5) dotsString = "[" + nDots*"." + (20-nDots)*" " + "]" percentString = "{0:.0f}%".format(percent) if current != 0: ETR = (deltaTime*(total - cur...
# # This file is part of opsd. # # opsd 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 3 of the License, or # (at your option) any later version. # # opsd is distributed in the hope that it wil...
f query_status(self): with self._daemon.connect() as dome: status = dome.status() if status['heartbeat_status'] in [DomeHeartbeatStatus.TrippedClosing, DomeHeartbeatStatus.TrippedIdle]: return DomeStatus.Timeout if status['shutt...
rStatus.Opening, DomeShutterStatus.Closing] or \ status['shutter_b'] in [DomeShutterStatus.Opening, DomeShutterStatus.Closing]: return DomeStatus.Moving return DomeStatus.Open def ping_heartbeat(self): print('dome: sending heartbeat ping') with self._daemon.conn...
"""Twitter crawler script""" import tweepy from database import MongoDB class Twitter(object): # pylint: disable=too-few-public-methods """Class Twitter""" def __init__(self): self.consumer_key = "40GvlhlFPNbVGkZnPncPH8DgB" self.consumer_secret = "G595ceskX8iVH34rsuLSqpFROL0
brp8ezzZR2dGvTKvcpPsKPw" self.access_token = "397905190-LXMFC0clhtDxx5cITBWVFqVUKNQBKuqM06Ls4k5n" self.access_token_secret = "
nPzoHy5UwzOPUZVZO3JhBFRL3WgdM0jJKignxIzQ6nAS1" self.auth = tweepy.OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.set_access_token(self.access_token, self.access_token_secret) self.api = tweepy.API(self.auth) # Method to print our tweets def print_tweets(self, count=1): ...
# -*- coding: utf-8 -*- """ Kay preparse management command. :Copyright: (c) 2009 Accense Technology, Inc. Takashi Matsuo <tmatsuo@candit.jp>, All rights reserved. :license: BSD, see LICENSE for more details. """ import os import sys from os import listdir, path, mkdir fro...
le_app_templates(app): env = app.jinja2_env target_dirs = [dir for dir in app.app_settings.TEMPLATE_DIRS\ if os.path.isdir(dir)] for app in app.app_settings.INSTALLED_APPS: if app.startswith("kay."): continue mod = import_string(app) target_dirs.extend(find_templ
ate_dir(os.path.dirname(mod.__file__), ('kay'))) for dir in target_dirs: dest = prepare_destdir(dir) print_status("Now compiling templates in %s to %s." % (dir, dest)) compile_dir(env, dir, dest)
from linked_list import LinkedList class Stack(object): def __ini
t__(self, iterable=None): self._list = LinkedList(iterable) def push(self, val): self._list.insert(
val) def pop(self): return self._list.pop()
#!/usr/bin/env python # Dependencies.py - discover, read, and write dependencies file for make. # The format like the output from "g++ -MM" which produces a # list of header (.h) files used by source files (.cxx). # As a module, provides # FindPathToHeader(header, includePath) -> path # FindHeadersInFile(filePath...
returned by OS may be arbitrary sourceFiles.sort(key=ciKey) for sourceName in sourceFiles: objName = os.path.splitext(os.path.basename(sourceName))[0]+objExt headerPaths = FindHeadersInFileRecursive(sourceName, includePath, renames) depsForSource = [sourceName] + headerPaths depsToAppend = [Remov...
eturn the stem of a filename: "CallTip.o" -> "CallTip" """ return os.path.splitext(os.path.basename(p))[0] def InsertSynonym(dependencies, current, additional): """ Insert a copy of one object file with dependencies under a different name. Used when one source file is used to create two object files with diffe...
""" Module for Image annotations using annotator. """ from lxml import etree from pkg_resources import resource_string from xmodule.x_module import XModule from xmodule.raw_module import RawDescriptor from xblock.core import Scope, String from xmodule.annotator_mixin import get_instructions, html_to_text from xmodule....
self.user_email = self.runtime.get_real_user(self.runtime.anonymous_student_id).email except Exception: # pylint: disable=broad-except self.user_email = _("No email address found.") def _extract_instructions(self, xmltree): """ Removes <instructions> from the xmltr...
rameters to template. """ context = { 'display_name': self.display_name_with_default, 'instructions_html': self.instructions, 'token': retrieve_token(self.user_email, self.annotation_token_secret), 'tag': self.instructor_tags, 'openseadragonjson': self...
#task_H def dijkstra(start, graph): n = len(graph) D = [None] * n D[start] = 0 index = 0 Q = [start] while index < len(Q): v = Q[index] index += 1 for u in graph[v]: if D[u] == None or D[v] + min(graph[v][u]) < D[u]: D[u] = D[v] + min(graph[v][u]) Q.append(u) return D def reverse(graph): n = l...
)} for i in range(n): for v in graph[i]: for w in graph[i][v]: add(graph_reversed, v, i, w) def add(graph, a, b, w): if b in graph[a]: grph[a][b].append(w) else: g
raph[a][b] = [w] def min_vertex(x, D, graph): A = {v: w + D[v] for v, w in zip([u for u in graph[x].keys if D[u] != None], [min(graph[x][u]) for u in graph[x].keys if D[u] != None])} L = list(A.items) min_i = L[0][0] min_v = L[0][1] for v in A: if A[v] < min_v: min_v = A[v] min_i = v return min_i def pat...
from . import test_attachment fast
_suite = [test_attachment,
]
from .forms import SetupForm from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.shortcuts import redirect from splunkdj.decorators.render import render_to from splunkdj.setup import create_setup_view_context @login_required def home(request): # Redire...
result = create_setup_view_context( request, SetupForm, reverse('twitter2:home')) # HACK: Workaround DVPL-4647 (Splunk 6.1 and below): # Refresh current app's state so that non-framework views # o
bserve when the app becomes configured. service = request.service app_name = service.namespace['app'] service.apps[app_name].post('_reload') return result
gnals to nose that this function is or is not a test Parameters ---------- tf : bool If True specifies this is a test, not a test otherwise e.g >>> from numpy.testing.decorators import setastest >>> @setastest(False) ... def func_with_test_in_name(arg1, arg2): pass ... >>> ...
on. This is useful for tests that may require costly imports, to delay the cost until the test suite is actually executed. msg : string Message to give on raising a SkipTest exception Returns ------- decorator : function Decorator, which, when applied to a fun
ction, causes SkipTest to be raised when the skip_condition was True, and the function to be called normally otherwise. Notes ----- You will see from the code that we had to further decorate the decorator with the nose.tools.make_decorator function in order to transmit function name, ...
"""Test the Advantage Air Sensor Platform.""" from datetime import timedelta from json import loads from homeassistant.components.advantage_air.const import DOMAIN as ADVANTAGE_AIR_DOMAIN from homeassistant.components.advantage_air.sensor import ( ADVANTAGE_AIR_SERVICE_SET_TIME_TO, ADVANTAGE_AIR_SET_COUNTDOWN...
ntity_id = "sensor.ac_one_time_to_on" state = hass.st
ates.get(entity_id) assert state assert int(state.state) == 0 entry = registry.async_get(entity_id) assert entry assert entry.unique_id == "uniqueid-ac1-timetoOn" value = 20 await hass.services.async_call( ADVANTAGE_AIR_DOMAIN, ADVANTAGE_AIR_SERVICE_SET_TIME_TO, {AT...
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # 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 #...
3 of the License, 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 received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### import survey_update_wizard
import subprocess from typing import List, Optional from approvaltests import ensure_file_exists from approvaltests.command import Command from approvaltests.core.reporter import Reporter from approvaltests.utils import to_json PROGRAM_FILES = "{ProgramFiles}" class GenericDiffReporterConfig: def __init__(self,...
config = {"name": self.name, "path": self.path} return to_json(config) @staticmethod def run_command(command_array): subprocess.Popen(command_array) def g
et_command(self, received: str, approved: str) -> List[str]: return [self.path] + self.extra_args + [received, approved] def report(self, received_path: str, approved_path: str) -> bool: if not self.is_working(): return False ensure_file_exists(approved_path) command_arr...
es have no head commit parent_commits = list() # END handle parent commits else: for p in parent_commits: if not isinstance(p, cls): raise ValueError("Parent commit '%r' must be of type %s" % (p, cls)) # end check parent com...
.split()[-1].decode('ascii')))) # END for each parent line self.parents = tuple(self.parents) # we don't know actual author encoding before we have parsed it, so keep the lines around author_line = next_line committer_line = readline() # we might run into one or more me...
while next_line.startswith(b'mergetag '): next_line = readline() while next_line.startswith(b' '): next_line = readline() # end skip mergetags # now we can have the encoding line, or an empty line followed by the optional # message. self....
# -*- coding: utf-8 -*- # 中文对齐不能用python自带的函数,需要自己根据中文长度增/减空格 # Python 2.7.12 & matplotlib 2.0.0 import re from urllib2 import * import matplotlib.pyplot as plt #Get a set of records from nba.hupu.com due to given team def getDataSet(team): statUserAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (K...
self.result = '胜' else: self.result = '负' if statRecord[0] == self.team: self.place = '客' self.opp = statRecord[1]
#Get the score of this game self.scoreSelf = re.findall(r'^\d+', statRecord[2].strip())[0] self.scoreOpp = re.findall(r'\d+$', statRecord[2].strip())[0] self.score = self.scoreSelf + '-' + self.scoreOpp else: self.place = '主' ...
import threading import upnp import nupnp class DiscoveryThread(threading.Thread): def __init__(self, bridges): super(DiscoveryThread,
self).__init__() self.bridges = bridges self.upnp_thread = upnp.UPnPDiscoveryThread(self.bridges) self.nupnp_thread = nupnp.NUPnPDiscoveryThread(self.bridges) def run(self): self.upnp_thread.start() self.nupnp_thread.start() self.upnp_threa
d.join() self.nupnp_thread.join() def discover(): bridges = set() discovery_thread = DiscoveryThread(bridges) discovery_thread.start() discovery_thread.join() return bridges
# Copyrig
ht 2014-2017 The ODL contributors # # This file is part of ODL. # # 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 https://mozilla.org/MPL/2.0/. from __future__ import absolute_import __all__ = () ...
localmeans_functionals import * __all__ += nonlocalmeans_functionals.__all__
__autho
r__ = 'Ahmed Hani Ibrahim' from LearningAlgorithm import * class RPROP(LearningAlgorithm): def learn(self, learningRate, input, output, network): """ :param learningRate: :param input: :param output: :param network: :return: "
"" pass
tes and sr: sd, ed = dates PromotedLinkRoadblock.add(sr, sd, ed) jquery.refresh() @validatedForm(VSponsorAdmin(), VModhash(), dates=VDateRange(['startdate', 'enddate'], reference_date=promote.promo_datetim...
lta(days=g.max_promote_future),
reference_date=promote.promo_datetime_now, business_days=True, sponsor_override=True), link=VLink('link_id36'), bid=VBid('bid', min=0, max=g.max_promote_bid, coerce=False, error=errors.BAD_BID), ...
from django.conf.urls import patterns, url urlpatterns
= patterns( 'mtr.utils.views', url(r'^model/(?P<name>.+)/pk/(?P<pk>\d+)$',
'model_label', name='model_label') )
#!/usr/bin/python # -*- coding: utf-8 -*- """ Script de comprobación de entrega de ejercicio Para ejecutarlo, desde la shell: $ python check.py login_github """ import os import random import sys ejercicio = 'X-Serv-14.5-Sumador-Simple' student_files = [ 'servidor-sumador.py' ] repo_files = [ 'check...
o va bien, no ha de mostrar nada)" print for filename in student_files: if filename in github_file_list: os.system('pep8 --repeat --show-source --statistics /tmp/' + aleatorio + '/'
+ filename) else: print "Fichero " + filename + " no encontrado en el repositorio." print
import os import re import sys from setuptools import setup, find_packages PY3 = sys.version_info[0] == 3 here = os.path.abspath(os.path.dirname(__file__)) name = 'pyramid_kvs' with open(os.path.join(here, 'README.rst')) as readme: README = readme.read() with open(os.path.join(here, 'CHANGES.rst')) as changes: ...
", "Topic :: I
nternet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI", "License :: OSI Approved :: GNU General Public License v2 (GPLv2)", ], author='Gandi', author_email='feedback@gandi.net', url='https://github.com/Gandi/pyramid_kvs', keywords='web pyramid pylons', packag...
from django.core.urlresolvers import reverse from kishore.models import Artist, Song, Release from base import KishoreTestCase class ArtistTestCase(KishoreTestCase): def test_index(self): resp = self.client.get(reverse('kishore_artists_index')) self.assertEqual(resp.status_code, 200) def test...
self): resp = self.client.get(reverse('kishore_songs_index')) self.assertEqual(resp.status_code, 200) def test_detail(self): s = Song.objects.get(pk=1
) resp = self.client.get(s.get_absolute_url()) self.assertEqual(resp.status_code, 200) def test_player_html(self): with self.settings(KISHORE_AUDIO_PLAYER="kishore.models.SoundcloudPlayer"): s = Song.objects.get(pk=1) self.assertTrue(s.get_player_html()) ...
"""
LMS specific monitoring helpers. "
""
#----------------------------------------------------------------------------- # Copyright (c) 2005-2020, PyInstaller Development Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # # The full license is in the file COPYING.txt, ...
pache-2.0 #----------------------------------------------------------------------------- import os import sys # On Mac OS X tell enchant library where to look for enchant backends (aspell, myspell, ...). # Enchant is looking for backends in directory 'PREFIX/lib/enchant' # Note: env. var. ENCHANT_PREFIX_
DIR is implemented only in the development version: # https://github.com/AbiWord/enchant # https://github.com/AbiWord/enchant/pull/2 # TODO Test this rthook. if sys.platform.startswith('darwin'): os.environ['ENCHANT_PREFIX_DIR'] = os.path.join(sys._MEIPASS, 'enchant')
# # Copyright 2018 Analytics Zoo Authors. # # 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...
ilder from zoo.orca.automl.auto_estimator import AutoEstimator from zoo.chronos.model.Seq2Seq_pytorch import model_creator from .base_automodel import BasePytorchAutomodel class AutoSeq2Seq(BasePytorc
hAutomodel): def __init__(self, input_feature_num, output_target_num, past_seq_len, future_seq_len, optimizer, loss, metric, lr=0.001, lstm_hidden_dim=128, ...
import netifaces from netaddr import * for inter in netifaces.interfaces(): addrs = netifaces.ifaddresses(inter) try: print(addrs) print(addrs[netifaces.AF_INET][0]["addr"]) print(addrs[netifaces.AF_INET][0]["broadcast"]) print(addrs[netifaces.AF_INET][0]["netmask"]) loc...
t_lan_ip(): global local_ip return local_ip def get_broadcast_ip(): global broadcast return broadcast def get_all_ips(): global ips return ips def
get_gateway(): global gateway return gateway def get_mac(): global mac return mac
__author__ = 'sibirrer' #this file is ment to be a shell script to be run with Monch cluster # set up the scene from cosmoHammer.util.MpiUtil import MpiPool import time import sys import pickle import dill start_time = time.time() #path2load = '/mnt/lnec/sibirrer/input.txt' path2load = str(sys.argv[1]) f = open(pa...
, n_run, n_burn, mean_start, sigma_start, lowerLimit, upperLimit, threadCount=1, init_pos=None, mpi_monch=True) # save the output pool = MpiPool(None) if pool.isMaster(): f = open(path2dump, 'wb') pickle.dump(samples, f) f.close() end_time = time.time() print(end_time
- start_time, 'total time needed for computation') print('Result saved in:', path2dump) print('============ CONGRATULATION, YOUR JOB WAS SUCCESSFUL ================ ')
#! /usr/bin/env python """ This program plots the average electronic energy during a NAMD simulatons averaged over several initial conditions. It plots both the SH and SE population based energies. Example: plot_average_energy.py -p . -nstates 26 -nconds 6 Note that the number of states is the same as given in the ...
rage(np.sum(eav_outs, axis=1), axis=1) el_ene_pops = np.average(np.sum(eav_pops, axis=1), axis=1) # Ensamble average scaled to the lowest excitation energy. # This way the cooling converge to 0. lowest_hl_gap = np.average(np.amin(energies[:, 1:, :], axis=1), axis=1) ene_outs_ref0 = el_ene_outs - low...
e_outs_ref0, ene_pops_ref0) def read_cmd_line(parser): """ Parse Command line options. """ args = parser.parse_args() attributes = ['p', 'nstates', 'nconds'] return [getattr(args, p) for p in attributes] # ============<>=============== if __name__ == "__main__": msg = "plot_states_pops...
"""Detail firewall.""" # :license: MIT, see LICENSE for more details. import click import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import firewall from SoftLayer.CLI import formatting
from SoftLayer import utils @click.command() @click.argument('identifier') @environment.pass_env def cli(env, identifier): """Detail firewall.""" mgr = SoftLayer.FirewallManager(env.client) firewall_type, firewall_id = firewall.parse_id(identifier) if firewall_type == 'vlan': rules = mgr.ge...
rules = mgr.get_standard_fwl_rules(firewall_id) env.fout(get_rules_table(rules)) def get_rules_table(rules): """Helper to format the rules into a table. :param list rules: A list containing the rules of the firewall :returns: a formatted table of the firewall rules """ table = forma...
#!/usr/bin/python # Python modules imports from optparse import OptionParser, make_option import pyupm_grove as g import os, sys, socket, uuid, dbus, dbus.service import dbus.mainloop.glib #import gardening_system try: from gi.repository import GObject except ImportError: import gobject as GObject # Set up consta...
evice_path) server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM) server_sock.settimeout(1) server_sock.send("Hello, this is Edison!") try: while True: try: data = server_sock.recv(1024) gardening_system.fu...
pass gardening_system.myProgram() except IOError: pass server_sock.close() print("\nYour device is now disconnected\nPress [ENTER] to continue") def bluetoothConnection(): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = db...
#!../
venv/bin/python import sys print (sys.argv[1:
])
FORE response = self.client.get(reverse('search.advanced'), qs) results = json.loads(response.content)['results'] eq_([q1.get_absolute_url()], [r['url'] for r in results]) qs['created'] = constants.INTERVAL_AFTER response = self.client.get(reverse('search.advanced'), qs) ...
, ) for prod, total in prod_vals: for i in range(total): doc = document(locale=u'en-US', category=10, save=True) doc.p
roducts.add(prod) revision(document=doc, is_approved=True, save=True) self.refresh() qs = {'a': 1, 'w': 1, 'format': 'json'} for prod, total in prod_vals: qs.update({'product': prod.slug}) response = self.client.get(reverse('search.advanced'), qs) ...
# ********************************************************************** <==== from artmgr.transport.basew import BaseWTransport # ********************************************************************** ====> import os import sys import errno import stat import re # chunksize for reading/writing local files CHUNK = ...
mkpath_recursive( head ) os.mkdir( path ) # --------------------------------------------------------------------- class LocalTransport( BaseWTransport ): """ A full R/W transport instance that uses a locally visible directory to store and read all artifact data """ def __init__...
subrepo ): """ Constructor @param basedir (str): local folder to use @param subrepo (str): name of the repository we are dealing with """ if not basedir: raise InvalidArgumentError("Empty basedir in local transport") if not subrepo: ra...
#author :haiyfu #date:April 14 #description: #contact:haiyangfu512@gmail.com """ This little part is to check how many different values in a column and store the unqiue values in a list. For FCBF initially. The last column is the class . """ from sys import argv #only count the target file and return...
script_
nm,src_file,out_file=argv wrt_rc(rc_gn(src_file),out_file)
# Copyright 2020 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
e(self, example: JsonDict, model: lit_model.Model,
dataset: lit_dataset.Dataset, config: Optional[JsonDict] = None) -> List[JsonDict]: """Naively scramble all words in an example. Note: Even if more than one field is to be scrambled, only a single example will be produced, unlike other generators which will produce multiple ...
import re import html # The regular string.split() only takes a max number of splits, # but it won't unpack if there aren
't enough values. # This function ensures that we always get the wanted # number of returned values, even if the
string doesn't include # as many splits values as we want, simply by filling in extra # empty strings at the end. # # Some examples: # split("a b c d", " ", 3) = ["a", "b", "c d"] # split("a b c" , " ", 3) = ["a", "b", "c"] # split("a b", " ", 3) = ["a", "b", ""] def split(s, sep, count): return (s + ((count ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import io import os import sys import re from setuptools import setup if sys.argv[-1] == "publish": os.system("python setup.py sdist upload") sys.exit() packages = [ "the_big_username_blacklist" ] # Handle requirements install_requires = [] tests_requires...
={"the_big_username_blacklist": "the_big_username_blacklist"}, include_package_data=True, install_requires=install_requires, license="MIT", zip_safe=False, classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Natural Language :: Eng...
anguage :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: Implementation :: PyPy" ], )
#SBaaS from .stage02_physiology_graphData_io import stage02_physiology_graphData_io from SBaaS_models.models_COBRA_execute import models_COBRA_execute from .stage02_physiology_analysis_query import stage02_physiology_analysis_query #System import copy class stage02_physiology_graphData_execute(stage02_physiology_graph...
_physiology_sampledData_query'; elif weights_I == 'stage02_physiology_simulatedData_query': weights = self.import_graphWeights_simulatedData(row['
simulation_id']); weights_str = 'stage02_physiology_simulatedData_query'; else: print('weights source not recognized'); # run the analysis for different algorithms/params for ap in algorithms_params_I: shortestPaths = exCOB...
from __future__ import absolute_import, division, print_function from dynd._pydynd import w_type, \ make_var_dim, make_strided_dim, make_fixed_dim, make_cfixed_dim __all__ = ['var', 'strided', 'fixed', 'cfixed'] class _Dim(object): __slots__ = [] def __mul__(self, rhs): if isinstance(rhs, w...
return 'ndt.fixed' class _CFixed(_Dim): """ Creates a cfixed dimension when combined with other types. Examples -------- >>> ndt.cfixed[3] * ndt.int32 ndt.type('cfixed[3] * int32') >>> ndt.fixed[5] * ndt.cfixed[2] * ndt.float64 ndt.type('5 * cfixed[2] * float64') """ __slot...
return (self,) else: raise TypeError('Need to specify ndt.cfixed[dim_size],' + ' not just ndt.cfixed') def create(self, eltype): return make_cfixed_dim(self.dim_size, eltype) def __getitem__(self, dim_size): return _CFixed(dim_size) def _...
from django.contrib.contenttypes.fields import GenericRelation from django.db import models from django.urls import reverse from django.utils.encoding import python_2_unicode_compatible from extras.models import CustomFieldModel, CustomFieldValue from utilities.models import CreatedUpdatedModel from utilities.utils im...
(models.Model): """ An arbitrary collection of T
enants. """ name = models.CharField(max_length=50, unique=True) slug = models.SlugField(unique=True) class Meta: ordering = ['name'] def __str__(self): return self.name def get_absolute_url(self): return "{}?group={}".format(reverse('tenancy:tenant_list'), self.slug) ...
# -*- encoding: utf-8 -*- from __future__ import absolute_import import requests import json import logging from bs4 import BeautifulSoup as htmldoc def carrier_lookup(): return None class CarrierLookup(object): def __init__(self, number, logname=None): self.number = number self._logname =...
Type': 'lookup', 'PhoneNumber': "{0}".format(self.numb
er), 'VisitorSid': sid, 'CSRF': csrf, } log.debug('\nparams: {0}\n'.format(jsonify(params))) url = '{0}/functional-demos'.format(host) r = s.post(url, params=params) info = json.loads(r.content) return info
#!/usr/bin/env python # # Copyright 2014 Simone Campagna # # 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 l...
result = self.filter_validation_result(result) self.set_paths(base_dir, reset=reset) if throw_on_errors and result: raise ConfigmentValidateError(result) c_result = ConfigObjWrap( infile=result, stringify=True, unrepr=True, ind...
t(BaseConfigment): def __init__(self, filename=None, default_mode=None): super(Configment, self).__init__( filename=filename, default_mode=default_mode, ) def impl_initialize(self, throw_on_errors=False): try: return self.do_validation(reset=False, th...
""" compact_group.py - Part of millennium-compact-groups package Defines CompactGroup object to handle information about a single compact group. Copyright(C) 2016 by Trey Wenger; tvwenger@gmail.com Chris Wiens; cdw9bf@virginia.edu Kelsey Johnson; kej7a@virginia.edu GNU General Public License v3 (GNU GPLv3) This pro...
# mass in annulus annulus_mass = np.sum(self.neighbors['mvir']) annulus_mass = annulus_mass/(4.*np.pi/3. * (radius**3. - self.radius**3.)) self.annular_mass_ratio = annulus_mass/sphere_mass def calc_secondtwo_mass_ratio(self
): """ Calculate the ratio of the virial masses of the second largest members to the virial mass of the largest member """ sorted_masses = np.sort(self.members['mvir']) self.secondtwo_mass_ratio = (sorted_masses[-2]+sorted_masses[-3])/sorted_masses[-1]
from .test_base_class import ZhihuClientC
lassTest PEOPLE_SLUG = 'giantchen' class TestPeopleBadgeNumber(ZhihuClientClassTest): def test_badge_topics_number(self): self.assertEqual( len(list(self.client.people(PEOPLE_SLUG).badge.topics)), 2, ) def test_people_has_badge(self): self.assertTrue(self.client.people(PE...
e(self.client.people(PEOPLE_SLUG).badge.has_identity) def test_people_is_best_answerer_or_not(self): self.assertTrue(self.client.people(PEOPLE_SLUG).badge.is_best_answerer) def test_people_identify_information(self): self.assertIsNone(self.client.people(PEOPLE_SLUG).badge.identity)
#! /bin/python import xbh as xbhpkg x
bh = xbhpkg.Xbh() #xbh.switch_to_app() xbh.calc_checksum() print(xbh.g
et_results())
class FieldRegistry(object): _registry = {} def add_field(self, model,
field): reg = self.__class__
._registry.setdefault(model, []) reg.append(field) def get_fields(self, model): return self.__class__._registry.get(model, []) def __contains__(self, model): return model in self.__class__._registry
""" Generates 40 random numbers and writes them to a file. No number is repeated. ~ Created by Elijah Wilson 2014 ~ """ # used for generating random integers from random import randint # open the output file -> "in.data" f = open("in.data", "w") # create an empty list succ = [] # loops throu
gh 40 times for generating numbers for x in xrange(0,40): # generate random int between 1111 & 9999 randNum = randint(1111, 9999) # check to see if it was already generated if randNum not in succ: # put the random number in the list succ.append(str(randNum)) else: # while the randNum has already been genera...
# generate a new one while randNum in succ: randNum = randint(1111, 9999) # put the random number in the list succ.append(str(randNum)) # loops through 40 times for writing to file for x in xrange(0,40): # makes sure it isn't the last line to be written # to write a new line char if x != 39: f.write(suc...
# -*- coding: utf-8 -*- ############################################################################### # # ZipFile # Creates a zipped version of the specified Box file and returns a link to the new compressed file. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License...
stance of the ZipFile Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(ZipFile, self).__init__(temboo_ses
sion, '/Library/Box/Files/ZipFile') def new_input_set(self): return ZipFileInputSet() def _make_result_set(self, result, path): return ZipFileResultSet(result, path) def _make_execution(self, session, exec_id, path): return ZipFileChoreographyExecution(session, exec_id, path) cl...
import os import platform from setuptools import setup # "import" __version__ __version__ = 'unknown' for line in open('sounddevice.py'): if line.startswith('__version__'): exec(line) break MACOSX_VERSIONS = '.'.join([ 'macosx_10_6_x86_64', # for compatibility with pip < v21 'macosx_10_6_...
'Operating System :: OS Independent', 'Programming Language :: P
ython', 'Programming Language :: Python :: 3', 'Topic :: Multimedia :: Sound/Audio', ], cmdclass=cmdclass, )
#!/usr/bin/env python """The MySQL database methods for foreman rule handling.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from grr_response_core.lib import rdfvalue from grr_response_server import foreman_rules from grr_response_server.databases im...
ForemanRules(self, cursor=None): cursor.execute("SELECT rule FROM foreman_
rules") res = [] for rule, in cursor.fetchall(): res.append(foreman_rules.ForemanCondition.FromSerializedBytes(rule)) return res @mysql_utils.WithTransaction() def RemoveExpiredForemanRules(self, cursor=None): now = rdfvalue.RDFDatetime.Now() cursor.execute( "DELETE FROM foreman_r...
import traceback from vstruct2.compat import int2bytes, bytes2int # This routine was coppied from vivisect to allow vstruct # to be free from dependencies MAX_WORD = 16 def initmask(bits): return (1<<bits)-1 bitmasks = [ initmask(i) for i in range(MAX_WORD*8) ] def bitmask(value,bits): return value & bitmasks...
ch can dynamically change the size of a primitive.
''' self._vs_size = size def _prim_setval(self, newval): valu = self._prim_norm(newval) self._vs_value = valu # if requested, write changes back to bytearray / fd if self._vs_writeback: byts = self._prim_emit(valu) if self._vs_backbytes != None: ...
import pytest
import tensorflow as tf import numpy as np import tfs.core.layer.ops as ops from tfs.core.layer.dropout import Dropout from tfs.network import Network net = Network() @pytest.fixture def l(): l = Dropout( net, keep_prob=1.0, ) return l class TestDropout: def test_build_inverse(self,l): _in = tf.z...
# coding = utf-8 __author__ = 'Forec' import xlwt import re book = xlwt.Workbook(encoding = 'utf-8', style_compression=0) sheet = book.add_sheet('student',cell_overwrite_o
k = True) line = 0 info = re.compile(r'\"(\d+)\"
: \"(.*?)\"') with open('city.txt',"r") as f: data = f.read() for x in info.findall(data): for i in range(len(x)): sheet.write(line,i,x[i]) line+=1 book.save('city.xls')
# Copyright (C) 2014 Optiv, Inc. (brad.spe
ngler@optiv.com) # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. from lib.cuckoo.common.abstracts import Signature class InjectionRWX(Signature): name = "injection_rwx" description = "Creates RWX memory" severity = 2 confidence...
) filter_apinames = set(["NtAllocateVirtualMemory","NtProtectVirtualMemory","VirtualProtectEx"]) filter_analysistypes = set(["file"]) def on_call(self, call, process): if call["api"] == "NtAllocateVirtualMemory" or call["api"] == "VirtualProtectEx": protection = self.get_argument(call,...
# -*- mode: python; coding: utf-8; -*- import os APP_NAME = "SLog" VERSION = "0.9.4" WEBSITE = "http://vialinx.org" LICENSE = """ SLog is a PyGTK-based GUI for the LightLang SL dictionary. Copyright 2007 Nasyrov Renat <renatn@gmail.com> This file is part of SLog. SLog is free software; you can redistribute it and/...
os.path.join(INSTALL_PREFIX, "s
hare", "pixmaps") LOCALE_DIR = os.path.join(INSTALL_PREFIX, "share", "locale") DATA_DIR = os.path.join(INSTALL_PREFIX, "share", "slog") LOGO_ICON = "slog.png" LOGO_ICON_SPY = "slog_spy.png" #FTP_LL_URL = "ftp://ftp.lightlang.org.ru/dicts" FTP_LL_URL = "ftp://etc.edu.ru/pub/soft/for_linux/lightlang" FTP_DICTS_URL = ...
var='<project>', help='Default project (name or ID)', ) common.add_project_domain_option_to_parser(parser) parser.add_argument( '--password', metavar='<password>', help='Set user password', ) parser.add_argument( '--pass...
elp='Enable user (default)', ) enable_group.add_argument( '--disable', action='store_true',
help='Disable user', ) parser.add_argument( '--or-show', action='store_true', help=_('Return existing user'), ) return parser def take_action(self, parsed_args): identity_client = self.app.client_manager.identity proje...
from temboo.Library.Zendesk.Search.SearchA
ll import SearchAll, SearchAllInputSet
, SearchAllResultSet, SearchAllChoreographyExecution from temboo.Library.Zendesk.Search.SearchAnonymous import SearchAnonymous, SearchAnonymousInputSet, SearchAnonymousResultSet, SearchAnonymousChoreographyExecution
import random ## Course texture colors ## ########################### class Course(object): def __init__(self, num): ## Default colors, fall back to these fog = [0,0,0] light_road = [0,0,0] dark_road = [0,0,0] light_offroad = [0,0,0] dark_offroad = [0,0,0] li...
p[1]),int(temp[2])] elif line.startswith("dark_wall = "): ## Dark wall strip temp = line.strip("dark_wall = ").split(",")
dark_wall = [int(temp[0]),int(temp[1]),int(temp[2])] elif line.startswith("light_rumble = "): ## Light rumble strip temp = line.strip("light_rumble = ").split(",") light_rumble = [int(temp[0]),int(temp[1]),int(temp[2])] elif line.startswith("dark_rumble...
""" End to end test of the internal reporting user table loading task. """ import os import logging import datetime import pandas from luigi.date_interval import Date from edx.analytics.tasks.tests.acceptance import AcceptanceTestCase from edx.analytics.tasks.url import url_path_join log = logging.getLogger(__nam...
_code']) try: # A ValueError will be thrown if the column names don't match or the two data frames are not square. self.assertTrue(all(d_user == expected)) except ValueError:
self.fail("Expected and returned data frames have different shapes or labels.")
# -*- coding: utf-8 -*- # ERPNext - web based ERP (http://erpnext.com) # Copyright (C) 2012 Web Notes Technologies Pvt 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 3 of ...
License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # default settings that can be made for a user. from __future__ import unicode_literals import frappe # product_name = "ERPNext" product_name = "let
zERP" user_defaults = { "Company": "company", "Territory": "territory" }
__author__ = 'Sulantha' import logging class PipelineLogger: logFunctions={'info':logging.info, 'debug':logging.debug, 'warning':logging.warning, 'error':logging.error, 'critical':logging.critical, 'exception':logging.exception} ...
e)
notator import model from rpython.rtyper.llannotation import SomePtr from rpython.annotator.signature import SignatureError from rpython.translator.translator import TranslationContext, graphof from rpython.rtyper.lltypesystem import rstr from rpython.rtyper.annlowlevel import LowLevelAnnotatorPolicy def annotate_at(...
pass def g(): D1().f(D2()) a = annotate_at(g) argtype = sigof(a, C.__dict__['f'])[0] assert isinstance(argtype, model.SomeInstance) assert argtype.classdef.classdesc.pyobj == C def test_self_error(): class C(object): @signature(types.self(), returns=t
ypes.none()) def incomplete_sig_meth(self): pass exc = py.test.raises(SignatureError, annotate_at, C.incomplete_sig_meth).value assert 'incomplete_sig_meth' in str(exc) assert 'finishsigs' in str(exc) def test_any_as_argument(): @signature(types.any(), types.int(), returns=types.fl...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # sin título.py # # Copyright 2012 Jesús Hómez <jesus@soneview> # # 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. # # This program is distributed in the hope that it will be us...
ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License 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 #...
"""Command line tool for creating audioMD metadata.""" from __future__ import unicode_literals, print_function import os import sys import click import six import audiomd from siptools.mdcreator import MetsSectionCreator from siptools.utils import fix_missing_metadata, scrape_file click.disable_unicode_literals_war...
adata audiomd_dict = create_audiomd_metadata( filepath, filerel, self.workspace ) if '0' in audiomd_dict and len(audiomd_dict) == 1: self.add_md(metadata=audiomd_dict['0'], filename=(filerel if filerel else filepath)) else: for...
md_dict): self.add_md(metadata=audio, filename=(filerel if filerel else filepath), stream=index) # pylint: disable=too-many-arguments def write(self, mdtype="OTHER", mdtypeversion="2.0", othermdtype="AudioMD", section=None, s...
deDocs=True): def streamResult(resp): CHUNK_SIZE=1024 data = resp.read(CHUNK_SIZE) while len(data) > 0: yield data data = resp.read(CHUNK_SIZE) try:
resp = self._getView(urlBase,startKey=startKey,endKey=endKey,includeDocs=includeDocs) return streamResult(resp) except HTTPError as ex: abort(404, "not found") def _orderParmaByView(self,params,view): def makeEndKey(key): from copy import deepcopy n...
in key last = newkey[-1] # if the last element is a list, just append an empty object to the last element's list if isinstance(last, list): last.append({}) # if the last element in an object, it becomes a bit tricky # *...
# -*- coding: utf-8 -*- __all__ = ("clear_tags", "get_tex
t_from_html", "clear_text") def clear_tags(obj): """ Remove not used blocks, such as table of contents, advertisements """ SEARCH_TAG = ["div", "table"] for i in SEARCH_TAG: res= obj.soup(i) for row in res: if row["align"]=="right":
row.clear() res= obj.soup("title") if len(res): res[0].clear() def join_rows(obj): """ Join formatted rows into paragraphs. Need check splitted words. Skipped in this solution """ pass def get_text_from_html(obj): """ Return text without html tags ...
distinct groups for the given query grouped by the fields in group_by. """ sql, params = self._get_num_groups_sql(query, group_by) cursor = readonly_connection.connection().cursor() cursor.execute(sql, params) return self._cursor_rowcount(cursor) class Machine(dbmodels....
db_table = 'tko_machines' class Kernel(dbmodels.Model): ''' The Linux Kernel used during a test ''' #: A numeric and automatic integer that uniquely identifies a given #: machine. This is the primary key for the resulting table created #: from this model. kernel_idx = dbmodels.AutoField(p...
kernel hash kernel_hash = dbmodels.CharField(max_length=105, editable=False) #: base base = dbmodels.CharField(max_length=90) #: printable printable = dbmodels.CharField(max_length=300) class Meta: db_table = 'tko_kernels' class Patch(dbmodels.Model): ''' A Patch applied to a ...
# -*- coding: utf-8 -*- #------------------------------------------------------------ # tvalacarta - XBMC Plugin # Canal para ecuador tv # http://blog.tvalacarta.info/plugin-xbmc/tvalacarta/ #------------------------------------------------------------ import os import sys import urlparse,re import urllib import datet...
= True YOUTUBE_CHANNEL_ID = "RTVEcuador" def isGeneric(): return True def mainlist(item):
logger.info("tvalacarta.channels.ecuadortv mainlist") return youtube_channel.playlists(item,YOUTUBE_CHANNEL_ID)
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging, os logging.basicConfig(level=logging.INFO) from deepy.networks import RecursiveAutoEncoder from deepy.trainers import SGD
Trainer, LearningRateAnnealer from util import get_data, VECTOR_SIZE model_path = os.path.join(os.path.dirname(__file__), "models", "rae1.gz") if __name__ == '__main__': model = RecursiveAutoEncoder(input_dim=V
ECTOR_SIZE, rep_dim=10) trainer = SGDTrainer(model) annealer = LearningRateAnnealer() trainer.run(get_data(), epoch_controllers=[annealer]) model.save_params(model_path)
def migrate(cr, version): if not version: return # Replace
ids of better_zip by ids of city_zip cr.execute(""" ALTER TABLE crm_event_compassion DROP CONSTRAINT crm_event_compassion_zip_id_fkey; UPDATE crm_event_compassion e SET zip_id = ( SELE
CT id FROM res_city_zip WHERE openupgrade_legacy_12_0_better_zip_id = e.zip_id) """)
# Copyright 2017 Huawei Technologies Co.,LTD. # 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 # # Unl...
: super(TestFPGAProgramController, self).setUp() self.headers = self.gen_headers(self.context) self.deployable_uuids = ['0acbf8d6-e02a-4394-aae3-57557d209498'] @mock.patch('cyborg.objects.Deployable.get') @mock.patch('cyborg.agent.rpcapi.AgentAPI.program_fpga_with_bits
tream') def test_program(self, mock_program, mock_get_dep): self.headers['X-Roles'] = 'admin' self.headers['Content-Type'] = 'application/json' dep_uuid = self.deployable_uuids[0] fake_dep = fake_deployable.fake_deployable_obj(self.context, ...
''' Created on Oct 11, 2014 @author: mshepher ''' from globals import Globals class Order(object): EIGENAAR = 0 DIER = 1 GESLACHT = 2 GECASTREERD = 3 AKTIEF = 4 OVERGANGS = 5 GEWICHT = 6 #numerical PAKKETKG = 7 #float SOORT = 8 PUP = 9 RAS = 10 def __init__(self,orde...
None self.portie = 'beide' def get_prefers(self): return self.prefers
def set_prefers(self, value): self.prefers = value def get_base(self): return ','.join(self.base) def is_allergic(self,stuff): '''true if animal is allergic to stuff''' return stuff in self.donts def get_donts(self): return self.donts def set_donts...
from djang
o.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField() user = m
odels.ForeignKey(User)
import csv from util.helper import * import util.plo
t_defaults from matplotlib.ticker import MaxNLocator from pylab import figure parser = argparse.ArgumentParser() parser.add_argument('--file', '-f', help="data file direct
ory", required=True, action="store", dest="file") parser.add_argument('-o', help="Output directory", required=True, action="store", dest="dir") args = parser.parse_args() to_plot...
# 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. # # This program is distributed in the hope that it will be useful, # bu...
None(device) def test_get_first_unused_and_safely_removable_not_first(self): not_safe = OUT_OK.copy() not_safe[7] = not_safe[7].replace("11122122", "01021112") virttest.utils_zc
hannels.cmd_status_output = mock.Mock(return_value=(0, "\n".join(not_safe))) subchannel_paths = SubchannelPaths() subchannel_paths.get_info() device = subchannel_paths.get_first_unused_and_safely_removable() self.assertIsNotN...
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) import os from pant...
a, pants_run.stdout_data)) expected_files = ('.classpath', '.project',) workdir = os.path.join(path, project_name) self.assertTrue(os.path.exists(workdir), 'Failed to find project_dir at {dir}.'.format(dir=workdir)) self.assertTrue(a...
with open(os.path.join(workdir, '.classpath')) as classpath_f: classpath = classpath_f.read() # should be at least one input; if not we may have the wrong target path self.assertIn('<classpathentry kind="src"', classpath) return classpath # Test Eclipse generation on example targets; idea...
#!/usr/bin/env python # coding=utf-8 from __future__ import division, print_function, unicode_literals import re import unicodedata h1_start = re.compile(r"^\s*=(?P<title>[^=]+)=*[ \t]*") valid_title = re.compile(r"[^=]+") general_heading = re.compile(r"^\s*(={2,6}(?P<title>" + valid_title.pattern + ...
.compile(r"[^\w\-_\s]+") def strip_accents(s): return ''.join( (c for c in unicodedata.normalize('NFD', s) if unicodedata.category( c) != 'Mn')) REPLACEMENTS = { ord('ä'): 'ae', ord('ö'): 'oe', ord('ü'): 'ue', ord('ß'): 'ss', ord('Ä'): 'Ae', ord('Ö'): 'Oe', ord('Ü...
_unallowed_chars(s): s = invalid_symbols.sub('', s) return s def remove_and_compress_whitespaces(s): return '_'.join(s.split()).strip('_') def turn_into_valid_short_title(title, short_title_set=(), max_length=20): st = substitute_umlauts(title) st = strip_accents(st) st = remove_unallowed_ch...
# Copyright 2010 Google Inc. # # 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 ...
value > 0'); self._compressed_pixel_data_container = self.Member(GIF_BLOCK, 'pixel_data'); self._pixel_data_container = \ self._compressed_pixel_data_container.ContainMember( \ LZW_compressed_data, 'pixel_data', \ self._lzw_minimum_code_size.value); self._pixel_data = se...
STRING, 'pixel_data', \ self._descriptor._Width.value * self._descriptor._Height.value);
import psycopg2 from db.enums import * base = psycopg2.connect("dbname='cardkeepersample' user='andrew' host='localhost' password='1234'") cursor = base.cursor() # Wrapped queries in alphabetic order def active_packs(user_id, start=0, count=10): query = """SELECT packs.pack_id, packs.name FROM user_packs, packs...
r_id)) return cursor.fetchall() def update_card_data(user_id, card_id, answer): query = """UPDATE user_cards SET times_reviewed = times_reviewed+1, correct_answers = correct_answers+%s WHERE user_id = %s AND card_id = %s""" cursor.execute(query, (answer, user_id, card_id)) base.commit...
user_id, card_id, status): query = """UPDATE user_cards SET status = %s WHERE user_id = %s AND card_id = %s""" cursor.execute(query, (status, user_id, card_id)) base.commit() def update_pack_name(pack_id, new_name): query = 'UPDATE packs SET name = %s WHERE pack_id = %s;' cursor.ex...
'max_length': '100'}), 'packagesum': ('django.db.models.fields.CharField', [], {'max_length': '40', 'null': 'True', 'blank': 'True'}), 'public': ('django.db.models.fields.CharField', [], {'default': "'no'", 'max_length': '3'}) }, 'deploy.packagecondition': { 'Meta': {...
ed.ForeignKey', [], {'blank': 'True', 'related_name': "'child'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': "orm['inventory.entity']"}), 'timeprofile': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['deploy.timeprofile']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': '...
: ('django.db.models.fields.CharField', [], {'default': "'undefined'", 'max_length': '100', 'null': 'True', 'blank': 'True'}), 'entity': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['inventory.entity']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'id': (...
from django.contrib import admin from .models import BackgroundImages, Widget class WidgetAdmin(admin.ModelAdmin): list_display = (
'name', 'link', 'is_featured') ordering = ('-id',) class BackgroundAdmin(admin.ModelAdmin): list_display = ('name', 'created_at') ordering = ('-id',) admin.site.register(Widget, WidgetAd
min) admin.site.register(BackgroundImages, BackgroundAdmin)
# Copyright (c) 2017. Mount Sinai School of Medicine # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file exce
pt 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 # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, eith...
ermissions and # limitations under the License. """ Commandline arguments related to error handling """ from __future__ import print_function, division, absolute_import def add_error_args(arg_parser): error_group = arg_parser.add_argument_group( title="Errors", description="Options for error hand...