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
inspirehep/json-merger
docs/conf.py
Python
gpl-2.0
10,681
0.005243
# -*- coding: utf-8 -*- # # This file is part of Inspirehep. # Copyright (C) 2016 CERN. # # Inspirehep is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any...
th = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True
# Custom sidebar templates, maps document names to template names. html_sidebars = { '**': [ 'about.html', 'navigation.html', 'relations.html', 'searchbox.html', 'donate.html', ] } # Additional templates that should be rendered to pages, maps page names to # template nam...
jrief/django-shop-productvariations
shop_textoptions/cart_modifier.py
Python
bsd-3-clause
1,084
0.002768
#-*- coding: utf-8 -*- from decimal import Decimal from shop.cart.cart_modifiers_base import BaseCartModifier class TextOptionsOptionsCartModifier(BaseCartModifier): ''' This modifier adds an extra field to the cart to let the lineitem "know" about product options and their respective price. ''' d...
on the product options the client selected for the current cart_item (if any) ''' # process text_options as passed through the variation object if cart_item.variation.has_key('text_options'): for value in cart_item.variation['text_options'].
itervalues(): label = value['name'] + ': ' + value['text'] price = Decimal(value['price']) * len(value['text']) * cart_item.quantity # Don't forget to update the running total! cart_item.current_total += price cart_item.extra_price_fields.a...
gcrahay/FIR
incidents/authorization/mixin.py
Python
gpl-3.0
3,251
0.001846
import functools from django.contrib.auth.models import Permission from django.db import models from incidents.authorization import AuthorizationManager class AuthorizationModelMixin(models.Model): _permissions_cache = {} authorization = AuthorizationManager() class Meta: abstract = True @...
m) perm_obj = Permission.objects.get(content_type__app_label=app_label, codename=codename) perm_id = perm_obj.pk cls._permissions_cache[perm] = perm_id permissions.append(perm_id)
return permissions @classmethod def get_authorization_paths(cls, user, permission=None): if user.is_superuser: return cls.objects.all() user_obj = user user = user.pk qs_filter = {'acl__user': user} if permission is not None: if not isins...
safarijv/sbo-selenium
sbo_selenium/testcase.py
Python
bsd-2-clause
27,455
0.001421
from __future__ import absolute_import import io import json import logging import os import re import socket import sys import time from django.core.servers.basehttp import WSGIServer from django.test import LiveServerTestCase from django.test.testcases import QuietWSGIRequestHandler from django.utils import six imp...
ion from selenium.webdriver import Chrome, DesiredCapabilities, Firefox, PhantomJS from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver from selenium.webdriver.support.color import Color from selenium.webdriver.support.ui import Select from selenium.webdriver.support.wait import WebDriverWait
from sbo_selenium.conf import settings logger = logging.getLogger('django.request') # Storage for Sauce Labs session IDs so they can be logged in bulk sauce_sessions = [] ADD_ACCESSIBILITY_SCRIPT = """ var script = document.createElement('script'); script.src = '/static/js/axs_testing.js'; document.body.appendChild...
snyderr/robotframework
setup.py
Python
apache-2.0
4,132
0.011617
#!/usr/bin/env python import sys import os from os.path import abspath, join, dirname from subprocess import list2cmdline from distutils.core import setup from distutils.command.install_scripts import install_scripts try: import setuptools # use setuptools when available except ImportError: pass CURDIR = ...
'jyrebot'] elif sys.platform == 'cli': SCRIPTS = ['ipybot', 'ipyrebot'] else: SCRIPTS = ['pybot'] SCRIPTS = [join('src', 'bin', s) for s in SCRIPTS + ['robot', 'rebot']] if WINDOWS: SCRIPTS = [s+'.bat' for s in SCRIPTS] class custom_install_scripts(install_scripts): def run(self): install_scr...
replace_interpreter_in_bat_files(self): print("replacing interpreter in robot.bat and rebot.bat.") interpreter = list2cmdline([sys.executable]) for path in self.get_outputs(): if path.endswith(('robot.bat', 'rebot.bat')): with open(path, 'r') as input: ...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.2/Lib/copy_reg.py
Python
mit
1,861
0.005373
"""Helper to provide extensibility for pickle/cPickle. This is only useful to add pickle support for extension types defined in C, not for instances of user-defined classes. """ from types import ClassType as _ClassType __all__ = ["pickle","constructor"] dispatch_table = {} safe_constructors = {} def pickle(ob_typ...
t__(obj, state) return obj _reconstructor.__safe_for_unpickling__ = 1 _HEAPTYPE = 1<<9 def _reduce(self): for base in self.__class__.__mro__: if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE: break else: base = object # not really reachable if base is object...
y: dict = self.__dict__ except AttributeError: dict = None else: dict = getstate() if dict: return _reconstructor, args, dict else: return _reconstructor, args
pelson/cartopy
setup.py
Python
lgpl-3.0
15,098
0.000199
# (C) British Crown Copyright 2011 - 2018, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option)...
= os.getenv('CONDA_DEFAULT_ENV') if conda is not None and conda in sys.prefix: # Conda does not provide pkg-config compatibi
lity, but the search paths # should be set up so that nothing extra is required. We'll still check # the version, though. proj_version = find_proj_version_by_program(conda) if proj_version < PROJ_MIN_VERSION: print( 'Proj version %s is installed, but cartopy requires at least ' ...
golismero/golismero
golismero/api/data/vulnerability/injection/xss.py
Python
gpl-2.0
2,381
0.00168
#!/usr/bin/python # -*- coding: utf-8 -*- __license__ = """ GoLismero 2.0 - The web knife - Copyright (
C) 2011-2014 Authors: Jekkay Hu | jekkay<@>gmail.com Daniel Garcia Garcia a.k.a cr0hn | cr0hn<@>cr0hn.com Mario Vilas | mvilas<@>gmail.com Golismero project site: http://golismero-project.com Golismero project mail: contact@golismero-project.com This program is
free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; with...
kralf/morsel
python/lib/morsel/control/keyboard.py
Python
gpl-2.0
2,440
0.015574
from morsel.panda import * from morsel.nodes.controller import Controller from morsel.core.event_handler import EventHandler #------------------------------------------------------------------------------- class Keyboard(Controller): def __init__(self, keys = [], delay = None, **kargs): super(Keyboard, self).__...
lf.keyMap[self.keys[i][1]]: command[i] += self.increments[i]*period command[i] = min(command[i], self.actuator.limits[i][1]) elif command[i] != 0: command[i] -= self.increments[i]*period*command[i]/abs(command[i]) if abs(command[i]) <= abs(self.increments[i]*period): ...
and
all-of-us/raw-data-repository
rdr_service/model/survey.py
Python
bsd-3-clause
2,272
0.00088
from protorpc import messages from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship from typing import List from rdr_service.model.base import Base from rdr_service.model.code import Code from rdr_service.model.utils import EnumZeroBased, UTCDateTime class Survey(Base): ...
veyQuestion'] = relationship('SurveyQuestion', back_populates='survey') class SurveyQuestionType(messages.Enum): """Question types available on Redcap""" TEXT = 0 NOTES = 1 CALC = 2 DROPDOWN = 3 RADIO = 4 CHECKBOX = 5 YESNO = 6 TRUEFALSE = 7 FILE = 8 SLIDER = 9 UNKNOWN ...
', Integer, ForeignKey(Survey.id)) survey = relationship(Survey, back_populates='questions') codeId = Column('code_id', Integer, ForeignKey(Code.codeId)) code = relationship(Code) questionType = Column('question_type', EnumZeroBased(SurveyQuestionType)) validation = Column(String(256)) validat...
duyet-website/api.duyet.net
lib/flask_limiter/extension.py
Python
mit
20,800
0.003606
""" the flask extension """ import warnings from functools import wraps import logging from flask import request, current_app, g, Blueprint from werkzeug.http import http_date from limits.errors import ConfigurationError from limits.storage import storage_from_string, MemoryStorage from limits.strategies import STRAT...
_method, methods, error_message, exempt_when): self._limit = limit
self.key_func = key_func self._scope = scope self.per_method = per_method self.methods = methods and [m.lower() for m in methods] or methods self.error_message = error_message self.exempt_when = exempt_when @property def limit(self): return self._limit() if c...
kennedyshead/home-assistant
tests/components/kulersky/test_config_flow.py
Python
apache-2.0
3,098
0
"""Test the Kuler Sky config flow.""" from unittest.mock import MagicMock, patch import pykulersky from homeassistant import config_entries, setup from homeassistant.components.kulersky.config_flow import DOMAIN async def test_flow_success(hass): """Test we get the form.""" await setup.async_setup_component...
ponents.kulersky.config_flow.pykulersky.discover", return_value=[], ), patch( "homeassistant.components.kulersky.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], {}, ...
) assert result2["type"] == "abort" assert result2["reason"] == "no_devices_found" await hass.async_block_till_done() assert len(mock_setup_entry.mock_calls) == 0 async def test_flow_exceptions_caught(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_no...
chryswoods/Sire
wrapper/python/scripts/package_sire.py
Python
gpl-2.0
2,504
0.00839
from Sire.Base import * import Sire import shutil import sys import time import os import tempfile import glob from os.path import getsize, join siredir = os.path.abspath( getInstallDir() ) print("\n#################################################################") print( "# This script will create a sire.run i...
print("...files removed. Saved %d MB of space" % (py_saved_space/(1024*1024))) # Now use the share/Sire/remove_root.py script to replace all # absolute paths with {[{ROOT}]} print("Removing absolute directory references... (may take a while)...") os.system("%s %s %s %s" % (python_exe, remove_path, tm...
.") share_dir = Sire.Base.getShareDir().replace(Sire.Base.getInstallDir(),"./tmp_sire.app") os.system("%s --current %s %s \"Sire Molecular Simulation Framework\" %s/build/install_sire.sh" \ % (makeself, tempdir, sire_run, share_dir)) print( "\nAll done :-). Just type %s to install Sire." % s...
pyhmsa/pyhmsa
doc/source/conf.py
Python
mit
10,278
0.006519
import os import runpy # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General c...
ing with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [
'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.pngmath', ] # 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 source files. #source_encoding = 'utf-8-sig' # The mas...
nemobis/bots
ia-archivio-lastampa.py
Python
gpl-3.0
15,953
0.020194
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Bot to download archiviolastampa.it and upload it to the Internet Archive """ # # (C) Federico Leva, 2020 # # Distributed under the terms of the MIT license. # __version__ = '0.3.0' import collections import concurrent.futures import csv import datetime from internetarch...
h open(day + '/' + dayfile.name, 'r') as j: try: pages = json.load(j) pagecount = len(pages['pageList']) except json.decoder.JSONDecodeError: print("WARNING: Could not open JSON for day {}".format(day)) pass return imagecount, pagecount, identifier def verifyDirectory(): """ Verify the co...
delimiter='\t', lineterminator='\n', quoting=csv.QUOTE_MINIMAL, ) writer.writerow(['Date', 'Image count', 'Page count', 'Identifier']) days = set([d.name for d in Path('.').iterdir() if re.match('[0-9-]{10}', d.name)]) for day in days: imagecount, pagecount, identifier = getDayCounts(day) if imagecount...
albertz/music-player
mac/pyobjc-framework-Cocoa/PyObjCTest/test_nsrange.py
Python
bsd-2-clause
1,400
0.000714
from Foundation import * from PyObjCTools.TestSupport import * try: unicode except NameError: unicode = str try: long except NameError: long = int class TestNSRange (TestCase): def testStructs(self): v = NSRange() self.assertHasAttr(v, 'location') self.assertHasAttr(v, '...
MaxRange(v), 5) self.assertResultIsBOOL(NSLocationInRange) self.assertIs(NSLocationInRange(3, v), True) self.assertIs(NSLocationInRange(15, v), False) self.assertResultIsBOOL(NSEqualRanges) self.assertIs(NSE
qualRanges(v, v), True) v = NSUnionRange((1, 3), (5, 10)) self.assertIsInstance(v, NSRange) v = NSIntersectionRange((1, 4), (3, 5)) self.assertIsInstance(v, NSRange) v = NSStringFromRange((9, 10)) self.assertIsInstance(v, unicode) w = NSRangeFromString(v) ...
seibert/blaze-core
blaze/aterm/terms.py
Python
bsd-2-clause
3,957
0.007076
#------------------------------------------------------------------------ # Terms #------------------------------------------------------------------------ class ATerm(object): def __init__(self, term, annotation=None): self.term = term self.annotation = annotation def __str__(self): ...
r.term else: raise ValueError() def __ne__(self, other): if isinstance(other, ATerm): return self.term != other.term else: raise ValueError() def __repr__(self): return str(self) class AAppl(object): def __init__(self, spine, args): ...
(self.spine) + arepr(self.args, '(', ')') def __repr__(self): return str(self) class AString(object): def __init__(self, val): assert isinstance(val, str) self.val = val def __str__(self): return '"%s"' % (self.val) def __repr__(self): return str(self) class ...
iksaif/euscan
euscanwww/djeuscan/migrations/0020_auto__add_field_userprofile_email_every.py
Python
gpl-2.0
15,896
0.007801
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigratio
n from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'UserProfile.email_every' db.add_column('djeuscan_userprofile', 'email_every', self.gf('django.db.models.fields.IntegerField')(default=1), k
eep_default=False) def backwards(self, orm): # Deleting field 'UserProfile.email_every' db.delete_column('djeuscan_userprofile', 'email_every') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary...
dreadrel/UWF_2014_spring_COP3990C-2507
notebooks/scripts/book_code/code/permute.py
Python
apache-2.0
865
0.001156
# File permute.py def permute1(seq): if not seq:
# Shuffle any sequence: list return [seq] # Empty sequence else: res = [] for i in range(len(seq)): rest = seq[:i] + seq[i+1:] # Delete current node for x in permute1(rest): # Permute the others res.append(seq[...
# Empty sequence else: for i in range(len(seq)): rest = seq[:i] + seq[i+1:] # Delete current node for x in permute2(rest): # Permute the others yield seq[i:i+1] + x # Add node at front
phani00/tovp
tovp/promotions/jinja2tags.py
Python
mit
398
0.002513
from __future__ import absolute_import # import jinja2 from jinja
2.ext import Extension from .templatetags.promotions_tags import promo_ballance class PromotionsExtension(Extension): def __init__(self, environment): super(Promo
tionsExtension, self).__init__(environment) environment.filters["promo_ballance"] = promo_ballance # Nicer import name core = PromotionsExtension
grouan/udata
udata/core/spatial/search.py
Python
agpl-3.0
979
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from udata.search import Model
SearchAdapter from .models import GeoZone __all__ = ('GeoZoneSearch', ) class GeoZoneSearch(ModelSearchAdapter): model = GeoZone fuzzy = True mapping = { 'properties': {
'zone_suggest': { 'type': 'completion', 'index_analyzer': 'standard', 'search_analyzer': 'standard', 'payloads': True, }, } } @classmethod def serialize(cls, zone): return { 'zone_suggest': { ...
plotly/python-api
packages/python/plotly/plotly/validators/scatterternary/hoverlabel/_align.py
Python
mit
591
0.001692
import _plotly_utils.basevalidators class AlignValidator(_
plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="align", parent_name="scatterternary.hoverlabel", **kwargs ): super(AlignValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_o...
("values", ["left", "right", "auto"]), **kwargs )
alirizakeles/tendenci
tendenci/apps/invoices/tasks.py
Python
gpl-3.0
4,238
0.000944
import os from datetime import datetime from django.forms.models import model_to_dict from django.db.models.fields import DateTimeField from django.db.models.fields.related import ManyToManyField, Foreign
Key from django.contrib.contenttypes.fields import GenericRelation from celery.task import Task from tendenci.apps.perms.models import TendenciBaseModel from tendenci.apps.exports.utils import render_csv class InvoiceExportTask(Task): """Export Task for Celery This exports the entire queryset of a given Tenden...
gs): """Create the xls file""" fields = ( 'id', 'guid', 'object_type', 'object_id', 'title', 'tender_date', 'bill_to', 'bill_to_first_name', 'bill_to_last_name', 'bill_to_company', ...
xemul/criu-scripts
hdr-scan.py
Python
gpl-2.0
1,679
0.03514
#!/usr/bin/env python import sys import os sdir = sys.argv[1] def file_includes(path): incs = filter(lambda x: x.startswith('#include'), open(path)) if not incs: return None incs = map(lambda x: x.strip().split()[1], incs) incs = filter(lambda x: x.startswith('"') and x.endswith('"'), incs) if not incs: r...
def scan(p, seen_set, bad_set, dep = 0, c_path = []): print ' ' * dep + '%s' % p incs = file_includes(p) if not incs: # Terminating header print ' ' *
dep + '---' return # Headers, that don't include other headers are # OK to be looped into. But those, that continue # the inclustion chain shouldn't meet any longer c_path.append(p) seen_set[p] = ' -> '.join(c_path) print ' ' * dep + '-->' for i in incs: d = inc_dir(i) if not d: if not i.startswith('...
sebastic/stetl
stetl/outputs/httpoutput.py
Python
gpl-3.0
3,524
0.001986
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Output classes for ETL. # # Author: Just van den Broecke # from stetl.output import Output from stetl.util import Util from stetl.packet import FORMAT import httplib import base64 log = Util.get_log('httpoutput') class HttpOutput(Output): """ Output via HTTP p...
ost", self.host) webservice.putheader("User-Agent", "Stetl Python http") webservice.putheader("Content-Type", self.content_type) # webservice.putheader("Accept", self.accept_type) webservice.putheader("Content-Length", "%d" % len(payload)) # basic auth: http://mozgovipc.blogspot...
e Authorization header like: 'Basic base64encode(username + ':' + password) if self.user is not None: auth = base64.encodestring('%s:%s' % (self.user, self.password)).replace('\n', '') webservice.putheader("Authorization", "Basic %s" % auth) webservice.endheaders() webse...
technolotrix/tests
tests/selenium/footer/page.py
Python
apache-2.0
1,389
0.00504
from element import BasePageElement from locators import PageFooterLocators from selenium.webdriver.common.action_chains import ActionChains class BasePage(object): def __init__(self, driver): self.driver = driver class FooterPage(BasePage): def is_copyright_matches(self): return "Lauren...
" in self.driver.page_source def click_github_button(self): element = self.driver.find_element(*PageFooterLocators.GET_GITHUB_BUTTON) element.click() return "https://github.com/technolotrix" in self.driver.current_url def click_linkedin_button(self): element = self.driver.find_...
return "https://www.linkedin.com/in/nicolelns" in self.driver.current_url def click_twitter_button(self): element = self.driver.find_element(*PageFooterLocators.GET_TWITTER_BUTTON) element.click() return "" in self.driver.current_url def click_gplus_button(self): element...
sklnet/openblackhole-enigma2
lib/python/Components/TuneTest.py
Python
gpl-2.0
10,722
0.029379
from enigma import eDVBFrontendParametersSatellite, eDVBFrontendParametersTerrestrial, eDVBFrontendParametersCable, eDVBFrontendParameters, eDVBResourceManager, eTimer class Tuner: def __init__(self, frontend, ignore_rotor=False): self.frontend = frontend self.ignore_rotor = ignore_rotor # transponder = (freque...
IDs = True>) # 3) finishedChecking() is called, when the run is finished class TuneTest: def __init__(self, feid, stopOnSuccess = -1, stopOnError = -1): self.stopOnSuccess = stopOnSuccess self.stopOnError = stopOnError self.feid = feid self.transponderlist = [] self.currTuned = None print "
TuneTest for feid %d" % self.feid if not self.openFrontend(): self.oldref = self.session.nav.getCurrentlyPlayingServiceOrGroup() self.session.nav.stopService() # try to disable foreground service if not self.openFrontend(): if self.session.pipshown: # try to disable pip if hasattr(self.session, 'inf...
thorwhalen/ut
slurp/util.py
Python
mit
2,391
0.001255
__author__ = 'thor' from bs4 import BeautifulSoup from functools import wraps @wraps(BeautifulSoup.find_all, assigned=('__module__', '__qualname__', '__annotations__', '__name__')) def gen_find(tag, *args, **kwargs): """Does what BeautifulSoup.find_all does, but as an iterator. See find_all documentation...
'*': '%2A', '+': '%2B',
',': '%2C', '/': '%2F', ':': '%3A', ';': '%3B', '<': '%3C', '=': '%3D', '>': '%3E', '?': '%3F', '@': '%40', ...
ghorn/debian-casadi
docs/api/examples/algebra/LinearSolver.py
Python
lgpl-3.0
2,711
0.020657
# # This file is part of CasADi. # # CasADi -- A symbolic framework for dynamic optimization. # Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl, # K.U. Leuven. All rights reserved. # Copyright (C) 2011-2014 Greg Horn # # CasADi is free software; you can...
# Give it the matrix b t0 = time.time() for i in range(100): s.solve() st = (time.time()-t0)/100 x_ = s.getOutput("X") print "" print solver print "=" * 10 print "Sum of r
esiduals = %.2e" % sumAll(fabs(x-x_)) print "Preparation time = %0.2f ms" % (pt*1000) print "Solve time = %0.2f ms" % (st*1000) assert(sumAll(fabs(x-x_))<1e-9) #! Note that these
earwig/earwigbot
earwigbot/commands/access.py
Python
mit
6,303
0.000952
# -*- coding: utf-8 -*- # # Copyright (C) 2009-2015 Ben Kurtovic <ben.kurtovic@gmail.com> # # 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 ...
\x0302{1}\x0F.".format(name, rule) self.reply(data, msg) else: rule = "{0}!{1}@{2}".form
at(nick, ident, host) msg = "No bot {0} matching \x0302{1}\x0F.".format(name, rule) self.reply(data, msg) def get_user_from_args(self, data, permdb): if not permdb.is_owner(data): msg = "You must be a bot owner to add or remove users to the access list." ...
linuxmint/mint4win
tests/test_backend.py
Python
gpl-2.0
3,126
0.004479
# tools/pywine -O tests/test_backend.py import unittest import
sys, os sys.path.insert(0, 'build
\\wubi\\lib') from wubi.backends.win32 import backend from version import application_name, version, revision from wubi import application import mock from wubi.backends.win32 import registry class BackendTests(unittest.TestCase): def setUp(self): w = application.Wubi(application_name, version, ...
enkore/i3pystatus
i3pystatus/ticker.py
Python
mit
1,604
0.002494
from i3pystatus import IntervalModule import yfinance as yf class Ticker(IntervalModule): """ Displays stock ticker information from yahoo finance Re
quires: yfinance """ settin
gs = ( ("symbol", "Stock symbol to track"), ("interval", "Update interval (in seconds)"), ("good_color", "Color of text while 'regularMarketPrice' is above " "good_threshold"), ("bad_color", "Color of text while 'regularMarketPrice' is below " "bad_threshold"), ...
katuyo/symbol-exchange
integration/script.py
Python
mit
1,297
0.003873
# coding=utf8 import random import logging import json import time from httplib2 import Http from logging import handlers LOG_FILE = '../logs/WSCN_client.log' handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5) # 实例化handler handler.setFormatter(logging.Formatter('%(asctime)...
obj = json.loads(c) logger.info("%s, %s", obj['order_id'], exchange_type) def random_type(): return str(random.choice(["buy", "sell", "buy_market", "sell_market"])) def random_amount(): return str(random.randrange(1, 100, 1)) def random_price(): return str(round(random.uniform(90.00, 1...
in__': for i in range(0, 1000): send() time.sleep(0.230)
raphaelvalentin/qtlayout
Projects/Bridges/bridge5.py
Python
gpl-2.0
11,681
0.016608
inf = 1000 def Bridge4x4(width1 = 5.0, width2=10.0, spacing = 3.01/1.1): angle = -45.0 # y0 = 0.0 y1 = y0 + 0.5*spacing + 0.5*width1 y2 = y1 + 0.5*(width1+width2) + spacing y_1 = y0 - 0.5*spacing - 0.5*width2 y_2 = y_1 - 0.5*(width1+width2) - spacing # line1 = Line(Poin...
ine(Point(-inf, y3r), Point(inf, y3r)) line6 = Line(Point(-inf, y4r), Point(inf, y4r)) point1
= line1.Intersect(line3) point2 = line3.Intersect(line5) point3 = line4.Intersect(line6) point4 = line2.Intersect(line4) bridge2 = Primitive( ) bridge2.append( point4 ) bridge2.append( Point(point4.x-3, point4.y) ) bridge2.append( Point(point4.x-3, point1.y) ) bridge2.append( p...
jsfenfen/freefcc
scraper/scrape_settings.py
Python
bsd-3-clause
331
0.009063
settings = { 'SCRAPE_DELAY_TIME': 1,
'SCRAPER_USER_AGENT_STRING':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7;
rv:29.1) Gecko/20100101 Firefox/29.0', 'YEAR_LIST': [2014], 'CSV_LOCATION': "station_listings/%s.csv", 'MANIFEST_LOCATION': "manifest_files/%s.csv", 'PDF_DIR': "pdfs/", 'TXT_DIR': "txts/", }
gumblex/jieba
jieba/__init__.py
Python
mit
19,003
0.000947
from __future__ import absolute_import, unicode_literals __version__ = '0.39' __license__ = 'MIT' import re import os import sys import time import logging import marshal import tempfile import threading from math import log from hashlib import md5 from ._compat import * from . import finalseg if os.name == 'nt': ...
ltotal += freq for ch in xrange(len(word)): wfrag = word[:ch + 1] if wfrag not in lfreq: lfreq[wfrag] = 0 except ValueError: raise ValueError( 'invalid dict
ionary entry in %s at Line %s: %s' % (f_name, lineno, line)) f.close() return lfreq, ltotal def initialize(self, dictionary=None): if dictionary: abs_path = _get_abs_path(dictionary) if self.dictionary == abs_path and self.initialized: return ...
vacuus/django-codesnip
tests/test_forms.py
Python
lgpl-3.0
771
0
from django.test import Tes
tCase from codesnip.forms import SnippetForm from codesnip.models import Snippet from . import utils class TestSnippetForm(TestCase): def test_language_sort(self): form = SnippetForm() assert form.fields['language'].choices == sorted(form.fields ...
key=lambda x: x[1]) def test_valid_data_and_save(self): # This data should be valid\ form = SnippetForm(data=utils.VALID_SNIPPET_ARGS) assert form.is_valid() snippet = form.save() for data in utils.VALID_SNIPPET_ARGS: assert getattr(snippet, data) == utils....
wagoodman/bridgy
tests/test_inventory_set.py
Python
mit
6,497
0.008312
import os import mock import pytest import bridgy.inventory from bridgy.inventory import InventorySet, Instance from bridgy.inventory.aws import AwsInventory from bridgy.config import Config def get_aws_inventory(name): test_dir = os.path.dirname(os.path.abspath(__file__)) cache_dir = os.path.join(test_dir, '...
all_instances = inventorySet.instances(filter_sources='awesome') # aws_instances = [ # Instance(name
='test-forms', address='devbox', aliases=('devbox', 'ip-172-31-8-185.us-west-2.compute.internal', 'i-e54cbaeb'), source='aws (aws)', container_id=None, type='VM'), # Instance(name='devlab-forms', address='devbox', aliases=('devbox', 'ip-172-31-0-138.us-west-2.compute.internal', 'i-f7d726f9'), source='aws (aws)...
xpclove/autofp
diffpy/pyfullprof/phase.py
Python
gpl-3.0
27,563
0.010086
#!/usr/bin/env python ############################################################################## # # diffpy.pyfullprof by DANSE Diffraction group # Simon J. L. Billinge # (c) 2010 Trustees of the Columbia University # in the City of New York. All rights reserve...
4: "intensities of nuclear reflection from Rigid b
ody groups", 5: "intensities of magnetic reflection from conical magnetic structure in real space", 10: "nuclear and magnetic phase with Cartesian magnetic moment", -10:"nuclear and magnetic phase with spherical magnetic moment", 15: "comm...
enovance/managesf
managesf/controllers/htp.py
Python
apache-2.0
2,279
0
# # Copyright (C) 2014 eNovance SAS <licensing@enovance.com> # # 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...
por
t htpasswd import logging logger = logging.getLogger(__name__) class Htpasswd(object): def __init__(self, configuration): self.filename = None if getattr(configuration, "htpasswd", None): self.filename = configuration.htpasswd.get('filename') # Ensure file exists ...
QISKit/qiskit-sdk-py
qiskit/providers/basicaer/basicaerjob.py
Python
apache-2.0
4,441
0.001801
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
/concurrent.futures.html#future-objects Args: timeout (float):
number of seconds to wait for results. Returns: qiskit.Result: Result object Raises: concurrent.futures.TimeoutError: if timeout occurred. concurrent.futures.CancelledError: if job cancelled before completed. """ return self._future.result(timeout=t...
Kwistech/PlanB
classes/updater.py
Python
mit
477
0
class Updater(object): """Command-line Updater class.""" def __init__(self): """Initialize all updates to be displayed in the command-line.""" self.header = "Backing
up data...\n" self.working = "Currently backing up '{}'..." self.success = "Successfully backed up '{}' to '{}'.\n" self.file_exists_error = "ERROR: File Exists!\n" self.file_not_found_error = "ERROR: File Not Found!\n" self.end = "Backup Done!"
CasualGaming/studlan
studlan/wsgi.py
Python
mit
425
0
# -*- coding: utf-8 -*- """ WSGI config
for studlan project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 's...
gs.settings') application = get_wsgi_application()
RobLoach/lutris
lutris/gui/dialogs.py
Python
gpl-3.0
11,016
0.000182
# -*- coding: utf-8 -*- """Common message dialogs""" import os from gi.repository import GLib, Gtk, Gdk, GObject from lutris import api, pga, runtime, settings from lutris.gui.widgets import DownloadProgressBox from lutris.util import datapath class GtkBuilderDialog(GObject.Object): def __init__(self, parent=No...
ButtonsType.OK, parent=parent) self.set_markup(message) if secondary: self.format_secondary_text(secondary) self.run() self.destroy() class QuestionDialog(Gtk.MessageDialog): """Ask th
e user a question.""" YES = Gtk.ResponseType.YES NO = Gtk.ResponseType.NO def __init__(self, settings): super(QuestionDialog, self).__init__( message_type=Gtk.MessageType.QUESTION, buttons=Gtk.ButtonsType.YES_NO ) self.set_markup(settings['question']) ...
Elico-Corp/odoo-addons
pos_membership/__openerp__.py
Python
agpl-3.0
694
0
# -*- coding: utf-8 -*- # © 2016 Elico Corp (www.elico-corp.com). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Membership Management - POS Membership', 'version': '8.0.1.0.2', 'category': 'Generic Modules', 'depends': [ 'account_membership_balance', 'po...
_accountant', 'account_voucher', ], 'author': 'Elico Corp', 'license': 'AGPL-3', 'website': 'https://www.elico-corp.com', 'data': [ 'views/pos_membership.xml',
'views/partner_view.xml' ], 'qweb': [ 'static/src/xml/pos.xml' ], 'installable': True, 'application': False, }
noba3/KoTos
addons/plugin.video.mega/resources/lib/platform_libraries/Linux/64bit/Crypto/Hash/MD4.py
Python
gpl-2.0
254
0.035433
def __bootstrap__(): global __bootstrap__, __loader__, __file__
import sys, pkg_resources, imp _
_file__ = pkg_resources.resource_filename(__name__,'MD4.so') del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__) __bootstrap__()
seantis/suitable
setup.py
Python
gpl-3.0
1,752
0
# -*- coding: utf-8 -*- from setuptools import setup, Command name = "suitable" description = "Suitable is a thin wrapper around the Ansible API." def get_long_description(): with open('README.rst') as readme_file: for line in readme_file.readlines(): if description in line: ...
yield line.replace('\n', '') class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self):
import sys import subprocess errno = subprocess.call([sys.executable, 'runtests.py']) raise SystemExit(errno) setup( name='suitable', version='0.17.2', url='http://github.com/seantis/suitable/', license='GPLv3', author='Denis Krienbühl', author_email='denis@href.ch...
embali/imgpy
tests/test_convert.py
Python
mit
746
0
from tempfile import TemporaryFile import pytest from imgpy import Img @pytest.mark.parametrize('image', ({ 'sub': 'anima/bordered.gif', 'convert': 'L', 'mode': 'P' }, { 'sub': 'anima/clear.gif',
'convert': 'L', 'mode': 'P' }, { 'sub': 'fixed/bordered.jpg', 'convert': 'L', 'mode': 'L' }, { 'sub': 'fixed/clear.jpg', 'convert': 'L', 'mode': 'L' }, )) def test_convert(path, image): with Img(fp=path(image['sub'])) as src, TemporaryFile() as tf: src.convert(image['convert'])...
rc.height, image['mode'], src.frame_count)
xr09/metrocontador
metrocontador.py
Python
mit
3,516
0.005119
#!/usr/bin/python import sys from PyQt4.QtCore import pyqtSignature, SIGNAL, QSettings, QVariant from PyQt4.QtGui import (QDialog, QApplication, QSpinBox, QLabel, QPushButton, QGridLayout, qApp, QIcon) from calculos import importe NAME = "Metro Contador" COMPANY = "metrocontador" PROGRAM="...
ayout.addWidget(lab_consumo, 0, 2) layout.addWidget(lab_impor
te, 0, 3) layout.addWidget(lab_previa, 1, 0) layout.addWidget(lab_actual, 2, 0) layout.addWidget(self.spinbox_prev, 1, 1) layout.addWidget(self.spinbox_act, 2, 1) layout.addWidget(self.spinbox_cons, 1, 2) layout.addWidget(self.lab_importe, 1, 3) layout.addWidget(s...
UdK-VPT/Open_eQuarter
mole/stat_corr/window_wall_ratio_south_MFH_by_building_age_correlation.py
Python
gpl-2.0
514
0.040856
# OeQ autogenerated correlation for 'Window/Wall Ratio South in Correlation to the Bu
ilding Age' import math import numpy as np import oeqCorrelation as oeq def get(*xin): # OeQ autogenerated correlation for 'Window to Wall Ratio in Southern Direction' A_WIN_S_BY_AW= oeq.correlation( const= 20818.6194135, a= -42.6513518642,
b= 0.0327511835635, c= -1.11718058834e-05, d= 1.42836626434e-09, mode= "lin") return dict(A_WIN_S_BY_AW=A_WIN_S_BY_AW.lookup(*xin))
eduNEXT/edunext-platform
import_shims/lms/discussion/signals/handlers.py
Python
agpl-3.0
404
0.009901
"""Deprecated import support. Auto-generated by i
mport_shims/generate_shims.sh.""" # pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-
suppression,line-too-long from import_shims.warn import warn_deprecated_import warn_deprecated_import('discussion.signals.handlers', 'lms.djangoapps.discussion.signals.handlers') from lms.djangoapps.discussion.signals.handlers import *
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/mx/DateTime/mxDateTime/test.py
Python
gpl-3.0
63
0.015873
../../../../../../share/pyshared/mx
/DateTime/mxDateTime/test
.py
tanium/tanium_soul_py
build_soul.py
Python
mit
24,066
0.001953
#!/usr/bin/python # -*- coding: utf-8 -*- """Tanium SOUL package builder.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import codecs import datetime import imp import io import logging import os i...
["attrs"] props = attrs["properties"] [self._update_prop(x) for x in props] lprop = attrs["list_prop"] self._update_prop(lprop)
if lprop else None constants = attrs["constants"] cprops = self._sort_props([x for x in props if x["obj_type"] not in self.SIMPLE_TYPES]) sprops = self._sort_props([x for x in props if x["obj_type"] in self.SIMPLE_TYPES]) ignores = attrs.get("ignores", []) tv = {} tv.u...
factorlibre/l10n-spain
l10n_es_aeat/wizard/__init__.py
Python
agpl-3.0
84
0
# -*- coding: utf-8 -*- from . impor
t compare_boe_file from . import export_to_b
oe
bjorand/django-allauth
allauth/compat.py
Python
mit
414
0
import django if django.VERSION > (1, 8,): from collections import OrderedDict else: from django.utils.datastructures import SortedDict as OrderedDict # noqa try: from urllib.parse import parse_qsl, urlparse, urlunparse except ImportError: from urlparse import parse_qsl, urlparse, urlunparse # noqa ...
# noqa
mdakin/engine
tools/dart/update.py
Python
bsd-3-clause
3,372
0.0086
#!/usr/bin/python # Copyright 2015 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. """Pulls down the current dart sdk to third_party/dart-sdk/. You can manually force this to run again by removing third_party/dart-sdk/STA...
he dart sdk: Just change this url! We write this to the stamp # file after we download, and then check the stamp file for differences. SDK_URL_BASE = ('http://gsdview.appspot.com/dart-archive/channels/dev/raw/' '1.13.0-dev.6.0/sdk/') LINUX_64_SDK = 'dartsdk-linux-x64-release.zip' MACOS_64_SDK = 'dartsd...
abspath(os.path.join(THIS_DIR, '..', '..')) DART_SDK_DIR = os.path.join(MOJO_DIR, 'third_party', 'dart-sdk') STAMP_FILE = os.path.join(DART_SDK_DIR, 'STAMP_FILE') LIBRARIES_FILE = os.path.join(DART_SDK_DIR,'dart-sdk', 'lib', '_internal', 'libraries.dart') PATCH_FILE = os.path.join(MOJO_DIR...
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/importlib/_bootstrap_external.py
Python
gpl-3.0
53,437
0.000374
"""Core implementation of path-based import. This module is NOT meant to be directly imported! It has been designed such that it can be bootstrapped into Python as the implementation of import. As such it requires the injection of specific modules and attributes in order to work. One should use importlib as the public...
ge for each incompatible change to the bytecode. # # The value of CR and LF is incorporated so if you ever read or write # a .pyc file in text mode the magic
number will be wrong; also, the # Apple MPW compiler swaps their values, botching string constants. # # The magic numbers must be spaced apart at least 2 values, as the # -U interpeter flag will cause MAGIC+1 being used. They have been # odd numbers for some time now. # # There were a variety of old schemes for setting...
gratipay/gratipay.com
gratipay/cli/sync_npm.py
Python
mit
1,160
0.005172
# -*- coding: utf-8 -*- """Define the top-level function for the ``sync-npm`` cli. """ from __future__ import absolute_import, division, print_function, unicode_literals import time from aspen import log from gratipay import wireup from gratipay.sync_npm import consume_change_stream, get_last_seq, production_change_...
"Picking up with npm sync at {}.".format(last_seq)) stream = production_change_stream(last_seq) consume_change_stream(stream, db) try: last_seq = get_last_seq(db) sleep_for = 60 log( 'Encountered an error, will pick up with %s in %s seconds (Ctrl-C to ...
ing except KeyboardInterrupt: return
repotvsupertuga/repo
plugin.program.jogosEmuladores/speedtest.py
Python
gpl-2.0
6,577
0.013836
# This code is licensed under The GNU General Public License version 2 (GPLv2) # If you decide to fork this code please obey by the licensing rules. # # Thanks go to the-one who initially created the initial speedtest code in early 2014 # That code broke but it didn't take too much to fix it, if you get problems it's m
ost likely # down to the fact that you need to use another download link that plays nicely with XBMC/Kodi import xbmc, xbmcplugin import xbmcgui import xbmcaddon import urllib import time import os import sys import datetime ADDON_ID = 'plugin.program.jogosEmuladores' ADDON = xbmcaddon.Addon(id=ADDON_ID) HOME...
Wizard[/COLOR]" max_Bps = 0.0 currently_downloaded_bytes = 0.0 #----------------------------------------------------------------------------------------------------------------- def download(url, dest, dp = None): if not dp: dp = xbmcgui.DialogProgress() dp.create(AddonTitle,"Connecting to server"...
ancafarcas/superdesk-core
apps/publish/content/kill.py
Python
agpl-3.0
8,067
0.003967
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014, 2015 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from e...
item that is contained in normal non takes package # and the package itself is not killed. packages = self.package_service.get_packages(origi
nal[config.ID_FIELD]) if packages and packages.count() > 0: for package in packages: if package[ITEM_STATE] != CONTENT_STATE.KILLED and package.get(PACKAGE_TYPE, '') == '': raise SuperdeskApiError.badRequestError(message='This item is in a package. ' ...
jithinbp/SEELablet-apps
seel_res/GUI/B_ELECTRONICS/A_BJT_AND_FET/D_NFET_GS_ID.py
Python
gpl-3.0
3,753
0.045297
#!/usr/bin/python ''' Study Common Emitter Characteristics of NPN transistors. Saturation currents, and their dependence on base current can be easily visualize
d. ''' from __future__ import print_function import time,sys,os from SEEL_Apps.utilitiesClass import utilitiesClass from .templates import ui_NFET as NFET from PyQt4 import QtCore, QtGui import pyqtgraph as pg import numpy as np params = { 'image' : 'transistorCE.png', 'name':'N-FET Transfer\nCharacteristics', 'hi...
setupUi(self) self.I=kwargs.get('I',None) self.I.set_gain('CH1',2) self.setWindowTitle(self.I.H.version_string+' : '+params.get('name','').replace('\n',' ') ) self.plot=self.add2DPlot(self.plot_area,enableMenu=False) self.sig = self.rightClickToZoomOut(self.plot) labelStyle = {'color': 'rgb(255,255,255)',...
ArcherSys/ArcherSys
skulpt/test/run/pkga/pkgb/modc.py
Python
mit
54
0
prin
t "imported modc" stuff = 942 things = "
squirrel"
thinkopensolutions/odoo-brazil-banking
l10n_br_account_payment_boleto/boleto/document.py
Python
agpl-3.0
13,938
0.000502
# -*- coding: utf-8 -*- ############################################################################## # # Account Payment Boleto module for Odoo # Copyright (C) 2012-2015 KMEE (http://www.kmee.com.br) # @author Luis Felipe Miléo <mileo@kmee.com.br> # # This program is free software: you can redistribute it...
Exception(u'Configure o tipo de boleto no modo
de ' u'pagamento') @staticmethod def getBoletoClass(move_line): bank_code = move_line.payment_mode_id.bank_id.bank.bic return bank.get_class_for_codigo(bank_code) def __init__(self, move_line, nosso_numero): self._cedente(move_line.company_id) ...
gbiggs/rtshell
test/blorg.py
Python
lgpl-3.0
55
0.036364
a = 'blorg' def format(data
): return 'formatted
'
dougbenjamin/panda-harvester
pandaharvester/harvestercloud/google_startup_script.py
Python
apache-2.0
7,639
0.00432
#!/usr/bin/env python """ This script will be executed at the VM startup time. - It will download the proxy and panda queue from Google instance metadata - It will download the pilot wrapper from github and execute it - It will upload the pilot logs to panda cache """ import requests try: import subprocess32 as s...
ion token') # get the
URL (e.g. panda cache) to upload logs logs_frontend_w_url = METADATA_URL.format("logs_url_w") logs_frontend_w = get_url(logs_frontend_w_url, headers={"Metadata-Flavor": "Google"}) logging.debug('[main] got url to upload logs') # get the URL (e.g. panda cache) where the logs can be downloaded afterward...
Vauxoo/purchase
purchase_rfq_xls/model/purchase.py
Python
lgpl-3.0
6,913
0
# coding: utf-8 ########################################################################### # Module Writen to OpenERP, Open Source Management Solution # Copyright (C) Vauxoo (<http://vauxoo.com>). # All Rights Reserved # #############Credits######################################################### # Coded ...
################################################# # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or (at your # option) any later version. # #...
URPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ############################################################################### import base...
AtonLerin/pymel
tests/test_uitypes.py
Python
bsd-3-clause
8,047
0.001367
from __future__ import with_statement import sys import unittest import maya.cmds as cmds import pymel.core as pm import pymel.core.uitypes as ui if not hasattr(pm, 'currentMenuParent'): def currentMenuParent(): return ui.PyUI(cmds.setParent(q=1, menu=1)) pm.currentMenuParent = currentMenuParent cla...
elf.win): with pm.formLayout(): tsl = pm.textScrollList() tsl.extend(['a','b','c']) # Make sure this is NOT None self.as
sertEqual(tsl.getSelectItem(), []) if not pm.about(batch=1): for key, obj in globals().items(): if isinstance(obj, unittest.TestCase): del globals()[key] obj.__name__ = '_canceledTest_' + obj.__name__
eyalbenivri/amaterasu
executor/src/test/resources/py4j/tests/instrumented.py
Python
apache-2.0
5,570
0
from collections import deque import weakref import py4j.protocol as proto from py4j.clientserver import ( ClientServerConnection, ClientServer, JavaClient, PythonServer) from py4j.java_gateway import ( CallbackServer, JavaGateway, GatewayClient, GatewayProperty, PythonProxyPool, GatewayConnection, Callbac...
rgs, **kwargs) register_cre
ation(self) def _create_connection(self, socket_instance, stream): connection = InstrCallbackConnection( self.pool, stream, socket_instance, self.gateway_client, self.callback_server_parameters, self) return connection class InstrCallbackConnection(CallbackConnection): ...
jbassen/edx-platform
lms/djangoapps/certificates/views/xqueue.py
Python
agpl-3.0
10,063
0.002286
""" Views used by XQueue certificate generation. """ import json import logging from django.conf import settings from django.contrib.auth.models import User from django.http import HttpResponse, Http404, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import...
': 'unable to lookup key' }), mimetype='a
pplication/json') if 'error' in xqueue_body: cert.status = status.error if 'error_reason' in xqueue_body: # Hopefully we will record a meaningful error # here if something bad happened during the # certificate generation process ...
amaurywalbert/twitter
net_structure/old/hashmap_plot_network_structure_with_betweenness.py
Python
gpl-3.0
5,411
0.02556
# -*- coding: latin1 -*- ################################################################################################ # # import snap, datetime, sys, time, json, os, os.path, shutil, time, random, math import numpy as np from math import* # Script auxiliar para cálculos matemáticos que deve estar no mesmo diretóri...
###
####################################################################################################################################### ## Status - Versão 1 - Script para plotar propriedades estruturais das redes-ego ## ## ERRRO DE ALOCAÇÃO DE MEMÓRIA!!!!! #################################################...
ahmedbodi/temp_vert
qa/rpc-tests/bip68-112-113-p2p.py
Python
mit
27,353
0.008006
#!/usr/bin/env python3 # Copyright (c) 2015 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_...
run() def send_generic_input_tx(self, nod
e, coinbases): amount = Decimal("49.99") return node.sendrawtransaction(ToHex(self.sign_transaction(node, self.create_transaction(node, node.getblock(coinbases.pop())['tx'][0], self.nodeaddress, amount)))) def create_transaction(self, node, txid, to_address, amount): inputs = [{ "txid" : tx...
diegoguimaraes/django
tests/reserved_names/models.py
Python
bsd-3-clause
910
0
""" 18. Using SQL reserved names Need to use a reserved SQL name as a column name or table name? Need to include a hyphen in a column or table name? No problem. Django quotes names appropriately behind the scenes, so your database won't complain about reserved-name
usage. """ from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Thing(models.Model): when = models.CharField(max_leng
th=1, primary_key=True) join = models.CharField(max_length=1) like = models.CharField(max_length=1) drop = models.CharField(max_length=1) alter = models.CharField(max_length=1) having = models.CharField(max_length=1) where = models.DateField(max_length=1) has_hyphen = models.CharField(max_le...
n4hy/gnuradio
gr-uhd/examples/usrp_wfm_rcv.py
Python
gpl-3.0
11,057
0.008411
#!/usr/bin/env python # # Copyright 2005-2007,2009,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (a...
self.u.set_samp_rate(usrp_rate) dev_rate = self.u.get_samp_rate() nfilts = 32 chan_coeffs = optfir.low_pass (nfilts, # gain nfilts*usrp_rate, # sampling rate 80e3, # passband cutoff ...
115e3, # stopband cutoff 0.1, # passband ripple 60) # stopband attenuation rrate = usrp_rate / dev_rate self.chan_filt = blks2.pfb_arb_resampler_ccf(rrate, chan_coef...
hdzierz/Kaka
kaka/wsgi.py
Python
gpl-2.0
383
0.002611
""" WSGI config for kaka project. It exposes the WSGI callable as a module-level
variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefau
lt("DJANGO_SETTINGS_MODULE", "kaka.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
jpoullet2000/emelem
tests/base_tests.py
Python
apache-2.0
2,524
0.005151
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import json import os import unittest import logging from emelem import app, cli, db, appbuilder, security, sm logging.basicConfig(format='%(asctime)s:%(...
n(self): self.login() resp = s
elf.get_resp('/emelem/models/4/') log.info(resp) self.assertIn('"sklearn"', resp)
chshu/openthread
tools/harness-automation/cases/border_7_1_5.py
Python
bsd-3-clause
1,877
0
#!/usr/bin/env python # # Copyright (c) 2019, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notic...
prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR C...
UREMENT 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 SOFTWARE, EVEN IF ADVISED OF THE # POSSIBI...
entrepidea/projects
python/tutorials/algo/leetcode_easy/valid_parenthesis.py
Python
gpl-3.0
1,750
0.005714
""" desc: to check if the parentheses come in pairs. source: https://leetcode.com/problems/valid-parentheses/ date: 04/21/19 """ class Stack: def __init__(self): self.stack = [] def push(self,val): self.stack.append(val) return True def peek(self): return self.stack[-1]...
if stack.pop() != '(': return False return stack.is_em
pty() def test_valid_parentheses(): assert valid_parentheses('([{}])') == True def main(): test_stack() if __name__ == '__main__': main()
chenjic215/nickvoice
setup.py
Python
apache-2.0
347
0
#!/usr/bin/env python from setuptools import setup, find_packa
ges setup( name='pullstring-python', version='1.0.1', description='Python SDK to access the PullString Web API', author='PullString', author_email='
support@pullstring.com', url='https://github.com/pullstring/pullstring-python', packages=['pullstring'], )
rochacbruno/python-pagseguro
setup.py
Python
mit
1,420
0
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup readme = open('README.md').read() with open('requirements.txt') as reqs: requirements = reqs.read().split() setup( name='pagseguro', version='0.3.4', description='Pagseguro API v2 wr...
hacbruno/python-pagseguro', packages=['pagseguro', ], package_dir={'pagseguro': 'pagseguro'}, include_package_data=True, install_requires=requirements, long_description=readme,
long_description_content_type='text/markdown', license='MIT', test_suite='tests', zip_safe=False, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: ...
Nikita1710/ANUFifty50-Online-Mentoring-Platform
project/fifty_fifty/content/migrations/0004_auto_20170803_0535.py
Python
apache-2.0
700
0
# -*- coding: utf-8 -*- # Generated by Django 1.
11.1 on 2017-08-03 05:35 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('content', '0003_post_docfile'), ] operations = [ migrations.RemoveField( model_name='post', name='author', ...
name='published_date', ), migrations.RemoveField( model_name='post', name='text', ), ]
google/jax
jax/experimental/jax2tf/converters_eval/converters.py
Python
apache-2.0
6,284
0.009548
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
lt, tf_result, rtol)
# TFLite doesn't allow existing references to its data when it is # invoked. We therefore delete TF results so we can run multiple inputs on # the same interpreter. del tf_result del tf_results def jax2tf_xla(module: lib.ModuleToConvert): """Converts the given `module` using the jax2tf em...
google-research/falken
service/generated_flatbuffers/tflite/SpaceToDepthOptions.py
Python
apache-2.0
2,795
0.002147
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
namespace: tflite import flatbuffers from flatbuffers.compat import import_numpy np = import_numpy() class SpaceToDepthOptions(object
): __slots__ = ['_tab'] @classmethod def GetRootAsSpaceToDepthOptions(cls, buf, offset): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = SpaceToDepthOptions() x.Init(buf, n + offset) return x @classmethod def SpaceToDepthOptionsBufferHasIdent...
robocomp/robocomp
libs/innermodel-python3/innermodel_python3/innermodelprismaticjoint.py
Python
gpl-3.0
1,984
0.013609
from innermodeltransform import InnerModelTransform class InnerModelPrismaticJoint (InnerModelT
ransform): def __init__(self, id: s
tr, min: float, max: float, value: float, offset: float, port: int = 0, axis: str = 'z', home: float = 0, parent: 'InnerModelTransform' = None): super (InnerModelPrismaticJoint, self).__init__ (id, 'static', 0, 0, 0, 0, 0, 0, 0, parent) self.value = value self.offset = offset ...
OCA/social
mail_attach_existing_attachment_account/tests/test_mail_attach_existing_attachment_account.py
Python
agpl-3.0
1,621
0.001235
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import Form, common class TestMailAttachExistingAttachmentAccount(common.SavepointCase): @classmethod def setUpClass(cls): super().setUpClass() cls.product = cls.env["pr...
cls.income_account = cls.env["account.account"].search( [("user_type_id", "=", account_type.id)], limit=1, ) invoice_form = Form( cls.env["account.move"].with_context(default_move_type="out_invoice") ) invoice_form.partner_id = cls.partner wit...
orm.save() cls.invoice.action_post() def test_account_invoice_send(self): compose = Form( self.env["account.invoice.send"].with_context( active_ids=self.invoice.ids, default_model=self.invoice._name, default_res_id=self.invoice.id, ...
raccoongang/edx-platform
cms/envs/common.py
Python
agpl-3.0
42,534
0.002962
# -*- coding: utf-8 -*- """ This is the common settings file, intended to set sane defaults. If you have a piece of configuration that's dependent on a set of feature flags being set, then create a function that returns the calculated value based on the value of FEATURES[...]. Modules that extend this one can change th...
selector in the header 'SHOW_HEADER_LANGUAGE_SELECTOR': False, # Set this to False to facilitate cleaning up invalid xml from your modulestore. 'ENABL
E_XBLOCK_XML_VALIDATION': True, # Allow public account creation 'ALLOW_PUBLIC_ACCOUNT_CREATION': True, # Whether or not the dynamic EnrollmentTrackUserPartition should be registered. 'ENABLE_ENROLLMENT_TRACK_USER_PARTITION': True, } ENABLE_JASMINE = False ############################# SOCIAL MEDIA S...
quantmind/pulsar
pulsar/utils/version.py
Python
bsd-3-clause
2,619
0
from datetime import datetime import os import subprocess symbol = {'alpha': 'a', 'beta': 'b'} def get_version(version, filename=None): assert len(version) == 5 assert version[3] in ('alpha', 'beta', 'rc', 'final') main = '.'.join(map(str, version[:3])) sub = '' if version[3] == 'alpha' and versi...
out=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=cwd,
universal_newlines=True).communicate()[0] def get_git_changeset(filename=None): """Returns a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so i...
js0701/chromium-crosswalk
tools/telemetry/telemetry/internal/platform/power_monitor/android_power_monitor_base.py
Python
bsd-3-clause
1,359
0.011038
# Copyright 2014 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. import logging from telemetry.internal.platform import power_monitor class AndroidPowerMonitorBase(power_monitor.PowerMonitor): # Abstract class. # p...
al usage. %s' % (power_data)) if power_data['application_energy_consumption_mwh'] == 0: logging.warning('Power data is re
turning 0 usage for %s. %s' % (package, power_data))
joshlk/scrapy
scrapy/tests/test_spidermiddleware_offsite.py
Python
bsd-3-clause
1,982
0.004036
from unittest import TestCase from scrapy.http import Response, Request from scrapy.spider import Spider from scrapy.contrib.spidermiddleware.offsite import OffsiteMiddleware from scrapy.utils.test import get_crawler class TestOffsiteMiddleware(TestCase): def setUp(self): self.spider = self._get_spider(...
tp://offsite.tld/'),
Request('http://offsite.tld/scrapytest.org'), Request('http://offsite.tld/rogue.scrapytest.org'), Request('http://rogue.scrapytest.org.haha.com'), Request('http://roguescrapytest.org')] reqs = onsite_reqs + offsite_reqs out ...
rlishtaba/py-algorithms
py_algorithms/array/circular_array.py
Python
mit
1,512
0
class CircularArray: __slots__ = '_list', '_front', '_rear', '_n' def __init__(self, n): self._list = [None for _ in range(n)] self._n = n self._front = 0 self._rear = 0 def size(self): if self._rear >= self._front: return self._rear - self._front ...
if __name__ == '__main__': arr = CircularArray(5) arr.enqueue(1)
arr.enqueue(2) arr.enqueue(3) print(arr.dequeue()) print(arr.dequeue()) arr.enqueue(9) arr.enqueue(4) arr.enqueue(5) arr.enqueue(6) arr.enqueue(7) arr.enqueue(8) arr
openkamer/openkamer
person/tests.py
Python
mit
11,436
0.001662
import datetime import requests from django.test import TestCase from wikidata import wikidata from person.models import Person from person.util import parse_name_surname_initials, parse_surname_comma_surname_prefix class TestFindName(TestCase): @classmethod def setUpTestData(cls): cls.p1 = Person...
idata_item.get_label() forename, surname, surname_prefix = Person.get_name_parts(fullname, wikidata_item) self.assertEqual(forename, 'Sybrand') self.assertEqual(surname, 'Haersma Buma') self.assertEqual(surname_prefix, 'van') def test_chantal_nijkerken_de_haan(self):
wikidata_id = 'Q19830701' wikidata_item = wikidata.WikidataItem(wikidata_id) fullname = wikidata_item.get_label() forename, surname, surname_prefix = Person.get_name_parts(fullname, wikidata_item) self.assertEqual(forename, 'Chantal') self.assertEqual(surname, 'Nijkerken...
marioyc/Hand-written-Digit-Recognition
Assignment 1 - Neural networks/predict.py
Python
mit
628
0.011146
from numpy import * from sigmoid import sigmoid def predict(Theta, X): # Takes as input a number of instances and the network learned variables # Returns a vector of the predicted labels # Useful values m = X.shape[0] num_labels = Theta[-1].shape[0] num_layers = len(Theta) + 1 # You need ...
turn the following variables correctly p = zeros((1,m)) for t in ra
nge(0,m): a = X[t] for i in range(0,num_layers - 1): a = insert(a,0,values=1,axis=0) z = a.dot(transpose(Theta[i])) a = sigmoid(z) p[0][t] = argmax(a) return p
SINGROUP/pycp2k
pycp2k/classes/_cartesian_eigs1.py
Python
lgpl-3.0
746
0.002681
from pycp2k.inputsection import InputSection from ._each421 import _each421 class _cartesian_eigs
1(InputSection): def __init__(self): InputSection.__init__(self) self.Section_parameters = None self.Add_last = None self.Common_iteration_levels = None self.Filename = None self.Log_print_key = None self.Backup_copies = None self.EACH = _each421() ...
', 'Common_iteration_levels': 'COMMON_ITERATION_LEVELS', 'Backup_copies': 'BACKUP_COPIES'} self._subsections = {'EACH': 'EACH'} self._attributes = ['Section_parameters']
jimsize/PySolFC
pysollib/winsystems/common.py
Python
gpl-3.0
3,751
0
#!/usr/bin/env python # -*- mode: python; coding: utf-8; -*- # --------------------------------------------------------------------------- # # Copyright (C) 1998-2003 Markus Franz Xaver Johannes Oberhumer # Copyright (C) 2003 Mt. Hood Playing Card
Co. # Copyright (C) 2005-2009 Skomoroh # # 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 later version. #
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along...
UT-CHG/PolyADCIRC
examples/pyGriddata/manufactureGAP_vertical.py
Python
bsd-3-clause
610
0.001639
i
mport polyadcirc.run_framework.domain as dom import polyadcirc.pyGriddata.manufacture_gap as manu grid_dir = '.' domain = dom.domain(grid_dir) domain.read_spatial_grid() x_values = [n.x for n in domain.node.values()] y_values = [n.y for n in domain.node.values()] xr = max(x_values) xl = min(x_values) yu = max(y_valu...
, 0, 0, 1] p3 = [.2, .3, .4, .1] rand_rect = manu.random_vertical(x_points, yl, yu, [1, 2, 3, 4], p_sections= [p1, p2, p3]) manu.write_gapfile(rand_rect, xl, yl, 'sections.asc')
antoinecarme/pyaf
tests/model_control/detailed/transf_RelativeDifference/model_control_one_enabled_RelativeDifference_MovingMedian_Seasonal_DayOfMonth_SVR.py
Python
bsd-3-clause
174
0.045977
import tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_
model( ['RelativeDifference'] , ['MovingMedian'
] , ['Seasonal_DayOfMonth'] , ['SVR'] );
virtuald/exaile
xl/plugins.py
Python
gpl-2.0
9,679
0.003926
# Copyright (C) 2008-2010 Adam Olsen # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that...
return False sys.path.insert(0, path) plugin = imp.load_source(pluginname, os.path.join(path,'__init__.py')) if hasattr(plugin, 'plugin_class'): plugin = plugin.plugin_class() sys.path = sys.path[1:] self.loaded_plugins[pluginname] = plugin return plu...
except (tarfile.ReadError, OSError): raise InvalidPluginError( _('Plugin archive is not in the correct format.')) #ensure the paths in the archive are sane mems = tar.getmembers() base = os.path.basename(path).split('.')[0] if os.path.isdir(os.path.join(self...
themylogin/flask-security
flask_security/forms.py
Python
mit
9,925
0.000101
# -*- coding: utf-8 -*- """ flask_security.forms ~~~~~~~~~~~~~~~~~~~~ Flask-Security forms module :copyright: (c) 2012 by Matt Wright. :copyright: (c) 2017 by CERN. :license: MIT, see LICENSE for more details. """ import inspect from flask import Markup, current_app, flash, request from flas...
ass email_required = Required(message='EMAIL_NOT_PROVIDED') email_validator = Email(message='INVALID_EMAIL_ADDRESS') password_required = Required(message='PASSWORD_NOT_PROVIDED') password_length = Length(min=6, max=1
28, message='PASSWORD_INVALID_LENGTH') def get_form_field_label(key): return _get_i18n_domain(current_app).lazy_gettext(_default_field_labels.get(key, '')) def unique_user_email(form, field): if _datastore.get_user(field.data) is not None: msg = get_message('EMAIL_ALREADY_ASSOCIATED', email=field.da...
juliotrigo/restfulwebapi
restfulwebapisite/urls.py
Python
bsd-3-clause
1,035
0.005797
# -*- coding: utf-8 -*- """urls module of the website.""" from django.conf.urls imp
ort patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'restfulwebapisite.views.home', name='home'), # url(r'^restfulwebapisite/', include('restfulwebapisite.foo.urls')), # ...
Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^cinema/', include('cinema.urls', namespace='cinema', app_name='cinema')), url(r'^accounts/', include('accounts.urls', namespace='accounts', app_name='accounts')), #url(r'^i18n/', include('django.conf.urls.i...
satary/fretty
image_widget.py
Python
gpl-2.0
4,816
0.016822
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) Grigoriy A. Armeev, 2015 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as· # published by the Free Software Foundation. # # This program is distributed in the hope th...
''' self.currentPath=self.label.path=path self.pixmap=QtGui.QPixmap(path) self.label.initsize=self.pixmap.size() size=self.size()#-QtCore.QSize(20,20) self.resizeImage(size) def emitWigetPressedSignal(self, coord, path):
''' Emits signal imageWigetPressed wich provides coordinates of in pixels (as on initial picture) and path to that picture ''' self.emit(QtCore.SIGNAL("imageWigetPressed"),coord,path) def emitWigetHoveredSignal(self, coord, path): ''' Emits signal imag...
jlegendary/orange
Orange/OrangeWidgets/Unsupervised/OWSOMVisualizer.py
Python
gpl-3.0
52,366
0.00802
""" <name>SOM Visualizer</name> <description>Visualizes a trained self organising maps.</description> <icon>icons/SOMVisualizer.svg</icon> <contact>Ales Erjavec (ales.erjavec(@at@)fri.uni-lj.si)</contact> <priority>5020</priority> """ import orange, orngSOM import math, numpy import OWGUI, OWColorPalette from OWWidget...
Brush(QBrush(self.colorSchema(index))) def paint(self, painter, option, widget=0): QGraphicsEllipseItem.paint(self, painter, option, widget) class MajorityProbChart(MajorityChart): d
ef __init__(self, *args, **kwargs): MajorityChart.__init__(self, *args, **kwargs) index = int(numpy.argmax(list(s