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
Adarnof/adarnauth-eveonline
eveonline/tasks.py
Python
gpl-3.0
2,156
0.000464
from celery.task import periodic_task from celery import shared_task from eveonline.models import Character, Corporation, Alliance from eveonline.providers import eve_provider_factory from datetime import timedelta @shared_task def update_character(obj_id, provider=None): """ Updates a given character model a...
lta(hours=3)) def update_all_characters(): """ Triggers an update of all Character models """ char_ids = [c.id for c in Character.objects.all()] provider = eve_provider_factory() for obj_id in char_ids: update_character.delay(obj_id, provider=provider) @periodic_task(run_every=timedelt...
provider = eve_provider_factory() for obj_id in corp_ids: update_corporation.delay(obj_id, provider=provider) @shared_task # data only changes very rarely on CCP intervention, don't queue periodically def update_all_alliances(): """ Triggers an update of all Alliance models """ alliance_i...
armstrong/armstrong.core.arm_layout
tests/backends/_common.py
Python
apache-2.0
4,747
0.000421
import abc import random import fudge from contextlib import contextmanager from ..support.models import * class BackendTestCaseMixin(object): __metaclass__ = abc.ABCMeta @abc.abstractproperty # pragma: no cover def backend_class(self): """backend_class = TestThisBackend""" def __init__(se...
el_name_in_template_name(self): model = Foobar() with self.model_meta_randomizer(model, 'object_name') as object_name: expected = ['layout/%s/%s/%s.html' % ( model._meta.app_label, object_name, self.name)] result = self.backend.get_layout_template_name(model, sel...
name = "random_%d" % random.randint(100, 200) expected = ['%s%s.html' % (self.root_model_path, name)] result = self.backend.get_layout_template_name(Foobar(), name) self.assertEqual(expected, result) def test_proper_model_inheritance_order(self): model = SubFoobar() mod...
beomyeol/models
inception/inception/slim/ops.py
Python
apache-2.0
18,781
0.003408
# Copyright 2016 Google Inc. 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 or agree...
model is in training mode. trainable: whether or not the variables should be trainable or not. restore
: whether or not the variables should be marked for restore. scope: Optional scope for variable_scope. reuse: whether or not the layer and its variables should be reused. To be able to reuse the layer scope must be given. Returns: a tensor representing the output of the operation. """ inputs_s...
freneticmonkey/epsilonc
resources/scripts/core/basesingleton.py
Python
mit
263
0.015209
''' Created on Nov 19, 2011 @author: scottporter '''
class BaseSingleton(object): _instance = None @classmethod def get_instance(cls): if cls._instance is No
ne: cls._instance = cls() return cls._instance
bwmichael/jccc-cis142-python
old/roll-the-dice.py
Python
apache-2.0
871
0
## # @author Brandon Michael # Roll the dice based on the user's input. Track double rolls and display # the double totals. # import the random library import random # Set the start and end values the same as a dice start = 1 end = 6 # Set the running total for doubles found totalDoubles = 0 # Get th
e number of t
imes we need to roll the dice rolls = int(input("Enter the number of dice rolls: ")) # Loop through the number of rolls for num in range(0, rolls, 1): # Capture the rolls to check for doubles roll_1 = random.randint(start, end) roll_2 = random.randint(start, end) # Check if rolls equal each other, and...
maxamillion/ansible
test/support/integration/plugins/modules/mongodb_user.py
Python
gpl-3.0
16,253
0.002953
#!/usr/bin/python # (c) 2012, Elliott Foster <elliott@fourkitchens.com> # Sponsored by Four Kitchens http://fourkitchens.com. # (c) 2014, Epic Games, Inc. # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __m...
se: burgers name: bob password: 12345 state: present ssl: True - name: Delete 'burgers' database user with name 'bob'. mongodb_user: database: burgers name: bob state: absent - name: Define more users with various specific roles (if not defined, no roles is assign
ed, and the user will be added via pre mongo 2.2 style) mongodb_user: database: burgers name: ben password: 12345 roles: read state: present - name: Define roles mongodb_user: database: burgers name: jim password: 12345 roles: readWrite,dbAdmin,userAdmin state: present - na...
ipedrazas/dotmarks-api
src/app.py
Python
apache-2.0
197
0.005076
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __na
me__ == "__main__": app.run(host='0.0.0.0', port=5000, debug=True, threaded=True)
gurkslask/hamcwebc
tests/test_models.py
Python
bsd-3-clause
1,951
0
# -*- coding: utf-8 -*- """Model unit tests.""" import datetime as dt import pytest from hamcwebc.user.models import Role, User from .factories import UserFactory @pytest.mark.usefixtures('db') class TestUser: """User tests.""" def test_get_by_id(self): """Get user by ID.""" user =
User('foo', 'foo@bar.com') user.save() retrieved = User.get_by_id(user.id) assert retrieved == user def test_created_at_defaults_to_datetime(self): """Test creation date.""" user = User(username='foo', email='foo@bar.com') user.save() assert bool(user.creat...
r = User(username='foo', email='foo@bar.com') user.save() assert user.password is None def test_factory(self, db): """Test user factory.""" user = UserFactory(password='myprecious') db.session.commit() assert bool(user.username) assert bool(user.email) ...
vertical-knowledge/flask-ripozo
flask_ripozo_tests/integration/dispatcher.py
Python
gpl-2.0
1,809
0.001106
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from flask import Flask, request from flask_ripozo.dispatcher import get_request_query_body_args import json import unittest2 class TestDispatcherFlaskIntegration(uni...
query_body_args(request) self.assertDictEqual(b, body) def test_headers_copyable(self): """ Tests that the headers returned from get_request_query_body_args appropriately returns the headers as a dic
tionary that can be copied """ app = Flask('myapp') with app.test_request_context('/'): q, b, headers = get_request_query_body_args(request) headers2 = headers.copy() self.assertDictEqual(headers, headers2)
therewillbecode/ichnaea
ichnaea/data/internal.py
Python
apache-2.0
4,710
0
from collections import defaultdict from datetime import datetime import pytz import simplejson from ichnaea.data.export import ( MetadataGroup, ReportUploader, ) class InternalTransform(object): # *_id maps a source section id to a target section id # *_map maps fields inside the section from sour...
two-tuple position_id = ('position', None) position_map = [ ('latitude', 'lat'), ('longitude', 'lon'), 'accuracy', 'altitude', ('altitudeAccuracy', 'altitude_accuracy'), 'age', 'heading', 'pressure', 'speed', 'source', ] ...
cell_map = [ ('radioType', 'radio'), ('mobileCountryCode', 'mcc'), ('mobileNetworkCode', 'mnc'), ('locationAreaCode', 'lac'), ('cellId', 'cid'), 'age', 'asu', ('primaryScramblingCode', 'psc'), 'serving', ('signalStrength', 'signal'), ...
AlexanderPease/IntroBot
lib/mongo.py
Python
gpl-3.0
653
0.02144
import logging import pymongo import sett
ings class Proxy(object): _db = None def __getattr__(self, name): if Proxy._db == None: # lazily connect to the db so we pickup the right environment settings mongo_database = settings.get('mongo_database') print mongo_database logging.info("connecting to mongo at %s:%d/%s" % (mongo_da...
ost'], mongo_database['port'], mongo_database['db'])) connection = pymongo.MongoClient(mongo_database['host'], mongo_database['port'], connectTimeoutMS=5000, max_pool_size=200) Proxy._db = connection[mongo_database['db']] return getattr(self._db, name) db = Proxy()
GoogleCloudPlatform/sap-deployment-automation
third_party/github.com/ansible/awx/installer/roles/image_build/files/settings.py
Python
apache-2.0
2,976
0.00168
# AWX settings file import os def get_secret(): if os.path.exists("/etc/tower/SECRET_KEY"): return open('/etc/tower/SECRET_KEY', 'rb').read().strip() ADMINS = () STATIC_ROOT = '/var/lib/awx/public/static' PROJECTS_ROOT = '/var/lib/awx/projects' AWX_ANS
IBLE_COLLECTIONS_PATHS = '/var/lib/awx/vendor/awx_ansible_collections' JOBOUTPUT_ROOT = '/var/lib/awx/job_status' SECRET_KEY = get_secret() ALLOWED_HOSTS = ['*'] # Container environments don't like chroots AWX_PROOT_ENABLED = False CLUSTER_HOST_ID = "awx" SYSTEM_UUID = '00000000-0000-0000-0000-000000000000' CSRF...
###################################################################### # EMAIL SETTINGS ############################################################################### SERVER_EMAIL = 'root@localhost' DEFAULT_FROM_EMAIL = 'webmaster@localhost' EMAIL_SUBJECT_PREFIX = '[AWX] ' EMAIL_HOST = 'localhost' EMAIL_PORT = 25 EM...
gazoo74/linux
scripts/gdb/linux/config.py
Python
gpl-2.0
1,302
0
# SPDX-License-Identifier: GPL-2.0 # # Copyright 2019 Google LLC. import gdb import zlib from linux import utils class LxConfigDump(gdb.Command): """Output kernel config to the filename specified as the command argument. Equivalent to 'zcat /proc/config.gz > config.txt' on a running target""" ...
dbError("Can't find config, enable CONFIG_IKCONFIG?") inf = gdb.inferiors()[0] zconfig_buf = utils.read_memoryview(inf, py_config_ptr, py_config_size).tobytes()
config_buf = zlib.decompress(zconfig_buf, 16) with open(filename, 'wb') as f: f.write(config_buf) gdb.write("Dumped config to " + filename + "\n") LxConfigDump()
SteveDiamond/cvxpy
cvxpy/reductions/complex2real/atom_canonicalizers/constant_canon.py
Python
gpl-3.0
912
0
""" Copyright 2013 Steven Diamond 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 appl
icable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from cvxpy.expre
ssions.constants import Constant def constant_canon(expr, real_args, imag_args, real2imag): if expr.is_real(): return Constant(expr.value.real), None elif expr.is_imag(): return None, Constant(expr.value.imag) else: return (Constant(expr.value.real), Constant(expr.v...
cathyyul/sumo
tools/build/checkSvnProps.py
Python
gpl-3.0
6,649
0.004061
#!/usr/bin/env python """ @file checkSvnProps.py @author Michael Behrisch @date 2010 @version $Id: checkSvnProps.py 14493 2013-08-24 21:24:04Z behrisch $ Checks svn property settings for all files. SUMO, Simulation of Urban MObility; see http://sumo-sim.org/ Copyright (C) 2010-2013 DLR (http://www.dlr.de/) and...
file]) if ex
t in _SOURCE_EXT: if name == 'property' and self._property == "svn:keywords" and self._value != _KEYWORDS\ or name == "target" and not self._hadKeywords: print self._file, "svn:keywords", self._value if self._fix: subproc...
neuropower/neuropower
neuropower/apps/designtoolbox/batch/neurodesign.py
Python
mit
6,551
0.009312
import django import sys import os sys.path.append('/tmp/neuropower-web/neuropower') os.environ['DJANGO_SETTINGS_MODULE'] = 'settings.settings' django.setup() from neurodesign import design, experiment, population, generate, msequence, report from sqlalchemy.exc import OperationalError, DatabaseError from django.core....
n.F) if POP.wei
ghts[1] > 0: desdata = DesignModel.objects.filter(SID=sid).first() runform = DesignRunForm(None, instance=desdata) form = runform.save(commit=False) form.running = 3 form.metrics = "" form.bestdesign = '' form.save() POP.cle...
Babtsov/Python-Scripts
emailExtract.py
Python
mit
2,106
0.006648
# This program extracts UF email addresses from a CSV file and prints them organized by class sections. import os import re COURSE_NAME = "EEE3308C" def extractEmailAddress(list): for item in list: if "@ufl.edu" in item: return item raise RuntimeError def extractCVSInfo(namePattern): ...
" CSV files in the current directory: ", csvFiles) print("Please make sure there is only one " + COURSE_NAME + " CSV f
ile and try again.") exit() elif len(csvFiles) == 0: print("No " + COURSE_NAME + " CSV file found in current directory. Please try again.") exit() try: with open(csvFiles[0], "r") as studentInfo: lines = [row.split(",") for row in studentInfo] except EnvironmentEr...
flyapen/UgFlu
flumotion/admin/gtk/overlaystep.py
Python
gpl-2.0
5,429
0.000553
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com). # All rights reserved. # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the ...
cal' def __init__(self, wizard, video_producer): self.model = Overlay(video_producer) WorkerWizardStep.__init__(self, wizard) # Public API def getOverlay(self): if self.model.hasOverlay():
return self.model # Wizard Step def setup(self): self.text.data_type = str self.add_proxy(self.model, ['show_logo']) self.add_proxy(self.model.properties, ['show_text', 'text']) def workerChanged(self, worker): self.model.worker = worker self._checkElements() ...
ActiveState/code
recipes/Python/535129_Groupby_hierarchy_tree/recipe-535129.py
Python
mit
396
0.007576
from
operator import itemgetter from itertools import groupby def groupby2(cols, lst, lev=0): if not cols: return str(list(lst)) keyfun = itemgetter(cols[0]) srted = sorted(list(lst), key=keyfun) output = "" for key, iter in groupby(srted, key=keyfun): output += "\n"+" "*lev+"%10s:"%...
, lev+1) return output
sequana/sequana
test/test_phred.py
Python
bsd-3-clause
1,451
0.002757
from sequana import Quality from sequana import phred def test_quality(): q = Quality('ABC') q.plot() assert q.mean_quality == 33 q = phred.QualitySanger('ABC') q = phred.QualitySolexa('ABC') def test_ascii_to_quality(): assert phred.ascii_to_quality("!") == 0 assert phred.ascii_to_qual...
to_proba(): assert phred.quality_to_proba_sanger(0) == 1 assert phred.quality_to_proba_sanger(40) == 0.0001 def test_others(): #sanger proba quality assert phred.
proba_to_quality_sanger(0) == 93 assert phred.proba_to_quality_sanger(0.0001) == 40 assert phred.proba_to_quality_sanger(1) == 0 assert phred.proba_to_quality_sanger(2) == 0 # solexa proba quality assert phred.proba_to_quality_solexa(0) == 62 assert abs(phred.proba_to_quality_solexa(0.0001) - ...
Just-D/chromium-1
content/test/gpu/gpu_tests/gpu_test_expectations.py
Python
bsd-3-clause
3,819
0.006546
# 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 test_expectations # Valid expectation conditions are: # # Operating systems: # win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlio...
ined_conditions if x in BROWSER_TYPE_MODIFIERS] browser_matches = ((not browser_expectations) or browser.browser_type in browser_expectations) if not browser_matches: return False angle_renderer = '' gpu_info = None if browser.supports_system_...
tes.get('gl_renderer') if gl_renderer: if 'Direct3D11' in gl_renderer: angle_renderer = 'd3d11' elif 'Direct3D9' in gl_renderer: angle_renderer = 'd3d9' elif 'OpenGL' in gl_renderer: angle_renderer = 'opengl' angle_expectations = [x for x in expectation.us...
jicksy/oneanddone_test
vendor-local/lib/python/caching/invalidation.py
Python
mpl-2.0
7,039
0.000142
import collections import functools import hashlib import logging import socket from django.conf import settings from django.core.cache import cache as default_cache, get_cache, parse_backend_uri from django.core.cache.backends.base import InvalidCacheBackendError from django.utils import encoding, translation try: ...
"" new_keys = keys = set(map(flush_key, keys)) flush = set(keys) # Add other flush keys from the lists, which happens when a parent # object includes a foreign key. while 1: to_flush = self.get_flush_lists(new_keys) flush.update(to_flush) new_...
keys.update(new_keys) else: return flush, keys def add_to_flush_list(self, mapping): """Update flush lists with the {flush_key: [query_key,...]} map.""" flush_lists = collections.defaultdict(set) flush_lists.update(cache.get_many(mapping.keys())) f...
HarmonyEnterpriseSolutions/harmony-platform
src/gnue/common/utils/FileUtils.py
Python
gpl-2.0
1,224
0.001634
# -*- coding: iso-8859-1 -*- # # This file is part of GNU Enterprise. # # GNU Enterprise 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. # # GNU Enter...
NTABILITY 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 # Lic
ense along with program; see the file COPYING. If not, # write to the Free Software Foundation, Inc., 59 Temple Place # - Suite 330, Boston, MA 02111-1307, USA. # # Copyright 2001-2007 Free Software Foundation # # FILE: # FileUtils.py # # DESCRIPTION: # Common file/url/resource related utilities # # NOTES: # TODO: Depr...
simpleenergy/epochdatetimefield
setup.py
Python
mit
1,135
0.003524
#!/usr/bin/env python from setuptools import setup, find_packages import subprocess import os __doc__ = """ App for Django to allow using datetime objects over integer fields. """ def read
(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() STAGE = 'alpha' version = (0, 1, 1, STAGE) def get_version(): number = '.'.join(map(str, version[:3])) stage = version[3] if stage == 'final':
return number elif stage == 'alpha': process = subprocess.Popen('git rev-parse HEAD'.split(), stdout=subprocess.PIPE) stdout, stderr = process.communicate() return number + '-' + stdout.strip()[:8] setup( name='epochdatetimefield', version=get_version(), description=__doc__, ...
lucashanke/houseofdota
manage.py
Python
mit
266
0.003759
#!/usr/bin/env python3 import
os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "houseofdota.production_settings") from django.core.management import execute_from_command_line execute_from_command_li
ne(sys.argv)
rkuchan/Tax-Calculator
docs/source/conf.py
Python
mit
11,210
0.00678
# -*- coding: utf-8 -*- # # Tax Calculator documentation build configuration file, created by # sphinx-quickstart on Mon Mar 9 17:06:10 2015. # # 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...
to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_dom
ain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML...
ikargis/horizon_fod
openstack_dashboard/dashboards/admin/hypervisors/tables.py
Python
apache-2.0
3,056
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 B1 Systems GmbH # # 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 #...
or.local_gb) def get_local_used(hypervisor): return sizeformat.diskgbformat(hypervisor.local_gb_used) class AdminHypervisorsTable(tables.DataTable): hostname = tables.Column("hypervisor_hostname", link=("horizon:admin:hypervisors:detail"), verbose_na...
pervisor_type", verbose_name=_("Type")) vcpus = tables.Column("vcpus", verbose_name=_("VCPUs (total)")) vcpus_used = tables.Column("vcpus_used", verbose_name=_("VCPUs (used)")) memory = tables.Column(get_memory, ...
kreczko/rootpy
rootpy/stats/dataset.py
Python
gpl-3.0
1,394
0.005022
# Copyright 2012 the rootpy developers # distributed under the terms of the GNU General Public License from __future__ import absolute_import import ROOT from . import log; log = log[__name__] from .. import QROOT, asrootpy from ..base import NamedObject from ..extern.six import string_types __all__ = [ 'DataSet...
lf): return asrootpy(self.dataset_.get(self.idx_)) @property def weight(self): self.dataset_.get(self.idx_) #set current ev
ent return self.dataset_.weight() def __len__(self): return self.numEntries() def __getitem__(self, idx): return DataSet.Entry(idx, self) def __iter__(self): for idx in range(len(self)): yield DataSet.Entry(idx, self) def createHistogram(self, *args, *...
RENCI/xDCIShare
hs_app_timeseries/migrations/0002_auto_20150813_1247.py
Python
bsd-3-clause
302
0
# -*- coding: utf-8 -*- from _
_future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('hs_app_timeseries', '0001_initial'), ] operations = [ migrations.DeleteModel('TimeSeriesResource'
), ]
wathen/PhD
MHD/FEniCS/MyPackage/PackageName/PETScFunc/__init__.py
Python
mit
26
0
from PETScMatOps import
*
mitodl/micromasters
financialaid/migrations/0006_update_tierprogram.py
Python
bsd-3-clause
574
0.001742
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-09-28 18:38 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('financialaid', '0005_switch_jsonfield'), ] operatio...
'tier', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tier_programs', to='financia
laid.Tier'), ), ]
Lonkal/ProjectEuler
problem4.py
Python
mit
255
0.058824
#problem 4 import math def isPalidrome(t
est): return str(test) == str(test)[::-1] #op extended slicing feature max = 0 for i in range(999,99,-
1): for j in range(999,99,-1): prod = i*j if isPalidrome(prod) and prod > max: max = prod print max
softwaremechanic/Miscellaneous
Python/hw.py
Python
gpl-2.0
49
0
def a(*a
rgs, **kwargs): print("hello world")
zstackorg/zstack-utility
cephprimarystorage/cephprimarystorage/cdaemon.py
Python
apache-2.0
1,450
0.006897
''' @author: frank ''' import sys, os, os.path from zstacklib.utils import log from zstacklib.utils import linux import zstacklib.utils.iptables as iptables pidfile = '/var/run/zstack/ceph-primarysto
rage.pid' log.configure_log('/var/log/zstack/ceph-primarystorage.log') logger = log.get_logger(__name__) import cephagent def pr
epare_pid_dir(path): pdir = os.path.dirname(path) if not os.path.isdir(pdir): os.makedirs(pdir) def main(): usage = 'usage: python -c "from cephprimarystorage import cdaemon; cdaemon.main()" start|stop|restart' if len(sys.argv) != 2 or not sys.argv[1] in ['start', 'stop', 'restart']: ...
typesupply/dialogKit
install.py
Python
mit
852
0.014085
"""Install script for the dialogKit Package. This script installs a _link_ to the current location of dialogKit. It does not copy anything. It also means that if you move your dialogKit folder, you'll have to run the install script again. """ from distutils.sysconfig import get_python_lib import os, sys def instal...
me, 'w') f.write(srcDir) f.close() return fileName dir = os.path.join(os.path.dirname(os.path.normpath(os.path.abspath(sys.argv[0]))), "Lib") p = install(dir, "dialogKit") print "dialogKit is now installed." print "(Note that you have to run the install script
again if you move your dialogKit folder)"
jpoullet2000/cgs-benchmarks
hbase-benchmarks/hbase_import_process.py
Python
apache-2.0
21,976
0.011058
#!/usr/bin/python # -*- coding: utf-8 -*- import os import urllib import zlib import zipfile import math import sys import json import time import bz2 import gzip import binascii import requests import random from subprocess import * import subprocess import threading import MySQLdb # See http:/...
database = "Iridia" highlander_user = "iridia" highlander_password = "iri.2742" local_host = "127.0.0.1" local_database = "highlander_chromosomes" local_user = "root" local_password = "Olgfe65grgr" current_server_url = 'http://62.210.254.52' cluster_url = 'http://insilicodb.ulb.ac.be:8888' querySession =...
'gdegols','password':'z9FNeTrQJYaemAtyUVva'} r = querySession.post(cluster_url+'/accounts/login/',data=info) target_database = "hbase" # "hbase" or "impala_text" global_upload_state = False # If False, we download the data. If True, we upload the data previously downloaded. # This function returns the differe...
ininex/geofire-python
resource/lib/python2.7/site-packages/pyrebase/pyrebase.py
Python
mit
21,697
0.001751
import requests from requests import Session from requests.exceptions import HTTPError try: from urllib.parse import urlencode, quote except: from urllib import urlencode, quote import json import math from random import uniform import time from collections import OrderedDict from sseclient import SSEClient im...
fresh_token"] } return user def get_account_info(self, id_token): request_ref = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key
={0}".format(self.api_key) headers = {"content-type": "application/json; charset=UTF-8"} data = json.dumps({"idToken": id_token}) request_object = requests.post(request_ref, headers=headers, data=data) raise_detailed_error(request_object) return request_object.json() def sen...
wking/thumbor
thumbor/storages/redis_storage.py
Python
mit
4,944
0
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com timehome@corp.globo.com import logging from json import loads, dumps from datetime import da...
host=self.context.config.REDIS_STORAGE_SERVER_HOST, db=self.context.config.REDIS_STORAGE_SERVER_DB, password=self.context.config.REDIS_STORAGE_SERVER_PASSWORD ) if self.shared_client: Storage.storage = storage return storage def on_redis_error(self, fn...
: '''Callback executed when there is a redis error. :param string fname: Function name that was being called. :param type exc_type: Exception type :param Exception exc_value: The current exception :returns: Default value or raise the current exception ''' if sel...
nananan/Cinnamon
analyzePackage.py
Python
gpl-3.0
39,675
0.009679
#!/usr/bin/python import scapy #import scapy_ex import os,sys import printerInfo import enum from enum import Enum from scapy.all import * import time, datetime #from time import sleep class Message(Enum): AUTH = "0" DEAUTH = "1" PROBE_REQ = "2" PROBE_RESP = "3" HAND_SUCC = "4" HAND_F...
DER_LOG + date + AnalyzePackage.EXTENSION_LOG #self.fileLog = open(self.titleLog, "w+") f = open("DISASS.txt", "w+") f.close() def createArrayInfo(self,macAP, macClient): if (macAP,macClient) not in self.deauthentInfo: self.deauthentInfo[(macAP,macClient)] = 0
if (macAP,macClient) not in self.authentInfo: self.authentInfo[(macAP,macClient)] = 0 if (macAP,macClient) not in self.associationRequestInfo: self.associationRequestInfo[(macAP,macClient)] = 0 if (macAP,macClient) not in self.associationResponceInfo: self.asso...
googleapis/python-secret-manager
samples/generated_samples/secretmanager_v1_generated_secret_manager_service_set_iam_policy_sync.py
Python
apache-2.0
1,501
0.000666
# -*- coding: utf-8 -*- # Copyright 2022 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...
matically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-secretmanager # [START secretmanager_v1_generated_SecretManagerService_SetIamPolicy_sync...
) # Initialize request argument(s) request = secretmanager_v1.SetIamPolicyRequest( resource="resource_value", ) # Make the request response = client.set_iam_policy(request=request) # Handle the response print(response) # [END secretmanager_v1_generated_SecretManagerService_SetIam...
ezralalonde/cloaked-octo-sansa
01/qu/02.py
Python
bsd-2-clause
342
0.005848
# Write Pyth
on code to print out how far light travels # in centimeters in one nanosecond. Use the variables # defined below. speed_of_light = 299792458 # meters per second meter = 100 # one meter is 100 centimeters nanosecond = 1.0/1000000000 # one billionth of a second print speed_of_light * meter * n...
osecond
techtonik/pip
tests/lib/options_helpers.py
Python
mit
792
0
"""Provides helper classes for testing option handling in pip """ import os from pip._inter
nal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.commands import commands_dict class FakeCommand(Command): name = 'fake' summary = name def main(self, args): index_opts = cmdoptions.make_option_group( cmdoptions.index_group, s...
n_before = os.environ.copy() commands_dict[FakeCommand.name] = FakeCommand def teardown(self): os.environ = self.environ_before commands_dict.pop(FakeCommand.name)
elopezga/ErrorRate
ivi/lecroy/lecroyBaseScope.py
Python
mit
71,778
0.00255
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012-2014 Alex Forencich 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...
'i1080': 'i1080l50hz', 'i1080l60hz': 'i1080l60hz'} PolarityMapping = {'positive': 'pos', 'negative': 'neg'} GlitchConditionMapping = {'less_than': 'less', 'greater_than': 'gre
'} WidthConditionMapping = {'within': 'rang'} SampleModeMapping = {'real_time': 'rtim', 'equivalent_time': 'etim'} SlopeMapping = { 'positive': 'pos', 'negative': 'neg', 'either': 'eith', 'alternating': 'alt'} MeasurementFunctionMapping = { 'rise_time': 'risetime', 'fall_tim...
cliburn/flow
src/plugins/visual/TwoDFrame/colormap.py
Python
gpl-3.0
1,367
0.027067
#!/usr/bin/env python # """ These functions, when given a magnitude mag between cmin and cmax, return a colour tuple (red, green, blue). Light blue is cold (low magnitude) and yellow is hot (high magnitude). """ import math def floatRgb(mag, cmin, cmax, alpha=1.0): """ Return a tuple of floats between ...
= floatRgb(mag, cmin, cmax) return (int(red*255), int(green*255), int(blue*255)) def htmlRgb(mag, cmin, cmax): """ Return a tuple of strings to be used in HTML documents.
""" return "#%02x%02x%02x"%rgb(mag, cmin, cmax)
dmartinezgarcia/Python-Programming
Chapter 8 - Software Objects/exercise_3.py
Python
gpl-2.0
2,406
0.006234
# Exercise 3 # #
Create a "back door" in the Critter Caretaker program that shows the exact values of the object's attributes. # Accomplish this by printing the object when a secret selection, not listed in the menu, is entered as the user's # choice. (Hint: add the special method __str__() to the Critter class.) #
class Critter(object): """A virtual pet""" def __init__(self, name, hunger = 0, boredom = 0): self.name = name self.hunger = hunger self.boredom = boredom def __str__(self): string = "Name: " + self.name + "\n" string += "Hunger: " + self.hunger + "\n" strin...
orbitfp7/nova
nova/compute/utils.py
Python
apache-2.0
19,092
0.000262
# Copyright (c) 2011 OpenStack Foundation # # 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 ...
= exc_info[2] if tb: details = ''.join(traceback.format_tb(tb)) return unicode(details) def add_instance_fault_from_exc(context, instance, fault, exc_info=None): """Adds the specified fault to the database.""" fault_obj = objects.InstanceFault(context=context) fault_obj.host = CON...
_obj.instance_uuid = instance['uuid'] fault_obj.update(exception_to_dict(fault)) code = fault_obj.code fault_obj.details = _get_fault_details(exc_info, code) fault_obj.create() def get_device_name_for_instance(context, instance, bdms, device): """Validates (or generates) a device name for instance...
singulared/aiohttp
tests/test_py35/test_cbv35.py
Python
apache-2.0
351
0
from unittest import moc
k from aiohttp import web from aiohttp.web_urldispatcher import View async def test_render_ok(): resp = web.Response(text='OK') class MyView(View): async def get(self): return resp reque
st = mock.Mock() request._method = 'GET' resp2 = await MyView(request) assert resp is resp2
LunarLanding/agipibi
python/example_tektronix_2432.py
Python
gpl-3.0
6,565
0.003809
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2012,2013 Thibault VINCENT <tibal@reloaded.fr> # # This file is part of Agipibi. # # Agipibi 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, e...
49,49,49,50,50,49,50,49,49,49,0,0,0,0,-1,-1,-2,0,0,0,0,0,0,-2,0 # ,0,0,-1,0,0,-1,-1,0,0,0,0,0,-1,0,-1,0,0,0,0,0,-1,0,0,0,1,-1,0,0,0,0,0,0,0,0,0 # ,0,-1,0,0,0,0,0,-3,-1,-1,0,0,0,-1,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,-1,-1, # 0,0,1,0,0,-1,-2,0,0,0,0,1,-1,0,0,0,-1,-1,48,50,49,50,49,49,50,49,50,50,49,49, # 49,49,48,4...
49,49,50,50,49,49,49,49,50,49,50,50,49,49,49,49,50,50,49,49,50,49,49,50, # 49,49,49,50,49,49,50,50,49,49,50,0,0,0,0,-1,0,-1,-2,0,0,-1,0,0,0,-2,0,0,0,-1, # 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,-1,0,0,0,1,0,0,0,0,-1,0,-1,0,-1,0,0, # -2,0,0,-1,0,0,0,0,-1,0,0,0,0,-1,0,-1,0,-1,0,0,-1,0,0,-2,0,0,0,0,0,0,0,0,0,-1, # 0...
openai/cleverhans
scripts/make_confidence_report_bundle_examples.py
Python
mit
4,354
0.008268
#!/usr/bin/env python3 """ make_confidence_report_bundle_examples.py Usage: make_confidence_report_bundle_examples.py model.joblib a.npy make_confidence_report_bundle_examples.py model.joblib a.npy b.npy c.npy where model.joblib is a file created by cleverhans.serial.save containing a picklable cleverhans.mode...
port TEST_START, TEST_END from cleverhans.confidence_report import WHICH_SET FLAGS = flags.FLAGS def main(argv=None): """ Make a confidence report and save it to disk. """ assert len(argv) >= 3 _name_
of_script = argv[0] model_filepath = argv[1] adv_x_filepaths = argv[2:] sess = tf.Session() with sess.as_default(): model = serial.load(model_filepath) factory = model.dataset_factory factory.kwargs['train_start'] = FLAGS.train_start factory.kwargs['train_end'] = FLAGS.train_end factory.kwargs['te...
linkcheck/linkchecker
tests/checker/telnetserver.py
Python
gpl-2.0
3,383
0.000887
# Copyright (C) 2012 Bastian Kleineidam # # 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 distribute...
ckname()[1] t = threading.Thread(None, serve_forever, args=(server, clients, stop_event)) t.start() # wait for server to start up tries = 0 while tries < 5: tries += 1 try: client = telnetlib.Telnet(timeout=TIMEOUT) client.open(host, port) client.w...
r, clients, stop_event): """Run poll loop for server.""" while True: if stop_event.is_set(): return server.poll() for client in clients: if client.active and client.cmd_ready: handle_cmd(client) def handle_cmd(client): """Handle telnet client...
benctamas/zerorpc-logging
logstream_test.py
Python
apache-2.0
3,399
0.006472
import zerorpc import gevent.queue import logging import sys logging.basicConfig() # root logger logger = logging.getLogger() # set the mimimum level for root logger so it will be possible for a client # to subscribe and receive logs for any log level logger.setLevel(0) class QueueingLogHandler(logging.Handler): ...
or("logger {0} is not available".format(logger_name)) level_name_upper = level_name.upper() if level_name else "NOTSET" try: level = getattr(logging, level_name_upper) except AttributeError, e: raise AttributeError("log level {0} is not available".format(level_name_upper...
logging.getLogger(logger_name) formatter = logging.Formatter(fmt) handler = self._HANDLER_CLASS(q, level, formatter) logger.addHandler(handler) self._logging_handlers.add(handler) self.logger.debug("new subscriber for {0}/{1}".format(logger_name or "root", level_name_up...
deeponion/deeponion
contrib/seeds/makeseeds.py
Python
mit
8,058
0.003723
#!/usr/bin/env python3 # Copyright (c) 2013-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Generate seeds.txt from Pieter's DNS seeder # import re import sys import dns.resolver import collect...
net = 'onion' ipstr = sortkey = m.group(1) port = int(m.group(2)) else: net = 'ipv6' if m.group(1) in ['::']: # Not interested in localhost retu
rn None ipstr = m.group(1) sortkey = ipstr # XXX parse IPv6 into number, could use name_to_ipv6 from generate-seeds port = int(m.group(2)) else: # Do IPv4 sanity check ip = 0 for i in range(0,4): if int(m.group(i+2)) < 0 or int(m.group(i+2)) > ...
dontnod/weblate
weblate/fonts/admin.py
Python
gpl-3.0
1,510
0
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2019 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # 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, eith...
implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # from django.contrib import admin from webla...
yle", "project", "user"] search_fields = ["family", "style"] list_filter = [("project", admin.RelatedOnlyFieldListFilter)] ordering = ["family", "style"] class InlineFontOverrideAdmin(admin.TabularInline): model = FontOverride extra = 0 class FontGroupAdmin(WeblateModelAdmin): list_display =...
yanndavin/judge_offline
setup.py
Python
bsd-2-clause
532
0.00188
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() with open('LICENSE') as f: license =
f.read() setup( name='judge_offline', version='0.1.0', description='Provides personal judge similar hackrank or judge online', long_description=readme, author='Yann Davin', aut
hor_email='yann.davin@gmail.com', url='https://github.com/yanndavin/judge_offline', license=license, packages=find_packages(exclude=('samples', 'docs')) )
beregond/jsonmodels
tasks.py
Python
bsd-3-clause
251
0
"""Tasks for invoke.""" from invoke import task, run @task def test(): run('./setup.py test --quick') @task def fulltest(): run(
'./setup.py test') @task def coverage():
run('./setup.py test', hide='stdout') run('coverage html')
kelvinwong-ca/django-select-multiple-field
test_projects/django14/suthern/models.py
Python
bsd-3-clause
1,575
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import ( force_text, python_2_unicode_compatible) from django.utils.translation import ugettext_lazy as _ from select_multiple_field.models import Se...
(BBQ, _('BBQ')), ) dips = SelectMultipleField( blank=True, default='', include_blank=False, max_length=6,
max_choices=3, choices=DIP_CHOICES ) def __str__(self): return "pk=%s" % force_text(self.pk) def get_absolute_url(self): return reverse('ftw:detail', args=[self.pk])
mirkobrombin/Bottles
src/views/bottle_preferences.py
Python
gpl-3.0
30,960
0.001227
# bottle_preferences.py # # Copyright 2020 brombinmirko <send@mirko.pm> # # 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...
hild() spinner_vkd3dbool = Gtk.Template.Child() spinner_nvapi = Gtk.Template.Child() spinner_nvapibool = Gtk.Template.Child() spinner_runner = Gtk.Template.Child() spinner_win = Gtk.Template.Child() # endregion def __init__(self, window, config, **kwargs): super().__init__(**kwargs)...
ed", self.__show_dll_overrides_view) self.btn_manage_runners.connect("clicked", self.window.show_prefs_view) self.btn_manage_dxvk.connect("clicked", self.window.show_prefs_view) self.btn_manage_vkd3d.connect("clicked", self.window.show_prefs_view) self.btn_manage_nvapi.connect("clicked",...
jkyeung/XlsxWriter
xlsxwriter/test/comparison/test_cond_format01.py
Python
bsd-2-clause
1,643
0.000609
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """...
filename = 'cond_format01.xlsx' test_dir = 'xlsxwriter/test/comparison/' self.got_filename = test_dir + '_test_' + filename self.exp_filename = test_dir + 'xlsx_files/' + filename self.ignore_files = [] self.ignore_elements = {} def test_create_file(self): """Te...
orksheet = workbook.add_worksheet() cell_format = workbook.add_format({ 'color': '#9C0006', 'bg_color': '#FFC7CE', 'font_condense': 1, 'font_extend': 1 }) worksheet.write('A1', 10) worksheet.write('A2', 20) worksheet.write('A3', 3...
antononcube/ConversationalAgents
Packages/Python/ExternalParsersHookUpApp/examples.py
Python
gpl-3.0
1,315
0.004563
import pandas from ExternalParsersHookUp import RakuCommandFunctions from ExternalParsersHookUp import ParseWorkflowSpecifications dfStarwars = pandas.read_csv("https://raw.githubusercontent.com/antononcube/R-packages/master/DataQueryWorkflowsTests/inst/extdata/dfStarwars.csv") dfStarwarsFilms = pandas.read_csv("https...
orkflowsTests/inst/extdata/dfStarwarsStarships.csv") # res = RakuCommandFunctions.RakuCommand( 'say ToDataQueryWorkflowCode("use dfStarwars; select mass and height; cross tabulate mass and height", "Python-pandas")', 'DSL::English::DataQueryWorkflows') # print(res.stdout) # exec(res.stdout) # print(obj) # command1 = ...
filter 'species' is 'Human' or 'mass' is greater than 120; select homeworld and species; cross tabulate homeworld and species" command2 = 'use dfStarwars; filter "species" is "Human" or "mass" is greater than 120; select homeworld and species; cross tabulate homeworld and species' res = ParseWorkflowSpecifications.ToD...
opalmer/aws
awsutil/dns.py
Python
mit
1,168
0.000856
import boto import argparse try: import urllib2 except ImportError: # Python 3 import urllib.request as urllib2 from awsutil.logger import logger def set_public_record(): parser = argparse.ArgumentParser(description="Updates DNS records") parser.add_argument( "--address", default=url...
) parser.add_argument( "hostname", help="The hostname to establish the DNS record for" ) args = parser.parse_args() if not args.hostname.endswith("."): parser.error("Expected record to end with '.'") zone_name = ".".join(list(filter(bool, args.hostname.split(".")))[-2:])...
.hostname) if record is None: logger.info("Creating A %s %s", args.hostname, args.address) zone.add_a(args.hostname, args.address, ttl=60) else: logger.info("Updating A %s %s", args.hostname, args.address) zone.update_record(record, args.address, new_ttl=60)
catapult-project/catapult
telemetry/telemetry/internal/util/binary_manager.py
Python
bsd-3-clause
9,298
0.008496
# 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. from __future__ import print_function from __future__ import absolute_import import contextlib import logging import os import py_utils from py_utils import...
onfigs)) try: manager.PrefetchPaths(target_platform) if host_platform is not None: manager.PrefetchPaths(host_platform) except dependency_manager.NoPathFoundError as e: logging.error('Error when trying to
prefetch paths for %s: %s', target_platform, e) if fetch_devil_deps: devil_env.config.Initialize() devil_env.config.PrefetchPaths(arch=platform.GetArchName()) devil_env.config.PrefetchPaths() def ReinstallAndroidHelperIfNeeded(binary_name, install_path, device): """ Install a bin...
darthbhyrava/pywikibot-local
pywikibot/version.py
Python
mit
18,495
0.000162
# -*- coding: utf-8 -*- """Module to determine the pywikibot version (tag, revision and date).""" # # (C) Merlijn 'valhallasw' van Deen, 2007-2014 # (C) xqt, 2010-2015 # (C) Pywikibot team, 2007-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __versi...
@rtype: C{tuple} of two C{str} and a C{time.struct_time} """ if not os.path.isdir(os.path.join(path, '.svn')): path = os.path.join(path, '..') _program_dir = path filename = os.path.join(_program_dir, '.svn/entries') if os.path.isfile(filename): with open(filename) as entries: ...
for i in range(3): entries.readline() tag = entries.readline().strip() t = tag.split('://') t[1] = t[1].replace('svn.wikimedia.org/svnroot/pywikipedia/', '') tag = '[%s] %s' % (t[0], t[1]) ...
magayorker/magatip
scripts/add_gold.py
Python
mit
735
0
import argparse # parse
argument import datetime from tinydb import TinyDB import config parser = argparse.ArgumentParser(description='Refill Gold To Bot') parser.add_argument('-n', help='Number of credits', required=True) parser.add_argument('-c', help='Currency', required=True) parser.add_argument('-p', help='Price of credits (total)', r...
d.json') db.insert({ "user_buyer": "", "quantity": args.n, "price": (float(args.n) / float(args.p)), "currency": args.c, "amount": "", "total_price": args.p, "usd_price": "", 'tx_id': "", 'status': "refill", 'time': datetime.datetime.now().isoformat(), }) db.close()
ekristen/mythboxee
xml/__init__.py
Python
mit
1,360
0.000735
"""Core XML support for Python. This package contains four sub-packages: dom -- The W3C Document Object Model. This supports DOM Level 1 + Namespaces. parsers -- Python wrappers for XML parsers (currently only supports Expat). sax -- The Simple API for XML, developed by XML-Dev, led by David
Megginson and ported to Python by Lars Marius Garshol. This supports the SAX 2 API. etree -- The ElementTree XML library. This is a subset of the full ElementTree XML release. """ __all__ = ["dom", "parsers", "sax", "etree"] # When being checked-out without options, this has the form # "<dol...
: 41660 $".split()[-2:][0] _MINIMUM_XMLPLUS_VERSION = (0, 8, 4) import os # only prefer _xmlplus if the environment variable PY_USE_XMLPLUS is defined if 'PY_USE_XMLPLUS' in os.environ: try: import _xmlplus except ImportError: pass else: try: v = _xmlplus.version_inf...
ysarbaev/contrib-python-qubell-client
qubell/api/public/application.py
Python
apache-2.0
5,682
0.003872
# Copyright (c) 2013 Qubell Inc., http://qubell.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 applicable law or agr...
content, verify=False, headers=headers) log.debug(resp.text) if resp.status_code == 200: self.manifest = manifest return resp.json() raise exceptions.ApiError('Unable to upload manifest to application id: %s, got error: %s' % (self.applicationId, resp.text)) def laun...
aders = {'Content-Type': 'application/json'} #if not 'environmentId' in argv.keys(): # argv['environmentId'] = self.context.environmentId data = json.dumps(argv) resp = requests.post(url, auth=(self.auth.user, self.auth.password), data=data, verify=False, headers=headers) log...
diplomacy/research
diplomacy_research/models/draw/tests/draw_model_test_setup.py
Python
mit
7,985
0.004634
# ============================================================================== # Copyright 2019 - Philip Paquette # # NOTICE: 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 rest...
n (False, True): if not use_prefetching: _, policy_details = yield self.adapter.get_orders(locs, state_proto,
'FRANCE', phase_history_proto, possible_orders_proto, **kwargs) else: fe...
SJIT-Hackerspace/SJIT-CodingPortal
QuestionDumps/migrations/0001_initial.py
Python
apache-2.0
823
0.003645
# -*- coding
: utf-8 -*- # Generated by Django 1.9.1 on 2017-01-10 08:39 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Document', ...
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('docfile', models.FileField(upload_to='documents/%Y/%m/%d')), ('subCategory', models.IntegerField(choices=[(4, 'Syllogism'), (5, 'Arithmetic Reasoning'), (6, 'Series Completion')])...
audy/domain-name-generator
tld.py
Python
mit
2,280
0.001754
#!/usr/bin/env python3 import sys import argparse def parse_arguments(): """ parse the arguments """ p = argparse.ArgumentParser() p.add_argument( "--words-file", help="file with list of words [/usr/share/dict/words]", default="/usr/share/dict/words", ) p.add_argument( ...
d_argument( "--leet", help="generate domains that replace letters with numbers", action="store_true", ) p.add_argument("--min-size", default=0, type=int, help="minimum word length") p.add_argument("--max-size", default=100000, type=int, help="maximum word length") return p.pars...
def iter_words(handle): """ iterate over list of words in text file """ return (word.strip().lower() for word in handle) def get_tlds(tlds_file): """ iterate over list of tlds in text file """ with open(tlds_file) as handle: return [line.split()[0].strip().lower() for line in handle] d...
AustereCuriosity/astropy
astropy/units/tests/test_quantity_ufuncs.py
Python
bsd-3-clause
38,162
0.000079
# The purpose of these tests are to ensure that calling ufuncs with quantities # returns quantities with the right units, or raises exceptions. import warnings import pytest import numpy as np from numpy.testing.utils import assert_allclose from ... import units as u from ...tests.helper import raises from ...extern...
assert np.multiply(4., 2. / u.s) == 8. / u.s def test_multiply_array(self): assert np.all(np.multiply(np.arange(3.) * u.m, 2. / u.s) == np.arange(0, 6., 2.) * u.m / u.s) @pytest.mark.parametrize('function', (np.divide, np.true_divide)) def test_divide_scalar(self, func...
., 2.) * u.m / u.s assert function(4. * u.m, 2.) == function(4., 2.) * u.m assert function(4., 2. * u.s) == function(4., 2.) / u.s @pytest.mark.parametrize('function', (np.divide, np.
dpdani/tBB
tBB/settings.py
Python
gpl-3.0
7,813
0.002048
#!/usr/bin/python3 # # tBB 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. # # tBB 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 with this program. If not, see <http://www.gnu.org/licenses/>. """ This module takes care of representing and handling settings throughout tBB. """ import enum import re import datetime valid_item_name = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]...
bollu/sagenb
sagenb/notebook/cell.py
Python
gpl-3.0
82,188
0.002569
# -*- coding: utf-8 -*- """ A Cell A cell is a single input/output block. Worksheets are built out of a list of cells. """ ########################################################################### # Copyright (C) 2006 William Stein <wstein@gmail.com> # # Distributed under the terms of the GNU General Public ...
hand, we don't want to loose the output of big matrices # and numbers, so don't make this too small. MAX_OUTPUT = 32000 MAX_OUTPUT_LINES = 120 # Used to detect and format tracebacks. See :func:`format_exce
ption`. TRACEBACK = 'Traceback (most recent call last):' # This regexp matches "cell://blah..." in a non-greedy way (the ?), so # we don't get several of these combined in one. re_cell = re.compile('"cell://.*?"') re_cell_2 = re.compile("'cell://.*?'") # same, but with single quotes # Matches script blocks. re_scrip...
bollwyvl/nosebook
setup.py
Python
bsd-3-clause
1,949
0
import os from setuptools import setup # you'd add this, too, for `python setup.py test` integration from setuptools.command.test import test as TestCommand class NosebookTestCommand(TestCommand): def run_tests(self): # Run nose ensuring that argv simulates running nosetests directly import nose ...
'nosetests', '-c', './.noserc']) def read(fname): """ Utility function to read the README file. Used for the long_
description. It's nice, because now 1) we have a top level README file and 2) it's easier to type in the README file than to put a raw string in below ... """ return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="nosebook", version="0.4.0", author="Nicholas Bollw...
mozilla/firefox-flicks
vendor-local/lib/python/celery/canvas.py
Python
bsd-3-clause
14,524
0.000413
# -*- coding: utf-8 -*- """ celery.canvas ~~~~~~~~~~~~~ Composing task workflows. Documentation for these functions are in :mod:`celery`. You should not import from this module directly. """ from __future__ import absolute_import from copy import deepcopy from functools import partial as _partia...
, **kwargs) if kwargs else self.kwargs, dict(self.options, **options) if options else self.options) def clone(self, args=(), kwargs={}, **opts): # need to deepcopy options so origins links etc. is not modified. args, kwargs, opts = self._merge(args, kwargs, opts) s = Signatu...
'kwargs': kwargs, 'options': deepcopy(opts), 'subtask_type': self.subtask_type, 'immutable': self.immutable}) s._type = self._type return s partial = clone def _freeze(self, _id=None): opts = self.options ...
trudikampfschaf/flask-microblog
mail.py
Python
bsd-3-clause
273
0.014652
#!flask/bin/python from flask.ext.mail import Message
from app import app, mail from config import ADMINS msg = Message('test subject', sender = ADMINS[0], recipients = ADMINS) msg.body = 'text body' msg.html = '<b>HTML</b> body' with app.app_context(): mail.send(msg)
tomoyuki-nakabayashi/ICS-IoT-hackathon
sample/python-camera/python-camera.py
Python
mit
475
0.035789
# -*-
coding: utf-8 -*- import cv2 # device number "0" cap = cv2.VideoCapture(0) while(True): # Capture a frame ret, frame = cap.read() # show on display cv2.imshow('frame',frame) # waiting for keyboard input key = cv2.waitKey(1) & 0xFF # Exit if "q" pressed if key == ord('q'): break # Save if "s" pressed ...
rite(path,frame) # When everything done, release the capture cap.release() cv2.destroyAllWindows()
ox-it/talks.ox
talks/audit_trail/forms.py
Python
apache-2.0
812
0.002463
from __future__ import absolute_import import urllib from django import forms DEFAULT_DATE_FORMATS = ["%d/%m/%Y"] DEFAULT_TIME_FORMATS = ["%H:%M"] class RevisionsFilteringForm(forms.Form): from_date = forms.SplitDateTimeField(label="From", required=False, ...
s=DEFAULT_DATE_FORMATS, input_time_formats=DEFAULT_TIME_FORMA
TS) def as_url_args(self): return urllib.parse.urlencode(self.data)
manuelep/openshift_v3_test
wsgi/web2py/gluon/contrib/plural_rules/af.py
Python
mit
598
0.006689
#!/usr/bin/e
nv python # -*- coding: utf8 -*- # Plural-Forms for af (Afrikaans (South Africa)) nplurals=2 # Afrikaans language has 2 forms: # 1 singular and 1 plural # Determine plural_id for number *n* as sequence of positive # integers: 0,1,... # NOTE! For singular form ALWAYS return plural_id = 0 get_plural_id = l...
or words (or phrases) not found in plural_dict dictionary # construct_plural_form = lambda word, plural_id: (word + 'suffix')
vincentrose88/civAdder
civ_battleroyal_leader_civ_adder.py
Python
mit
3,793
0.006327
import sys def get_civ_leader(civ_leader_file): """Reads in a file with civs mapped to leaders and add it to a dict. """ return {leader.strip('\n'): country for line in civ_leader_file for (country, leader) in [line.split('\t')]} def get_all_names(civ_leader): """Reads in all ...
lse: new_line.extend( (' '.join(split_line[start_word_num:word_num]), ' {} ({}){} '.format(' '.join(leader), civ,
punct))) start_word_num = word_num + len(leader) word_num = word_num + len(leader) else: word_num += 1 else: word_num += 1 new_line.append(' '.join(split_line[start_word_num:])) out.append(''.join(new...
dandygithub/kodi
addons/DEPRECATED/plugin.video.unified.search/resources/lib/search_db.py
Python
gpl-3.0
3,245
0.005855
#!/usr/bin/python # Writer (c) 2012, MrStealth # Rev. 1.1.1 # License: Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0) # -*- coding: utf-8 -*- import os import sqlite3 as sqlite import xbmcaddon import xbmc __addon__ = xbmcaddon.Addon(id='plugin.video.unified.search') #addon_path = __addon__.getAd...
r(self, search_id): self.execute("SELECT MAX(counter) FROM searches WHERE id=%d" % search_id) return self.cursor.fetchone()[0] def all(self): self.execute("SELECT * FROM searches ORDER BY id DESC") return [{'id': x[0], 'keyword': x[1], 'counter': x[2]} for x in self.cursor.fetchall(...
if os.path.isfile(self.filename): self.connect() self.execute('DELETE FROM searches') self.db.commit() def close(self): self.cursor.close() self.db.close()
reiths/ros_spinnaker_interface
examples/example_ros_spinnaker_interface.py
Python
mit
2,533
0.006317
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author Stephan Reith @date 31.08.2016 This is a simple example to demonstrate how the ROS Spinnaker Interface can be used. You will also need a ROS Listener and a ROS Talker to send and receive data. Make sure they communicate over the same ROS topics and std_msgs....
incoming ROS values. ros_topic_recv='from_spinnaker', # the ROS topic used for the outgoing ROS values. clk_rate=1000, # mainloop clock (update) rate in Hz. ros_output_rate=10) # number of ROS messages send out per second. # Build ...
ation and optionally record the spikes and voltages. pynn.Projection(ros_interface, pop, pynn.OneToOneConnector(weights=5, delays=1)) pop.record() pop.record_v() pynn.run(simulation_time) spikes = pop.getSpikes() pynn.end() # Plot import pylab spike_times = [spike[1] for spike in spikes] spike_ids = [spike[0] fo...
praekelt/mc2
mc2/controllers/base/admin.py
Python
bsd-2-clause
378
0
fro
m django.contrib import admin from mc2.controllers.base.models import Controller class ControllerAdmin(admin.ModelAdmin): search_fields = ('state', 'name') list_filter = ('state',) list_display = ('name', 'state', 'organization') list_editable = ('organization',) readonly_fields = ('state', 'owne...
ontroller, ControllerAdmin)
amolenaar/gaphor
gaphor/diagram/diagramtools/tests/conftest.py
Python
lgpl-2.1
570
0.001754
import pytest from gaphas.painter import BoundingBoxPainter from gaphas.view import GtkView from gaphor.diagram.painter import It
emPainter from gaphor.diagram.selection import Selection from gaphor.diagram.tests.fixtures import diagram, element_factory, event_manager @
pytest.fixture def view(diagram): view = GtkView(model=diagram, selection=Selection()) view._qtree.resize((-100, -100, 400, 400)) item_painter = ItemPainter(view.selection) view.painter = item_painter view.bounding_box_painter = BoundingBoxPainter(item_painter) return view
djangraw/PsychoPyParadigms
BasicExperiments/FourLetterTask.py
Python
mit
9,655
0.020818
#!/usr/bin/env python2 """Implement a visuospatial working memory task described in Mason et al., Science 2007 (doi: 10.1126/science.1131295)""" # FourLetterTask.py # Created 12/17/14 by DJ based on SequenceLearningTask.py # Updated 11/9/15 by DJ - cleanup, instructions from psychopy import core, visual, gui, data, ...
e task','Not sure','Mostly on inward thoughts','Completely on inward thoughts') probe2_string = 'How aware were you of where your attention was?' probe2_options = ('Very aware','Somewhat aware','Neutral','Somewhat unaware','Very unaware') # ========================== # # ===== SET UP STIMULI ===== # # ================...
y to get a previous parameters file expInfo = fromFile('lastFourLetterParams.pickle') except:#if not there then use a default set expInfo = {'subject':'abc', 'session':'1'} dateStr = time.strftime("%b_%d_%H%M", time.localtime())#add the current time #present a dialogue to change params dlg = gui.DlgFromDict(ex...
Wesalius/EloBot
pywikibot/families/meta_family.py
Python
gpl-3.0
641
0
# -*- coding: utf-8 -*- """Family module for Meta Wiki.""" # # (C) Pywikibot team, 2005-2018 # # Dis
tributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals from pywikibot import family # The meta wikimedia family class Family(family.WikimediaOrgFamily): """Family class for Meta Wiki.""" name = 'meta' interwiki_forward = 'wikipedia' cross_allowed = ...
'_default': (('/doc',), ['meta']), }
VirusTotal/content
Packs/McAfee_DXL/Integrations/McAfee_DXL/McAfee_DXL.py
Python
mit
7,105
0.002252
from typing import Dict import tempfile from dxlclient.client_config import DxlClientConfig from dxlclient.client import DxlClient from dxlclient.broker import Broker from dxlclient.message import Event import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * INTEGRATION_NAM...
evel}' def push_hash(self, hash_obj, trust_level, topic): trust_level_key = self.TRUST_LEVEL[trust_level] if topic: self.push_ip_topic = topic self.send_event(self.pu
sh_hash_topic, f'hash:{hash_obj};trust_level:{trust_level_key}') return f'Successfully pushed hash {hash_obj} with trust level {trust_level}' def get_client_config(self): config = DxlClientConfig( broker_ca_bundle=self.broker_ca_bundle, cert_file=self.cert_file, ...
ds-hwang/chromium-crosswalk
tools/perf/page_sets/memory_health_story.py
Python
bsd-3-clause
3,234
0.007112
# Copyrigh
t 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. import logging import re from telemetry.page import page as page_module from telemetry.page import shared_page_state from telemetry import story from devil.android.s...
int: disable=import-error from devil.android.sdk import keyevent # pylint: disable=import-error DUMP_WAIT_TIME = 3 URL_LIST = [ 'http://google.com', 'http://vimeo.com', 'http://yahoo.com', 'http://baidu.com', 'http://cnn.com', 'http://yandex.ru', 'http://yahoo.co.jp', 'http://amazon.c...
MischaLundberg/bamsurgeon
scripts/makevcf.py
Python
mit
2,120
0.010377
#!/usr/bin/env python import sys,os import textwrap def print_header(): print textwrap.dedent("""\ ##fileformat=VCFv4.1 ##phasing=none ##INDIVIDUAL=TRUTH ##SAMPLE=<ID=TRUTH,Individual="TRUTH",Description="bamsurg
eon spike-in"> ##INFO=<ID=CIPOS,Number=2,Type=Integer,Description="Confidence interval around POS for imprecise variants"> ##INFO=<ID=IMPRECISE,Number=0,Type=Flag,Description="Imprecise structural variation"> ##INFO=<ID=SVTYPE,Number=1,Type=String,Description="Type of structural variant"> ##INFO=<ID=SVL...
cription="Difference in length between REF and ALT alleles"> ##INFO=<ID=SOMATIC,Number=0,Type=Flag,Description="Somatic mutation in primary"> ##INFO=<ID=VAF,Number=1,Type=Float,Description="Variant Allele Frequency"> ##INFO=<ID=DPR,Number=1,Type=Float,Description="Avg Depth in Region (+/- 1bp)"> ##INFO=...
magacoin/magacoin
contrib/zmq/zmq_sub.py
Python
mit
1,425
0.002105
#!/usr/bin/env python2 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import array import binascii import zmq import struct port = 25332 zmqContext = zmq.Context() zmqSubSoc...
t.setsockopt(zmq.SUBSCRIBE, "hashbrick") zmqSubSocket.setsockopt(zmq.SUBSCRIBE, "hashtx") zmqSubSocket.setsockopt(zmq.SUBSCRIBE, "rawbrick") zmqSubSocket.setsockopt(zmq.SUBSCRIBE, "rawtx") zmqSubSocket.connect("tcp://127.0.0.1:%i" % port) try: while True: msg = zmqSubSocket.recv_multipart() topic =...
if len(msg[-1]) == 4: msgSequence = struct.unpack('<I', msg[-1])[-1] sequence = str(msgSequence) if topic == "hashbrick": print '- HASH BRICK ('+sequence+') -' print binascii.hexlify(body) elif topic == "hashtx": print '- HASH TX ('+sequence+') ...
alaasalman/taskit
TIAboutDialog.py
Python
gpl-3.0
2,548
0.008634
""" Copyright 2007 Alaa Salman <alaa@codedemigod.com> This file is part of TaskIt. TaskIt 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...
should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import sys from PyQt4 import QtGui from PyQt4 import QtCore from
ui import AboutDialog class TIAboutDialog(QtGui.QDialog): def __init__(self, p_Parent = None): QtGui.QDialog.__init__(self, p_Parent) self.ui = AboutDialog.Ui_Dialog() self.ui.setupUi(self) htmlAboutAuthor = """<html> <body> TaskIt GTD A...
xiangcai/todother
controller/search.py
Python
lgpl-3.0
3,591
0.011139
import os import sys import logging import uuid import re import json import string import tornado.web import tornado.escape import urlparse import urllib import Levenshtein from controller.base import * from module.todo_entity import TodoMatchEntity _todo_prefix = "t:" _person_prefix = "p:" _friend_prefix = "f:"...
t_argument("page",0)) _pagesize=30 print keyword if not keyword: return if keyword.startswith(_person_prefix): return self.person_search(keyword) elif keyword.startswith(_friend_prefix): ret
urn self.friend_search(keyword) else: return self.todo_search(keyword) def person_search(self,orakeyword): result = [] keyword = orakeyword[len(_person_prefix):len(orakeyword)] entries = self.db.query("SELECT * FROM auth_user WHERE nickname like %s","%%"+keyword+"%%") ...
jruizgit/rules
setup.py
Python
mit
2,665
0.011632
try: from setuptools import setup, Extension from setuptools.command import install_lib as _install_lib except ImportError: from distutils.core import setup, Extension from distutils.command import install_lib as _install_lib from codecs import open from os import path from os import environ from sys import pla...
2': environ['CFLAGS'] = '-std=c99 -D_GNU_SOURCE -_WIN32' elif platform == 'darwin': environ['CFLAGS'] = '-std=c99 -D_GNU_SOURCE -fcommon' else: environ['CFLAGS'] = '-std=c99 -D_GNU_SOURCE' # Patch "install_lib" command to run build_clib before build_ext # to properly work with easy_install. # See: http://bugs....
): self.run_command('build_py') if self.distribution.has_c_libraries(): self.run_command('build_clib') if self.distribution.has_ext_modules(): self.run_command('build_ext') rules_lib = ('durable_rules_engine_py', {'sources': ['src/rules/%s.c' % src for src in ('json', 'rete'...
luboslenco/cyclesgame
blender/arm/logicnode/sound_play_sound.py
Python
lgpl-3.0
652
0.004601
import bpy fr
om bpy.props import * from bpy.types import Node, NodeSocket from arm.logicnode.arm_nodes import * class PlaySoundNode(Node, ArmLogicTreeNode): '''Play sound node''' bl_idname = 'LNPlaySoundRawNode' bl_label = 'Play Sound' bl_icon = 'QUESTION' property0: PointerProperty(name='', type=bpy.types.Sou...
ext, layout): layout.prop_search(self, 'property0', bpy.data, 'sounds', icon='NONE', text='') add_node(PlaySoundNode, category='Sound')
dmpetrov/dataversioncontrol
dvc/env.py
Python
apache-2.0
396
0
DV
C_CHECKPOINT = "DVC_CHECKPOINT" DVC_DAEMON = "DVC_DAEMON" DVC_PAGER = "DVC_PAGER" DVC_ROOT = "DVC_ROOT" DVCLIVE_PATH = "DVCLIVE_PATH" DVCLIVE_SUMMARY = "DVCLIVE_SUMMARY" DVCLIVE_HTML = "DVCLIVE_HTML" DVCLIVE_RESUME = "DVCLIVE_RESUME" DVC_IGNORE_ISATTY = "DVC_IGNORE_ISATTY" DVC_EXP_GIT_REMOTE = "DVC_EXP_GIT_REMOTE" DVC_...
google-research/language
language/conpono/evals/run_finetune_coherence.py
Python
apache-2.0
18,761
0.005863
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
f.FixedLenFeature([8], tf.int64) def _decode_record(record, name_to_features): """Decodes a record to a TensorFlow example.""" example = tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but the TPU only supports tf.int32. # So cast all int64 to int32. for na...
"""The actual input function.""" batch_size = params["batch_size"] if len(expanded_files) == 1: d = tf.data.TFRecordDataset(expanded_files[0]) if is_training: d = d.repeat() d = d.shuffle(buffer_size=256) else: dataset_list = [ tf.data.TFRecordDataset(expanded_fi...
kudlav/dnf
dnf/cli/completion_helper.py
Python
gpl-2.0
6,785
0.002211
#!/usr/bin/env python # # This file is part of dnf. # # Copyright 2015 (C) Igor Gnatenko <i.gnatenko.brain@gmail.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 Li...
ds.upgrade.UpgradeCommand): def __init__(self, args): super(UpgradeCompletionCommand, self).__init__(args) def configure(self, args): self.cli.demands.root_user = False self.cli.demands.available_repos = True self.cli.demands.sack_acti
vation = True def run(self, args): for pkg in ListCompletionCommand.updates(self.base, args[0]): print(str(pkg)) class DowngradeCompletionCommand(dnf.cli.commands.downgrade.DowngradeCommand): def __init__(self, args): super(DowngradeCompletionCommand, self).__init__(args) def...
opencobra/cobrapy
src/cobra/util/solver.py
Python
gpl-2.0
21,838
0.000687
"""Additional helper functions for the optlang solvers. All functions integrate well with the context manager, meaning that all operations defined here are automatically reverted when used in a `with model:` block. The functions defined here together with the existing model functions should allow you to implement cus...
Objective( Zero, direction=model.solver.objective.direction ) for reaction, coef in value.items(): model.solver.ob
jective.set_linear_coefficients( {reaction.forward_variable: coef, reaction.reverse_variable: -coef} ) elif isinstance(value, (Basic, optlang.interface.Objective)): if isinstance(value, Basic): value = interface.Objective( value, direction=model.solve...
castlecms/castle.cms
castle/cms/vocabularies.py
Python
gpl-2.0
11,750
0.001106
import pycountry from Acquisition import aq_parent from castle.cms.fragments.interfaces import IFragmentsDirectory from castle.cms.browser.survey import ICastleSurvey from plone import api from plone.registry.interfaces import IRegistry from Products.CMFCore.utils import getToolByName from zope.component import getAllU...
eVocabulary(terms) MimeTypeVocabulary = MimeTypeVocabularyFactory() @implementer(IVocabularyFactory) class RobotBehaviorVocabularyFactory(object): def __call__(self, context): terms = [ { 'value': 'index', 'title': 'Index', }, { ...
'title': 'Follow links', }, { 'value': 'noimageindex', 'title': 'Do not index images', }, { 'value': 'noarchive', 'title': 'Search engines should not show a cached link to this page on a SERP.', ...
benekex2/smart_mirror
motiondetect.py
Python
gpl-3.0
449
0.046771
import os #for OS program calls import sys #For Clean sys.exit command import time #for sleep/pause import
RPi.GPIO as io #read the GPIO pins io.setmode(io.BCM) pir_pin = 17 screen_saver = False io.setup(pir_pin, io.IN) while True: if screen_saver: if io.input(pir_pin): os.system("xscreensaver-command -deactivate") screen_saver = False else: time.sleep(300) os.system("xscreensaver-command -activate") ...
aver = True
OCA/connector-cmis
cmis/models/cmis_backend.py
Python
agpl-3.0
4,701
0
# © 2014-2015 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # Copyright 2016 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging from odoo import api, fields, models from odoo.exceptions import UserError from odoo.tools.translate import _ from ..exceptions import...
le_name = file_name.replace("_", r"\_") return file_name def safe_query(self, query, file_name, repo): args = map(self.sanitize_input, file_name) return repo.query(query % ''.j
oin(args))
tnemis/staging-server
schoolnew/views.py
Python
mit
219,616
0.044382
from django.views.generic import ListView, DetailView, CreateView, \ DeleteView, UpdateView, \ ArchiveIndexView, DateDetailView, \ DayArchiveView, MonthArchiveView, \ TodayArchiveView, Wee...
Ictentry.objects.filter(school_key=basic.id) passper_det=Passpercent.objects.filter(school_key=basic.id) infra a=basic.udise_code response = HttpResponse(content_type='application/pdf') filename = str(a) infra_edit_chk='Yes' response['Content-Disposition'] = 'attachement'; 'filename={0}.pdf'.forma...
) pdf=render_to_pdf( 'printpdfschool.html', { 'basic':basic, 'admin':admin, 'academic':academic, 'infra': infra, 'class_det':class_det, 'schgroup_det':schgroup_det, 'post_det':post_det, 'parttime_det':parttime_det, 'land_det':land_det, 'build_det':...