prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
from indiefilmrentals.products.models im | port *
from shop_simplecategories.models import *
def categories(request):
ret | urn {'categories': Category.objects.all()} |
flow.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a... | io/en/master/', None),
'sqlalchemy': ('https://docs.sqlalchemy.org/en/latest/', None),
'hdfs': ('https://hdfscli.readthedocs.io/en/latest/', None),
# google-cloud-python
'google-cloud-automl': ('https://googleapis.dev/python/automl/latest', None),
'google-cloud-bigquery': ('https://googleapis.dev/py... | gle-cloud-bigquery-storage': ('https://googleapis.dev/python/bigquerystorage/latest', None),
'google-cloud-bigtable': ('https://googleapis.dev/python/bigtable/latest', None),
'google-cloud-container': ('https://googleapis.dev/python/container/latest', None),
'google-cloud-core': ('https://googleapis.dev/pyt... |
.
first_image_file = image_path % 1
if os.path.exists(stdout_path):
stdout = open(stdout_path).read()
else:
stdout = ''
if os.path.exists(time_path):
time_elapsed = float(open(time_path).read())
if not os.path.exists(first_image_file) or \
... | # have it happen with the rest. Ideally the should be written to 'thumb_file' | as well, and then
# copied to the _images folder during the `Copying Downloadable Files` step like the rest.
if not os.path.exists(car_thumb_path):
os.makedirs(car_thumb_path)
if os.path.exists(first_image_file):
# We generate extra special thumbnails for the carousel
... |
# -*- coding: utf-8 -*-
'''
Interface with a Junos device via proxy-minion.
'''
# Import python libs
from __future__ import print_function
from __future__ import absolute_import
import logging
# I | mport 3rd-party libs
import jnpr.junos
import jnpr.junos.utils
import jnpr.junos.utils.config
import json
HAS_JUNOS = True
__proxyenabled__ = ['junos']
thisproxy = {}
log = l | ogging.getLogger(__name__)
def init(opts):
'''
Open the connection to the Junos device, login, and bind to the
Resource class
'''
log.debug('Opening connection to junos')
thisproxy['conn'] = jnpr.junos.Device(user=opts['proxy']['username'],
host=opts... |
from PyQt5.QtCore import pyqtSlot, QThread, pyqtSignal
import os
from PyQt5.QtWidgets import QFileDialog, QProgressDialog, QMessageBox
from PyQt5.QtCore import pyqtSlot, QObject
from books.soldiers import processData
import route_gui
from lxml import etree
import multiprocessing
import math
class XmlImport(QObject):
... | ressDialog.setValue(0)
self.file = file
self.thread.run = self._runProcess
self.thread.start()
def _runProcess(self):
try:
xmlDataDocument = self._getXMLroot(self.file[0])
#TODO: Lue xml:n metadata
try:
#TODO: Moniprosarituki?
... | b["bookseries"])(self._processUpdateCallback)
result = self.processor.startExtractionProcess(xmlDataDocument, self.file[0])
self.threadResultsSignal.emit(result)
except KeyError:
raise MetadataException()
except Exception as e:
if "DEV" in ... |
import dat | etime
import json
class Experience:
def __init__(self, date, event):
self._date = date
self._event = event
@classmethod
def reconstruct_from_db_data_event(cls, date, event):
event = json.loads(event)
date = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S.%f")
... | return exp
def time_from_this_event(self, event):
return self._date - event._date |
lper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__sa_valid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}... | pt (TypeError, ValueError):
raise Value | Error({
'error-string': """sc_valid must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, ... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | ype
)
body = separable_conv_block(
body,
"separable_conv_block_2",
int(64 * alpha),
int(128 * alpha),
downsample=True,
layout=layout,
dtype=dtype,
)
body = separable_conv_block(
body,
"separable_conv_block_3",
int(128 * alph... | ut,
dtype=dtype,
)
body = separable_conv_block(
body,
"separable_conv_block_4",
int(128 * alpha),
int(256 * alpha),
downsample=True,
layout=layout,
dtype=dtype,
)
body = separable_conv_block(
body,
"separable_conv_block_5",
... |
t can
can obscure some important differences. Abstract origin references are tracked
and annotated (unless disabled).
"""
import getopt |
import os
import re
import sys
import script_utils as u
# Input and output file (if not specified, defaults to stdin/stdout)
flag_infile = None
flag_outfile = None
# Perform normalization
flag_normalize = | True
# Compile units to be included in dump.
flag_compunits = {}
# Strip offsets if true
flag_strip_offsets = False
# Strip hi/lo PC and location lists
flag_strip_pcinfo = False
# Annotate abstract origin refs
flag_annotate_abstract = True
# Strip these
pcinfo_attrs = {"DW_AT_low_pc": 1, "DW_AT_high_pc": 1}
# Un... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | ord = "conn_pass"
zendesk_hook = ZendeskHook("conn_id")
zendesk_hook.get_connection = mock.Mock(return_value=conn_mock)
zendesk_hook.get_conn()
mock_zendesk.assert_called_once_with(zdesk_url='https://conn_host', zdesk_email='conn_login',
zdes... | ue)
@mock.patch("airflow.providers.zendesk.hooks.zendesk.Zendesk")
def test_zdesk_sideloading_works_correctly(self, mock_zendesk):
zendesk_hook = ZendeskHook("conn_id")
mock_connection = mock.Mock()
mock_connection.host = "some_host"
zendesk_hook.get_connection = mock.Mock(retur... |
# -*- coding:utf-8 -*-
from sqlalchemy import desc, func
from atlas.modeles.entities.vmSearchTaxon import VmSearchTaxon
def listeTaxons(session):
"""
revoie un tableau de dict :
label = nom latin et nom francais concatene, value = cd_ref
TODO Fonction inutile à supprimer !!!
"""
... | temp)
return taxonList
def listeTaxonsSearch(session, search, limit=50):
"""
Recherche dans la VmSearchTaxon en ilike
Utilisé pour l'autocomplétion de la recherche de taxon
:query SQLA_Session session
:query str search : chaine de charactere pour la recherche |
:query int limit: limite des résultats
**Returns:**
list: retourne un tableau {'label':'str': 'value': 'int'}
label = search_name
value = cd_ref
"""
req = session.query(
VmSearchTaxon.search_name,
VmSearchTaxon.cd_ref,
func.similari... |
Fields not provided will be None.
Partly backwards-compatible with :mod:`urlparse`.
Example: ::
>>> parse_url('http://google.com/mail/')
Url(scheme='http', host='google.com', port=None, path='/', ...)
>>> parse_url('google.com:80')
Url(scheme=None, host='google.com', port=80,... | aram accept_encoding:
Can be a boolean, list, or string.
``True`` translates to 'gzip,deflate'.
List will get joined by comma.
String | will be used as provided.
:param user_agent:
String representing the user-agent you want, such as
"python-urllib3/0.6"
:param basic_auth:
Colon-separated username:password string for 'authorization: basic ...'
auth header.
Example: ::
>>> make_headers(keep_alive=... |
from __future__ import absolute_ | import
from fulltext.backends import __html
from fulltext.util import run, assert_cmd_exists
from fulltext.util import BaseBackend
def cmd(path, **kwargs):
cmd = ['hwp5proc', 'xml']
cmd.extend([path])
return cmd
def to_text_with_backend(html):
return __html.handle_fobj(html)
class Backend(BaseBac... | nd(out)
|
e/views/entrance_exam.py for usage
is_entrance_exam = Boolean(
display_name=_("Is Entrance Exam"),
help=_(
"Tag this course module as an Entrance Exam. "
"Note, you must enable Entrance Exams for this course setting to take effect."
),
default=False,
s... | [resource_string(__name__, 'css/sequence/display.scss')],
}
js_module_name = "Sequence"
def __init__(self, *args, **kwargs):
super(SequenceModule, self).__init__(*args, **kw | args)
# If position is specified in system, then use that instead.
position = getattr(self.system, 'position', None)
if position is not None:
try:
self.position = int(self.system.position)
except (ValueError, TypeError):
# Check for https:... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import shutil
import sys
from setuptools import setup
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
with open(os.path.join(package, '__init__.py'), 'rb') as init_py:
src = in... | onment',
'Framework :: Django',
'Intended Audience :: Developers',
| 'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python ::... |
"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_... | emplate = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILA | BILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_temp... |
#!/usr/bin/env python3
from setuptools import setup, find_packages
version = '0.2.4'
setup(
name='lolbuddy',
version=version,
descri | ption='a cli tool to update league of legends itemsets and ability order from champion.gg',
author='Cyrus Roshan',
author_email='hello@cyrusroshan.com',
license='MIT',
keywords=['lol', 'league', 'league of legends', 'item', 'ability'],
url='https://github.com/CyrusRoshan/lolbuddy',
packages=find... | olbuddy:main',
],
},
)
|
return val
else:
if not info_only:
self.vended.setdefault(id(val), [val, 0])[1] += 1
t = hash(val) if isDictKey else None
return ProxyInfo(self.endpoint, id(val), proxyhash=t).packed()
def unpack(self, val, info_only = False):
if ProxyInfo.isPacked(val):
info = ProxyInfo.... | l = urandom(20)
self.sock.sendall(chal)
if self.sock.recv(20) != sha1(self.secret+chal).digest():
print >> sys.stderr, "Client failed challenge!"
return None
try:
self.vended = {}
self.sendmsg( | self.pack(obj))
while self.vended:
self.handle(self.recvmsg())
except socket.error as e:
if e.errno in (errno.EPIPE, errno.ECONNRESET): pass # Client disconnect is a non-error.
else: raise
finally:
del self.vended
def request(self, msg):
self.sendmsg(msg)
while True:
... |
# Copyright (c) 2015 Intel Research and Development Ireland Ltd.
#
# 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 app... | t_case['params']['vlan_receiver'] = '1006'
test_cases = [test_case]
:param iterations: Number of cycles to be executed (int)
:param heat_template: (string) File name of the heat template of the
workload to be deployed. It contains the
... | evaluated in the form of
#parameter_name. (See heat_templates/vTC.yaml as
example).
:param heat_template_parameters: (dict) Parameters to be provided
as input to the heat template.
See http://docs.op... |
django.contrib.auth.models import AnonymousUser
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse, NoReverseMatch, resolve, Resolver404
from django.db.models import Q
from django.utils.translation import override as force_language, ugettext_lazy as _
from cms.api import get_pag... | es=['cms-clipboard-empty'],
disabled=not clipboard_is_bound)
self._admin_menu.add_break(CLIPBOARD_BREAK)
# Disable toolbar
self._admin_menu.add_link_item(_('Disable toolbar'), url='?%s' % get_cms_setting('CMS_TOOLBAR_URL__DISABLE'))
self._admi... | LE_BREAK)
self._admin_menu.add_link_item(_('Shortcuts...'), url='#',
extra_classes=('cms-show-shortcuts',))
self._admin_menu.add_break(SHORTCUTS_BREAK)
# logout
self.add_logout_button(self._admin_menu)
def add_users_button(self, parent):
... |
`obj.foo` can be used in addition
to `obj['foo']`.
Raises Attribute/Key errors for missing references.
>>> o = Storage(a=1, b=2)
>>> assert(o.a == o['a'])
>>> assert(o.b == o['b'])
>>> o.a = 2
>>> print o['a']
2
>>> x = o.copy()
>>> assert(x == o)
>>> del o.a
>>> p... | kargs):
self.id = kargs['id']
self.abbreviation = kargs.get('abbreviation')
self.plural = kargs.get('plural')
self.pluralAbbreviation = kargs.get('pluralAbbreviation')
class RecipeImages(Storage):
"""Recipe images model."""
def __init__(self, **kargs):
self.hostedLargeU... | self.hostedSmallUrl = kargs.get('hostedSmallUrl')
class RecipeSource(Storage):
"""Recipe source model."""
def __init__(self, **kargs):
self.sourceRecipeUrl = kargs.get('sourceRecipeUrl')
self.sourceSiteUrl = kargs.get('sourceSiteUrl')
self.sourceDisplayName = kargs.get('sourceDispla... |
return last_visit < cutoff
def should_process_digest(realm_str):
# type: (str) -> bool
if realm_str in settings.SYSTEM_ONLY_REALMS:
# Don't try to send emails to system-only realms
return False
return True
# Changes to this should also be reflected in
# zerver/worker/queue_processors.py:Di... | continue
key = (user_message.message.recipient.type_id,
user_message.message.subject)
conversation_diversity[key].add(
user_message.message.sender.full_name)
conversation_length[key] += 1
diversity_list = list(conversation_diversity.items())
diversity_list... | e 4 best conversations from the diversity list
# and length list, filtering out overlapping conversations.
hot_conversations = [elt[0] for elt in diversity_list[:2]]
for candidate, _ in length_list:
if candidate not in hot_conversations:
hot_conversations.append(candidate)
if len... |
# -*- coding: utf-8 -*-
# Copyright 2015 Objectif Libre
#
# 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 ... | rn):
test_dir = os.path.join(os.p | ath.dirname(__file__), TESTS_DIR)
return driver.build_tests(test_dir,
loader,
host=None,
intercept=fixtures.setup_app,
fixture_module=py_fixtures)
|
from time import sleep
from worker import delayable
import requests
@delayable
def add(x, y, delay=None):
# | Simulate your work here, | preferably something interesting so Python doesn't sleep
sleep(delay or (x + y if 0 < x + y < 5 else 3))
return x + y
@delayable
def get(*args, **kwargs):
r = requests.get(*args, **kwargs)
return r.content
|
# Use this script to collapse a multi-level folder of images into one folder.
import fnmatch
import os
import shutil
folderName = 'unknown'
matches = []
for root, dirnames, filenames in os.walk(folderName):
for filename in fnmatch | .filter(filenames, '*.jpg'):
matches.append(os.path.join(root, filename))
idx = 0
for match in matches:
print match
shutil.move('./' + match, | './' + folderName + '/' + str(idx) + '.jpg')
idx = idx + 1 |
# -*- coding: UTF-8 -*-
import re
def mgo_text_split(query_text):
''' split text to support mongodb $text match on a phrase '''
sep = r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]'
word_lst = re.split(sep, query_text)
text_query = ' '.join('\"{}\"'.format(w) for w in word_lst)
return text_query
# 搜... | , 'server', 'hostname'):
fil | ter_lst.append({i: {"$regex": list[0], '$options': 'i'}})
query['$or'] = filter_lst
return query
|
# 005_cleaner.py
#####################################################################
##################################
# Import des modules et ajout du path de travail pour import relatif
import sys
sys.path.insert(0 , 'C:/Users/WILLROS/Perso/Shade/scripts/LocalWC-Shade-App/apis/')
from voca import AddLog , ... | Shade/scripts/LocalWC-Shade-App/apis/raw/{}_raw/'.format(missionName)
# Nom du fichier source
raw_file = 'src'
##################################
# retreiving raw string
raw_string_wi | th_tabs = open(work_dir + raw_file , 'r').read()
# replacing tabs with carriage return
raw_string_with_cr = raw_string_with_tabs.replace( '\t', '\n' )
# turning the string into a list
raw_list = raw_string_with_cr.splitlines()
# going through oddities finder
AddLog('subtitle' , 'Début de la fonction OdditiesFinde... |
P | ER_PAGE = 50
ANNOUNCE_INTERVAL = 30 | 0
|
import pygame
import os
from buffalo import utils
from item import Item
# User interface for trading with NPCs
# Similar to the crafting UI, with some minor differences
# The biggest thing is that it only appears when you "talk to" (read click on)
# A trader NPC and disappears when you leave that window, and only cont... | ight()))
self.tileTrades.append(t)
total_y += newTile.get_height()
newSurface = utils.empty_surface((228, total_y))
newSurface.fill((100,100,100,255))
currY = 0
for surf in tradeTiles:
newSurface.blit(surf, (0, currY))
currY += surf.get_height()
self.surface = newSurface
def ge | nerateTradeTile(self, trade):
y_length = 36 * (len(trade.price.keys()) / 3) + 78;
newScreen = utils.empty_surface((228, y_length))
for num, item in enumerate(trade.price.keys()):
x = ((num % 3) * TradingUI.BUTTON_SIZE) + TradingUI.PADDING
y = ((num / 3) * TradingUI.BUTTON_SIZE) + TradingUI.PADDING
itemS... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from datetime import datetime
from os import environ
from requests import get
from bs4 import BeautifulSoup, NavigableString
from icalendar import Calendar, Even... | join(d['Lieu'].stripped_strings).replace("\r\n", ' '))
event.add('uid', "%s@formation.ffme.fr" % (num,) )
event.add('description', 'http://www.ffme.fr/formation | /fiche-evenement/%s.html' % (num, ))
return event
def create_event_compet(d):
event = Event()
nom_lieu = tuple(d['Nom de la compétition Lieu'].stripped_strings)
dates = tuple(d['Date'].stripped_strings)
link = 'http://www.ffme.fr'+d['Nom de la compétition Lieu'].a.get('href')
event.add('summa... |
import sys
if __name__ == "__main__":
# Parse command line arguments
if len(sys.argv) < 2:
sys.exit("python {} <datasetFilename> {{<maxPoints>}}".format(sys.argv[0]))
datasetFilename = sys.argv[1]
if len(sys.argv) >= 3:
maxPoints = int(sys.argv[2])
else:
maxPoints = None
# Perform initial pass through fil... | setFilename, "r") as f:
line = f.readline()
while line:
lineCount += 1
line = f.readline()
# Read first line and use to make assumption about the dimensionality of each point
numDimensions = 0
with open(datasetFilename, "r") as f:
firstLine = f.readline()
numDimensions = len(firstLine.split())
# If di... | ataset is 0, print error message and exit
if numDimensions == 0:
sys.exit("Could not determine dimensionality of dataset")
# Print initial header at END of file (so we have number of points already)
if maxPoints:
numPoints = min(lineCount, maxPoints)
else:
numPoints = lineCount
print("{} {}".format(numDimen... |
_x * tile_x + wid.x,
pos_y * tile_y + wid.y),
size=(tile_x, tile_y))
Color(1, 1, 1, 1)
Rectangle(texture=self.trash_img.texture,
pos=(
pos_x * tile_x + wid.x,
... | ""Update the environment one step."""
if not self.initialized:
gen_popup("Error!", "You must load a map...").open()
self.btn_100step.state = "normal"
return
elif self.agentA == "Agent A" and self.agentB == "Agent B":
popup = gen_popup(
"Err... | lected, reset required...", False).open()
Clock.schedule_once(popup.dismiss, timeout=2)
Clock.schedule_once(self.partial_reset, timeout=2)
self.btn_100step.state = "down"
self.running = True
Clock.schedule_interval(partial(function, labels, wid, 100), 1 / 30.)
def bt... |
import socket
import string
from driver import driver
class WiFiMouseDriver(driver):
ACTION_KEYS = {
'TAB': 'TAB',
'ENTER': 'RTN',
'ESCAPE': 'ESC',
'PAGE_UP': 'PGUP',
'PAGE_DOWN': 'PGDN',
'END': 'END',
'HOME': 'HOME',
'LEFT': 'LF',
'UP': 'UP'... | Y
return self
def typeText(self, text):
format = "key "
for char in text:
self._send(format + str( | len(char)) + char)
return self
def press_action_key(self, name, shift=False, ctrl=False, alt=False):
if name not in WiFiMouseDriver.ACTION_KEYS:
raise ValueError('Unknown action key name: %s' % name)
format = "key "
command = str(WiFiMouseDriver.ACTION_KEYS[name])
... |
"""
Authenication and Authorization tests which require DC/OS Enterprise.
Currently test against root marathon. Assume we will want to test these
against MoM EE
"""
import common
import dcos
import pytest
import shakedown
from urllib.parse import urljoin
from dcos import marathon
from shakedown import credentials, e... | ), 'ser | vice/marathon/v2/apps'))
error = exc_info.value
assert str(error) == "You are not authorized to perform this operation"
@pytest.fixture(scope="function")
def billy():
shakedown.add_user('billy', 'billy')
shakedown.set_user_permission(rid='dcos:adminrouter:service:marathon', uid='billy'... |
(selfAddon.getAddonInfo('profile'))#selfAddon["profile"])
#F4Mversion=''
class interalSimpleDownloader():
outputfile =''
clientHeader=None
def __init__(self):
self.init_done=False
def thisme(self):
return 'aaaa'
def openUrl(self,url, ischunkDownloading=False):
try:
... | y(self.proxy, 'http')
response = openner.open(req)
data=response.read()
| return data
except:
#print 'Error in getUrl'
traceback.print_exc()
return None
def init(self, out_stream, url, proxy=None,g_stopEvent=None, maxbitRate=0):
try:
self.init_done=False
self.init_url=url
self.clie... |
# coding: utf-8
# Copyright 2017 Solthis.
#
# This file is part of Fugen 2.0.
#
# Fugen 2.0 is free software: you can redistribute it and/or modify
# i | t 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.
#
# Fugen 2.0 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANT | ABILITY 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 Fugen 2.0. If not, see <http://www.gnu.org/licenses/>.
import pandas as pd
from dateutil.relativedelta import relativedelta
from data... |
._machine = machine_class(machine_params.options)
self._machine.set_suppression(self._is_running)
self._machine.add_state_callback(self._machine_state_callback)
self._machine.add_stroke_callback(self._machine_stroke_callback)
self._machine_params = machine_params
... | nabled_extensions)
self._start_extensions(enabled_extensions - running_extensions)
# Trigger `config_changed` hook.
if config_update:
self._trigger_hook('config_changed', config_update)
# Update dictionaries.
config_dictionaries = OrderedDict(
(d.path, d)
... | self._dictionaries_manager.unload_outdated()
self._set_dictionaries([
d for d in self._dictionaries.dicts
if d.path in config_dictionaries and \
d.path in self._dictionaries_manager
])
# And then (re)load all dictionaries.
dictionaries = []
... |
node_target in node.targets:
visit(node_target, source, state)
visit(node.value, source, state)
target_names = get_names(node.targets[0])
value_names = get_names(node.value)
for target, value in zip(target_names, value_names):
if target and value:
path: QualifiedName = ("..... | e_source(
"""
def fun_old():
return 'result'
result = fun_old()
"""
)
assert [source.position(1, 4), source.position(3, 9)] == all_occurrence_positions(
source.position(1, 4)
)
def test_finds_class():
source = make_source(
"""
| class OldClass:
pass
instance = OldClass()
"""
)
assert [source.position(1, 6), source.position(4, 11)] == all_occurrence_positions(
source.position(1, 6)
)
def test_finds_method_name():
source = make_source(
"""
class A:
def old(s... |
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 Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permissi... | elf._pronouns = None
self._properties = None
self._triples = None
self._preprocessors = None
self._postprocessors = None
self._services = []
BaseConfigurationData.__init__(self, "brain")
def _get_brain_file_configuration(self, config_... | on = config_file.get_option(section, "extension")
directories = config_file.get_option(section, "directories")
return BrainFileConfiguration(files, extension, directories)
def load_config_section(self, config_file, bot_root):
brain = config_file.get_section(self.section_name)
if br... |
from mocket import Mocket, mocketize
from mocket.async_mocket import async_mocketize
from mocket.compat import byte_type, text_type
from mocket.mockhttp import Entry as MocketHttpEntry
from mocket.mockhttp import Request as MocketHttpRequest
from mocket.mockhttp import Response as MocketHttpResponse
def httprettifier... | name):
if name == "last_request":
return Mocket.last_request()
if name == "l | atest_requests":
return Mocket.request_list()
return getattr(Entry, name)
HTTPretty = MocketHTTPretty()
HTTPretty.register_uri = register_uri
httpretty = HTTPretty
__all__ = (
"HTTPretty",
"activate",
"async_httprettified",
"httprettified",
"enable",
"disable",
"reset"... |
"""Support for switches through the SmartThings cloud API."""
from __future__ import annotations
from collections.abc import Sequence
from pysmartthings import Capability
from homeassistant.components.switch import SwitchEntity
from . import SmartThingsEntity
from .const import DATA_BROKERS, DOMAIN
async def asyn... | rn the switch on."""
await self._device.switch_on(set_status=True)
# State is set optimistically in the command above, therefore update
# the entity state ahead of receiving the confirming push updates
self.async_write_ha_state()
@property
def is_on(self) -> bool:
"""Ret... | turn self._device.status.switch
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-05-30 17:02
from __future__ import unicode_literals
fro | m django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0062_auto_20171223_1552'),
]
operations = [
migrations.AddField(
model_name='event',
name='date_end',
| field=models.DateField(blank=True, default=None, null=True),
),
]
|
his method defines the model itself, and must be overloaded by derived classes
This function will update `self` with the layers required to execute the `call()` method
:param embeddings: The input feature indices
:param kwargs:
:return:
"""
def predict(self, batch_dict, **... | __init__(self):
super().__init__()
def zero_state(self, batchsz):
weight = next(self.parameters()).data
return (torch.autograd.Variable(weight.new(self.num_layers, batchsz, self.hsz).zero_()),
torch.autograd.Variable(weight.new(self.num_layers, batchsz, self.hsz).zero_()))
... | erty
def requires_state(self):
True
def init_generate(self, **kwargs):
pdrop = float(kwargs.get('dropout', 0.5))
self.num_layers = kwargs.get('layers', kwargs.get('num_layers', 1))
self.hsz = kwargs.get('hsz', kwargs.get('d_model'))
return WithDropoutOnFirst(LSTMEncoderW... |
import click
from pycolorterm.pycolorterm import print_pretty
from quarantine.cdc import CDC
from sh import ErrorReturnCode
@click.group()
def cli():
pass
@cli.command()
@click.argument('name')
@click.argument('pip_args', nargs=-1)
def install(na | me, pip_args):
"""Install the package. Pip args specified with --."""
cdc = CDC(name)
try:
cdc.install(pip_args)
except ErrorReturnCode as e:
print_pretty("<FG_RED>Something went wrong! Rolling back...<END>")
cdc.uninstall()
@cli.command()
@click.argument('name')
def uninstall(n... | cdc = CDC(name)
cdc.uninstall()
if __name__ == '__main__':
quarantine()
|
del_fields set field_description=%s where model=%s and name=%s', (vals['field_description'], vals['model'], vals['name']))
cr.commit()
cr.execute("""UPDATE ir_model_fields SET
model_id=%s, field_description=%s, ttype=%s, relation=%s,
... | # same function name, we let it override
# the old one.
new[c2] = c
exist = True
break
| if not exist:
new.append(c)
else:
new.extend(cls.__dict__.get(s, []))
nattr[s] = new
cls = type(name, (cls, parent_class), dict(nattr, _register=False))
if not getattr(cls, '_original_module', None):
... |
from model.info_cont | act import Infos
testdata = [
Infos(firstname="firstname1",lastname="lastname1"),
Infos(firstname="firstname2",lastna | me="lastname2")
] |
#__all__ = [ 'search', 'ham_dista | nce', 'lev_distance', 'distance', 'distance_matrix' ]
| |
from mock import patch
import mock
from kiwi.storage.subformat.vhdx import DiskFormatVhdx
class TestDiskFormatVhdx:
@patch('platform.machine')
def setup(self, mock_machine):
mock_machine.return_value = 'x86_64'
xml_data = mock.Mock()
xml_data.get_name = mock.Mock(
return_... | )
self.xml_state = mock.Mock()
self.xml_state.xml_data = xml_data
self.xml_state.get_image_version = mock.Mock(
return_value='1.2.3'
)
self.disk_format = DiskFormatVhdx(
self.xml_state, 'root_dir', 'target_dir'
)
def test_post_init(self):
... | assert self.disk_format.options == [
'-o', 'option=value', '-o', 'subformat=dynamic'
]
@patch('kiwi.storage.subformat.vhdx.Command.run')
def test_create_image_format(self, mock_command):
self.disk_format.create_image_format()
mock_command.assert_called_once_with(
... |
su = summ(loader2[ss:ss+send_len], send_len)
| # send command
data = swapSerialData("f7".decode("hex"))
data = swapSerialData(loader2[ss:ss+send_len])
#print "2 crc is: " + binascii.b2a_hex(data)
#print "2 my_crc is: " + | binascii.b2a_hex(su)
#print "i: " + str(i)
sys.stdout.write("\ri: " + str(i))
sys.stdout.write("\n")
serialPost(ser, "FF".decode("hex"))
elif s == 113:
serialPost(ser, "D010000000".decode("hex"))
elif s == 114:
serialPost(ser, "D1".... |
# Copyright (c) 2017 Charles University in Prague, Faculty of Arts,
# Institute of the Czech National Corpus
# Copyright (c) 2017 Tomas Machalek <tomas.machalek@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
#... | ix for a specified format.
arguments:
format -- format name (AbstractChartExport.get_format_name())
"""
raise NotImplementedError()
def export_pie_chart(self, data, | title, format):
"""
Export PIE chart data to a PIE chart of
a specified format.
arguments:
data -- chart data
title -- chart label
format -- format name (AbstractChartExport.get_format_name())
"""
raise NotImplementedError()
|
import config
#This module is used for calling the Wolfra | m Alpha API
#It defines a function that constructs an URL based on th | e query.
#NOTE: This module returns only the URL. This URL is passed in the bot.py file. Telegram Takes care of the rest.
def query(query):
question = query.replace(" ","+") #plus encoding
return "http://api.wolframalpha.com/v1/simple?appid={}&i=".format(config.WOLFRAM) + question + "&f... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010-2011, Volkan Esgel
#
# 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 the License, or (at your option)
# any l... | eateMainLayout(self):
self.mainLayout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
noteview = Plasma.TreeView(self.applet)
noteview.setStyleSheet("QTreeView { background: Transparent }")
nmodel = NoteModel(self.package().path(), noteview)
noteview.setModel(nmodel)
n... | veWidget().setHeaderHidden(True)
noteview.nativeWidget().setIndentation(0)
self.mainLayout.addItem(noteview)
self.viewerSize = noteview.size()
self.applet.setLayout(self.mainLayout)
def CreateApplet(parent):
return QuickNotes(parent)
|
: int = 300) -> str"
assert doc(m.kw_func_udl_z) == "kw_func_udl_z(x: int, y: int = 0) -> str"
assert doc(m.args_function) == "args_function(*args) -> tuple"
assert (
doc(m.args_kwargs_function) == "args_kwargs_function(*args, **kwargs) -> tuple"
)
assert (
doc(m.KWClass.foo0)
... | Invoked with:
""" # noqa: E501 line too long
)
assert mpk(-2, 3.5, pi=3.14159, e=2.71828) == (
-2,
3.5,
{"e": 2.71828, "pi": 3.14159},
)
assert mpak(7, 7.7, 7.77, 7.777, 7.7777, minusseven=-7) == (
7,
7.7,
(7.77, 7.777, 7.7777),
{"minu... | (3, 3.14159, (), {})
assert mpakd(j=2.71828) == (1, 2.71828, (), {})
assert mpakd(k=42) == (1, 3.14159, (), {"k": 42})
assert mpakd(1, 1, 2, 3, 5, 8, then=13, followedby=21) == (
1,
1,
(2, 3, 5, 8),
{"then": 13, "followedby": 21},
)
# Arguments specified both positio... |
import random
def preprocessing(maze | Map, mazeWidth, mazeHeight, playerLocation, opponentLocation, piecesOfCheese, timeAllowed):
return
def turn (mazeMap, mazeWidth, mazeHeight, playerLocation, opponentLocation, playerScore, opponentScore, piecesOfCheese, timeAllowed):
return
def postprocessing (ma | zeMap, mazeWidth, mazeHeight, playerLocation, opponentLocation, playerScore, opponentScore, piecesOfCheese, timeAllowed):
return
|
ces = services
self.zapFunc = zapFunc
if bouquetname != "":
Screen.setTitle(self, bouquetname)
self["list"] = EPGList( selChangedCB = self.onSelectionChanged,
timer = self.session.nav.RecordTimer,
time_epoch = config.misc.graph_mepg.prev_time_period.value,
overjump_empty = config.misc.graph_mep... | (self.nextPage, _("Go to next page of service")),
"8": (self.toTop, _("Go to first service")),
"0": (self.toEnd, _("Go to last service"))
}, -1)
self["inputactions"].csel = self
self.updateTimelineTimer = eTimer()
self.updateTimelineTimer.callback.append(self.moveTimeLines)
... | f.previousref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
def prevPage(self):
self["list"].moveTo(eListbox.pageUp)
def nextPage(self):
self["list"].moveTo(eListbox.pageDown)
def toTop(self):
self["list"].moveTo(eListbox.moveTop)
def toEnd(self):
self["list"].moveTo(eListbox.moveEnd)
def pre... |
behavior of the
Parameter. Parameters may have parent / child / sibling relationships to construct
organized hierarchies. Parameters generally do not have any inherent GUI or visual
interpretation; instead they manage ParameterItem instances which take care of
display and user interaction.
Not... | variable
'expanded': True,
#'limits': None, ## Thi | s is a bad plan--each parameter type may have a different data type for limits.
}
self.opts.update(opts)
self.childs = []
self.names = {} ## map name:child
self.items = weakref.WeakKeyDictionary() ## keeps track of tree items representing this parameter
self._... |
from protoplot.engine.options_container import OptionsContainer
from protoplot.engine.tag import make_tags_list
from protoplot.engine.item_metaclass import ItemMetaclass # @UnusedImport
from protoplot.engine.item_container import ItemContainer
# TODO options should be resolved in the proper order. Here's the proposed... | of
options (a tag is similar to a class in CSS).
An Item *subclass* has the following (class) attributes:
* An item accessor which will return a template item in | stance for a given
tag specification, which can be a string or the empty slice to specify
the default template. (TODO really empty slice?)
* An "all" property as a shortcut for [:]
* A "set" method as a shortcut for [:].set
* A constructor taking options like the set method
Item ... |
t):
for k, v in element.items():
html_class = 'collapsible_group'
# This allows us to later (in JavaScript) recursively highlight sections
# that are likely of interest to the user, i.e. whose exp | ectations can be
# modified.
if k and FULL_PASS in k:
html_class = 'highlighted_coll | apsible_group'
file_handle.write('<button type="button" class="%s">%s</button>\n' %
(html_class, k))
file_handle.write('<div class="content">\n')
_RecursiveHtmlToFile(v, file_handle)
file_handle.write('</div>\n')
elif isinstance(element, list):
for i in element:
... |
out.add_events(gtk.gdk.LEAVE_NOTIFY_MASK)
self.layout.connect("leave-notify-event", self.leave)
def update(self):
self.queue_draw()
def set_position_for_selected(self, x):
self.gradient.set_position(self.selected, x)
def set_color_for_selected(self, color):
color.position ... | for c in range(0, cnt):
if self.gradient.colors[c].position == col.position:
index = c
break
break
r = self.gradient.colors[index].red
g = self.gradient.colors[index].green
... | l = 0
r, g, b = l, l, l
context.set_source_rgba(r, g, b, 1.0)
context.stroke()
for color in range(len(self.gradient.colors)):
if color == self.selected:
delta = 10
else:
delta = 0
context.ne... |
one,
test_phone_numbers: dict = None,
project: str = None,
service_account_file: str = "",
):
channel.initialize()
self.name = name
self.display_name = display_name
self.allow_password_signup = allow_password_signup
self.enable_email_link_signin = ena... | .resource.name = Primitive.to_proto(self.name)
if Primitive.to_proto(self.display_name):
request.resource.display_name = Primitive.to_proto(self.display_name)
if Primitive.to_proto(self.allow_password_signup):
request.resource.allow_password_signup = Primitive.to_proto(
... | = Primitive.to_proto(
self.enable_email_link_signin
)
if Primitive.to_proto(self.disable_auth):
request.resource.disable_auth = Primitive.to_proto(self.disable_auth)
if Primitive.to_proto(self.enable_anonymous_user):
request.resource.enable_anonymous... |
import urllib2
import base64
import json
from link import *;
from | GitFetcher import GitHubFetcher;
username = "debuggerman"
password = "megadeth"
orgUrl = "https://api.github.com/orgs"
orgName = "coeus-solutions"
gitFetcher = GitHubFetcher(username = username, password = password, orgUrl = orgUrl, orgName = orgName)
gitFetcher.getOrgInfo() | |
from omelette.fromage.common import DrawableNode
class DrawableNode(DrawableNode) | :
def __init__(self, uml_object):
super(DrawableNode, self).__init__(uml_object)
| |
'''
Created on 20/10/2014
@author: fer
'''
if __name__ == '__main__':
print(' | hola')
x=32 #entero
print x
# variable mensaje
mensaje = "hola mundo"
print mensaje
#booleano
my_bool=True
print my_bool
#exponentes
calculo = 10**2
print calculo
print ("La variable calculo es de tipo: %s" % type(calculo))
print ("Clase %s" % type(calcul... | me__)
''' Conversion de tipos '''
entero = int(3.999)
print entero
real = float(3)
print real
cadena = str(32)
print type(cadena)
pass |
ricAAE(AggregateMetric):
"""
computes average absolute error
"""
def accumulate(self, groundTruth, prediction, accumulatedError, historyBuffer, result = None):
error = abs(groundTruth - prediction)
accumulatedError += error
if historyBuffer is not None:
historyBuffer.append(error)
i... | l.
For example, if you wanted to see the predictions generated for the TwoGram
metric, you would specify 'PassThruPredictions' as the 'errorMetric' parameter.
This metric class simply takes the prediction and outputs that as the
aggregateMetric value.
"""
def __init__(self, metricSpec):
self.spec =... | metricSpec.params.get("window", 1)
self.avg = MovingAverage(self.window)
self.value = None
def addInstance(self, groundTruth, prediction, record = None, result = None):
"""Compute and store metric value"""
self.value = self.avg(prediction)
def getMetric(self):
"""Return the metri... |
gy/
"""
import asyncio
import logging
import voluptuous as vol
import aiohttp
import async_timeout
from homeassistant.const import (
CONF_NAME, CONF_USERNAME, CONF_PASSWORD,
CONF_URL, CONF_WHITELIST, CONF_VERIFY_SSL)
from homeassistant.components.camera import (
Camera, PLATFORM_SCHEMA)
fr... | th
def camera_image(self):
"""Return bytes of camera image."""
return run_coroutine_threadsafe(
self.async_camera_image(), self.hass.loop).result()
@asyncio.coroutine
def async_camera_image(self):
"""Return a still image r | esponse from the camera."""
image_url = SYNO_API_URL.format(
self._synology_url, WEBAPI_PATH, self._camera_path)
image_payload = {
'api': CAMERA_API,
'method': 'GetSnapshot',
'version': '1',
'cameraId': self._camera_id
}
... |
import os
import pickle
import numpy as np
from tqdm import tqdm
class SumTree:
def __init__(self, capacity):
self.capacity = capacity
self.tree = np.zeros(2 * capacity - 1, dtype=np.float32)
self.data = np.empty(capacity, dtype=object)
self.head = 0
@property
def total_p... | ty, data):
tree_index = self._data_to_tree_index(self.head)
self.update_prio | rity(tree_index, priority)
self.data[self.head] = data
self.head += 1
if self.head >= self.capacity:
self.head = 0
def update_priority(self, tree_index, priority):
delta = priority - self.tree[tree_index]
self.tree[tree_index] = priority
while tree_index ... |
# SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
"""
Get a list of a package's plugins.
"""
from __future__ import print_function
def setup_parser(parser, completions=False):
parser.add_argument(
"--paths", type=str, default=None,
help="set package search path")
... | on.completer = PackageFamilyCompleter
def command(opts, parser, extra_arg_groups=None):
from rez.package_search import get_plugins
from rez.config import config
import os
import os.path
import sys
config.override("warn_none", True)
if opts.paths is None:
pkg_paths = None
else... | kg_paths = opts.paths.split(os.pathsep)
pkg_paths = [os.path.expanduser(x) for x in pkg_paths if x]
pkgs_list = get_plugins(package_name=opts.PKG, paths=pkg_paths)
if pkgs_list:
print('\n'.join(pkgs_list))
else:
print("package '%s' has no plugins." % opts.PKG, file=sys.stderr)
|
_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
parent_file_entry = file_entry.GetParentFileEntry()
self.assertIsNotNone(parent_file_entry)
self.assertEqual(parent_file_entry.name, 'a_director... | elf.assertFalse(file_entry.IsSocket())
| def testSubFileEntries(self):
"""Tests the number_of_sub_file_entries and sub_file_entries properties."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS, location='/',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPath... |
s:
add_qname(tag.text)
elif isinstance(tag, basestring):
if tag not in qnames:
add_qname(tag)
elif tag is not None and tag is not Comment and tag is not PI:
_raise_serialization_error(tag)
for key, value in elem.items():
if isin... | %s=\"%s\"" % (qnames[k], v))
if text or len(elem):
write(">")
if text:
write(_escape_cdata(text, encoding))
for e in elem:
_serialize_xml(write, e, encoding, qnames, None)
write("</" + tag + ">")
... | , "hr",
"img", "input", "isindex", "link", "meta", "param")
try:
HTML_EMPTY = set(HTML_EMPTY)
except NameError:
pass
def _serialize_html(write, elem, encoding, qnames, namespaces):
tag = elem.tag
text = elem.text
if tag is Comment:
write("<!--%s-->" % _escape_cdata(text, enco... |
# -*- coding: utf-8 -*-
'''
Flixnet Add-on
Copyright (C) 2017 homik
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 the License, or
(at your option) any l... | er 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 General Public License for more details.
You should have received a copy of the GNU General P... | urllib, urlparse, re
from resources.lib.modules import cleantitle
from resources.lib.modules import client
class source:
def __init__(self):
self.priority = 1
self.language = ['pl']
self.domains = ['filiser.tv']
self.base_link = 'http://filiser.tv/'
self.url_transl = 'emb... |
from gh_frespo_integration.utils import github_adapter
from gh_frespo_integration.models import *
from django.conf import settings
import logging
from datetime import timedelta
__author__ = 'tony'
logger = logging.getLogger(__name__)
def get_repos_and_configs(user):
repos = []
github_username = user.github_u... | ype = repo_dict['owner']['type']
name = repo_dict['name']
repodb = Repo.newRepo(owner, owner_type, name, gh_id, user)
repodb.save()
config = get_repo_config_by_repo_and_user(repodb, user)
if not config:
config = UserRepoConfig.newConfig(user, repodb)
... | d)
config.new_only = True
config.save()
my_repo_ids.append(gh_id)
UserRepoConfig.objects.filter(user__id = user.id).exclude(repo__gh_id__in = my_repo_ids).delete()
def add_sponsorthis_comments():
configs = UserRepoConfig.objects.filter(add_links = True)
logger.debug('starting sponso... |
if i != numOfCols - 2:
retTxt += ' & '
else:
retTxt += ' \\\\\n'
elif horizontal.name == 'hline':
... | oScale = root.find('certificate').find('logoScale').text
certificateCourse = root.find('certificate').find('course').text
certificateStream = root.find('certificate').find('stream').text
certificateUnivName = root.find('certificate').find('univName').text
abstractFontFamily = root.find('abstractControl... | tex = fillContent(tex, 'newcommand{\projectTitle}{', projectTitle)
tex = fillContent(tex, 'newcommand{\guide}{', guide)
tex = fillContent(tex, 'newcommand{\principal}{', principal)
tex = fillContent(tex, 'newcommand{\HOD}{', HOD)
tex = fillContent(tex, 'newcommand{\durationLong}{', durationLong)
... |
from django.contrib impo | rt admin
from widgy.admin import WidgyAdmin
from widgy.contrib.page_builder.models | import Callout
admin.site.register(Callout, WidgyAdmin)
|
from django.db i | mport models
from gitireadme.utils import getUploadToPath
import datetime
class Article(models.Model):
name = models.CharField(max_length=255,blank=True,null=True)
path = models.CharField(max_length=255,blank=True,null=True)
class ArticleAlias(models.Model):
repo = models.CharField(max_length=255,blank=T... | |
al("_fn", _fn.__name__)
self.assertEqual(
"fn doc. (deprecated)"
"\n"
"\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s."
"\nInstructions for updating:\n%s"
"\n"
"\nArgs:"
"\n arg0: Arg 0."
"\n arg1: Arg 1."
"\n"
"\nReturns:... | eprecated(date, instructions)
def _fn(arg0, arg1):
return arg0 + arg1
# Assert function docs are properly updated.
self.assertEqual("_fn", _fn.__name__)
self.assertEqual(
"DEPRECATED FUNCTION"
"\n"
"\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s."
"\nIn... | )
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
@test.mock.patch.object(logging, "warning", autospec=True)
def test_instanc... |
# coding=UTF-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
#import tornado
from tornado import ioloop , web , httpserver , websocket , options
#import handler function
import handler
import os
#set server s | ettings
server_settings = {
"static_path": os.path.join(os.path.dirname(__file__), "static"),
"xsrf_cookies": True,
"autoreload": True,
#"login_url": "/accounts/login",
"debug":True,
"template_path":os.path.join(os.path.dirname(__file__),"templates"),
}
#the handlers list
handlers=[
(r"/?",handler.Mai... | in__":
options.parse_command_line()
app_server = httpserver.HTTPServer(web.Application(handlers,**server_settings))
app_server.listen(options.options.port)
ioloop.IOLoop.current().start() |
"""
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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.
CVXPY is distributed i... | eate_leq(lh_expr, rh_expr)
self.assertEqual(constr.size, size)
vars_ = get_expr_vars(constr.expr)
ref = [(x.data, size), (y.data, size)]
if PY2:
self.assertItemsEqual(vars_, | ref)
else:
self.assertCountEqual(vars_, ref)
def test_sum_entries(self):
"""Test sum entries op.
"""
size = (5, 5)
x = create_var(size)
expr = sum_entries(x)
self.assertEqual(expr.size, (1, 1))
self.assertEqual(len(expr.args), 1)
s... |
########################################
# Automatically genera | ted, do not edit.
########################################
from pyvisdk.thirdparty import Enum
VirtualDiskAd | apterType = Enum(
'busLogic',
'ide',
'lsiLogic',
)
|
self.d0 = 0.0
self.d1 = 0.0
self.d2 = 0.0
def __getitem__(self, i):
"""
Return the value at the i'th index of the vector.
@param i the vector index
@return the value at the i'th index of the vector.
"""
if i == 0:
return self... | (Node.EPS * Node.EPS)
drabs = sqrt(drsq)
phii = self.mass / drabs
hg.phi0 -= phii
mor3 = phii / drsq
dr *= mor3
hg.acc0 += dr
return hg
class Body(Node):
"""A class used to representing particles in the N-body simulation."""
def __init__(s... | """Create an empty body."""
Node.__init__(self)
self.vel = Vec3()
self.acc = Vec3()
self.new_acc = Vec3()
self.phi = 0.0
def expand_box(self, tree, nsteps):
"""
Enlarge cubical "box", salvaging existing tree structure.
@param tree the root o... |
from random import sample
import os
songList = []
songDict = None
userPlayList = []
directory = ''
def getSongs(name, limit):
global songList
global directory
print('*'*30)
print('* Minerando ', str(limit), ' músicas *')
print('*'*30)
status = 0
if not os.path.exists(directory):
os... | w+'
)
toSaveFile.write('id,title\n')
song | Set = sample(
set(
open(
'config/data/oneMillionSongs/originalCleanEntry/songs.csv',
'r+'
)
), limit
)
for line in songSet:
if (status % 1000 == 0):
print ("-> [", status, "]")
lineSplit = line.split(',')
... |
# -*- coding: utf-8 -*-
from django.core import exceptions
from django.utils.importlib import import_module
__author__ = 'jb'
MIGRATION_MANAGERS = {}
DEFAULT_MANAGER = None
def load_manager(path):
"""
Code taken from django.
Copyright (c) Django Software Foundation and individual contributors.... | and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials pro | vided with the distribution.
3. Neither the name of Django nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIB... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" A script to manage development tasks """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from os import path as p
from manager import Manager
from subprocess import call
manager = Manager()
_basedir = p.d... | d
def test(where=None, stop=False):
"""Run nose and script tests"""
opts = '-xv' if stop else '-v'
opts += 'w % | s' % where if where else ''
call([p.join(_basedir, 'helpers', 'test'), opts])
@manager.command
def register():
"""Register package with PyPI"""
call('python %s register' % p.join(_basedir, 'setup.py'), shell=True)
@manager.command
def release():
"""Package and upload a release"""
sdist()
whe... |
"""
Unique place for all runscripts to set the module path.
(i.e. if you have a copy of TEMareels in some place on your
hard disk but not in PYTHONPATH).
NOTE: it is reco | mmended to keep a copy of all TEMareels
module files with your data/analysis, as future versions
will be not necessarily backwards compatible.
Copyright (c) 2013, rhambach.
This file is part of the TEMareels package and released
under th | e MIT-Licence. See LICENCE file for details.
"""
# location of the TEMareels package on the hard disk
# (if not specified in PYTHONPATH)
pkgdir = '../..';
import sys
from os.path import abspath;
sys.path.insert(0,abspath(pkgdir));
|
import _plot | ly_utils.basevalidators
class SourceattributionValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="sourceattribution",
parent_name="layout.mapbox.layer",
**kwargs
):
super(SourceattributionValidator, self).__init__(
plot... | =parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
role=kwargs.pop("role", "info"),
**kwargs
)
|
# coding=utf-8
"""
InaSAFE Disaster risk assessment tool by AusAid - **Clipper test suite.**
Contact : ole.moller.nielsen@gmail.com
.. note:: 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... | re.layers()
self.assertEqual(len(layers), 1)
self.assertIn(layer_name, layers)
# Add the same layer with another name.
layer_name = 'another_vector_flood'
result = data_store.add_layer(vector_layer, layer_name)
self.assertTrue(result[0])
# We should have two lay... | expected = path.absoluteFilePath() + '|layername=' + layer_name
self.assertEqual(data_store.layer_uri(layer_name), expected)
# Test a fake layer.
self.assertIsNone(data_store.layer_uri('fake_layer'))
# Test to add a raster
layer_name = 'raster_flood'
layer = standard_da... |
lf._g_upper = None
self._g_lower = None
try:
self.nlte_species = self.plasma_parent.nlte_species
except:
self.nlte_species = nlte_species
def get_g_lower(self, g, lines_lower_level_index):
if self._g_lower is None:
g_lower = np.array(g.ix[lines_lo... | _emission_factor
class TauSobolev(ProcessingPlasmaProperty):
"""
Attributes
----------
tau_sobolev : Pandas DataFrame, dtype float
Sobolev optical depth for each line. Indexed by line.
Columns as zones.
"""
outputs = ('tau_sobo | levs',)
latex_name = ('\\tau_{\\textrm{sobolev}}',)
latex_formula = ('\\dfrac{\\pi e^{2}}{m_{e} c}f_{lu}\\lambda t_{exp}\
n_{lower} \\Big(1-\\dfrac{g_{lower}n_{upper}}{g_{upper}n_{lower}}\\Big)',)
def __init__(self, plasma_parent):
super(TauSobolev, self).__init__(plasma_parent)
sel... |
#!/usr/bin/env python
"""
Get an action by name (name is not a supported selector for action)
"""
# import the basic python packages we need
import os
import sys
import tempfile
import pprint
import traceback
# disable python from generating a .pyc file
sys.dont_write_bytecode = True
# change me to the path of pytan ... | class
kwargs = {}
kwargs["objtype"] = u'action'
kwargs["name"] = u'Distribute Tanium Standard Utilities'
print "...CALLING: handler.get() with args: {}".format | (kwargs)
try:
handler.get(**kwargs)
except Exception as e:
print "...EXCEPTION: {}".format(e)
# this should throw an exception of type: pytan.exceptions.HandlerError
# uncomment to see full exception
# traceback.print_exc(file=sys.stdout)
'''STDOUT from running this:
...CALLING: pytan.handler() with... |
from . import base
from grow.common import utils
from protorpc import messages
import logging
import os
import re
if utils.is_appengine():
sass = None # Unavailable on Google App Engine.
else:
import sass
SUFFIXES = frozenset(['sass', 'scss'])
SUFFIX_PATTERN = re.compile('[.](' + '|'.join(map(re.escape, SUFF... | _fullname, 'w') as css_file:
if isinstance(css, unicode):
| css = css.encode('utf-8')
css_file.write(css)
result[sass_fullname] = css_fullname
elif os.path.isdir(sass_fullname):
css_fullname = os.path.join(css_path, name)
subresult = self.build_directory(sass_fullname, css_fullname,
... |
sCLI'
copyright = u'2014'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
import hdfs
# The short X.Y version.
version = hdfs.__version__.rsplit('.', 1)[0]
# The full version, including alpha... | or the epub file. It defaults to the project name.
#epub_basename = u'hdfs'
# The HTML theme for the epub output. Since the default themes are not opt | imized
# for small screen space, using the same theme for HTML and epub output is
# usually not wise. This defaults to 'epub', a theme designed to save visual
# space.
#epub_theme = 'epub'
# The language of the text. It defaults to the language option
# or en if the language is not set.
#epub_language = ''
# The sche... |
from __future__ import print_function, unicode_literals, division, absolute_import
import os
import sys
import string
import random
import hashlib
import logging
import subprocess
from io import StringIO
import config
def valid_path(path):
"""
Returns an expanded, absolute path, or None if the path does not ... | ath)[0]
# Get a list of the archive's contents
contents = list_contents(rar_file_path)
extracted_files = []
# Extract the archive
command = ' | "{unrar}" x -o+ -- "{file}" "{destination}"'
command = command.format(unrar=config.UNRAR_PATH, file=rar_file_path, destination=destination_dir)
logging.debug(command)
try:
subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError as e:
o... |
"""Config flow for TP-Link."""
from __future__ import annotations
from typing import Any
from kasa import SmartDevice, SmartDeviceException
from kasa.discover import Discover
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components import dhcp
from homeassistant.const import CO... | discovery_confirm()
async def async_step_discovery_confirm(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Confirm discovery."""
assert self._discovered_device is not None
if user_input is not None:
return self._async_crea | te_entry_from_device(self._discovered_device)
self._set_confirm_only()
placeholders = {
"name": self._discovered_device.alias,
"model": self._discovered_device.model,
"host": self._discovered_device.host,
}
self.context["title_placeholders"] = placeho... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python | 如何生成 200 个激活码(或者优惠券)?
import random
import string
def activation_code(chars = string.ascii_uppercase + string.digits, length=16):
return ''.join([random.choice(char | s) for i in range(length)])
if __name__ == '__main__':
code_collection = set()
for i in range(200):
code = activation_code()
if code not in code_collection:
code_collection.add(code)
else:
continue
|
"""
Simple http server to create streams for asyncio tests
"""
import asyncio
import aiohttp
from aiohttp import web
import codecs
from utils.streamdecoder import DecodingStreamReader
async def get_data(host, port):
url = 'http://{}:{}/'.format(host, port)
decoder = codecs.getincrementaldecoder('utf-8')(erro... | ORT = '56789'
loop = asyncio.get_event_loop()
server = UTF8Server()
server.start_server(loop, HOST, PORT)
print("serving on", server.srv.sockets[0].getsockname())
try:
task = asyncio.ensure_future(get_data(HOST, PORT)) |
loop.run_until_complete(task)
finally:
server.stop_server(loop)
loop.close()
|
../../../../../../share/pyshared/twi | sted/pers | isted/journal/base.py |
__author | __ = 'mFoxRU'
import scipy.signal as sps
from abstractwavelet import AbstractWavelet
class Ricker(AbstractWavelet):
name = 'Ricker(MHAT)'
params = {}
def fn(self):
return sps.rick | er
|
.option.global_options import GlobalOptions
from pants.option.optionable import Optionable
from pants.option.options import Options
from pants.option.scope import GLOBAL_SCOPE, ScopeInfo
from pants.util.dirutil import read_file
from pants.util.memo import memoized_method, memoized_property
from pants.util.ordered_set i... | ef set(self):
self._value = True
def __bool__(self):
return self._value
is_v2_exclusive = IsV2Exclusive()
@dataclass(frozen=True)
class OptionsBootstrapper:
"""Holds the result of the first stage of options parsing, and assists with parsing full
options."""
env_tuples: Tuple[Tuple[... | Tuple[str, ...]
args: Tuple[str, ...]
config: Config
@staticmethod
def get_config_file_paths(env, args) -> List[str]:
"""Get the location of the config files.
The locations are specified by the --pants-config-files option. However we need to load the
config in order to proces... |
import redis
class RedisAdapter:
storage = None
host = None
port = None
def __init__(self, host, port):
if not self.storage:
self.sto | rage = redis.StrictRedis(host=host, port=int(port), db=0)
def get_storage(self) | :
return self.storage
|
#
# Copyright (c) 2013 Red Hat, 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 t... | ass DictUtils(object):
'''
Provides dict services
'''
@staticmethod
def exclude(dct, keys=[]):
"""
Removes given items from the disct
@param dct: the ditc to look at
@param keys: the keys of items to pop
@return | : updated dict
"""
if dct:
for key in keys:
if dct.has_key(key):
dct.pop(key)
|
import os
import numpy
from numpy.distutils.misc_util impor | t Configuration
def configuration(parent_package="", top_path=None):
config = Configuration("tree", parent_package, top_path)
libraries = []
if os.name == 'posix':
libraries.append('m')
config.add_extension("_tree",
sources=["_tree.c"],
include... | extra_compile_args=["-O3"])
config.add_subpackage("tests")
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().todict())
|
sts", dest="showTests",
help="Show all discovered tests",
action="store_true", default=False)
group.add_option("", "--use-processes", dest="useProcesses",
help="Run tests in parallel with processes (not threads)",
action="store_... |
if not args:
parser.error('No inputs specified')
if opts.numThreads is None:
# Python <2.5 has a race condition causing lit to always fail with numThreads>1
# http://bugs.python.org/issue1731717
# I haven't seen this bug occur with 2.5.2 and later, so only enable multiple
# threads by defau | lt there.
if sys.hexversion >= 0x2050200:
opts.numThreads = lit.util.detectCPUs()
else:
opts.numThreads = 1
inputs = args
# Create the user defined parameters.
userParams = dict(builtinParameters)
for entry in opts.userParameters:
if '=' not in entry... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.