repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
blorenz/indie-film-rentals
indiefilmrentals/products/processors.py
Python
bsd-3-clause
169
0.017751
from indiefilmrentals
.products.models import * from shop_simplecategories.models import * def categories(request): return {'categories': Category.o
bjects.all()}
owlabs/incubator-airflow
docs/conf.py
Python
apache-2.0
17,740
0.001522
# -*- coding: utf-8 -*- # flake8: noqa # Disable Flake8 because of all the sphinx imports # # 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 licens...
flow/lineage', '_api/airflow/logging_config', '_api/airflow/macros', '_api/airflow/migrations', '_api/airflow/plugins_manager', '_api/airflow/security', '_api/airflow/serialization', '_api/airflow/settings', '_api/airflow/sentry', '_api/airflow/stats', '_api/airflow/task', '_...
oapi_templates', 'howto/operator/gcp/_partials', ] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended ...
NelisVerhoef/scikit-learn
doc/sphinxext/gen_rst.py
Python
bsd-3-clause
40,198
0.000697
""" Example generation for the scikit learn Generate the rst files for the examples by iterating over the python example files. Files that generate images should start with 'plot' """ from __future__ import division, print_function from time import time import ast import os import re import shutil import traceback i...
value[i] = int(value[i]) except ValueError: pass elif dict_str[pos + 1] == '{': # value is another dictionary subdict_str = _select_block(dict_str[pos:], '{', '}') value = _parse_dict_recursive(sub...
raise ValueError('error when parsing dict: unknown elem') key = key.strip('"') if len(key) > 0: dict_out[key] = value pos_last = dict_str.find(',', pos_tmp) if pos_last < 0: break pos_last += 1 pos = ...
smallyear/linuxLearn
salt/salt/proxy/junos.py
Python
apache-2.0
1,727
0.001158
# -*- 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 # Import 3rd-party libs import jnpr.junos import jnpr.junos.utils import jnpr.junos.utils.config import json HAS_JUNOS = Tru...
isproxy['conn'].connected def shutdown(opts): ''' This is called when the proxy-minion is exiting to make sure the connection to the device is closed cleanly. ''' log.debug('Proxy module {0} shutting down!!'.format(opts['id'])) try: thisproxy['conn'].close() except Exception: ...
roxy['conn'].rpc.get_software_information())
Learning-from-our-past/Kaira
qtgui/xmlImport.py
Python
gpl-2.0
4,469
0.005147
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): ...
"Extraction failed", errMessage + str(e)) msgbox.show() @pyqtSlot(dict) def _processFinished(self, result): self.result = result self.finishedSignal.emit(self.result, self.filepath) def _processUpdateCallback(self, i, max): self.threadUpdateSignal.emit(i, max) def _g...
arser(encoding="utf-8") tree = etree.parse(filepath, parser=parser) #ET.parse(filepath) return tree.getroot() class MetadataException(Exception): def __init__(self): self.msg = "ERROR: The document doesn't contain bookseries attribute in the beginning of the file. Couldn't import. Try " \...
semiirs/ai_project
common/experience.py
Python
gpl-3.0
462
0.002165
import datetime 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") exp = Experience(date, event) return exp def time_from_this_event(self, event): return self._date - event._date
google/gnxi
oc_config_validate/oc_config_validate/models/macsec.py
Python
apache-2.0
391,144
0.007626
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType fr
om pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListType fr
om pyangbind.lib.yangtypes import YANGDynClass from pyangbind.lib.yangtypes import ReferenceType from pyangbind.lib.base import PybindBase from collections import OrderedDict from decimal import Decimal from bitarray import bitarray import six # PY3 support of some PY2 keywords (needs improved) if six.PY3: import bu...
dmlc/tvm
python/tvm/relay/testing/mobilenet.py
Python
apache-2.0
7,444
0.000672
# 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...
shape = (depthwise_channels, 1) + kernel_size elif layout == "NHWC": wshape = kernel_size + (depthwise_channels, 1) else: raise Valu
eError("Invalid layout: " + layout) bn_axis = layout.index("C") weight = relay.var(name + "_weight", shape=wshape, dtype=dtype) conv1 = layers.conv2d( data=data, weight=weight, channels=depthwise_channels, groups=depthwise_channels, kernel_size=kernel_size, st...
thanm/devel-scripts
normalize-dwarf-objdump.py
Python
apache-2.0
10,730
0.014073
#!/usr/bin/python3 """Filter to normalize/canonicalize objdump --dwarf=info dumps. Reads stdin, normalizes / canonicalizes and/or strips the output of objdump --dwarf to make it easier to "diff". Support is provided for rewriting absolute offsets within the dump to relative offsets. A chunk like <2><2d736>: Abbrev ...
n = len(untracked_dwrefs) if flag_normalize: unk = (" <untracked %d>" % (n+1)) else: unk = (" <untracked 0x%s>" % absref) untracked_dwrefs[absref] = unk val = unk if code == 2: val = oval if flag_strip_pcinfo: if attr in pcinfo_attrs: val = "<stripped>" return...
an input line.""" global linebuffered global linebuf if linebuffered: linebuffered = False u.verbose(3, "buffered line is %s" % linebuf) return linebuf line = inf.readline() u.verbose(3, "line is %s" % line.rstrip()) return line def unread_line(line): """Unread an input line.""" global lin...
spektom/incubator-airflow
tests/providers/zendesk/hooks/test_zendesk.py
Python
apache-2.0
5,046
0.000396
# # 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...
nse.headers.get.return_value = sleep_time conn_mock.call = mock
.Mock( side_effect=RateLimitError(msg="some message", code="some code", response=mock_response)) zendesk_hook = ZendeskHook("conn_id") zendesk_hook.get_conn = mock.Mock(return_value=conn_mock) with self.a...
PnEcrins/GeoNature-atlas
atlas/modeles/repositories/vmSearchTaxonRepository.py
Python
gpl-3.0
1,550
0.000647
# -*- 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 !!! """ req = session.query(VmSearchTaxon.search_name, VmSearchTaxon.cd_ref).all() taxonList = list() for r in req: temp = {"label": r[0], "value": r[1]} taxonList.append(temp) return taxonList def listeTaxonsSearch(session, search, limit=50): ...
r 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, ...
ryfx/modrana
core/backports/urllib3_python25/util.py
Python
gpl-3.0
11,071
0.000542
# urllib3/util.py # Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt) # # This module is part of urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from __future__ import absolute_import from base64 import b64encode from socket import error as So...
PROTOCOL_SSLv23 from ssl import SSLContext # Modern SSL?
from ssl import HAS_SNI # Has SNI? except ImportError: pass from .packages import six from .exceptions import LocationParseError, SSLError class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])): """ Datastructure for representing an HTTP URL. Used as a return...
btimby/fulltext
fulltext/backends/__hwp.py
Python
mit
544
0
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([p
ath]) return cmd def to_text_with_backend(html): return __html.handle_fobj(html) class Backend(BaseBackend): def check(self, title): assert_cmd_exists('hwp5proc')
def handle_path(self, path): out = self.decode(run(*cmd(path))) return to_text_with_backend(out)
nttks/edx-platform
common/lib/xmodule/xmodule/seq_module.py
Python
agpl-3.0
13,629
0.001761
""" xModule implementation of a learning sequence """ # pylint: disable=abstract-method import json import logging from pkg_resources import resource_string import warnings from lxml import etree from xblock.core import XBlock from xblock.fields import Integer, Scope, Boolean, Dict from xblock.fragment import Fragme...
d_student_view(context) # Do we have an alternate rendering # from the edx_proctoring subsystem? if view_html: fragment.add_content(view_html) return fragment for child in self.get_display_items(): progress = child.get_progress() ...
ment.add_frag_resources(rendered_child) # `titles` is a list of titles to inject into the sequential tooltip display. # We omit any blank titles to avoid blank lines in the tooltip display. titles = [title.strip() for title in child.get_content_titles() if title.strip()] ...
orf/django-rest-framework-jwt
setup.py
Python
mit
3,404
0
#!/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...
paths} if sys.argv[-1] == 'publish':
if os.system('pip freeze | grep wheel'): print('wheel not installed.\nUse `pip install wheel`.\nExiting.') sys.exit() if os.system('pip freeze | grep twine'): print('twine not installed.\nUse `pip install twine`.\nExiting.') sys.exit() os.system('python setup.py sdist bdist_...
titilambert/home-assistant
homeassistant/components/template/switch.py
Python
apache-2.0
6,023
0.000332
"""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_...
riendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ): """Initialize the Template switch.""" super().__
init__( availability_template=availability_template, icon_template=icon_template, entity_picture_template=entity_picture_template, ) self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) self._name = friendly_n...
CyrusRoshan/lolbuddy
setup.py
Python
mit
674
0.001484
#!/usr/bin/env python3 from setuptools import setup, find_packages version = '0.2.4' setup( name='lolbuddy', version=version, description='a cli tool to update league of legends itemsets and ability order from champion.gg', author='Cyrus Roshan', author_email='hello@cyrusroshan.com', license=...
CyrusR
oshan/lolbuddy', packages=find_packages(), package_data={}, install_requires=[ 'requests-futures >= 0.9.5', ], entry_points={ 'console_scripts': [ 'lolbuddy=lolbuddy:main', ], }, )
KernelAnalysisPlatform/KlareDbg
static2/ida/remoteobj.py
Python
gpl-3.0
16,409
0.016942
#!/usr/bin/env python # remoteobj v0.4, best yet! # TODO: This will get wrecked by recursive sets/lists/dicts; need a more picklish method. # TODO: Dict/sets/lists should get unpacked to wrappers that are local for read-only access, # but update the remote for write access. Note that __eq__ will be an interesting...
', '__reversed__', '__contains__', '__getslice__', '__setslice__', '__delslice__', '__add__', '__sub__', '__mul__', '__floordiv__', '__mod__', '__divmod__', '__pow__', '__lshift__', '__rshift__', '__and__', '__xor__', '__or__', '__div__', '__truediv__', '__radd__', '__rsub__', '__rmul__', '__rdiv__', '__rtruediv__', '_...
loordiv__', '__imod__', '__ipow__', '__ilshift__', '__irshift__', '__iand__', '__ixor__', '__ior__', '__neg__', '__pos__', '__abs__', '__invert__', '__complex__', '__int__', '__long__', '__float__', '__oct__', '__hex__', '__index__', '__coerce__', '__enter__', '__exit__'): exec "def {special}(self, *args, **kwargs)...
dtudares/hello-world
yardstick/yardstick/vTC/apexlake/experimental_framework/api.py
Python
apache-2.0
6,381
0
# 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...
ributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for th
e specific language governing permissions and # limitations under the License. import experimental_framework.benchmarking_unit as b_unit from experimental_framework import heat_template_generation, common class FrameworkApi(object): @staticmethod def init(): """ Initializes the Framework ...
czpython/django-cms
cms/cms_toolbars.py
Python
bsd-3-clause
32,747
0.003237
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib import admin from django.contrib.auth import get_permission_codename, get_user_model from django.contrib.auth.models import AnonymousUser from django.contrib.sites.models import Site from django.core.urlresolvers import reverse, NoReverseMatch...
# admin self._admin_me
nu.add_sideframe_item(_('Administration'), url=admin_reverse('index')) self._admin_menu.add_break(ADMINISTRATION_BREAK) # cms users settings self._admin_menu.add_sideframe_item(_('User settings'), url=admin_reverse('cms_usersettings_change')) self._admin_menu.add_break(U...
dgilland/yummly.py
yummly/models.py
Python
mit
8,795
0
"""Yummly data models. """ from inspect import getargspec class Storage(dict): """An object that is like a dict except `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 =...
args['searchValue']
self.shortDescription = kargs['shortDescription'] self.type = kargs['type'] c
verma-varsha/zulip
zerver/lib/digest.py
Python
apache-2.0
10,690
0.001403
from __future__ import absolute_import from typing import Any, Callable, Dict, Iterable, List, Set, Tuple, Text from collections import defaultdict import datetime import pytz import six from django.db.models import Q, QuerySet from django.template import loader from django.conf import settings from django.utils.time...
] for elt in diversity_list[:2]] for candidate, _ in length_list: if candidate not in hot_conversations: hot_conversations.append(candidate) if len(hot_conversations) >= 4: break # There was so much overlap between the diversity and length lists that we # still have ...
iversity items to pad # out the hot conversations. num_convos = len(hot_conversations) if num_convos < 4: hot_conversations.extend([elt[0] for elt in diversity_list[num_convos:4]]) hot_conversation_render_payloads = [] for h in hot_conversations: stream_id, subject = h users...
muraliselva10/cloudkitty
cloudkitty/tests/gabbi/rating/pyscripts/test_gabbi.py
Python
apache-2.0
1,187
0
# -*- 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 ...
mplied. See the # License for the specific language governing permissions and limitations # under the License. # # @author: Stéphane Albert # import os from gabbi import driver from cloudkitty.tests.gabbi import fixtures from cloudkitty.tests.gabbi.rating.pyscripts import fixtures as py_fixtures TESTS_DIR = 'g...
loader, host=None, intercept=fixtures.setup_app, fixture_module=py_fixtures)
vals/google_devnull
tasks.py
Python
mit
361
0.00831
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(de
lay 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
ajagnanan/docker-opencv-api
openface/images/collapse.py
Python
apache-2.0
465
0.004301
# 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 matc...
1
ysrc/xunfeng
views/lib/QueryLogic.py
Python
gpl-3.0
2,319
0.002621
# -*- 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 # 搜索逻辑 def querylogic(list): query = {} if len(list) > 1 or len(list[0].split(':')) > 1: for _ in list: if _.find(':') > -1: q_key, q_valu...
elif q_key == 'banner': zhPattern = re.compile(u'[\u4e00-\u9fa5]+') contents = q_value match = zhPattern.search(contents) # 如果没有中文用全文索引 if match: query['banner'] = {"$regex": q_value, '$options':...
sighill/shade_app
apis/raw/005_raw/005_cleaner.py
Python
mit
1,625
0.015423
# 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 , ...
ing the string into a list raw_list = raw_string_with_cr.splitlines() # going through oddities finder AddL
og('subtitle' , 'Début de la fonction OdditiesFinder') list_without_oddities = OdditiesFinder( raw_list ) # going through string formatter ref_list = [] AddLog('subtitle' , 'Début de la fonction StringFormatter') for line in list_without_oddities: ref_list.append( StringFormatter( line ) ) ###################...
kron4eg/django-btt
settings.py
Python
gpl-3.0
39
0
PE
R_PAGE = 50 ANNOUNC
E_INTERVAL = 300
benjamincongdon/adept
tradingUI.py
Python
mit
3,586
0.037646
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...
TradingUI: BUTTON_SIZE = 32 PADDING = 6 def __init__(self, inventory, tradeSet): self.tradeSet = tradeSet self.inventory = inventory self.surface = utils.empty_surface((228,500)) self.surface.fill((100,100,100,100)) self.pos = (utils.SCREEN_W / 2 + self.surface.get_width() / 2 + 350, utils.SCREEN_H / 2 ...
adeTable(self): self.surface = utils.empty_surface((228,500)) self.surface.fill((100,100,100,100)) self.tileRects = list() self.tileTrades = list() tradeTiles = list() total_y = 0 for t in self.tradeSet: newTile = self.generateTradeTile(t) tradeTiles.append(newTile) self.tileRects.append(pygame.R...
albatros69/Divers
scrap_ffme.py
Python
gpl-3.0
3,373
0.006235
#!/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...
R-CALNAME", "Calendrier formations FFME") urls = ('http://www.ffme.fr/formation/calendrier-liste/FMT_ESCSAE.html', 'http://www.ffme.fr/formation/calendrier-liste/
FMT_ESCSNE.html', #'http://www.ffme.fr/formation/calendrier-liste/FMT_ESCFCINI.html', 'http://www.ffme.fr/formation/calendrier-liste/FMT_ESCMONESP.html', ) for u in urls: for d in scrape_url(u): cal.add_component(create_event_formation(d)) with open('cal_formation.ics', 'w') as f: f.wri...
DonaldWhyte/multidimensional-search-fyp
scripts/read_multifield_dataset.py
Python
mit
1,612
0.030397
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...
{}".format(numDimensions, numPoints)) # Output dataset header which defines dimensionality of data and number of points # Read entire file line-by-line, printing out each line as a point with open(datasetFilename, "r") as f: pointsRead = 0 line = f.readline() while line: fields = line.split() floatField...
is maximum number of points have been read pointsRead += 1 if maxPoints and pointsRead >= maxPoints: break # Read next line of file line = f.readline()
valefranz/AI-Project-VacuumEnvironment
aima-ui-2a.py
Python
apache-2.0
17,529
0.000628
''' aima-ui project ============= This is just a graphic user interface to test agents for an AI college course. ''' from kivy.uix.button import Button from kivy.uix.togglebutton import ToggleButton from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.uix.label import Label from kivy.uix.b...
:d}".format(self.scoreB)) def update_canvas(self, labels, wid, *largs): """Update the canvas to respect the environment.""" wid.canvas.clear() self.counter.text = str(self.counter_steps) n_x, n_y = max([thing.location for thing in self.env.things]) tile_x = wid.width / float...
t(n_y + 1) labelA, labelB = labels with wid.canvas: for thing in [thing for thing in self.env.things if isinstance(thing, Dirt) or isinstance(thing, Clean)]: pos_x, pos_y = thing.location if isinstance(thing,...
obi1kenobi/pyre
WiFiMouse/wifimouse_driver.py
Python
mit
2,923
0.002053
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'...
+ str(moveY)) currY -= moveY 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) ...
Caerostris/marathon
tests/system/marathon_auth_common_tests.py
Python
apache-2.0
2,070
0.004831
""" 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...
ter:service:marathon', uid='billy', action='full') shakedown.set_user_permission(rid='dcos:service:marathon:marathon:services:/', uid='billy', action='full') yield shakedown.remove_user_permission(rid='dcos:adminrouter:service:marathon', uid='billy', action='full') shakedown.remove_user_permission(rid='...
) @pytest.mark.usefixtures('credentials') def test_authorized_non_super_user(billy): with shakedown.dcos_user('billy', 'billy'): client = marathon.create_client() len(client.get_apps()) == 0
noam09/kodi
script.module.israeliveresolver/lib/interalSimpleDownloader.py
Python
gpl-3.0
10,978
0.017216
import xml.etree.ElementTree as etree import base64 from struct import unpack, pack import sys import io import os import time import itertools import xbmcaddon import xbmc import urllib2,urllib import traceback import urlparse import posixpath import re import socket from flvlib import tags from flvlib import helper...
req.set_proxy(self.proxy, 'http') response = openner.open(req) return response except: #print 'Error in getUrl' traceback.print_exc() return None def getUrl(self,url, ischunkDownloading=False): try: post=None openner...
else: req = urllib2.Request(url) ua_header=False if self.clientHeader: for n,v in self.clientHeader: req.add_header(n,v) if n=='User-Agent': ua_header=True if not...
Solthis/Fugen-2.0
data/indicators/lost_back_patients.py
Python
gpl-3.0
3,277
0.000305
# 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 # 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 ver...
ame(self, limit_date, start_date=None, include_null_dates=False): lost_prev = LostPatient
s(self.fuchia_database) arv_started = ArvStartedPatients(self.fuchia_database) n_limit = limit_date - relativedelta(months=1) n_start = start_date - relativedelta(months=1) i = (lost_prev & arv_started) prev_lost_patients = i.get_filtered_patients_dataframe( getLastDa...
openstenoproject/plover
plover/engine.py
Python
gpl-2.0
20,307
0.00064
from collections import namedtuple, OrderedDict from functools import wraps from queue import Queue import os import shutil import threading from plover import log, system from plover.dictionary.loading_manager import DictionaryLoadingManager from plover.exception import DictionaryLoaderException from plover.formatti...
es): '''Recreate default dictionaries. Each default dictionary is recreated if it's in use by the current config and missing. ''' for dictionary in dictionaries_files: # Ignore assets. if dictionary.startswith(ASSET_SCHEME): continue # Nothing to do if dictiona
ry file already exists. if os.path.exists(dictionary): continue # Check it's actually a default dictionary. basename = os.path.basename(dictionary) if basename not in system.DEFAULT_DICTIONARIES: continue default_dictionary = os.path.join(system.DICTIONARI...
thisfred/breakfast
tests/test_attempt_12.py
Python
bsd-2-clause
21,250
0.000659
import ast from collections import defaultdict from contextlib import ExitStack, contextmanager from functools import singledispatch from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Union from breakfast.position import Position from breakfast.source import Source from tests import make_source Qua...
and is_method and not is_static_method(node):
with state.scope("."): state.alias(("..", "..", "..", "..")) generic_visit(node, source, state) @visit.register def visit_class(node: ast.ClassDef, source: Source, state: State) -> None: position = node_position(node, source, column_offset=len("class "))...
CHT5/program-y
src/programy/config/brain.py
Python
mit
8,932
0.007053
""" Copyright (c) 2016 Keith Sterling 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, merge, publish, distribute,...
self._triples = self._get_file_option(config_file, "triples", files, bot_root) self._preprocessors = self._get_file_option(config_file, "preprocessors", files, bot_root) self._postprocessors = self._get_f
ile_option(config_file, "postprocessors", files, bot_root) else: logging.warning("Config section [files] missing from Brain, default values not appropriate") raise Exception ("Config section [files] missing from Brain") services = config_file.get_section("service...
mindflayer/python-mocket
mocket/plugins/httpretty/__init__.py
Python
bsd-3-clause
3,152
0.000317
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...
Pretty :)", adding_headers=None, forcing_headers=None, status=200, responses=None, match_querystring=False, priority=0, **headers ): headers = httprettifier_headers(headers) if adding_headers is not None: headers.update(httprettifier_headers(adding_headers)) if forcing...
nse.set_base_headers = force_headers else: Response.set_base_headers = Response.original_set_base_headers if responses: Entry.register(method, uri, *responses) else: Entry.single_register( method, uri, body=body, status=status, ...
jawilson/home-assistant
homeassistant/components/smartthings/switch.py
Python
apache-2.0
1,911
0.000523
"""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...
"""Turn the switch off.""" await self._device.switch_off(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() async def async_turn_on(self, **kwargs)...
"Turn 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: """...
OKThess/website
main/migrations/0063_event_date_end.py
Python
mit
469
0
#
-*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-05-30 17:02 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0062_auto_20171223_1552'), ] operations = [ migrations.AddField( ...
='event', name='date_end', field=models.DateField(blank=True, default=None, null=True), ), ]
dpressel/baseline
baseline/pytorch/lm/model.py
Python
apache-2.0
11,032
0.001813
from baseline.pytorch.torchy import * from eight_mile.pytorch.layers import TransformerEncoderStack, subsequent_mask, MultiHeadedAttention from baseline.model import LanguageMode
l, register_model from eight_mile.pytorch.serialize import load_tlm_npz import torch.autograd import os class LanguageModelBase(nn.Module, LanguageModel): def __init__(self): super().__init__() def save(self, outname): torch.save(self, outname) basename, _ = os.path.splitext(outname) ...
def create_loss(self): return SequenceCriterion(LossFn=nn.CrossEntropyLoss) @classmethod def load(cls, filename, **kwargs): device = kwargs.get('device') if not os.path.exists(filename): filename += '.pyt' model = torch.load(filename, map_location=device) mo...
Raynes/quarantine
quarantine/__main__.py
Python
apache-2.0
719
0.002782
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(name, pip_args): """Install the package. Pip args specified with...
the package, environment and all.""" cdc
= CDC(name) cdc.uninstall() if __name__ == '__main__': quarantine()
ksrajkumar/openerp-6.1
openerp/osv/orm.py
Python
agpl-3.0
245,233
0.004592
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
in_tree_view) transfer_modifiers_to_node(
modifiers, node) def test_modifiers(what, expected): modifiers = {} if isinstance(what, basestring): node = etree.fromstring(what) transfer_node_to_modifiers(node, modifiers) simplify_modifiers(modifiers) json = simplejson.dumps(modifiers) assert json == expected, "%s !=...
Alex-Chizhov/python_training
home_works/data/contacts.py
Python
apache-2.0
166
0.018072
from model.info_contact import
Infos testdata = [ Infos(firstname="firstname
1",lastname="lastname1"), Infos(firstname="firstname2",lastname="lastname2") ]
vfulco/scalpel
lib/gravity/tae/match/__init__.py
Python
lgpl-3.0
94
0.031915
#__all__ = [ 'search', 'ham_distance', 'lev_distance', 'distance', 'distance_matrix' ]
b1-systems/kiwi
test/unit/storage/subformat/vhdx_test.py
Python
gpl-3.0
1,314
0
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_...
def test_create_image_format(self, mock_command): self.disk_format.create_i
mage_format() mock_command.assert_called_once_with( [ 'qemu-img', 'convert', '-f', 'raw', 'target_dir/some-disk-image.x86_64-1.2.3.raw', '-O', 'vhdx', '-o', 'subformat=dynamic', 'target_dir/some-disk-image.x86_64-1.2.3.vhdx' ...
Ma3X/boot-talker
codes/python/talk.py
Python
gpl-3.0
19,742
0.020819
#!/usr/bin/env python # -*- coding: utf-8 -*- DEBUG = True observer = None ser_port = None s = 0 ser = None #-------------------------------------------------------------------- import signal import sys import os def signal_handler(
signal, frame): glob
al s, ser print '\nYou pressed Ctrl+C!' if s > 18: print "MTK_Finalize" serialPost(ser, "B7".decode("hex")) time.sleep(0.1) if ser.isOpen(): ser.close() #sys.exit(0) os._exit(0) signal.signal(signal.SIGINT, signal_handler) #--------------------------------------------------------...
tomachalek/kontext
lib/plugins/abstract/chart_export.py
Python
gpl-2.0
3,124
0
# 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 #...
""" return a content type identifier (e.g. 'application/json') """ raise NotImplementedError() def get_format_name(self): """ Return a format identifier. It should be both human-readable and unique within a single plug-in installation. It means that in c...
ns it may be necessary to modify some names to keep all the export functions available. """ raise NotImplementedError() def get_suffix(self): """ Return a proper file suffix (e.g. 'xlsx' for Excel). """ raise NotImplementedError() def export_pie_...
SiddharthSham/PetAteMyHW
wolfram.py
Python
gpl-3.0
692
0.023121
import config #This module is used for calling the Wolfram Alpha API #It defines a funct
ion that constructs an URL based on the query. #NOTE: This module returns only the URL. This URL is passed in the bot.py file. Telegram Takes care of the rest. de
f query(query): question = query.replace(" ","+") #plus encoding return "http://api.wolframalpha.com/v1/simple?appid={}&i=".format(config.WOLFRAM) + question + "&format=image" #returns ONLY the URL directly. ...
vesgel/quicknotes
plasmoid/contents/code/main.py
Python
gpl-3.0
1,970
0.001015
#!/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...
ckgroundHints(Plasma.Applet.DefaultBackground) """ self.setBackgroundHints(Plasma.Applet.NoBackground) self.__createMainLayout() width = self.viewerSize.width() + 20 height = self.viewerSize.height() - 20 self.
resize(width, height) def __createMainLayout(self): self.mainLayout = QGraphicsLinearLayout(Qt.Vertical, self.applet) noteview = Plasma.TreeView(self.applet) noteview.setStyleSheet("QTreeView { background: Transparent }") nmodel = NoteModel(self.package().path(), noteview) ...
YannickJadoul/Parselmouth
pybind11/tests/test_kwargs_and_defaults.py
Python
gpl-3.0
10,048
0.001393
# -*- coding: utf-8 -*- import pytest import env # noqa: F401 from pybind11_tests import kwargs_and_defaults as m def test_function_signatures(doc): asse
rt doc(m.kw_func0) == "kw_func0(arg0: int, arg1: int) -> str" assert doc(m.kw_func1) == "
kw_func1(x: int, y: int) -> str" assert doc(m.kw_func2) == "kw_func2(x: int = 100, y: int = 200) -> str" assert doc(m.kw_func3) == "kw_func3(data: str = 'Hello world!') -> None" assert doc(m.kw_func4) == "kw_func4(myList: List[int] = [13, 17]) -> str" assert doc(m.kw_func_udl) == "kw_func_udl(x: int, y:...
vgripon/PyRat
imports/dummyplayer.py
Python
gpl-3.0
440
0.018182
import random def preprocessing(mazeMap, mazeWidth, mazeHeight, playerLocation, opponentLocation, piecesOfCheese, timeAllowed): retur
n def turn (mazeMap, mazeWidth, mazeHeight, playerLocation, opponentLocation, playerScore, opponentScore, piecesOfCheese, timeAllowed): return def postprocessing (mazeMap, mazeWidth, mazeHeight, play
erLocation, opponentLocation, playerScore, opponentScore, piecesOfCheese, timeAllowed): return
noox-/stbgui-1
lib/python/Plugins/Extensions/GraphMultiEPG/GraphMultiEpg.py
Python
gpl-2.0
40,917
0.034216
from skin import parseColor, parseFont, parseSize from Components.config import config, ConfigClock, Con
figInteger, Confi
gSubsection, ConfigYesNo, ConfigSelection, ConfigSelectionNumber from Components.Pixmap import Pixmap from Components.Button import Button from Components.ActionMap import HelpableActionMap from Components.HTMLComponent import HTMLComponent from Components.GUIComponent import GUIComponent from Components.EpgList import...
hiuwo/acq4
acq4/pyqtgraph/parametertree/Parameter.py
Python
mit
29,533
0.009142
from ..Qt import QtGui, QtCore import os, weakref, re from ..pgcollections import OrderedDict from .ParameterItem import ParameterItem PARAM_TYPES = {} PARAM_NAMES = {} def registerParameterType(name, cls, override=False): global PARAM_TYPES if name in PARAM_TYPES and not override: raise Exception("Pa...
opt:val, ...} ## Emitted when anything changes about this parameter at all. ## The second argument is a string indicating what changed ('value', 'childAdded', etc..) ## The third argument can be any extra information about the change sigStateChanged = QtCore.Signal(object, object, object) ## self, ...
QtCore.Signal(object, object) # self, changes # changes = [(param, change, info), ...] # bad planning. #def __new__(cls, *args, **opts): #try: #cls = PARAM_TYPES[opts['type']] #except KeyError: #pass ...
deffi/protoplot
protoplot/engine/item.py
Python
agpl-3.0
6,684
0.006882
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...
en(self): return [(name, attrib
ute) for name, attribute in self.__dict__.items() if isinstance(attribute, Item)] def containers(self): return [(name, attribute) for name, attribute in self.__dict__.items() if isinstance(attribute, ItemContainer)] ############# ## Options ## #...
nwjs/chromium.src
testing/unexpected_passes_common/result_output.py
Python
bsd-3-clause
21,925
0.007206
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Methods related to outputting script results in a human-readable format. Also probably a good example of how to *not* write HTML. """ from __future__ imp...
ance(semi_stale_dict, data_types.TestExpectationMap) assert isinstance(active_dict, data_types.TestExpectationMap) logging.info('Outputting results in format %s', output_format) stale_str_dict = _ConvertTestExpectationMapToStringDict(stale_dict) semi_stale_str_dict = _ConvertTestExpectationMapToStringDict(semi_...
ults) unused_expectations_str_list = _ConvertUnusedExpectationsToStringDict( unused_expectations) if output_format == 'print': file_handle = file_handle or sys.stdout if stale_dict: file_handle.write(SECTION_STALE + '\n') RecursivePrintToFile(stale_str_dict, 0, file_handle) if semi_st...
jaliste/sanaviron
sanaviron/ui/gradienteditor.py
Python
apache-2.0
10,331
0.00242
#!/usr/bin/python # -*- coding: utf-8 -*- import gtk from objects.gradientcolor import GradientColor from objects.gradient import Gradient from interfaces.signalizable import Signalizable class GradientLine(gtk.Viewport): def __init__(self, moving_callback=None, color_callback=None, gradient=None): """ ...
self.gradient.update() self.queue_draw() return True def enter(self, widget, event): return True def leave(self, widget, event): self._motion = False self.x = event.x self.queue_draw() return True def press(self, widget, event): ...
f.move = True cnt = len(self.gradient.colors) if cnt > 0: for col in range(0, cnt): if (self.gradient.colors[col].position > (event.x / self.width - 0.01)) and ( self.gradient.colors[col].position < (event.x / self.width + 0.01)): self....
GoogleCloudPlatform/declarative-resource-client-library
python/services/identitytoolkit/beta/tenant.py
Python
apache-2.0
10,862
0.002025
# Copyright 2022 Google LLC. 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 applicable law o...
up ) self.enable_email_link_signin = Primitive.from_proto( response.enable_email_link_signin ) self.disable_auth = Primitive.from_proto(response.disable_auth) self.enable_anonymous_user = Primitive.from_proto( response.enable_anonymous_user ) ...
se.test_phone_numbers) self.project = Primitive.from_proto(response.project) def delete(self): stub = tenant_pb2_grpc.IdentitytoolkitBetaTenantServiceStub(channel.Channel()) request = tenant_pb2.DeleteIdentitytoolkitBetaTenantRequest() request.service_account_file = self.service_acc...
debuggerman/gitstats.py
gitstats.py
Python
mit
344
0.031977
import urllib2 import base64 import json from li
nk 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.getOr
gInfo()
pienkowb/omelette
omelette/fromage/test/data/node.py
Python
gpl-3.0
175
0.005714
from omelette.fromage.common import Draw
ableNode c
lass DrawableNode(DrawableNode): def __init__(self, uml_object): super(DrawableNode, self).__init__(uml_object)
arkadoel/AprendiendoPython
PrimerosPasos/dos.py
Python
gpl-3.0
579
0.018998
''' Created on 20/10/2014 @author: fer ''' if __name__ == '__main__': print('hola') x=32 #entero print x # variabl
e 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(calculo).__name__) ''' Conversion de tipos ''' entero = ...
) print type(cadena) pass
runt18/nupic
src/nupic/frameworks/opf/metrics.py
Python
agpl-3.0
54,801
0.012992
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
ion(metricSpec) elif metricName == 'altMAPE': return MetricAltMAPE(metricSpec) elif metricName == 'MAPE': return MetricMAPE(metricSpec) elif metricName == 'multi': return MetricMulti(metricSpec) elif metricName == 'negativeLogLikelihood': return MetricNegativeLogLikelihood(metricSpec) else: ...
############################################################################### # Helper Methods and Classes # ################################################################################ class _MovingMode(object): """ Helper class for computing windowed moving ...
morphis/home-assistant
homeassistant/components/camera/synology.py
Python
apache-2.0
8,436
0.000119
""" Support for Synology Surveillance Station Cameras. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/camera.synology/ """ import asyncio import logging import voluptuous as vol import aiohttp import async_timeout from homeassistant.cons...
'passwd': password, 'session': 'SurveillanceStation',
'format': 'sid' } auth_req = None try: with async_timeout.timeout(TIMEOUT, loop=hass.loop): auth_req = yield from websession.get( login_url, params=auth_payload ) auth_resp = yield from auth_req.json() return a...
akshaykurmi/reinforcement-learning
atari_breakout/per.py
Python
mit
4,539
0.000881
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...
le(self, batch_size): self.beta = np.min([1., self.beta + self.beta_annealing_rate]) priority_segment =
self.tree.total_priority / batch_size min_probability = self.tree.min_priority / self.tree.total_priority max_weight = (min_probability * batch_size) ** (-self.beta) samples, sample_indices, importance_sampling_weights = [], [], [] for i in range(batch_size): value = np.rand...
instinct-vfx/rez
src/rez/cli/plugins.py
Python
apache-2.0
1,176
0
# 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") PKG_action = parser.add_argument( "PKG", type=str, help="package to list plugins for") if completions: from rez.cli._complete_util import PackageFamilyCompleter PKG_action.comp
leter = 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: ...
joachimmetz/dfvfs
tests/vfs/apfs_file_entry.py
Python
apache-2.0
30,722
0.002181
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the file entry implementation using pyfsapfs.""" import unittest from dfvfs.lib import definitions from dfvfs.path import factory as path_spec_factory from dfvfs.resolver import context from dfvfs.resolver import resolver from dfvfs.vfs import apfs_attribute ...
ne(file_entry) self.assertEqual(file_entry.name, 'another_file') def testSize(self): """Test the size property.""" path_spec = path_spec_factory.Factory.NewPathSpec( definitions.TYPE_INDICATOR_APFS, identifier=self._IDENTIFIER_ANOTHER_FILE, location='/a_directory/another_file', ...
parent=self._apfs_container_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) self.assertEqual(file_entry.size, 22) def testGetAttributes(self): """Tests the _GetAttributes function.""" path_spec = path_spec_factory.Factory.NewPathSp...
bikashgupta11/javarobot
src/main/resources/jython/Lib/xml/etree/ElementTree.py
Python
gpl-3.0
56,932
0.001194
# # ElementTree # $Id: ElementTree.py 3440 2008-07-18 14:45:01Z fredrik $ # # light-weight XML support for Python 2.3 and later. # # history (since 1.2.6): # 2005-11-12 fl added tostringlist/fromstringlist helpers # 2006-07-05 fl merged in selected changes from the 1.3 sandbox # 2006-07-05 fl removed support for ...
_class__(tag, attrib) ## # (Experimental) Copies the current element. This creates a # shallow copy; subelements will be shared with the original tree. # # @return A new element instance. def copy(self): elem = self.makeelement(self.tag, self.attrib)
elem.text = self.text elem.tail = self.tail elem[:] = self return elem ## # Returns the number of subelements. Note that this only counts # full elements; to check if there's any content in an element, you # have to check both the length and the <b>text</b> attribute.
azumimuo/family-xbmc-addon
plugin.video.showboxarize/resources/lib/sources_pl/filister.py
Python
gpl-2.0
5,852
0.003418
# -*- 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...
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import urllib, urlparse, re from re
sources.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 = 'embed?salt=%s' self.sear...
eahneahn/free
djangoproject/gh_frespo_integration/services/github_services.py
Python
agpl-3.0
5,113
0.008801
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...
) if github_username: repos = github_adapter.fetch_repos(github_username) for repo_dict in repos: gh_id = repo_dict['id'] repodb = get_repodb_by_githubid(gh_id) if repodb: user_re
po_config = get_repo_config_by_repo_and_user(repodb, user) if user_repo_config: repo_dict['add_links'] = user_repo_config.add_links repo_dict['new_only'] = user_repo_config.new_only return repos def get_repodb_by_githubid(gh_id): repos = Repo.objects.filter(gh_id = g...
vijeshm/eezyReport
eezyReport.py
Python
mit
16,797
0.006727
from lxml import etree import os from BeautifulSoup import BeautifulSoup from itertools import chain def replacements(text): text = text.replace('&gt;', '\\textgreater ') text = text.replace('&lt;', '\\textless ') text = text.replace('&', '\&') text = text.replace('_', '\_') text = text.replace('%'...
n}' elif content.name == 'subsection': attrs = dict(content.attrs) if not attrs.has_key('name'): print "One of the subsections do not have a 'name' attribute or is misspelled. Please correct it and re-run." exit(0) elif ...
else: retTxt += '\\begin{projSubSection}{' + attrs['name'] + '}' + convertToTex(str(content)) + '\\end{projSubSection}' elif content.name == 'img': props = dict(content.attrs) if not props.has_key('id'): print "One of the ima...
j00bar/django-widgy
widgy/contrib/page_builder/admin.py
Python
apache-2.0
165
0
from django.contrib import admin f
rom widgy.admin import WidgyAdmin from widgy.contrib.page_builder.models import Callout admin.site.register(Callout, WidgyAdmi
n)
gitireadme/gitireadme.server
gitireadme/article/models.py
Python
apache-2.0
391
0.023018
from django.db import models from gitireadme.utils import getUploadToPath import datetime class Article(models.Model): name = models.Char
Field(max_length=255,blank=True,null=True) path = models.CharField(max_length=255,blank=True,null=True) class Artic
leAlias(models.Model): repo = models.CharField(max_length=255,blank=True,null=True) article = models.ForeignKey(Article)
npuichigo/ttsflow
third_party/tensorflow/tensorflow/python/util/deprecation_test.py
Python
apache-2.0
28,547
0.004134
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
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." "\nInstructions for updating:" "\n%s" % (date
, instructions), _fn.__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _fn(1, 2)) 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,...
ken1277725/pythonweb-STT
server/server.py
Python
mit
1,001
0.034965
# 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 setti...
ult=8080, help="the application will be run on the given port", type=int) if __name__ == "__main__": options.parse_command_line() app_server = httpserver.HTTPServer(web.Application(handlers,**server_settings))
app_server.listen(options.options.port) ioloop.IOLoop.current().start()
sdpython/cvxpy
cvxpy/tests/test_lin_ops.py
Python
gpl-3.0
5,078
0
""" 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...
(self): """Test creating a variable. """ var = create_var((5, 4), var_id=1) self.assertEqual(var.size, (5, 4)) self.assertEqua
l(var.data, 1) self.assertEqual(len(var.args), 0) self.assertEqual(var.type, VARIABLE) def test_param(self): """Test creating a parameter. """ A = Parameter(5, 4) var = create_param(A, (5, 4)) self.assertEqual(var.size, (5, 4)) self.assertEqual(len(va...
xuru/pyvisdk
pyvisdk/enums/virtual_disk_adapter_type.py
Python
mit
239
0
#############################
########### # Automatically generated, do not edit. ######################################## from pyvisdk.thirdparty import Enum VirtualDiskAdapterType = Enum( 'busLogic', 'ide', 'lsiLogic',
)
shedskin/shedskin
examples/bh.py
Python
gpl-3.0
20,915
0.001004
""" A Python implementation of the _bh_ Olden benchmark. The Olden benchmark implements the Barnes-Hut benchmark that is decribed in: J. Barnes and P. Hut, "A hierarchical o(N log N) force-calculation algorithm", Nature, 324:446-449, Dec. 1986 The original code in the Olden benchmark suite is derived from the...
@param u the other operand of the subtraction. """ self.d0 -= u.d0 self.d1 -= u.d1 self.d2 -= u.d2 return self def __imul__(self, s): """ Multiply the vector times a scalar. @param s the scalar v
alue """ self.d0 *= s self.d1 *= s self.d2 *= s return self def __idiv__(self, s): """ Divide each element of the vector by a scalar value. @param s the scalar value. """ self.d0 /= s self.d1 /= s self.d2 ...
DiegoCorrea/ouvidoMusical
config/data/oneMillionSongs/mining.py
Python
mit
2,978
0.003359
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...
'- Finalizando o script!') def start(name, limit, userLimit=None): global directory global songDict directory = 'config/data/oneMillionSongs/sets/' + str(name) getSongs(name, limit) songDict = set(song
List) getPlayCount(name, limit, userLimit) ########## def main(): start(name="thousand", limit=1000) start(name="two_thousand", limit=2000) start(name="three_thousand", limit=3000) start(name="ten_thousand", limit=10000)
jbzdak/migration_manager
migration_manager/manager.py
Python
bsd-2-clause
2,915
0.009262
# -*- 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....
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, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT N
OT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ...
reubano/ckanutils
manage.py
Python
mit
2,296
0
#!/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...
style with flake8""" call('flake8 %s' % (where if where els
e ''), shell=True) @manager.command def pipme(): """Install requirements.txt""" call('pip install -r requirements.txt', shell=True) @manager.command def require(): """Create requirements.txt""" cmd = 'pip freeze -l | grep -vxFf dev-requirements.txt > requirements.txt' call(cmd, shell=True) @ma...
rhambach/TEMareels
runscripts/_set_pkgdir.py
Python
mit
674
0.01632
""" 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 recommended to keep a copy of all TEMareels module fil
es 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 the 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));
plotly/python-api
packages/python/plotly/plotly/validators/layout/mapbox/layer/_sourceattribution.py
Python
mit
521
0
import _plotly_utils.basevalidators class SourceattributionValidator(_plotly_utils.
basevalidators.StringValidator): def __init__( self, plotly_name="sourceattribution", parent_name="layout.mapbox.layer", **kwargs ): super(SourceattributionValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edi...
it_type", "plot"), role=kwargs.pop("role", "info"), **kwargs )
Gustry/inasafe
safe/datastore/test/test_geopackage.py
Python
gpl-3.0
5,299
0.000189
# 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...
_layer, standard_data_path) QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app() from safe.datastore.geopackage import GeoPackage # Decorator for expecting fails in windows but not other OS's # Probably we should move this somewhere in utils
for easy re-use...TS def expect_failure_in_windows(exception): """Marks test to expect a fail in windows - call assertRaises internally. ..versionadded:: 4.0.0 """ def test_decorator(fn): def test_decorated(self, *args, **kwargs): if sys.platform.startswith('win'): ...
orbitfold/tardis
tardis/plasma/properties/radiative_properties.py
Python
bsd-3-clause
11,605
0.003188
import logging import numpy as np import pandas as pd import numexpr as ne from astropy import units as u, constants as const from tardis.plasma.properties.base import ProcessingPlasmaProperty from tardis.plasma.properties.util import macro_atom logger = logging.getLogger(__name__) __all__ = ['StimulatedEmissionFac...
ues, stimulated_emission_factor, tau_sobolevs): #I wonder why? # Not sure who wrote this but the answer is that when the plasma is # first initialised (before the
first iteration, without temperature # values etc.) there are no j_blues values so this just prevents # an error. Aoife. if len(j_blues) == 0: return None macro_atom_data = self._get_macro_atom_data(atomic_data) if self.initialize: self.initialize_macro_a...
tanium/pytan
EXAMPLES/PYTAN_API/invalid_get_action_single_by_name.py
Python
mit
3,103
0.0029
#!/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 ...
ng output (uses two lines per log entry) handler_args['debugformat'] = False # optional, this saves all response objects to handler.session.ALL_REQUESTS
_RESPONSES # very useful for capturing the full exchange of XML requests and responses handler_args['record_all_requests'] = True # instantiate a handler using all of the arguments in the handler_args dictionary print "...CALLING: pytan.handler() with args: {}".format(handler_args) handler = pytan.Handler(**handler_ar...
denmojo/pygrow
grow/preprocessors/sass_preprocessor.py
Python
mit
3,649
0.002192
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...
(6) class SassPreprocessor(base.BasePreprocessor): KIND = 'sas
s' Config = Config def run(self, build=True): sass_dir = os.path.abspath(os.path.join(self.root, self.config.sass_dir.lstrip('/'))) out_dir = os.path.abspath(os.path.join(self.root, self.config.out_dir.lstrip('/'))) self.build_directory(sass_dir, out_dir) def build_directory(self, ...
laserson/hdfs
doc/conf.py
Python
mit
10,413
0.006914
# -*- coding: utf-8 -*- # # hdfs documentation build configuration file, created by # sphinx-quickstart on Thu Mar 6 16:04:56 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All ...
ere, as strings. They can be # extensions
coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of so...
hwkns/macguffin
files/utils.py
Python
gpl-3.0
5,724
0.001747
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 ...
=output.strip())) for relative_path in contents: path = os.path.join(destination_dir, relative_path) # Recursively extract until there are no R
AR files left if path.endswith('.rar'): extracted_files += unrar(path) else: extracted_files.append(path) # Return the list of paths return extracted_files def sha1(data): """ Return the SHA-1 hash of the given data. """ assert isinstance(data, (bytes, ...
home-assistant/home-assistant
homeassistant/components/tplink/config_flow.py
Python
apache-2.0
5,772
0.001213
"""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...
progress=False) e
xcept SmartDeviceException: errors["base"] = "cannot_connect" else: return self._async_create_entry_from_device(device) return self.async_show_form( step_id="user", data_schema=vol.Schema({vol.Optional(CONF_HOST, default=""): str}), ...
Show-Me-the-Code/python
pylyria/0001/0001_1.py
Python
mit
651
0.012939
# -*- coding: utf-8 -*- #!/usr/bin/e
nv 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(chars) for i in range(length)]) if __name__ == '__main__': code_colle...
set() for i in range(200): code = activation_code() if code not in code_collection: code_collection.add(code) else: continue
ethanfrey/aiojson
aiojson/echo_server.py
Python
bsd-3-clause
1,771
0.000565
""" 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')(errors='strict') async with aiohttp.get(url) as r: stream = DecodingStreamRe...
_(self): self.app = web.Application() self.app.router.add_route('GET', '/', self.hello) self.handler = self.app.make_handler() async def hello(self, request): return web.Response(body=b'M\xc3\xa4dchen mit Bi\xc3\x9f\n') # return web.Response(body=b'\xc3\x84\xc3\xa4\xc3\xa4\x...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/twisted/persisted/journal/base.py
Python
gpl-3.0
66
0.015152
../../../../../../share/pyshared/tw
isted/
persisted/journal/base.py
mFoxRU/cwaveplay
cwp/wavelets/ricker.py
Python
mit
215
0
__author__ = 'mFoxRU' import scipy.signal as sps from abstractwavelet imp
ort AbstractWavelet class Ricker(AbstractWavelet): name = 'Ricker(MHAT)' params = {} def fn(self)
: return sps.ricker
tdyas/pants
src/python/pants/option/options_bootstrapper.py
Python
apache-2.0
9,939
0.004628
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import itertools import os import sys from dataclasses import dataclass from pathlib import Path from typing import Dict, Iterable, List, Mapping, Optional, Sequence, Set, Tuple, Type fro...
sorted(env.items(), key=lambda x: x[0])) return cls( env_tuples=env_tuples, bootstrap_args=bargs, args=args, config=post_bootstrap_config ) @memoized_property def env(self) -> Dict[str, str]: return dict(self.env_tuples) @memoized_property def bootstrap_options(self...
p options, computed from the env, args, and fully discovered Config. Re-computing options after Config has been fully expanded allows us to pick up bootstrap values (such as backends) from a
MShel/PyChatBot
storage/Redis.py
Python
gpl-3.0
288
0
imp
ort redis class RedisAdapter: storage = None host = None port = None def __init__(self, host, port): if not self.storage: self.storage = redis.StrictRedis(host=host, port=int(port), db=0) def get_storage(self):
return self.storage
oVirt/ovirt-engine-sdk-tests
src/utils/dictutils.py
Python
apache-2.0
1,025
0.002927
# # 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 to in writing, software ...
the License for the specific language governing permissions and # limitations under the License. class DictUtils(object): ''' Provides dict services ''' @staticmethod def exclude(dct, keys=[]): """ Removes given items from the disct @param dct: the ditc to look at...
B3AU/waveTree
sklearn/waveTree/setup.py
Python
bsd-3-clause
672
0.001488
import os import numpy from numpy.distutils.misc_util import Configuration def configuration(parent_package="", top_path=None): config = Configuration("tree", parent_package, top_pa
th) libraries = [] if os.name == 'posix': libraries.append('m') config.add_extension("_tree", sources=["_tree.c"], include_dirs=[numpy.get_include()], libraries=libraries, extra_compile_args=["-O3"]) ...
)
JianpingZeng/xcc
xcc/java/utils/lit/lit/main.py
Python
bsd-3-clause
21,621
0.005041
#!/usr/bin/env python """ lit - LLVM Integrated Tester. See lit.pod for more information. """ from __future__ import absolute_import import math, os, platform, random, re, sys, time import lit.ProgressBar import lit.LitConfig import lit.Test import lit.run import lit.util import lit.discovery class TestingProgress...
action="store_true", default=False) group.add_option("-s", "--succinct", dest="succinct"
, help="Reduce amount of output", action="store_true", default=False) group.add_option("-v", "--verbose", dest="showOutput", help="Show test output for failures", action="store_true", default=False) group.add_option("-a", "--sho...