prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
import io import sys isPython3 = sys.version_info >= (3, 0) class Scribe: @staticmethod def read(path): with io.open(path, mode="rt", encoding="utf-8") as f: s = f.read() # go to beginning f.seek(0) return s @staticmethod de...
.open(path, mode="wt") as f: for line in lines: f.writelines(line.decode("utf8") + "\n") @staticmethod def
add_content(contents, path): if isPython3: with open(path, mode="a", encoding="utf-8") as f: f.writelines(contents) else: with io.open(path, mode="a") as f: f.writelines(contents.decode("utf8"))
rk=s.place_marker((472.692, 2503.57, 3680.28), (0.7, 0.7, 0.7), 167.804) if "particle_290 geometry" not in marker_sets: s=new_marker_set('particle_290 geometry') marker_sets["particle_290 geometry"]=s s= marker_sets["particle_290 geometry"] mark=s.place_marker((253.138, 2140.3, 4397.22), (0.7, 0.7, 0.7), 136.84) if...
sets["particle_301 geometry"] mark=s.place_marker((871.399, 3675.98, 3142.5), (0.7, 0.7, 0.7), 180.832) if "particle_3
02 geometry" not in marker_sets: s=new_marker_set('particle_302 geometry') marker_sets["particle_302 geometry"]=s s= marker_sets["particle_302 geometry"] mark=s.place_marker((1108.59, 3847.04, 3392.29), (0.7, 0.7, 0.7), 122.332) if "particle_303 geometry" not in marker_sets: s=new_marker_set('particle_303 geometr...
import os #os.system('git checkout develop') #os.system('git pull
origin develop') ret = os.system('python -u tools/jenkins-scripts/job-comment-
trigger.py') if ret == 0: exit(0) else: exit(1)
""" Tests course_creators.admin.py. """ from django.test import TestCase from django.contrib.auth.models import User from django.contrib.admin.sites import AdminSite from django.http import HttpRequest import mock from course_creators.admin import CourseCreatorAdmin from course_creators.models import CourseCreator fr...
creator group maintained in authz.py. """ def change_state(state, is_creator): """ Helper method for changing state """ self.table_entry.state = state self.creator_admin.save_model(self.requ
est, self.table_entry, None, True) self.assertEqual(is_creator, is_user_in_creator_group(self.user)) with mock.patch.dict('django.conf.settings.MITX_FEATURES', {"ENABLE_CREATOR_GROUP": True}): # User is initially unrequested. self.assertFalse(is_user_in_creator_group(self.us...
#!/usr/bin/env python from setuptools import setup setup(name='pgv', version='0.0.2', description="PostgreSQL schema versioning tool", long_description=open("README.rst").read(), author='Kirill Goldshtein', author_email='goldshtein.kirill@gmail.com', packages=['pgv', 'pgv.utils', '...
ests', scripts=['bin/pgv'], license='GPLv2', url='https://github.com/go1dshtein/pgv', classifiers=['Intended Audience :: Developers', 'Environme
nt :: Console', 'Programming Language :: Python :: 2.7', 'Natural Language :: English', 'Development Status :: 1 - Planning', 'Operating System :: Unix', 'Topic :: Utilities'])
# Create your views here. from django.shortcuts import render, redirect from django.views import generic f
rom Financers.models import Financers import re import random def financer_detail(request, name):
template_name = 'financer_detail.html' financer = '' if name != "Unknown": name = name.replace(',', '') financer = Financers().getFinancersContributions(name) profile = {} print financer profile['name'] = name context = {'profile': profile} return render(request, template_name, context) def finaner_cont...
#!/usr/bin/env python import importlib import inspect from django.core.management.base import BaseCommand from django.conf import settings from colab.plugins.utils.proxy_data_api import ProxyDataAPI class Command(BaseCommand): help = "Import proxy data into colab database" def handle(self, *args, **kwargs...
split('.')[-1]) module = importlib.import_module(module_path) for module_item_name in dir(module): module_item = getattr(module, module_item_name)
if not inspect.isclass(module_item): continue if issubclass(module_item, ProxyDataAPI): if module_item != ProxyDataAPI: api = module_item() api.fetch_data() break
from django.shortcuts import render from core.views import get_add_model_form from livestock.models import EggCollection, AnimalReport from livestock.forms import Eg
gCollectionForm, AnimalReportForm ADD_LIVESTOCK_TEMPLATE = 'livestock/add_livestock_model.html' def add_egg_collection(request): return get_add_model_form(request, ADD_LIVESTOCK_TEMPLATE,
EggCollection, 'Eggs', 'datetime', EggCollectionForm) def add_animal_report(request): return get_add_model_form(request, ADD_LIVESTOCK_TEMPLATE, AnimalReport, 'Animal Report', 'datetime', AnimalReportForm)
hould match the ones in Django. # You can see the list supported by Django at: # https://github.com/django/django/blob/master/django/conf/global_settings.py LANGUAGES = ( ("en", _("English")), ("fr", _("French")), ("de", _("German")), ("he", _("Hebrew")), ("hr", _("Croatian")), ("it", _("Ital...
database, using the SQL_ROLE configured above. "freppledb.reportmanager", "freppledb.execu
tesql", ) # Custom attribute fields in the database # After each change of this setting, the following commands MUST be # executed to create the fields in the database(s). # frepplectl makemigrations # frepplectl migrate OR frepplectl migrate --database DATABASE # # The commands will create migration files...
# 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 os from pant...
JarDependency(org='com.martiansoftware', name='nailgun-server',
rev='0.9.1'), ]) @classmethod def subsystem_dependencies(cls): return super(NailgunTaskBase, cls).subsystem_dependencies() + (Subprocess.Factory,) def __init__(self, *args, **kwargs): """ :API: public """ super(NailgunTaskBase, self).__init__(*args, **kwa...
#! /usr/bin/env python3 # encod
ing: utf-8 ''' http://projecteuler.net/problem=1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we
get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' # Since May 22 2012 from projecteuler import calctime n, a, b = 100000, 3, 5 # v1 def v1(): summ = 0 for i in range(n): if i%a == 0 or i%b == 0: summ += i return summ # v...
#!/usr/bin/env pyth
on # This script will tweet the text that is passed as an argument # Requires Twython, API credentials set as env vars # Usage: python status-tweet.py "Hello Everyone, this is my Raspberry Pi tweeting you more nonsense" import sys import os from twython import Twython import twitter_api_creds # Set Twitter Credentia...
") ACCESS_SECRET = os.getenv("ACCESS_SECRET") api = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET) # Tweet api.update_status(status=sys.argv[1][:140])
from django.db import models from django.utils import timezone class Post(models.Model): author = models
.ForeignKey('auth.User') title = models.CharField(max_length=200) t
ext = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title
EOPL T . T . 2 3 1 T . . T 3 3 EOPL T . . . 2 3 1 . T T T Rand Rand Rand [3] . T T . Rand Rand Rand [3] ...
).get() if (playback_state == PlaybackState.PLAYING): context.core.playback.pause().get() elif (playback_state == PlaybackState.PAUSED): context.core.playback.resume().get() elif state: context.core.playback.pause().get
() else: context.core.playback.resume().get() @protocol.commands.add('play', songpos=protocol.INT) def play(context, songpos=None): """ *musicpd.org, playback section:* ``play [SONGPOS]`` Begins playing the playlist at song number ``SONGPOS``. The original MPD server resumes...
#!/usr/bin/python # Copyright 2011, Thomas G. Dimiduk # # This file is part of GroupEng. # # Holopy 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 v
ersion 3 of the License, or # (at your option) any later version. # # Holopy 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 License for more details. # # You should h...
# Copyright (c) 2019 PaddlePaddle 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 appli...
def try_except_exit(): exception = None try: test_process = multiprocessing.Process(target=__test_process__) test_process.start() set_child_sig
nal_handler(id(self), test_process.pid) time.sleep(5) except SystemError as ex: self.assertIn("Fatal", cpt.get_exception_message(ex)) exception = ex return exception try_time = 10 exception = None for i in range(try_time): ...
# Rock-paper-scissors-lizard-Spock import random # helper functions def name_to_number(name): if name == "rock": name = 0 elif name == "Spock": name = 1 elif name == "paper": name = 2 elif name == "lizard": name = 3 elif name == "scissors": name = 4
else: print "No correct name given:" return name def number_to_name(number): if number == 0: number = "rock" elif number == 1: number = "Spock" elif number == 2: number = "paper" elif number == 3: number = "lizard" elif number == 4: ...
ber = "scissors" else: print "No correct number given:" return number def rpsls(player_choice): # print a blank line to separate consecutive games print # print out the message for the player's choice print "Player chooses", player_choice # convert the player's choice to player_nu...
from stripogram import html2text, html2safehtml # permet de conserver quelques tags html def HTML2SafeHTML( text, convert_br=True ): text = html2safehtml( text, valid_tags=('b', 'a', 'i', 'br', 'p')) if convert_br:
return newline_to_br(text) else: return text
def newline_to_br( text ): return text.replace( '\n', '<br/>' )
from kkross.exceptions import ModuleError, LoaderError from kkross.module import Module from glob import glob from yaml import safe_load import os def module_loader(module_dirs): '''Loads module YAML from ...''' module_paths = [] for module_dir in module_dirs: module_paths.extend(glob(os.path.jo...
'Failed to load module YAML data from "%s": "%s"' % (module_path, error_msg)) try: modules.append(Module(module_raw)) except Exception as error_msg: raise raise LoaderError('Failed
to load module from "%s": %s' % (module_path, error_msg)) return modules
# -*- coding: utf-8 -*- import asyncio from aiohttp import wsgi from irc3 import plugin import json @plugin class Webapp: requires = ['irc3.plugins.userli
st'] def __init__(self, bot): def server(): return wsgi.WSGIServerHttpProtocol(self.wsgi) self.bot = bot loop = asyncio.get_event_loop() self.bot.log.info('Starting webapp') asyncio.Task(loop.create_server( server, '127.0.0.1', 50
00)) def wsgi(self, environ, start_response): start_response('200 OK', [('Content-Type', 'application/json')]) plugin = self.bot.get_plugin('userlist') data = json.dumps(list(plugin.channels.keys())) return [data.encode('utf8')]
"""scons.Node.Python Python nodes. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without...
are the concatenation of all the contents of its sources. As the value need not be built when get_contents() is called, we cannot use the actual node.built_value."""
###TODO: something reasonable about universal newlines contents = str(self.value) for kid in self.children(None): contents = contents + kid.get_contents() return contents get_contents = get_text_contents ###TODO should return 'bytes' value def changed_since_last_b...
#!/usr/bin/env python #-*- coding:utf-8 -*- import os BASH_ATTRIBUTES = {"regular": "0", "bold": "1", "underline": "4", "strike": "9", "light": "1", "dark": "2", "invert": "7"} # invert bg and fg BASH_COLORS = {"black": "30", "red": "31", "green": "32", "yel...
BASH_BGCOLORS: ret += ";" + BASH_BGCOLORS[bgcolor] else: raise ValueError("Unknown background color: " + bgcolor) return ret + "m" def
is_bash(): return os.environ.get("SHELL", "unknown").endswith("bash") def _keys_sorted_by_values(adict): """Return list of the keys of @adict sorted by values.""" return sorted(adict, key=adict.get) if __name__ == "__main__": _main()
# test basic complex number functionality # constructor print(complex(1)) print(complex(1.2)) print(complex(1.2j)) print(complex("1")) print(complex("1.2")) print(complex("1.2j")) print(complex(1, 2)) print(complex(1j, 2j)
) # unary ops print(bool(1j)) print(+(1j)) print(-(1 + 2j)) # binary ops print(1j + False) print(1j + True) print(1j + 2) pr
int(1j + 2j) print(1j - 2) print(1j - 2j) print(1j * 2) print(1j * 2j) print(1j / 2) print((1j / 2j).real) print(1j / (1 + 2j)) ans = 0j ** 0; print("%.5g %.5g" % (ans.real, ans.imag)) ans = 0j ** 1; print("%.5g %.5g" % (ans.real, ans.imag)) ans = 0j ** 0j; print("%.5g %.5g" % (ans.real, ans.imag)) ans = 1j ** 2.5; pri...
# -*- coding: utf-8 -*- ################################################################################### # # Init.py # # Copyright
2015 Shai Seger <shaise at gmail dot com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General P
ublic 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, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PAR...
proximation.""" def __init__(self, L, F, K): super().__init__() self.L = graph.rescale_L(L, lmax=2) # Graph Laplacian, M x M self.F = F # Number of filters self.K = K # Polynomial order, i.e. filter size (number of hopes) def _inference(self, x, dropout): with tf.name_...
N, M = x.get_s
hape() # N: number of samples, M: number of features M = int(M) # Transform to Chebyshev basis xc = tf.transpose(x) # M x N def chebyshev(x): return graph.chebyshev(self.L, x, self.K) xc = tf.py_func(chebyshev, [xc], [tf.float32])[0] ...
# edit.py # buffer editing for both ST2 and ST3 that "just works" import inspect import sublime import sublime_plugin try: sublime.sublimexiki_edit_storage except AttributeError: sublime.sublimexiki_edit_storage = {} def run_callback(func, *args, **kwargs): spec = inspect.getfullargspec(func) if spec...
ace': view.replace, } func = funcs.get(self.cmd) if func: args = self.resolve_args(view, edit
) func(edit, *args) def resolve_args(self, view, edit): args = [] for arg in self.args: if isinstance(arg, EditFuture): arg = arg.resolve(view, edit) args.append(arg) return args class Edit: def __init__(self, view): self.vie...
from flask_wtf import FlaskForm from wtforms.fields import StringField, PasswordField, HiddenField, IntegerField, BooleanField from wtforms.validators import DataRequired from wtforms.widgets import HiddenInput class LoginForm(FlaskForm): username = StringField("username", validators=[DataRequired()]) passwor...
isit") can_edit = BooleanField("can_edit
") is_admin = BooleanField("is_admin")
from django.contrib import admin from moneymaker.models import Product from m
oneymaker.models import Income from moneymaker.models import Expense from moneymaker.models import ExpenseCategory from moneymaker.models import IncomeCategory class Exp
enseAdmin(admin.ModelAdmin): list_display = ('date', '__unicode__') admin.site.register(Product) admin.site.register(Income) admin.site.register(Expense, ExpenseAdmin) admin.site.register(ExpenseCategory) admin.site.register(IncomeCategory)
# -*- coding: utf-8 -*- # # Copyright © 2012-2013 Yury Konovalov <YKonovalov@gmail.com> # # This file is part of SSP. # # SSP 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, o...
nicate()[0] for r in re.finditer(r"(?m)^.*\s+dev\s+(?P<iface>[^\s]+).*$",s): ifaces.add(r.groupd
ict()['iface']) return ifaces except: LOG.error("Cannot run ping command.") raise def get_iface_by_route(ip): """Return the local interface name for specific IP address. None for indirectly routed addresses""" try: s = subprocess.Popen(["ip","r","g",ip], stderr=open('/dev/null', 'w'), stdout=subprocess.PIPE...
callback_classes = [ ['void', 'ns3::Ptr<ns3::Packet const>', 'double', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['...
igned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketT
ype', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::WifiMacHeader const&', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::Ptr<ns3::Packet>', 'ns3::Mac48Address', 'ns3::Mac48Address', 'ns3::empty', 'ns3::empty', 'ns3::em...
s, layers, chunks] ndim = shape.index(0) shape = shape[:ndim] # get [(slope, intercept), ...] scale factors for each axis scaling = [wave.GetScaling(ax) for ax in range(len(shape))] np.array(wave.GetNumericWaveData(typ)) * Access global variables: df = i.app.DataFolder("root") var = df.Variable(...
self._pollT
imer.start(100) def __call__(self, cmd, *args): # TODO: Handle optional values whenever they become supported in Igor messageID = self._getMessageID() future = concurrent.futures.Future() call = self.formatCall(cmd, params=args, messageID=messageID) try: self._so...
# -*- coding: utf-8 -*- """ Flaskr ~~~~~~ A microblog example application written as Flask tutorial with Flask and sqlite3. :copyright: (c) 2010 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from sqlite3 import dbapi2 as sqlite3 from flask import (Flask, request, session...
db = get_db() cur = db.execute('select title, text from entries order by id desc') entries = cur.fetchall() return render_template('show_entries.html', entries=entri
es) @app.route('/add', methods=['POST']) def add_entry(): if not session.get('logged_in'): abort(401) db = get_db() db.execute('insert into entries (title, text) values (?, ?)', [request.form['title'], request.form['text']]) db.commit() # 向下一次请求发送提示消息 flash('New entry wa...
#!/usr/bin/env python import sys import time import scapy.all as scapy SEQ_MAX = 2**32 - 1 previous_packets = set() def is_retransmission(packet): packet_key = "%d%d%d" % (packet[scapy.TCP].sport, packet[scapy.TCP].dport, packet[scapy.TCP].seq) i...
port - old_port #if diff < 0: # diff = 65535 - abs(diff) #print diff #old_port = packet[scapy.TCP].sport #for opt_name, opt_val in packet[scapy.TCP].options: # if opt_name == "Timestamp": #print packet.time, opt_val[0] if packet[scapy.IP]....
== "211.155.86.135": print "%s, %d, 1" % (t, packet[scapy.TCP].dport) else: print "%s, %d, 0" % (t, packet[scapy.TCP].dport) def main(): if len(sys.argv) != 2: print >> sys.stderr, "\nUsage: %s PCAP_FILE\n" % sys.argv[0] return 1 pcap_file = sys.argv[1] an...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Note: To use the 'upload' functionality of this file, you must: # $ pip install twine import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command # Package meta-data. NAME = 'plus_reader' DESCRIPTION = 'Recognition o...
Approved :: MIT License', 'Programming Language :: Python', # 'Programming Language :: Python :: 2.6', # 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', # 'Programming Language :: Python :: Implementation :: PyPy' ], # $ setup.py publish support. cmdclass={ 'publish': PublishCo...
Contents ='' #for t in parseObj.findAllPrevious(): # objContents = objContents+unicode(t) #find this in the original html last = objContents.find(unicode(parseObj)) done = False while not done: #chop the html in...
date if first == 0: done = True #If we've encoundered an issue, we no longer have a parsable object (doesn't matter why), so give up except: return mydate def NOTUSEDfindDate_mainMethod2(self, obj, ob...
t yield a date. This works fine if we don't care about the parse tree. I can't seem to be able to deep copy it, so any deletion on Copy A affects Copy B. Re-parsing for every content bit is too expensive. ''' chunkToParse =400 #size of the piece to send to the date parser ...
from
browser.models import Crop from django.contrib import admin admin.site.r
egister(Crop)
g: utf-8 -*- """Create one-mode (unipartite) projections from bipartite graphs. """ import networkx as nx # Copyright (C) 2011 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. __author__ = """Aric Hagberg (ha...
links=set(B[u]) & set(B[n]) for l in links: if not G.has_edge(u,n,l): G.add_edge(u,n,key=l) else: G.add_edges_from((u,n) for n
in nbrs2) return G def weighted_projected_graph(B, nodes, ratio=False): r"""Return a weighted unipartite projection of B onto the nodes of one bipartite node set. The weighted projected graph is the projection of the bipartite network B onto the specified nodes with weights representing the n...
#!/usr/bin/env python import sys import os import numpy as np import matplotlib.pyplot as plt from clawpack.pyclaw.solution import Solution import clawpack.visclaw.data as data rho = [1025.0,1045.0] eta_init = [0.0,-300.0] def plot_contour(data_dir="./_output",out_dir='./',num_layers=2,num_frames=1000,ref_lines=[-1...
= axes.contour(X,T,eta_plot, clines,colors='r') plot = axes.contour(X,T,eta_plot,-clines,colors='b') for ref_line in ref_lines: axes.plot([ref_line,ref_line],[0,2],'k:') # X ticks and labels axes.set_xticks([-300e3,-200e3,-100e3,-30e3]) a
xes.set_xticklabels([300,200,100,30],fontsize=15) axes.set_xlabel("Kilometers offshore",fontsize=15) axes.set_xlim([-200e3,0.0]) # First plot from left to right, write y ticks if layer == 0: plt.yticks(fontsize=15) axes.set_ylabel("Hours",fontsize=20) ...
import time from cloudbot import hook @hook.command(autohelp=False) def beats(text): """beats -- Gets the current time in .beats (Swatch Internet Time). """ if text.lower() == "wut": return "Instead of hours and minutes, the mean solar day is divided " \ "up into 1000 parts called \"....
tm_hour, t.tm_min, t.tm_sec utc = 3600 * h + 60 * m + s bmt = utc + 3600 # Biel Mean Time (BMT) beat = bmt / 86.4 if beat > 1000: beat -= 1000 return "Swatch Internet
Time: @%06.2f" % beat
# This file is part of OpenHatch. # Copyright (C) 2010 John Stumpo # # This program is free software: you can redistribu
te 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 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 imp...
received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from django.db import models import mysite.search.models class Step(models.Model): name = models.CharField(max_length=255, unique=True) class StepCompletion(mysite.search.models.Ope...
from ut_arena.settings import
*
import lean import lang.expr as expr # ========================================================= # Declaration Views class DeclView(lean.declaration): def __init__(self, decl): self.decl = decl def destruct(self): # type: DeclView -> (lean.name, ?, ?, lean.expr, lean.expr) return (s...
================ # Environment Views class EnvView(lean.environment): def __init__(self, env): # type: lean.environment -> None self.env = env def get_decls(self, f=None): # type: (lean.declaration -> bool) -> [lean.declaration] decls = [] self.env.for_each_declaration(...
, decls) return decls def get_theorems(self): # type: (lean.declaration -> bool) -> [lean.declaration] return self.get_decls(lambda decl: decl.is_theorem()) def thm_dict_of_decls(self, decls): # type: [lean.declaration] -> dict<lean.name, lean.expr> d_thm = {} ...
import struct
from . import crc16 class PacketWriter: MAX_PAYLOAD = 1584 MIN_LEN = 6 MAX_LEN = 1590 SOF = 0x01 OFFSET_SOF = 0 OFFSET_LENGTH = 1 OFFSET_CMD = 3 OFFSET_PAYLOAD = 4 def __init__(self): self._packet = None def Clear(self): self._packet = None def
NewSOF(self, v): self._packet[0] = chr(v) def PacketString(self): return "".join(self._packet) def AppendCrc(self): self.SetLength() ps = self.PacketString() crc = crc16.crc16(ps, 0, len(ps)) for x in struct.pack("H", crc): self._packet.append(x) ...
##Author - Sagar Vakkala (@codezoned) import numpy from PIL import Image def median_filter(data, filter_size): temp_arr = [] index = filter_size // 2 data_final = [] data_final = numpy.zeros((len(data), len(data[0]))) for i in range(len(data)): # Iterate over the Image Array for j...
c in range(filter_size): temp_arr.append(0) else: if j + z - index < 0 or j + index > len(data[0]) - 1: temp_arr.append(0) else: for k in range(filter_size): temp_...
emp_arr.sort() data_final[i][j] = temp_arr[len(temp_arr) // 2] temp_arr = [] return data_final def main(): ##Replace someImage with the noise image img = Image.open("someImage.png").convert("L") arr = numpy.array(img) ##3 defines the no of layers for the filter ##It a...
honpath = os.getenv( 'PYTHONPATH', '' ).split( ':' ) print 'Directories in PYTHONPATH:', pythonpath for p in pythonpath: if p == '': continue try: if os.path.normpath( p ) in sys.path: # In case a given directory is twice in PYTHONPATH it has to removed only once ...
self.out: with open( self.out, 'a' ) as outputFile: for _line in msg.split( "\n" ): if header: outLine = "%s UTC %s
[%s] %s" % ( time.strftime( '%Y-%m-%d %H:%M:%S', time.gmtime() ), level, self.name, _line ) print outLine if self.out: outputFile.write( outLin...
""" An utility module containing utility functions used by the grader module and some useful pre-test hooks. """ import json import traceback def import_module(path, name=None): if name is None: name = path import importlib.machinery loader = importlib.machinery.SourceFileLoader(name, path) ...
tr(value, '__call__') except: return False ## Function descriptions def beautifyDescription(description): """ Converts docstring of a function to a test description by removing excess whitespace and joining the answer on one line """ lin
es = (line.strip() for line in description.split('\n')) return " ".join(filter(lambda x: x, lines)) def setDescription(function, description): import grader old_description = grader.get_test_name(function) if old_description in grader.testcases: grader.testcases.remove(old_description) des...
#!/usr/bin/env python3 """ * Copyright (c) 2015 BEEVC - Electronic Systems This file is part of BEESOFT * 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...
, "FontType":"Bold", "FontSize":"12", "FontColor":"0,0,0" """ self.lblValXPos = int(float(self.lblValJson['X'])*self.displayWidth) lblValFontType = self.lblValJson['FontType'] lblValFontSize = int(float(self.lblValJson['FontSize...
= self.GetFont(lblValFontType,lblValFontSize) lblValFColor = self.lblValJson['FontColor'] splitColor = lblValFColor.split(",") self.lblValFontColor = pygame.Color(int(splitColor[0]),int(splitColor[1]),int(splitColor[2])) """ Load Labels Configuration """ ...
(c) c2 = docker_client.create_container(imageUuid=TEST_IMAGE_UUID, dataVolumes=['/bar']) docker_client.wait_success(c2) c3 = docker_client.create_container(imageUuid=TEST_IMAGE_UUID, dataVolumesFrom=[c.id, c2.id]) c3 = doc...
'driver': None, 'config': None
, }) c = docker_client.wait_success(c) assert c.state == 'running' assert c.pidMode is None assert c.logConfig == {'driver': None, 'config': None} c = super_client.reload(c) assert c.data.dockerInspect.HostConfig.LogConfig == {'Type': 'json-file', ...
element of PATH env['PATH'] = env['PATH'].split(os.pathsep, 1)[-1] del env['VIRTUAL_ENV'] # Make sure that we use the programs in the # current source directory's bin/ directory. path_ext = [os.path.join(os.getcwd(), 'bin')] # Also jack in the path cmd comes from, if it's absolute ...
tent-length': len(data)} def getheader(self, name, default=None):
return self.headers.get(name.lower(), default) def getheaders(self): return self.headers or {} def read(self, amt): self.data.read(amt) class Httplib2WsgiAdapter(object): def __init__(self, app): self.app = app def request(self, uri, method="GET", body=None, headers=None): ...
im
port s
ys from CTFd import create_app app = create_app() app.run(debug=True, host="0.0.0.0", port=int(sys.argv[1]))
#!/usr/bin/env python3 # Copyright 2017 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...
r.parse_args() with ImageInference(dish_classification.model()) as inference: image = Image.open(args.input) classes = dish_classification.get_classes( inference.run(image), top_k=5, threshold=0.1) for i, (label, score) in enumerate(classes): print('Result %d: %s (pr...
b=%f)' % (i, label, score)) if __name__ == '__main__': main()
from urllib import urlencode from urllib2 import urlopen from django.shortcuts import render from django.http import HttpResponse, Http404 from cms.utils.html import clean_html def index(request): url = "http://results.influenzanet.info/results.php?" + ur
lencode(request.GET) try: content = urlopen(url, timeout=5).read
() except: content = "" #content = clean_html(content, full=False) return render(request, 'sander/sander.html' , locals())
pr
int(len({(input()) for _ in range(int(input()))}))
from __future__ import print_function #from cms.sitemaps import CMSSitemap from django.conf.urls import * # NOQA from django.conf.urls.i18n import i18n_patterns from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from django.conf import settings admin.autodiscover() u...
terns('', url(r'^admin/', include(admin.site.urls)), # NOQA url(r'^', include('cms.urls')), # url(r'^taggit_autosuggest/', include('taggit_autosuggest.urls')), ) # This is only needed when using runserver. if settings.DEBUG: urlpatterns = patterns('', url(r'^media/(?P<path>.*)$', 'django.views...
A {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), ) + staticfiles_urlpatterns() + urlpatterns # NOQA
# coding: utf-8 """ Nordigen Account Information Services API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 2.0 (v2) Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import nordigen from nordigen...
s TestTokenApi(unittest.TestCase): """TokenApi unit test stubs""" def setUp(self): self.api = TokenApi() # noqa: E501 def tearDown(self): pass def test_j_wt_obtain(self): """Test case for j_wt_obtain """ pass def test_j_wt_refresh(self): """Test ...
from reportlab.pdfgen import canvas as pdf_container from reportlab.lib.pagesizes import letter, A4 from reportlab.lib.units import inch '''Contains methods to split lengthy sections so that they are able to fit within the pdf. After splitting the sections, it appends the newly formed sections to the "to_pdf_hold...
self.start_height += 20 self.new_pdf.save() class SongSection: def __init__(self, name): self.section = [] se
lf.name = name
ices, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redist...
# neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SO
FTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT...
f
rom flask.blueprints import Blueprint import logging from flask_login import login_required, current_user from waitlist.ts3.connection import send_poke from flask import jsonify bp = Blueprint('api_ts3', __name__) logger = logging.getLogger(__name__) @bp.route("/test_poke") @login_required def test_poke(): send_p...
n resp
----------------- def build_menu_transabyss(): ''' Build the menu Trans-ABySS. ''' while True: # print headers clib.clear_screen() clib.print_headers_with_environment(xlib.get_transabyss_name()) # print the menu options print('Options:') print() ...
_gmap_gsnap_name())) print(' 3. {0}'.format(xlib.get_quast_name())) print(' 4. {0}'.format(xlib.get_rnaquast_name())) print(' 5. {0} ({1} package)'.format(xlib.get_rsem_eval_name(), xlib.get_detonate_name())) print(' 6. {0}'.format(xlib.get_transrate_name())) print() ...
u RNA-seq') print() # get the selected option option = input('Input the selected option: ').upper() # process the selected option if option == '1': build_menu_busco() elif option == '2': build_menu_gmap() elif option == '3': b...
''' New Test For cpu bill Operations 1.test vm stop 2.test vm destory 3.test vm live migration 4.test vm clean @author Antony WeiJiang ''' import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.test_util as test_util import zstackwoodpecker.operations.b...
destroy() bill_cpu.compare("destory") test_util.test_logger("recover vm instance") vm.recover() vm.start() bill_cpu.compare("recover") test_util.test_logger("get host total and primarystorge type") Host_uuid = test_stub.get_resource_from_vmm(res_ops.HOST,vm.get_vm().zoneUuid,vm.get_vm().hostUuid) PrimaryFlag ...
_util.test_logger("antony %s" %(PrimaryFlag)) if Host_uuid and PrimaryFlag == 0: test_util.test_logger("migration vm instance") prices = bill_cpu.get_price_total() vm.migrate(Host_uuid) prices1 = bill_cpu.get_price_total() if prices1.total > prices.total: bill_cpu.compare("migration") else: test_ut...
from flask import rend
er_template from . import auth @auth.route('/login') def login(): return
render_template('auth/login.html')
from nose.tools import assert_equal import urllib from base import * from bibserver import web, ingest import os class TestWeb(object): @classmethod def setup_class(cls): web.app.config['TESTING'] = True cls.app = web.app.test_client() # fixture data recdict = fixtures['records...
est Collection', data=bibtex_data, )
) assert res.status == '401 UNAUTHORIZED', res.status def test_query(self): res = self.app.get('/query') assert res.status == '200 OK', res.status res = self.app.get('/query?q=title:non-existent') assert res.status == '200 OK', res.status out = json.loads(res.dat...
#!/usr/bin/env python2 """ Quick helper to add HTML5 DOCTYPE and <title> to every testcase. """ import os import re import sys def fixhtml(folder): changed = 0 for dirpath, _, filenames in os.walk(folder): for file in filenames: name, ext = os.path.splitext(file) if ext != '.ht...
continue path = '%s/%s' % (dirpath, file) title = ' '.join(name.split('-')) shouldbe = '<!DOCTYPE html>\n<title>%s</title>\n' % title with open(path, 'r') as f: content = f.read() if content.startswith(shouldbe): ...
e>\s*', '', content) with open(path, 'w') as f: f.write(shouldbe + content) return changed if __name__ == '__main__': folder = '.' if len(sys.argv) < 2 else sys.argv[1] changed = fixhtml(folder) print('Fixed %d files.' % changed)
ka`` :math:`10^{1}` ``deci`` :math:`10^{-1}` ``centi`` :math:`10^{-2}` ``milli`` :math:`10^{-3}` ``micro`` :math:`10^{-6}` ``nano`` :math:`10^{-9}` ``pico`` :math:`10^{-12}` ``femto`` :math:`10^{-15}` ``atto`` :math:`10^{-18}` ``zepto`` :math:`10^{-21}` ============ =======...
ath:`2^{20}` ``gibi`` :math:`2^{30}` ``tebi`` :math:`2^{40}` ``pebi`` :math:`2^{50}` ``exbi`` :math:`2^{60}` ``zebi`` :math:`2^{70}` ``yobi`` :math:`2^{80}` ============ ==========================================
======================= Mass ---- ================= ============================================================ ``gram`` :math:`10^{-3}` kg ``metric_ton`` :math:`10^{3}` kg ``grain`` one grain in kg ``lb`` one pound (avoirdupous) in kg ``pound`` one pound (avoirdupous) in...
import zstackwoodpecker.test_state as ts_header import os TestAction = ts_header.TestAction def path(): return dict(initial_formation="template5", checking_point=1, faild_point=100000, path_list=[ [TestAction.create_mini_vm, 'vm1', 'cluster=cluster2'], [TestAction.create_volume, 'volume1', 'cluster=cluster2', ...
_volume, 'vm2', 'volume2'], [TestA
ction.detach_volume, 'volume2'], [TestAction.create_volume, 'volume3', 'cluster=cluster1', 'flag=thick,scsi'], [TestAction.add_image, 'image1', 'root', 'http://172.20.1.28/mirror/diskimages/centos_vdbench.qcow2'], [TestAction.create_vm_backup, 'vm1', 'vm1-backup2'], [TestAction.delete_vm_backup, 'vm1-backup2'],...
import os from setuptools import setup with open('asv_test_repo/build_time_env.py', 'w') as f: f.write("env = {{}}\n".format(repr(dict(os.environ)))) setup(name='asv_test_repo', version="{version}", packages=['asv_test_repo'], # The following forces setuptools to generate .egg-info directory, ...
# Copyright (c) 2015 Amazon.com, Inc. or its affiliates. # All Rights Reserved # # Permission is hereby granted, free of charge, to any 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...
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # from boto.regioninfo import RegionInfo, get_regions from boto.regioninfo import connect def regions(): """ Get all available regions for the AWS CloudHSM service. :rtype: list :return: A list of :class:`bot...
""" from boto.cloudhsm.layer1 import CloudHSMConnection return get_regions('cloudhsm', connection_cls=CloudHSMConnection) def connect_to_region(region_name, **kw_params): from boto.cloudhsm.layer1 import CloudHSMConnection return connect('cloudhsm', region_name, connection_cls=CloudHSMConnection, ...
import os import sys sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..')) from models import gru_simple from helpers import checkpoint # Get the review summary file review_summary_file = 'extracted_data/review_summary.csv' # Initialize Checkpointer to ensure checkpointing checkpointer = checkpoint...
_size=128, test_batch_size=
128, memory_dim=128, learning_rate=0.05) gru_net.begin_session() gru_net.form_model_graph() gru_net.fit() gru_net.predict() gru_net.store_test_predictions()
to-site peer %s \ authentication mode pre-shared-secret', 'set vpn ipsec site-to-site peer %s \ authentication pre-shared-secret %s', 'set vpn ipsec site-to-site peer %s default-esp-group %s', 'set vpn ipsec site-to-site peer %s ike-group %s', 'set vpn ipsec site-...
'], ike['lifetime']['value']) ike_cmds[6] = ike_cmds[6] % ike['name'] ike_cmds[7] = ike_cmds[7] % (ike['
name'], dpd['interval']) ike_cmds[8] = ike_cmds[8] % (ike['name'], dpd['timeout']) sel
from datetime import datetime from operator import itemgetter import tmdbsimple from babel.dates import format_date from django.conf import settings from .exceptions import MovieNotInDb from .models import get_poster_url def get_tmdb(lang=None): tmdbsimple.API_KEY = settings.TMDB_KEY tmdbsimple.LANGUAGE = l...
: f"movie{tmdb_id}",
"releaseDate": movie.get("release_date"), "title": movie["title"], "poster": get_poster_url("small", poster), "poster2x": get_poster_url("normal", poster), } movies.append(movie) if options["sortByDate"]: movies = sort_by_da...
TABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSIN...
se('jstest' in test_info.keys(), 'test should not be a jstest') def test_analyze_non_test_file_returns_none(self
): """Tests analyze_test() using a non-test file.""" parser = TestParser('/some/madeup/path/somefile.html', MockHost()) test_info = parser.analyze_test(test_contents='<html>') self.assertIsNone(test_info, 'test should have been skipped') def test_analyze_csswg_manual_test(self): ...
censing information. # # Enhancements in shlex to tokenize closer to the way real shells do # from collections import deque import shlex import sys # We need to behave differently on 2,x and 3,x, because on 2.x # shlex barfs on Unicode, and must be given str. if sys.version_info[0] < 3: PY3 = False text_type ...
elif (nextchar in self.wordchars or nextchar in self.quotes or self.whitespace_split): self.token
+= nextchar else: if self.control: self.pbchars.append(nextchar) else: self.pushback.appendleft(nextchar) if self.debug >= 2: # pragma: no cover print("shlex: I see punct
np.all(p2.beams == exp_beams) def test_onedspectrum_specaxis_units(): test_wcs = WCS(naxis=1) test_wcs.wcs.cunit = ["m/s"] test_wcs.wcs.ctype = ["VELO-LSR"] p = OneDSpectrum(twelve_qty_1d, wcs=test_wcs) assert p.spectral_axis.unit == u.Unit("m/s") def test_onedspectrum_with_spectral_unit(): ...
eam = Beam(2.0 * u.arcsec) p = LDO(data, copy=False, beam=exp_beam) new_p = p.with_beam(newbeam) assert p.beam == exp_beam assert p.meta['beam'] == exp_beam assert new_p.beam == newbeam as
sert new_p.meta['beam'] == newbeam @pytest.mark.xfail(raises=BeamUnitsError, strict=True) @pytest.mark.parametrize(('LDO', 'data'), zip(LDOs, data_twelve)) def test_ldo_attach_beam_jybm_error(LDO, data): exp_beam = Beam(1.0 * u.arcsec) newbeam = Beam(2.0 * u.arcsec) data = data...
current.futures import ThreadPoolExecutor from PIL import Image from ..utils import getLogger from .mediaconfig import * logger = getLogger('transcode.transcoder') class Transcoder: "Nice object-oriented style transcoder implementation" @classmethod async def create(cls, loop=None): tc = cls() ...
er yet, demux audio and use *sox*
for compression, normalization, then remux - GIF summary, see https://superuser.com/questions/556029/how-do-i-convert-a-video-to-gif-using-ffmpeg-with-reasonable-quality/556031#556031 and https://superuser.com/questions/538112/meaningful-thumbnails-for-a-video-using-ffmpeg :param input: Video file ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # The MIT License (MIT) # # Copyright (c) 2014 Josh Brandoff # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including wi...
he following conditions: # # The above copyright notice and this permission notice shall be included in # all copies
or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR AN...
from django.db import models from django.contrib.auth.models import User from datetime import date # Create your models here. class Genre(models.Model): """ Model representing a book genre (e.g. Science Fiction, Non Fiction). """ name = models.CharField(max_length=200, help_text="Enter a book genre (e...
s is required to display genre
in Admin. """ return ', '.join([ genre.name for genre in self.genre.all()[:3] ]) display_genre.short_description = 'Genre' import uuid # Required for unique book instances class BookInstance(models.Model): class Meta: permissions = (("can_mark_returned", "Set book as returned"),) ...
# -*- coding: utf-8 -*- from model.contact import Contact from random import randrange def test_modify_some_contact(app, db, check_ui): random_value = str(app.get_random_int()) if app.contact.count() == 0: app.contact.add(Contact(first_name="First Contact")) # old_contacts = app.contact.get_contac...
index = randrange(len(old_contacts)) contact = Contact(first_name="name" + random_value, middle_name="middleName" + random_value, last_name="lastName" + random_value, nick_name="nickName" + random_value, title="title" + rand...
mobile_phone="mobilePhone" + random_value, work_phone="workPhone" + random_value, fax_phone="faxPhone" + random_value, email_1="email1@company" + random_value + ".com", email_2="email2@company" + random_value + "....
# PyVision License # # Copyright (c) 2006-2010 David S. Bolme # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, thi...
os.path import pyvision as pv # Th
e ASEF eye locator has patent complications. This next line # disables those warnings. pv.disableCommercialUseWarnings() from pyvision.face.CascadeDetector import CascadeDetector from pyvision.face.FilterEyeLocator import FilterEyeLocator if __name__ == "__main__": ilog = pv.ImageLog() # Load the face image...
# Generated from java-escape by ANTLR 4.5 from antlr4 import * # This class defines a complete listener for a parse tree produced by ODLv21Parser. class ODLv21Listener(ParseTreeListener): # Enter a parse tree produced by ODLv21Parser#label. def enterLabel(self, ctx): pass # Exit a parse tree prod...
dentifier. def exitScalarIdenti
fier(self, ctx): pass # Enter a parse tree produced by ODLv21Parser#ScalarSymbol. def enterScalarSymbol(self, ctx): pass # Exit a parse tree produced by ODLv21Parser#ScalarSymbol. def exitScalarSymbol(self, ctx): pass # Enter a parse tree produced by ODLv21Parser#ScalarS...
import sys import os.path import lzma import time import os import subprocess if "APPVEYOR_REPO_TAG" not in os.environ or os.environ["APPVEYOR_R
EPO_TAG"] != "true": print("Not uploading symbols since build is not tagged") sys.exit() sy
mbol_filename = sys.argv[1] with open(symbol_filename, "rt") as fh: first_line = next(fh).strip() tokens = first_line.split() expected_tokens = ['MODULE', 'windows', 'x86'] if tokens[0:3] != expected_tokens: raise RuntimeError("Expected first tokens to be " + str(expected_tokens) + ", but was: " + str(tokens[...
channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel ...
Run the base constructor. super().__init__( host=host, credentials=credentials, client_info=client_info, ) @classmethod def create_channel( cls, host: str = "googleads.googleapis.com", credentials: ga_credentials.Crede
ntials = None, scopes: Optional[Sequence[str]] = None, **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. Args: address (Optionsl[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authoriza...
from collections import OrderedDict from django.core.cache import cache from django.conf import settings import jingo import jinja2 from bedrock.firefox.models import FirefoxOSFeedLink from bedrock.firefox.firefox_details import firefox_desktop, firefox_android from bedrock.base.urlresolvers import reverse from lib....
, force_funnelcake=force_funnelcake, funnelcake_id=funnelcake_id, ) if d
ownload_link_direct == download_link: download_link_direct = False builds.append({'os': plat_os, 'os_pretty': plat_os_pretty, 'download_link': download_link, 'download_link_direct': download_link_direct}) ...
polygamma(0, self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg.is_Intege...
return -1 * (-1/z)**N * r @classmethod def eval(cls, n, z): n, z = map(sympify, (n, z)) if n.is_integer: if n.is_negative: ret
urn loggamma(z) else: if z.is_Number: if z is S.NaN: return S.NaN elif z is S.Infinity: if n.is_Number: if n is S.Zero: return S.Infinity ...
# -*- coding: utf-8 -*- # Copyright © 2012 Zulip, Inc. # # Permission is hereby granted, free of charge, to any 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, ...
f the conf/trac.ini file, like so: # # [components] # zulip_trac = enabled # # You may then need to restart trac (or restart Apache) for the bot # (or changes to the bot) to actually be loaded by trac. from trac.core import Component, implements from trac.ticket import ITicketChangeListener import sys import os.path s...
ULIP_API_PATH is not None: sys.path.append(config.ZULIP_API_PATH) import zulip client = zulip.Client( email=config.ZULIP_USER, site=config.ZULIP_SITE, api_key=config.ZULIP_API_KEY, client="ZulipTrac/" + VERSION) def markdown_ticket_url(ticket, heading="ticket"): # type: (Any, str) -> str r...
# -*- coding:utf-8 -*- #!/usr/bin/env python3 """ """ from collections import namedtuple from minghu6.inter
net.proxy_ip import proxy_ip from minghu6.text.seq_enh import filter_invalid_char URL_LIST_FILE_PATH = 'URList-{username:s}.txt' UrlName
Tuple = namedtuple('UrlNameTuple', ['url', 'title'])
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt, getdate, formatdate, cstr from erpnext.accounts.report.financial_statements import filter_accou...
{ "fieldname": "currency", "label": _("Currency"), "fieldtype": "Link", "options": "Currency", "hidden": 1 } ] def set_gl_entries_by_account(company, from_date, to_date, based_on, gl_entries_by_account, ignore_closing_entrie
s=False): """Returns a dict like { "account": [gl entries], ... }""" additional_conditions = [] if ignore_closing_entries: additional_conditions.append("and ifnull(voucher_type, '')!='Period Closing Voucher'") if from_date: additional_conditions.append("and posting_date >= %(from_date)s") gl_entries = frapp...
# -*- coding: utf-8 -*- """ oauthlib.parameters ~~~~~~~~~~~~~~~~~~~ This module contains methods related to `section 3.5`_ of the OAuth 1.0a spec. .. _`section 3.5`: http://tools.ietf.org/html/rfc5849#section-3.5 """ from __future__ import absolute_import, unicode_literals try: from urlparse import urlparse, url...
body): """Prepare the Form-Encoded Body. Per `section 3.5.2`_ of the spec. .. _`section 3.
5.2`: http://tools.ietf.org/html/rfc5849#section-3.5.2 """ # append OAuth params to the existing body return _append_params(oauth_params, body) def prepare_request_uri_query(oauth_params, uri): """Prepare the Request URI Query. Per `section 3.5.3`_ of the spec. .. _`section 3.5.3`: http://t...
lon_lat = [self.geo_range['longitude__min'], self.geo_range['latitude__max']] clusts = {'centroids': [lon_lat], 'boxes': []} else: # need to cluster geo data clusts = self.cluster_geo(uuids) ...
dist = self.get_point_distance(min_lon, min_lat, max_lon, max_lat) blur = dist * .025 if (min_lon + blur >= ch_box['min_lon'] and min_lon - blur <= ch_box['max_lon'])\ or (max_lon + blur >= ch_box['min_lon'] and max_lon - blur <= ch_box['max_lon']): overlap_lon = True ...
] and max_lat - blur <= ch_box['max_lat']): overlap_lat = True if overlap_lon and overlap_lat: overlap = True return overlap def get_point_distance(self, x, y, xx, yy): """ calculates the distance btween two points """ sqrd = ((x - xx) * (x - xx)) + ((y - yy)...
from .
_main import m
ain main()
class Solution
(object): def addBinary(self, a, b): len_a = len(a) len_b = len(b) length = max(len_a, len_b) c = [0] *
(length + 1) if len_a < len_b: a, b = b, a len_a, len_b = len_b, len_a for i in range(0, length): if len_a - 1 - i >= 0 and len_b - 1 - i >= 0: num_a = int(a[len_a - 1 - i]) num_b = int(b[len_b - 1 - i]) c[i] += (num_a...
import sys from qtpy.QtCore import Qt from qtpy.QtWidgets import QSplashScreen, QApplication from qtpy.QtGui import QColor, QPen, QFont from ert_gui.ertwidgets import resourceImage class ErtSplash(QSplashScreen): def __init__(self, version_string="Version string"): QSplashScreen.__init__(self) ...
type painter: QPainter""" w = self.width() h = self.height() margin =
10 background = QColor(210, 211, 215) text_color = QColor(0, 0, 0) foreground = QColor(255, 255, 255) painter.setBrush(background) painter.fillRect(0, 0, w, h, background) pen = QPen() pen.setWidth(2) pen.setColor(foreground) painter.setPen(pe...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import logging from askomics.libaskomics.ParamManager import ParamManager from askomics.libaskomics.rdfdb.SparqlQueryBuilder import SparqlQueryBuilder from askomics.libaskomics.rdfdb.QueryLauncher import QueryLauncher class TripleStoreExplorer(ParamManager): """ ...
settings, session, dico={}): ParamManager.__
init__(self, settings, session) self.log = logging.getLogger(__name__) def get_start_points(self): """ Get the possible starting points for your graph. :return: List of starting points :rtype: Node list """ self.log.debug(" =========== TripleStoreExplorer:g...
im
port os from flask import Flask, url_for, send_from_directory, flash, get_flashed_messages, session, request, render_template, redirect from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from configure_database import Base, F5Device, AFMStat, StatValue engine = create_engine('sqlite:///F5AFM_...
app = Flask(__name__) app.secret_key = '13641ijkqrewf9dflkq359faan230fanoacv92r3noj2398cncq92njfqwfughq9f0823nbr9fjawh90q23rlkijqhwef98qroh' #Added Favicon Support @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico', mimetype='image/vnd.microsoft....
import hangups from hangupsbot.utils import text_to_segments from hangupsbot.handlers import handler @handler.register(priority=7, event=hangups.ChatMessageEvent) def handle_forward(bot, event): """Handle message forwarding""" # Test if message is not empty if not event.text: return # Test i...
repend forwarded message with name of sender link = 'https://plus.google.com/u/0/{}/about'.format(event.user_id.chat_id) segments = text_to_segments('**[{}]({}):** '.format(event.user.full_name, link)) # Copy original message segments segments.extend(event.conv_event.segments) ...
attachments) yield from conv.send_message(segments) # If there are attachments, send them separately for image_id in image_id_list: yield from conv.send_message([], image_id=image_id)
e shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # comi...
#html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finishe...
h = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Clangdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4pape...
2, 1): (0, 1), (8, 33, 2, 2): (0, 1), (8, 33, 2, 3): (0, 1), (8, 33, 2, 4): (0, 1), (8, 33, 2, 5): (0, 1), (8, 33, 3, -5): (0, 1), (8, 33, 3, -4): (0, 0), (8, 33, 3, -3): (-1, -1), (8, 33, 3, -2): (0, 1), (8, 33, 3, -1): (0, 1), (8, 33, 3, 0): (0, 1), (8, 33, 3, 1): (0, 1), (8, 33, 3, 2): (0, 1), (8, 33, 3...
1, 1), (8, 35, -1, 5): (-1, 1), (8, 35, 0, -5): (1, 1), (8, 35, 0, -4): (1, 1), (8, 35, 0, -3): (-1, 1), (8, 35, 0, -2): (-1, 1), (8, 35, 0, -1): (-1, 1), (8, 35, 0, 0): (-1, 0), (8, 35, 0, 1): (-1, -1), (8, 35, 0, 2): (-1, 1), (8, 35, 0, 3): (-1, 1), (8, 35, 0, 4): (-1, 1), (8, 35, 0, 5): (-1, 1), (8, 35,...
5, 1, -4): (1, 1), (8, 35, 1, -3): (1, 0), (8, 35, 1, -2): (-1, 1), (8, 35, 1, -1): (-1, 1), (8, 35, 1, 0): (-1, 1), (8, 35, 1, 1): (-1, 1), (8, 35, 1, 2): (-1, 1), (8, 35, 1, 3): (-1, 1), (8, 35, 1, 4): (-1, 1), (8, 35, 1, 5): (-1, 1), (8, 35, 2, -5): (0, 0), (8, 35, 2, -4): (0, 1), (8, 35, 2, -3): (0, 1),...
###################################################################################### # class: LinkConsumer # purpose: consumes items in the outQueue and sends to parameterFetcher for processing ###################################################################################### import logging import Queue import t...
rameterFetcher import results class LinkConsumer(threading.Thread): def __init__(self, outQueue, projectDirectory, results): threading.Thread.__init__(self) self.outQueue = outQueue self.projectDirectory = projectDirectory #data storage self.results = results #logging self.logger = lo...
self.logger.debug('Consumer: getting parameters for ' + page) paramFetcher = parameterFetcher.ParameterFetcher(page, self.projectDirectory) paramFetcher.saveParameters(self.results) #parse parameters self.outQueue.task_done()
# coding: utf-8 #This file is part of numword. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. ''' numword for EN_GB ''' from numword_en import NumWordEN class NumWordENGB(NumWordEN): ''' NumWord EN_GB
''' def currency(self, val, longval=True): ''' Convert to currency ''' return self._split(val, hightxt=u"pound/s", lowtxt=u"pence", jointxt=u"and", longval=longval) _NW = NumWordENGB() def cardinal(value): ''' Convert to cardinal ''' ...
nal(value) def ordinal(value): ''' Convert to ordinal ''' return _NW.ordinal(value) def ordinal_number(value): ''' Convert to ordinal number ''' return _NW.ordinal_number(value) def currency(value, longval=True): ''' Convert to currency ''' return _NW.currency(value, l...
efault. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration --...
ion', u'taskflow Developers', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chap
ters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # l...
rn it. Used by reforms which need to modify the legislation_json, usually in the build_reform() function. Validates the new legislation. """ reference_legislation_json = self.reference.legislation_json reference_legislation_json_copy = copy.deepcopy(reference_legislation_json) ...
if path_index == len(path) - 1 else build_node(node, path_index + 1) ) if path[path_index] == key else node ) for key, node in root_node.iteritems() )) ...
ot_node)) updated_legislation = build_node(legislation_json, 0) return updated_legislation def updated_legislation_items(items, start_instant, stop_instant, value): """ This function is deprecated. Iterates items (a dict with start, stop, value key) and returns new items sorted by start date, ...