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
MineID/MineID
mineid/accounts/urls.py
Python
gpl-3.0
676
0
from django.conf.urls import patterns, include, url from .views import R
egistrationView, RegistrationComplete, SetEmailAddress, \ SwitchAccount urlpatterns = patterns( '', url(r'^register/$', RegistrationView.as_view(), name='registration_register'), url(r'^register/complete/$', RegistrationComplete.as_view(), name='registration_complete'),
url(r'^', include('mineid.accounts.auth_urls')), url(r'^', include('registration.backends.default.urls')), url(r'^set_email_address/$', SetEmailAddress.as_view(), name='set_email_address'), url(r'^switch_account/$', SwitchAccount.as_view(), name='switch_account'), )
ESOedX/edx-platform
openedx/core/djangoapps/content/block_structure/models.py
Python
agpl-3.0
9,770
0.001331
""" Models used by the block structure framework. """ from __future__ import absolute_import import errno from contextlib import contextmanager from datetime import datetime from logging import getLogger import six from six.moves import map from django.conf import settings from django.core.exceptions import Suspicio...
""" try: return cls.objects.get(data_usage_key=data_usage_key) except cls.DoesNotExist: log.info(u'BlockStructure: Not found in table; %s.', data_usage_key) raise BlockStructureNotFound(data_usage_key) @classmethod def update_or_create(cls, serialized_data, ...
tureModel entry for the given data_usage_key in the kwargs, uploading serialized_data as the content data. """ # Use an atomic transaction so the model isn't updated # unless the file is successfully persisted. with transaction.atomic(): bs_model, created = cl...
linkyndy/flask-remodel
flask_remodel/__init__.py
Python
mit
854
0
import rethinkdb as r from remodel.connection import pool class Remodel(object): def __init__(self, app=None,
db=None): self.app = app self.db = db if app is not None: self.init_app(app) def init_app(self, app): app.config.setdefault('REMODEL_POOL_SIZE', 5) app.config.setdefault('RETHINKDB_HOST', 'localhost') app.config.setdefault('RETHINKDB_PORT', '28015
') app.config.setdefault('RETHINKDB_AUTH', '') app.config.setdefault('RETHINKDB_DB', 'test') pool.configure(max_connections=app.config['REMODEL_POOL_SIZE'], host=app.config['RETHINKDB_HOST'], port=app.config['RETHINKDB_PORT'], ...
sclooney94/Python_3_AVI
migrations/0001_initial.py
Python
lgpl-3.0
1,309
0.00382
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-10-25 15:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies =
[ ('pipeline', '0002_auto_20161024_0848'), ] operations = [ migrations.CreateModel( name='DemoModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=Fal
se, verbose_name='ID')), ('user', models.CharField(editable=False, max_length=50, null=True)), ('expected_runtime', models.IntegerField(default=0)), ('resources_ram_mb', models.IntegerField(default=2000, help_text='Amount of RAM (M) to be allocated for the AviJob')), ...
MaterialsDiscovery/PyChemia
pychemia/code/vasp/incar.py
Python
mit
1,272
0.000786
import os from .input import VaspInput __author__ = "Guillermo Avendano-Franco" __copyright__ = "Copyright 2016" __version__ = "0.1" __maintainer__ = "Guillermo Avendano-Franco" __email__ = "gtux.gaf@gmail.com" __status__ = "Development" __date__ = "May 13, 2016" def read_incar(filename='INCAR'): """ Load t...
R'): """ Takes an object inputvars from pychemia a
nd save the file INCAR in the directory 'path' or save the file 'path' as a VASP INCAR file :param iv: (VaspInput) VASP Input variables :param filepath: (str) File path to write the INCAR file """ if os.path.isdir(filepath): filename = filepath + '/INCAR' else: filename = f...
FabricioMatos/ifes-dropout-machine-learning
lib/eda4.py
Python
bsd-3-clause
9,696
0.011861
# License: BSD 3 clause <https://opensource.org/licenses/BSD-3-Clause> # Copyright (c) 2016, Fabricio Vargas Matos <fabriciovargasmatos@gmail.com> # All rights reserved. '''' Tune the 3 most promissing algorithms and compare them ''' # Load libraries import os import time import pandas import numpy import matplotlib....
ing %s" % (grid_result.best_score_, grid_result.best_params_))
best_idx = grid_result.best_index_ #TODO: check it out if 'mean_test_score' is really what a want here cv_results = grid_result.cv_results_['mean_test_score'] results.append(cv_results) grid_scores = sorted(grid_result.grid_scores_, key=lambda x: x[2].mean(), reverse=True) first =...
28harishkumar/Social-website-django
comment/migrations/0003_auto_20150711_2109.py
Python
mit
525
0
# -*- coding: utf-8
-*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('comment', '0002_auto_
20150703_1252'), ] operations = [ migrations.RenameField( model_name='comment', old_name='post_id', new_name='post', ), migrations.RenameField( model_name='comment', old_name='user_id', new_name='user', ), ...
pietje666/plugin.video.vrt.nu
tests/run.py
Python
gpl-3.0
1,293
0.003094
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Dag Wieers (@dagwieers) <dag@wieers.com> # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """Run any Kodi VRT NU plugin:// URL on the commandline""" from __future__ import absolute_import, division, print_functi...
xbmcplugin') xbmcvfs = __import__('xbmcvfs') if len(sys.argv) <= 1: print("%s: URI argument missing\nTry '%s plugin://plugin.video.vrt.nu/recent/1' to test." % (sys.argv[0], sys.argv[0])) sys.exit(1) # Also support bare paths like /recent/2 if not sys.argv[1].startswith('plugin://'): sys.argv[1] = 'plugin...
nt('** Running URI %s with args %s' % (path, args)) addon.run([sys.argv[1], 0, args])
swryan/lazr.testing
src/lazr/testing/tests/test_docs.py
Python
lgpl-3.0
1,796
0
# Copyright 2009 Canonical Ltd. All rights reserved. # # This file is part of lazr.testing # # lazr.testing 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, version 3 of the License. # # lazr.testing is...
t os # pylint: disable-msg=F0401 from pkg_resources import ( resource_filename, resource_exists, resource_listdir, cleanup_resources) import unittest DOCTEST_FLAGS = ( doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE | doctest.REPORT_NDIFF) def test_su
ite(): "Run the doc tests (README.txt and docs/*, if any exist)" doctest_files = [ os.path.abspath(resource_filename('lazr.testing', 'README.txt'))] if resource_exists('lazr.testing', 'docs'): for name in resource_listdir('lazr.testing', 'docs'): if name.endswith('.txt'): ...
luotao1/Paddle
python/paddle/batch.py
Python
apache-2.0
2,180
0.004128
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy o
f th
e License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable 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 langua...
flavour/eden
modules/templates/CCC/layouts.py
Python
mit
10,084
0.003768
# -*- coding: utf-8 -*- __all__ = ("S3MainMenuLayout", "S3AboutMenuLayout", "MA", "S3LanguageMenuLayout", "ML", "S3PersonalMenuLayout", "MP", ) from gluon import current, URL, \ A, FORM, IMG, INPUT, LI, OPTION, SELECT, SPAN,...
ed items if not item.authorized: item.enabled = False item.visible = False elif item.enabled is None or item.enabled: item.enabled = True item.visible = True
if item.enabled and item.visible: items = item.render_components() if item.parent is not None: classes = [] if item.parent.parent is None: # Item at the top-level? toplevel = True if item.opts.r...
JoselynRuiz/Programacion-III
Clase 4/app/__diccionario__.py
Python
mit
1,723
0.007545
def imprimir_lista(x): print("\nMi lista de supermecardo") artIndice = 0 for a in x: print(str((int(x.index(a)+1))) + ". " + a) def imprimir_diccionario(w): print("\nMi lista de supermercado") for art, cant in w.items(): print("Articulo: " + str(art) + "(cantidad: " + str(cant) + ")...
o') print('2. qui
tar elemento') print('3. ver lista') print('4. salir') try: opc = int(input("OPCION:")) except ValueError: opc = 0 if opc == 1: print("\nVamos a ingresar un articulo a la lista") artInsertar = input("Articulo") # if artI...
puzcoin/test1
qa/rpc-tests/blockchain.py
Python
mit
2,834
0.000353
#!/usr/bin/env python2 # Copyright (c) 2014-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. # # Test RPC calls related to blockchain state. Tests correspond to code in # rpcblockchain.cpp. # from decimal import Decimal from test_framework.test_framework import BitcoinTestFramework from test_framework.authproxy import JSONRPCException from test_framework.util import ( initialize_chain, ...
connect_nodes_bi, ) class BlockchainTest(BitcoinTestFramework): """ Test blockchain-related RPC calls: - gettxoutsetinfo - verifychain """ def setup_chain(self): print("Initializing test directory " + self.options.tmpdir) initialize_chain(self.options.tmpdir) ...
meigrafd/Sample-Code
facebook-like.py
Python
mit
823
0.009721
#Tutorial : http://www.idiotinside.com/2015/02/13/get-number-of-likes-of-a-facebook-page-using-graph-api-in-python/ import urllib2 import json def getPageData(page_id): api_endpoint = "https://graph.facebook.com" fb_graph_url = api_endpoint+"/"+page_id try: api_request = urllib2.Request(fb_graph_ur...
return "JSON error" except IOError, e: if hasattr(e, 'code'): return e.code elif hasattr(e, 'reason'
): return e.reason page_id = "idiotinside" # username or id data = getPageData(page_id) print "Page Name:"+ data['name'] print "Likes:"+ str(data['likes']) print "Website:"+ data['link']
datamachine/twx.mtproto
twx/mtproto/util.py
Python
mit
791
0.005057
from codecs import encode import logging import zlib def substr(string, pos, length): return string[p
os:pos+length] def to_hex(_bytes, width=4): if len(_bytes) == 0: return None string = "" bytes_iter = iter(_bytes) try: if width < 1: while True: val = next(bytes_iter) string += '{:02X}'.format(val) while True: ...
h)): string += '{:02X}'.format(next(bytes_iter)) string += " " except StopIteration: return string def print_hex(_bytes, width=4): print(to_hex(_bytes, width)) def crc32(data): return zlib.crc32(data) & 0xffffffff # crc32 might be more than 32 bits because:...
Acehaidrey/incubator-airflow
airflow/providers/amazon/aws/hooks/sns.py
Python
apache-2.0
3,748
0.001601
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
tional, Union from
airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook def _get_message_attribute(o): if isinstance(o, bytes): return {'DataType': 'Binary', 'BinaryValue': o} if isinstance(o, str): return {'DataType': 'String', 'StringValue': o} if isinstance(o, (int, float)): return {'Da...
melizalab/django-lab-inventory
inventory/migrations/0002_auto_20150626_1805.py
Python
gpl-3.0
701
0.002853
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('inventory', '0001_initial'), ] operatio
ns = [ migrations.AddField( model_name='manufacturer', name='lookup_url', field=models.CharField(blank=True, max_length=64, null=True, help_text='url pattern to look up part number'),
), migrations.AddField( model_name='vendor', name='lookup_url', field=models.CharField(blank=True, max_length=64, null=True, help_text='url pattern to look up catalog number'), ), ]
tlplu/ran
ran.py
Python
gpl-3.0
58
0
#!
/usr/bin/env python3 import ran.main ran.main.main()
HydrelioxGitHub/home-assistant
tests/components/utility_meter/test_sensor.py
Python
apache-2.0
6,632
0
"""The tests for the utility_meter sensor platform.""" import logging from datetime import timedelta from unittest.mock import patch from contextlib import contextmanager from tests.common import async_fire_time_changed from homeassistant.const import EVENT_HOMEASSISTANT_START from homeassistant.setup import async_se...
assert
await async_setup_component(hass, DOMAIN, config) assert await async_setup_component(hass, SENSOR_DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) entity_id = config[DOMAIN]['energy_bill']['source'] hass.states.async_set(entity_id, 2, {"unit_of_measu...
janeen666/mi-instrument
mi/instrument/wetlabs/fluorometer/flort_d/driver.py
Python
bsd-2-clause
78,456
0.002537
#!/usr/bin/env python # coding=utf-8 """ @package mi.instrument.wetlabs.fluorometer.flort_d.driver @file marine-integrations/mi/instrument/wetlabs/fluorometer/flort_d/driver.py @author Art Teranishi @brief Driver for the flort_d Release notes: Initial development """ import datetime import time import re from mi.c...
class ScheduledJob(BaseEnum): """ List of jobs to be scheduled """ RUN_WIPER = 'ru
n_wiper' CLOCK_SYNC = 'clock_sync' ACQUIRE_STATUS = 'acquire_status' class Prompt(BaseEnum): """ Device I/O prompts. FLORT-D does not have a prompt. """ class InstrumentCommands(BaseEnum): """ Commands sent to the instrument """ # Instrument command strings INTERRUPT_INST...
DataDog/integrations-extras
traefik/tests/__init__.py
Python
bsd-3-clause
107
0
# (C) Datadog, Inc. 2018 # All rights reserved # Licensed under a 3-clause BSD styl
e license (see LICENSE)
scheib/chromium
third_party/blink/renderer/bindings/scripts/validator/framework/__init__.py
Python
bsd-3-clause
262
0
# Co
pyright 2021 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 .rule_base import RuleBase from .rule_store import RuleStore from .validator import Va
lidator
camallen/aggregation
experimental/graphicalClassification/MultiClassSubjectNode.py
Python
apache-2.0
227
0.013216
from SubjectNodes import
SubjectNode class MultiClassSubjectNode(SubjectNode): def __init__(self): SubjectNode.__init__(numClasses=1) def __changeClassificationAttributes__(self,attributesList)
: pass
zielmicha/satori
satori.core/satori/core/management/master_process.py
Python
mit
6,102
0.004589
# vim:ts=4:sts=4:sw=4:expandtab import ctypes from django.conf import settings import errno import fcntl import logging from multiprocessing import Process, Semaphore import sys import os from setproctitle import setproctitle from signal import signal, SIGINT, SIGTERM, SIGHUP, SIGKILL import signal ...
ot None and self.is_alive(): logging.error('Forcibly killing %s', self.name) os.kill(sel
f.pid, SIGKILL) except OSError: pass def do_handle_signal(self, signum, frame): sys.exit() def handle_signal(self, signum, frame): logging.info('%s caught signal %s', self.name, signalnames.get(signum, signum)) self.do_handle_signal(signum, frame) def run(self)...
fugitifduck/exabgp
lib/exabgp/__init__.py
Python
bsd-3-clause
138
0
# encoding: utf-8 """ __in
it__.py Created by Thomas Mangin on 2010-01-15. Copyright (c) 2009-2015 Exa Networks. All
rights reserved. """
archhurd/archweb
devel/migrations/0007_auto_assign_countries.py
Python
gpl-2.0
9,946
0.006535
# -*- coding: utf-8 -*- from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): # This is by no means an exhaustive list, but covered most of the time # zones selected by existing developers at the time I wrot...
'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "...
eld', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'devel.ma...
jharris119/ConstraintSatisfactionProblem
examples/wordsquare.py
Python
mit
6,259
0.001917
from csp import * from collections import Counter class WordSquare: """ Find a word square of the given size from the given dictionary. """ alphabet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') def __init__(self, wordsfile): """ Constructor. Arguments: wordsfile -- the ...
dd(word) self.letters_count.update(word[index]) # create a variable for each (row,col) pair in the word square self.variables = {(i, j): WordSquareVariable(self, (i, j)) for i in range(size) for j in range(size)} # create a constraint for each row and for each col (and the diag...
nstraints = set() WordSquareConstraint.lettermap = lettermap for i in range(size): self.constraints.add(WordSquareConstraint({self.variables[(i, col)] for col in range(size)})) self.constraints.add(WordSquareConstraint({self.variables[(row, i)] for row in range(size)})) i...
vahtras/amy
workshops/migrations/0026_add_missing_airports.py
Python
mit
1,529
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations AIRPORTS = [ ('ALC', 'Alicante', 'ES', 38.2821999, -0.558156), ('ARB', 'Ann Arbor, MI', 'US', 42.2229996, -83.7455978), ('BGR', 'Bangor, ME', 'US', 44.8073997, -68.8281021), ('CVG', 'Cincinnati, KY...
lname, country=country, latitude=latitude,
longitude=longitude) class Migration(migrations.Migration): dependencies = [ ('workshops', '0025_auto_20150707_0809'), ] operations = [ migrations.RunPython(add_bunch_of_new_airports), ]
jgosmann/psyrun
psyrun/__init__.py
Python
mit
345
0
fro
m psyrun.backend import DistributeBackend, LoadBalancingBackend from psyrun.mapper import ( map_pspace, map_pspace_parallel, map_pspace_hdd_backed) from psyrun.pspace import Param from psyrun.scheduler import ImmediateRun, Sqsub from psyrun.store import DefaultStore, PickleStore from psyrun.version import v...
Nukesor/mitra
mitra/models/entry.py
Python
mit
545
0.00367
from mitra import db class Entry(db.Model):
id = db.Column(db.Integer, primary_key=True) category_name = db.Column(db.String(120), db.ForeignKey('category.name')) userid = db.Column(db.Integer, db.ForeignKey('user.id')) date = db.Column(db.Date) name = db.Column(db.String(120)) amount = db.Column(db.Integer) def __init__(self, useri...
f.date = date self.name = name self.amount = amount
n3wb13/OpenNfrGui-5.0-1
lib/python/Plugins/Extensions/MediaPortal/resources/hosters/flyflv.py
Python
gpl-2.0
6,496
0.112719
# -*- coding: utf-8 -*- from Plugins.Extensions.MediaPortal.plugin import _ from Plugins.Extensions.MediaPortal.resources.imports import * def flyflv(self, data): parse = re.search('config: "(.*?)"', data, re.I) if parse: urlparts = re.findall("http://www.flyflv.com(.*?)\?e=(\d+)&ip=(.*?)$", parse.group(1)) if ...
c,d,x[i+4],6,-145523070); d=md5_ii(d,a,b,c,x[i+11],10,-1120210379); c=md5_ii(c,d,a,b,x[i+2],15,718787259); b=md5_ii(b,c,d,a,x[i+9],21,-343485551); a=safe_add(a,olda); b=safe_add(b,oldb); c=safe_add(c,oldc); d=safe_add(d,oldd); return (a,b,c,d) def rstr2binl(arg1): _local2 = [] for x in range((len(arg1) >> 2)+1): ...
al3 >> 5)] | ((ord(arg1[_local3 / 8]) & 0xFF) << (_local3 % 32))); _local3 = (_local3 + 8); string_local = str(_local2).strip('[]').replace(" ","") return _local2 def rstr2b64(_arg1): _local6 = 0 _local7 = 0 _local2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" _local3 = "" _local4 = le...
dgk/django-business-logic
tests/test_signals.py
Python
mit
1,402
0
# -*- coding: utf-8 -*- # from .common import * class SignalCatchException(Exception): pass def raise_on_enter(**kwargs): raise SignalCatchException(kwargs)
class SignalsTest(TestCase): def tearDown(self): signals.interpret_enter.disconnect(raise_on_enter) signals.interpret_leave.disconnect(raise_on_enter) signals.block_interpret_enter.disconnect(raise_on_enter) signals.block_interpret_leave.disconnect(raise_on_enter) def test_i...
ect(raise_on_enter) self.assertRaises(SignalCatchException, node.interpret, context) def test_interpret_leave(self): node = Node.add_root() context = Context() signals.interpret_leave.connect(raise_on_enter) self.assertRaises(SignalCatchException, node.interpret, context) ...
zhoffice/minos
owl/zktree/models.py
Python
apache-2.0
2,485
0.002414
from datetime import datetime import threading import zookeeper PERM_READ = 1 PERM_WRITE = 2 PERM_CREATE = 4 PERM_DELETE = 8 PERM_ADMIN = 16 PERM_ALL = PERM_READ | PERM_WRITE | PERM_CREATE | PERM_DELETE | PERM_ADMIN zookeeper.set_log_stream(open("cli_log.txt","w")) TIMEOUT = 10.0 class ZKClient(object): def __i...
perms_list.append("PERM_CREATE") if perms & PERM_DELETE: perms_list.append("PERM_DELETE") if perms & PERM_ADMIN: perms_l
ist.append("PERM_ADMIN") if perms & PERM_ALL == PERM_ALL: perms_list = ["PERM_ALL"] acl['perm_list'] = perms_list finally: zk.close()
kelle/astropy
astropy/visualization/units.py
Python
bsd-3-clause
2,941
0
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np __doctest_skip__ = ['quantity_support'] def quantity_support(format='latex_inline'): """ En...
plt.plot([1, 2, 3] * u.m) [...] ... plt.plot([101, 125, 150] * u.cm) [...] ... plt.draw() Parameters ---------- format : `astropy.units.format.Base` instance or str The name of a format or a formatter object. If not provided, defaults to ``latex_inline``....
from .. import units as u from matplotlib import units from matplotlib import ticker def rad_fn(x, pos=None): n = int((x / np.pi) * 2.0 + 0.25) if n == 0: return '0' elif n == 1: return 'π/2' elif n == 2: return 'π' elif n % 2...
andyzinsser/good-day
collectors/serializers.py
Python
mit
190
0
from rest_framework import serializers from collectors.models import Day class DaySerializer(serializers.ModelSerializer): class Meta: model = D
ay fiel
ds = ('result',)
jamescr/LibreScan
src/setup.py
Python
gpl-3.0
1,505
0.004651
import os from shutil import copyfile from setuptools import setup, find_packages import yaml USERHOME = os.environ["HOME"] RESOURCESPATH = './configuration' LIBRESCANPATH = USERHOME + "/LibreScanProjects" LSCONFIGPATH = USERHOME + "/.librescan" def create_folders(): try: os.mkdir(LIBRESCANPATH) exc...
sts") def create_config_files(): template_path = "/defaultProjectConfig.yaml" project_template = RESOURCESPATH + template_path copyfile(project_template, LSCONFIGPATH + template_path) if os.path.exists(LSCONFIGPATH+"/p
rojects.yaml"): os.remove(LSCONFIGPATH+"/projects.yaml") print("warning: projects.yaml file was deleted and recreated") os.mknod(LSCONFIGPATH+"/projects.yaml") if os.path.exists(LSCONFIGPATH+"/config.yaml"): os.remove(LSCONFIGPATH+"/config.yaml") print("warning: config.yam...
sounak98/coala-bears
tests/BearTestHelper.py
Python
agpl-3.0
171
0.005848
import logging logging.warning('This module is deprec
ated. Use ' '`coalib.testing.BearTestHelper` instead.') from coalib.testing.BearTestHelper
import *
jonnyhtw/cylc
lib/xdot.py
Python
gpl-3.0
97,799
0.003303
#!/usr/bin/env python # # Copyright 2008 Jose Fonseca # # This program 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) any later version. # # This ...
*= f height *= f descent *= f else: f = 1.0 if self.j == self.LEFT: x = self.x eli
f self.j == self.CENTER: x = self.x - 0.5*width elif self.j == self.RIGHT: x = self.x - width else: assert 0 y = self.y - height + descent cr.move_to(x, y) cr.save() cr.scale(f, f) cr.set_source_rgba(*self.select_pen(highligh...
takeshineshiro/cinder
cinder/api/contrib/types_extra_specs.py
Python
apache-2.0
7,548
0
# Copyright (c) 2011 Zadara Storage Inc. # 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-...
parent=dict(member_name='type', collection_name='types') )
resources.append(res) return resources
yosinski/deep-visualization-toolbox
caffevis/app.py
Python
mit
33,221
0.006893
#! /usr/bin/env python # -*- coding: utf-8 import sys import os import cv2 import numpy as np import time import StringIO from misc import WithTimer from numpy_cache import FIFOLimitedArrayCache from app_base import BaseApp from image_misc import norm01, norm01c, norm0255, tile_images_normalize, ensure_float01, tile_...
= self._net_channel_swap, raw_scale = self._range_scale, ) if isinstance(settings.caffevis_data_mean, basestring): #
If the mean is given as a filename, load the file try: filename, file_extension = os.path.splitext(settings.caffevis_data_mean) if file_extension == ".npy": # load mean from numpy array self._data_mean = np.load(settings.caffevis_data...
TerekhovaKate/Python_training
1.py
Python
apache-2.0
393
0.025445
from math import *
class Point: def __init__(self, _x, _y): self.x =_x self.y=
_y def distance (self, p2): dx = p2.x - self.x dy = p2.y - self.y return sqrt(dx*dx + dy*dy) def __eq__(self, other): return self.x == other.x and self.y == other.y a = Point(0,0) b = Point(3,4) print(a.distance(b)) print(a ==b) print(a == Point(0,0))
t794104/ansible
lib/ansible/modules/cloud/google/gcp_iam_role.py
Python
gpl-3.0
9,028
0.002326
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
n >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: state: description: - Whether the given object should exist in GCP choices: - present - absent default: present name: description: - The name of the role. required: true title: description: - A human-readable...
tle for the role. Typically this is limited to 100 UTF-8 bytes. required: false description: description: - Human-readable description for the role. required: false included_permissions: description: - Names of permissions this role grants when bound in an IAM policy. required: fal...
alxgu/ansible
lib/ansible/modules/cloud/google/gcp_compute_instance_group_facts.py
Python
gpl-3.0
7,002
0.002999
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
und, return nothing. if response.status_code == 404: return None # If no content, return nothing. if response.status_code == 204: return None try: module.raise_for_status(response) result = response.json() except getattr(json.decoder, 'JSONDecodeError', ValueError) ...
g="Invalid JSON response with error: %s" % inst) if navigate_hash(result, ['error', 'errors']): module.fail_json(msg=navigate_hash(result, ['error', 'errors'])) return result if __name__ == "__main__": main()
leaen/Codeeval-solutions
even-numbers.py
Python
mit
160
0.03125
import sys with open(sys.argv[1]) as input_file: for problem in input_file.readlines(): if (int(problem.strip()) %
2 == 0): print(1) else: print(0
)
cyroxx/rsftp
rsftp/test/test_filepath.py
Python
mit
1,262
0.002377
from twisted.trial.unittest import TestCase import treq from rsftp import rs from rsftp.test.mocks import mock_get, fakeGet404, fakeListResponseNonNumeric class RSFilePathTestCase(TestCase): def setUp(
self): self.test = rs.RSFilePath('https://example.com/public/') def tearDown(self): pass def test_child(self): self.patch(treq, 'get', mock_get) name = 'pictures' d = self.test.child(name) def cbChild(childPath): self.assertEqual(childPath.p
ath, 'https://example.com/public/pictures/') d.addCallback(cbChild) return d def test_childNonExistentPath(self): self.patch(treq, 'get', fakeGet404) name = 'doesnotexist/' d = self.test.child(name) return self.assertFailure(d, rs.filepath.NotFoundError) def...
jude/certmaster
certmaster/commonconfig.py
Python
gpl-2.0
1,224
0.003268
""" Default configuration values for certmaster items when not specified in config file. Copyright 2008, Red Hat, Inc see AUTHORS This software may be freely redistributed under the terms of the GNU general public license. You should have received a copy of the GNU General Public License along with this program; if ...
log_level = Option('INFO') listen_addr = Option('') listen_port = IntOption(51235) cadir = Option('/etc/pki/certmaster/ca') cert_dir = Option('/etc/pki/certmaster') certroot = Option('/var/lib/certmaster/certm
aster/certs') csrroot = Option('/var/lib/certmaster/certmaster/csrs') cert_extension = Option('cert') autosign = BoolOption(False) sync_certs = BoolOption(False) peering = BoolOption(True) peerroot = Option('/var/lib/certmaster/peers') hash_function = Option('sha256') class MinionConfig(Ba...
chickonice/AutonomousFlight
ROS/build/bluefox2/catkin_generated/pkg.installspace.context.pc.py
Python
gpl-3.0
901
0.00222
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX
= "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/odroid/ROS/install/include".split(';') if "/home/odroid/ROS/install/include" != "" else [] PROJECT_CATKIN_DEPENDS = "message_runtime".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lbluefox2;-l:/home/odroid/ROS/src/bluefox2/mvIMPACT/lib/armv7l/libmvBlueFOX.so;-l:/h...
anager.so;-l:/home/odroid/ROS/src/bluefox2/mvIMPACT/lib/armv7l/libmvPropHandling.so".split(';') if "-lbluefox2;-l:/home/odroid/ROS/src/bluefox2/mvIMPACT/lib/armv7l/libmvBlueFOX.so;-l:/home/odroid/ROS/src/bluefox2/mvIMPACT/lib/armv7l/libmvDeviceManager.so;-l:/home/odroid/ROS/src/bluefox2/mvIMPACT/lib/armv7l/libmvPropHan...
github/codeql
python/ql/test/query-tests/Variables/unused/test.py
Python
mit
2,148
0.018622
#Unused def fail(): for t in [TypeA, TypeB]: x = TypeA() run_test(x) #OK by name def OK1(seq): for _ in seq: do_something() print("Hi") #OK counting def OK2(seq): i = 3 for x in seq: i += 1 return i #OK check emptiness def OK3(seq): for thing in seq: ...
uence: do_something(x+1) #OK See ODASA-4153 and ODASA-4533 def fai
l5(t): x, y = t return x class OK9(object): cls_attr = 0 def __init__(self): self.attr = self.cls_attr __all__ = [ 'hello' ] __all__.extend(foo()) maybe_defined_in_all = 17 #ODASA-5895 def rand_list(): return [ random.random() for i in range(100) ] def kwargs_is_a_use(seq): for arg ...
base2Services/cloudformation-custom-resouces
src/s3-copy/cr_response.py
Python
mit
1,920
0.006771
import logging from urllib.request import urlopen, Request, HTTPError, URLError import json logger = logging.getLogger() logger.setLevel(logging.INFO) class CustomResourceResponse: def __init__(self, request_payload): self.payload = request_payload self.response = { "StackId": request...
n(req) logger.debug("Request to CFN API succeeded, nothing to do here") except HTTPError as e: logger.error("C
allback to CFN API failed with status %d" % e.code) logger.error("Response: %s" % e.reason) except URLError as e: logger.error("Failed to reach the server - %s" % e.reason)
fzimmermann89/pyload
module/plugins/hooks/JustPremium.py
Python
gpl-3.0
2,420
0.015289
# -*- coding: utf-8 -*- import re from module.plugins.internal.Addon import Addon class JustPremium(Addon): __name__ = "JustPremium" __type__ = "hook" __version__ = "0.25" __status__ = "testing" __config__ = [("activated", "bool", "Activated" , False), ...
multihosters = set(hoster for hoster in self.pyload.pluginManager.hosterPlugins \ if 'new_name' in hosterdict[hoster] \ and hosterdict[hoster]['new_name'] in premiumplugins) excluded = map(lambda domain: "".join(part.capitalize() for part in re...
ace(',', '|').replace(';', '|').split('|')) included = map(lambda domain: "".join(part.capitalize() for part in re.split(r'(\.|\d+)', domain) if part != '.'), self.get_config('included').replace(' ', '').replace(',', '|').replace(';', '|').split('|')) hosterlist = (premiumplugins...
boundlessgeo/qgis-connect-plugin
boundlessconnect/gui/fixedaspectsvgwidget.py
Python
gpl-2.0
1,963
0.001528
# -*- coding: utf-8 -*- """ *************************************************************************** fixedaspectsvgwidget.py --------------------- Date : August 2016 Copyright : (C) 2016 Boundless, http://boundlessgeo.com ***************************************************...
with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from qgis.PyQt.QtCore import QRect from qgis.PyQt.QtGui import QPainter from qgis.PyQt.QtSvg import QSvgWidget class FixedAspe
ctSvgWidget(QSvgWidget): def paintEvent(self, event): painter = QPainter(self) painter.setViewport(self.centeredViewport(self.size())) self.renderer().render(painter) def centeredViewport(self, size): width = size.width() height = size.height() aspectRatio = f...
Will1229/learnOpenstack
auth.py
Python
apache-2.0
771
0.002594
from os import environ as env def get_credentials(): print "Enter get_credentials" d = {} d['auth_url'] = env['OS_AUTH_URL'] d['username'] = env['OS_USERNAME'] d['password'] = env['OS_PASSWORD'] d['auth_url'] = env['OS_AUTH_URL'] d['tenant_name'] = env['OS_TENANT_NAME'] prin...
tials_v2(): print "Enter get_nova_credentials_v2" d = {} d['version'] = '2.1' d['username'] = env['OS_USERNAME'] d['api_key'] = env['OS_PASSWORD'] d['auth_url'] = env['OS_AUTH_URL'] d['project_id'] = env['OS_TENANT_NAME'] d['region_name'] = env['OS_REG
ION_NAME'] print d print "Return get_nova_credentials_v2" return d
sametmax/Django--an-app-at-a-time
ignore_this_directory/django/core/mail/backends/smtp.py
Python
mit
5,306
0.001696
"""SMTP email backend class.""" import smtplib import socket import ssl import threading from django.conf import settings from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.message import sanitize_address from django.core.mail.utils import DNS_NAME class EmailBackend(BaseEmailBackend):...
connection_params['timeout'] = self.timeout if self.use_ssl: connection_params.update({ 'keyfile': self.ssl_keyfile, 'certfile': self.ssl_certfile, }) try: self.connection = self.connection_class(self.host, self.port, **connec...
ions. if not self.use_ssl and self.use_tls: self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile) if self.username and self.password: self.connection.login(self.username, self.password) return True except (smtplib.SMTPE...
eduNEXT/edunext-platform
import_shims/studio/course_action_state/tests/test_rerun_manager.py
Python
agpl-3.0
461
0.008677
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh.""" # pyl
int: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppres
sion,line-too-long from import_shims.warn import warn_deprecated_import warn_deprecated_import('course_action_state.tests.test_rerun_manager', 'common.djangoapps.course_action_state.tests.test_rerun_manager') from common.djangoapps.course_action_state.tests.test_rerun_manager import *
mysociety/pombola
pombola/settings/tests_base.py
Python
agpl-3.0
1,485
0.018855
import os import shutil from pombola.config import config IN_TEST_MODE = True base_dir = os.path.abspath( os.path.join( os.path.split(__file__)[0], '..', '..' ) ) # Change the data dir in testing, and delete it to ensure that we have a clean # slate. Also print out a little warning - adds clutter to the test output b...
r, 'testing' ) ) if os.path.exists( data_dir ): shutil.rmtree( data_dir ) print("Running in test mode! (testing data_dir is '%s')" % data_dir) # For tests we've change the value of data_dir, so have to reset # these settings variables: MEDIA_ROOT = os.path.normpath( os.path.join( data_dir, "media_root/") ) STAT...
= os.path.join( data_dir, 'httplib2_cache' ) HANSARD_CACHE = os.path.join( data_dir, 'hansard_cache' ) MAP_BOUNDING_BOX_NORTH = None MAP_BOUNDING_BOX_SOUTH = None MAP_BOUNDING_BOX_EAST = None MAP_BOUNDING_BOX_WEST = None # A workaround so that functional tests don't fail with missing # assets, as suggested here: # ...
eli261/jumpserver
apps/authentication/api/__init__.py
Python
gpl-2.0
113
0
# -*- coding: utf
-8 -*- # from .auth import * f
rom .token import * from .mfa import * from .access_key import *
diamondIPP/eudaq-drs4
producers/explorer/srs-software/slow_control/reboot_FEC_ADC.py
Python
lgpl-3.0
238
0.02521
#! /usr/bin/env python ## ## code testing of class SlowControl ## import SlowControl # sl
ow control code import time sc = SlowControl.SlowControl(1) SlowControl.write_list(sc, 6007, [ 0xFFFFFFFF ], [ 0xFFFF8000 ], False,
False) quit()
smorgant/echo
echo/urls.py
Python
apache-2.0
854
0.001171
"""echo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='hom
e') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog...
tterns = [ url(r'^$', include('movies.urls')), url(r'^movies/', include('movies.urls')), url(r'^admin/', admin.site.urls), ]
chkvch/on_GP
v2/eos/chabrier.py
Python
gpl-2.0
7,299
0.009864
from scipy.interpolate import RectBivariateSpline as rbs from itertools import islice import numpy as np class eos: def __init__(self, path_to_data=None): if not path_to_data: import os path_to_data = os.environ['ongp_data_path'] npts_t = 121 npts_t -= 60 # skip lo...
for component in ('h', 'he'): path = {'h':h_path, 'he':he_path}[compo
nent] self.data[component] = {} for name in columns: self.data[component][name] = np.zeros((npts_p, npts_t)) it = 0 with open(path, 'r') as f: for i, line in enumerate(f.readlines()): if line[0] == '#': ...
eeriks/velo.lv
velo/payment/views/return_views.py
Python
gpl-3.0
1,552
0.001289
from django.http import Http404 from django.utils.decorators import method_decorator from django.views import View from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_exempt from velo.payment.models import Transaction from velo.core.utils import log_message __all__ = ['...
else: if request.POST.get('VK_REF', None): _id = request.POST.get('VK_REF', None) elif request.GET.get('VK_REF', None): _id = request.GET.get('VK_REF', None) elif request.POST.get('IB_PAYMENT_ID', None): _id = request.POST.get('IB...
ne) else: log.set_message("ERROR") raise Http404("ERROR") transaction = Transaction.objects.get(id=_id) log.set_object(transaction) integration_object = transaction.channel.get_class(transaction) return integration_object.verify_return(r...
dpinney/omf
omf/static/testFiles/test_feeder/test_feeder.py
Python
gpl-2.0
1,423
0.00773
import json from pathlib import Path import omf from omf
import feeder class Test_treeToNxGraph: def test
_newNetworkxAPI_returns_sameGraphAsOldNetworkXAPI(self): ''' Two unequal objects CAN have the same hash value. - networkx.Graph instances define __eq__ and __hash__, but that does not mean two unequal Graph objects will have different has values. Don't use hashes for comparison ''' ...
abdelwas/GossipPubSub
subscriber.py
Python
gpl-3.0
183
0.005464
import sys from gossip import Node if __name__ == '__main__': server_port = sys.argv[1] peers = sys.argv[2:] n = Node(serv
er_port, peers) while
True: pass
rohitkyadav/blog-api
src/posts/api/serializers.py
Python
mit
1,539
0.049383
from rest_framework.serializers import ( HyperlinkedIdentityField, ModelSerializer, SerializerMethodField, ) from comments.api.serializers import CommentSerializer from accounts.api.serializers import UserDetailSerializer from comments.models import Comment from posts.models import Post class PostCreateUpdateSer...
obj.image.url except: image = None return image def get_comments(self, obj): #content_type = obj.get_content_type #object_id = obj.id c_qs = Comment.objects.filter_by_instance(obj) comments = CommentSerializer(c_qs, many=True).data return comments class PostListSerializer(ModelSerializer
): url = post_detail_url user = UserDetailSerializer(read_only=True) class Meta: model = Post fields = [ 'url', 'user', 'title', 'slug', 'content', 'publish', ]
davidjamesca/ctypesgen
ctypesgen/libraryloader.py
Python
bsd-2-clause
13,802
0.001014
""" Load libraries - appropriately for all our supported platforms """ # ---------------------------------------------------------------------------- # Copyright (c) 2008 David James # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # mo...
called with mode RTLD_GLOBAL instead # of the default RTLD_LOCAL. Without this, you end up with # libraries not being loadable, resultin
g in "Symbol not found" # errors mode = ctypes.RTLD_GLOBAL def getplatformpaths(self, libname): if os.path.pathsep in libname: names = [libname] else: names = [fmt % libname for fmt in self.name_formats] for directory in self.getdirs(libname): ...
corbindavenport/me-irl-bot
memebot.py
Python
gpl-3.0
13,750
0.027927
import praw import json import requests import tweepy import time import os import csv import re import configparser import urllib.parse import sys from glob import glob from gfycat.client import GfycatClient from imgurpython import ImgurClient import distutils.core import itertools import photohash from PIL import Ima...
ile_path) # Imgur will sometimes return a single-frame thumbnail instead of a GIF, so we need to check for this if (file_extension == '.gif'): # Open the file using the Pillow library img = Image.open(imgur_file) # Get the MIME type mime = Image.MIME[img.format] if (mime == 'image/gif'): ...
so don't post it print('[EROR] Imgur has not processed a GIF version of this link, so it can not be posted') img.close() # Delete the image try: os.remove(imgur_file) except BaseException as e: print ('[EROR] Error while deleting media file:', str(e)) return else: return...
madscatt/zazzie
src_2.7/sassie/calculate/old_sascalc/hypred_library/run_sassie/plot.py
Python
gpl-3.0
1,043
0.04698
import locale import sys from matplotlib import pylab as plt from scipy.interpolate import interp1d import numpy def parse_pRDF(f): pRDFs={} count=0 for line in open(f).readlines(): words=line.split() if words[0]=="dstep": dstep=locale.atof(words[1]) continue e
lif words[0]=="nstep": nstep=locale.atof(words[1]) continue else: atom_type = words[0] pRDF=[] for word in words[1:]: pRDF.append(locale.atof(
word)) pRDFs[atom_type]=pRDF return (pRDFs,dstep) f=sys.argv[1] (pRDFs, dstep)=parse_pRDF(f) colors={"C":"k", "HC":"r", "N":"b", "HN":"g", "O":"m", "HO":"y", "S":"c"} X = numpy.linspace(0, 10+dstep, int(10/dstep)+1) scale=3 Xf = numpy.linspace(0, 10+dstep, (int(10/dstep)+1)*scale) for atom_type, pRDF in pRDFs.ite...
miraculixx/django-polls
polls/south_migrations/0008_auto__add_field_choice_code.py
Python
bsd-3-clause
6,286
0.008272
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from uuid import UUID class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Choice.code' db.add_column(u'polls_c...
'content_type': ('django.db.models.fields
.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}...
tseaver/google-cloud-python
texttospeech/tests/system/v1beta1/test_system_tts_v1beta1.py
Python
apache-2.0
1,499
0.000667
# Copyright 2019 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, ...
beta1.types.AudioConfig( audio_encoding=texttospeech_v1beta1.enums.AudioEncoding.MP3 ) response = client.synthesize_speech(synthesis_input, voice, audio_config) assert response.audio_content is not None def test_list_voices(self):
client = texttospeech_v1beta1.TextToSpeechClient() voices = client.list_voices() assert len(voices.voices) > 0
genialis/resolwe-bio
resolwe_bio/kb/serializers.py
Python
apache-2.0
1,086
0
""".. Ignore pydocstyle D400. =========== Serializers ===========
""" from rest_framework import serializers from resolwe.rest.serializers import SelectiveFieldMixin from .models import Feature, Mapping class FeatureSerializer(SelectiveFieldMixin, serializers.ModelSerializer): """Serializer for feature.""" class Meta: """Serializer configuration.""" mode...
"description", "feature_id", "full_name", "id", "name", "source", "species", "sub_type", "type", ] class MappingSerializer(SelectiveFieldMixin, serializers.ModelSerializer): """Serializer for mapping.""" ...
ericfischer/chromium-compact-language-detector
testData.py
Python
bsd-3-clause
49,155
0.009012
# coding=utf-8 # Copyright (c) 2009 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. # MKM: ported from FullTests in compact_lang_det_unittest_small.cc # MKM: string constants for test.py kTeststr_en = "confiscation of g...
ند به جای باز ی کتک کاری می کردند و همه چيز مثل قبل بود فقط من ماندم و يک دنيا حرف و انتظار تا عاقبت رسيد احضاريه ی ای با"; kTeststr_fi_Latn = " a joilla olet käynyt tämä kerro meille kuka ä olet ei tunnistettavia käyttötietoja kuten virheraportteja käytetään google deskto
pin parantamiseen etsi näyttää mukautettuja uutisia google desktop keskivaihto leikkaa voit kaksoisnapsauttaa"; kTeststr_fj_Latn = " i kina na i iri ka duatani na matana main a meke wesi se meke mada na meke ni yaqona oqo na meke ka dau vakayagataki ena ya
peterbraden/tensorflow
tensorflow/python/platform/logging_test.py
Python
apache-2.0
1,121
0.001784
# Copyright 2015 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 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....
============= from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.platform import googletest from tensorflow.python.platform import tf_logging as logging class EventLoaderTest(googletest.TestCase): def test_log(self): # Just chec...
jcfr/Midas
modules/remoteprocessing/remotescript/main.py
Python
apache-2.0
6,635
0.016277
#! /usr/bin/python import re import os import sys import time import pydas.communicator as apiMidas import pydas.exceptions as pydasException import uuid import json import shutil from zipfile import ZipFile, ZIP_DEFLATED from subprocess import Popen, PIPE, STDOUT from contextlib import closing # Load configuration fi...
eturn response # Send results to Midas def sendResults(file): """ Send Results """ cfg = loadConfig('config.cfg') cfginternal = loadConfig('config.internal.cfg') url = cfg['url'] interfaceMidas = apiMidas.Communicator (url) parameters = dict() parameters['token'] = cfginternal['tok...
t pydasException.PydasException, e: print "Unable to send results" print e return False return response # Handle Midas command def handleMidasResponse(response): """ Handle response """ if response['action'] == 'wait': print "Wait" time.sleep(120) elif response['action'] == 'pro...
hatchetation/freeipa
ipalib/base.py
Python
gpl-3.0
15,669
0.000447
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # 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, ei...
DEL_ERROR % (self.__class__.__name__, name) ) return object.__delattr__(sel
f, name) def lock(instance): """ Lock an instance of the `ReadOnly` class or similar. This function can be used to lock instances of any class that implements the same locking API as the `ReadOnly` class. For example, this function can lock instances of the `config.Env` class. So that this ...
arcolife/dockerComp
src/server/app/controller.py
Python
gpl-3.0
555
0.030631
from app.users.models import * from datetime import datetime def create_client(client_
IP, containers): pass def add_container(client_IP, container_id): pass def purge_container(client_IP, container_id): # if user modified the config on the fly # then remove one of the containers and # update this on The Channel pass def purge_client(client_IP): # counter = 3 pass def add_dat...
_IP): pass def add_result(container_id, client_IP): pass
kudrom/genesis2
genesis2/plugins/health/providers.py
Python
gpl-3.0
2,769
0.000361
from genesis2.core.core import Plugin, implements from genesis2.interfaces.gui import IMeter class BaseMeter (Plugin): """ Meters are determinable values (int, float, bool) representing system status (sysload, memory usage, service status, etc.) which are used and exported over HTTP by ``health`` buil...
rm preparations based on ``self.variant`` here. """ def get_variants(self): """ Implementation should return list of meter 'variants' here. """ return ['None'] def format_value(self): return None class BinaryMeter (BaseMeter): """ Base class for binary...
pe = 'binary' def get_value(self): """ Implementation should return binary meter value """ def format_value(self): BaseMeter.format_value(self) return {'value': self.get_value()} class DecimalMeter (BaseMeter): """ Base class for decimal/float value meters ...
darkpeach/AlgorithmCoding
_083_RemoveDuplicatesFromSortedList.py
Python
epl-1.0
599
0.001669
# Definiti
on for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ dummy = ListNode(0) dummy.next
= head ptr = head while head and head.next: if head.next.val != head.val: ptr.next = head.next ptr = head.next head = head.next if ptr: ptr.next = None return dummy.next
RKD314/yumstat
yumstat/apiclient/discovery.py
Python
mit
35,847
0.006416
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
Returns: A Resource object with methods for interacting with the service. """ # future is no longer used. future = {} if isinstance(service, basestring): service = simplejson.loads(service) base = urlparse.urljoin(service['rootUrl'], service['servicePath']) schema = Schemas(service) if mode...
JsonModel('dataWrapper' in features) return Resource(http=http, baseUrl=base, model=model, developerKey=developerKey, requestBui
0xddaa/pwndbg
pwndbg/commands/xinfo.py
Python
mit
4,499
0.003779
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import subprocess import gdb import pwndbg.arch import pwndbg.color.memory as M import pwndbg.commands imp...
addr, first.vaddr, rva, "+") # find possible LOAD segments that designate memory and file backings containing_loads = [seg for seg in pwndbg.elf.get_containing_segments(file_name, first.vaddr, addr) if seg['p_type'] == 'PT_LOAD'] for segment in containing_loads: if segment[...
t = addr - segment['p_vaddr'] print_line('File (Segment)', addr, segment['p_vaddr'], offset, '+') break for segment in containing_loads: if segment['p_type'] == 'PT_LOAD' and addr < segment['x_vaddr_file_end']: file_offset = segment['p_offset'] + (addr - segment['p_vaddr...
moto-timo/ironpython3
Tests/test_methodbinder1.py
Python
apache-2.0
57,530
0.016374
##################################################################################### # # Copyright (c) Microsoft Corporation. All rights reserved. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of th...
arg): if isinstance(arg, tuple): l = len(arg) # by purpose if l == 0: func() elif l == 1: func(arg[0]) elif l == 2: func(arg[0], arg[1]) elif l == 3: func(arg[0], arg[1], arg[2]) elif l == 4: func(arg[0], arg[1], arg[2], arg[3]) elif l == 5: func(arg[...
], arg[5]) else: func(*arg) else: func(arg) def _helper(func, positiveArgs, flagValue, negativeArgs, exceptType): for arg in positiveArgs: try: _my_call(func, arg) except Exception as e: Fail("unexpected exception %s when calling %s with %s\n%s" % (e,...
MarconiMediaGroup/JobTrak
web/code/mmg/jobtrak/public/models.py
Python
apache-2.0
267
0.026217
from django.db import models class
PageContent(models.Model): id = models.AutoField(primary_key=True) class Meta: verbose_name='Page Content' verbose_name_plural='Page Content' def __unicode__(se
lf): return u'PageContent'
Debian/openjfx
modules/web/src/main/native/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_frontend_dispatcher_implementation.py
Python
gpl-2.0
5,876
0.003744
#!/usr/bin/env python # # Copyright (c) 2014-2016 Apple Inc. All rights reserved. # Copyright (c) 2014 University of Washington. 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. Redistribution...
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILI
TY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. import logging import string from string import Template from cpp_generator import CppGenerator from cpp_generator_templates import CppGeneratorTemplates as CppTe...
iamxg/minindn-wifi
ndnwifi/averesultgraph-consumer-bread.py
Python
gpl-3.0
8,800
0.007045
# Draw graph x-axios is the number of nodes in the network. import re import sys import os import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter # useful for `logit` scale from mininet.log import setLogLevel, output, info # Read the experimental result data file in a specfied ...
0 for dataFileName in dataFileList: if not ("statResult" in dataFileName): dataFileList.pop(i) i = i+1 # Sort data file according to file name (the number of nodes) by using bubble algorithm i = 0 while i < len(dataFileList)-1: try: j = 0 whil...
len(dataFileList)-1-i: fileName = dataFileList[j].strip() startChar = fileName.index("-") + len("-") endChar = fileName.index(".", startChar) nodeNumber_j = fileName[startChar : endChar] # after j fileName=dataFileList[j+1]....
sam-m888/addons-source
lxml/superclasses.py
Python
gpl-2.0
655,543
0.004
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated Sun Jul 5 15:10:21 2015 by generateDS.py version 2.16a. # import sys import re as re_ import base64 import datetime as datetime_ import warnings as warnings_ from lxml import etree as etree_ Validate_simpletypes_ = True def parsexml_(infile, parser=None...
' % input_data def gds_validate_integer(self, input_data, node=None, input_name=''): return input_data def gds_format_integer_list(self, input_data, input_name=''): return '%s' % ' '.join(input_data) def gds_validate_integer_list( self, input_data, node=No...
try: int(value) except (TypeError, ValueError): raise_parse_error(node, 'Requires sequence of integers') return values def gds_format_float(self, input_data, input_name=''): return ('%.15f' % input_data).rstrip('0') ...
jbogaardt/chainladder-python
examples/plot_capecod_onlevel.py
Python
mit
2,182
0.00275
""" ===================================== Include On-leveling into Cape Cod ===================================== This example demonstrates how to incorporate on-leveling into the `CapeCod` estimator. The on-level approach emulates the approach taken
by Friedland in "Estimating Unpaid Claims Using Basic Techniques" Chapter 10. The `ParallelogramOLF` estimator is new in chainladder 0.7.9 as is the ``xyz`` triangle. """ import chainladder as cl import pandas as pd # Grab a triangle xyz = cl.load_sample('xyz') # Premium on-leveling factors rate_history = pd.DataF...
1/1/2004', '1/1/2005', '1/1/2006', '1/1/2007', '1/1/2008'], 'rate_change': [.02, .02, .02, .02, .05, .075, .15, .1, -.2, -.2] }) # Loss on-leveling factors tort_reform = pd.DataFrame({ 'date': ['1/1/2006', '1/1/2007'], 'rate_change': [-0.1067, -.25] }) # In addition to development, include onlevel estimat...
ENCODE-DCC/encoded
src/encoded/commands/extract_test_data.py
Python
mit
4,920
0.001829
import csv import loremipsum import random import re from encoded.loadxl import * class Anonymizer(object): """Change email addresses and names consistently """ # From Colander. Not exhaustive, will not match .museum etc. email_re = re.compile(r'(?i)[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}') random...
for row in dictrows: for k, v in kw.items(): if k in row: row[k] = v yield row return component def drop_rows_with_all_key_value(**kw): def component(dictrows): for row in dictrows: if not all(row[k] == v if k in row else Fals...
skip_rows_with_all_falsey_value('test'), skip_rows_with_all_key_value(test='skip'), skip_rows_with_all_falsey_value('test'), skip_rows_missing_all_keys('uuid'), drop_rows_with_all_key_value(_skip=True), ] def anon_pipeline(): anonymizer = Anonymizer() return extract_pi...
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Hash/test_SHA3_256.py
Python
mit
2,985
0.00335
# -*- coding: utf-8 -*- # # SelfTest/Hash/test_SHA3_256.py: Self-test for the SHA-3/256 hash function # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # e...
, perpetual, royalty-free, # non-exclusive li
cense to exercise all rights associated with the # contents of this file for any purpose whatsoever. # No rights are reserved. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOS...
c2corg/v6_api
c2corg_api/tests/views/test_topo_map.py
Python
agpl-3.0
16,155
0
import json from c2corg_api.models.route import Route from c2corg_api.models.topo_map import ArchiveTopoMap, TopoMap, MAP_TYPE from c2corg_api.models.topo_map_association import TopoMapAssociation from c2corg_api.models.waypoint import Waypoint from c2corg_api.tests.search import reset_search_index from c2corg_api.mod...
6],[689156.247019149,5728802.39591739],[668518.249382151,5728802.39591739]]]}' # noqa }, 'locales': [ {'lang': 'en', 'title': 'Lac d\'Annecy'} ] } body, doc = self.post_success(body, user='moderator') self.assertIsNotNone(body['geometry'].get(...
cument_archive self.assertEqual(archive_map.editor, 'IGN') self.assertEqual(archive_map.scale, '25000') self.assertEqual(archive_map.code, '3432OT') archive_locale = version.document_locales_archive self.assertEqual(archive_locale.lang, 'en') self.assertEqual(archive_loc...
jzitelli/python-gltf-experiments
jsobject.py
Python
mit
1,558
0.003209
"""For the dict-subclass JSobject (defined below), user-defined attribute names may collide with the inherited dict methods (e.g. "keys", "values", "items", etc), overwriting the inherited binding. For these special cases, the built-in dict methods are also bound to corresponding '__'-prefixed attribute names (e.g. "_...
NAMES.items(): dict.__setattr__(self, rename, self.__getattribute__(name)) for k, v in json_dict.items(): self[k] = v def __setattr__(self, k, v): if k in JSobject._BAD_NAMES: raise Exception('attribute name collision: %s' % k) if isinstance(
v, dict): v = JSobject(v) dict.__setitem__(self, k, v) dict.__setattr__(self, k, v) def __setitem__(self, k, v): self.__setattr__(k, v) def __delattr__(self, k): dict.__delitem__(self, k) dict.__delattr__(self, k) def __delitem__(self, k): self.__d...
treemo/circuits
docs/source/tutorials/woof/009.py
Python
mit
550
0.001818
#!/usr/bin/env python from circuits import Component, Event class bark(Event): """bark Event""" class Pound(Component): def __ini
t__(self): super(Pound, self).__init__() self.bob = Bob().register(self) self.fred = Fred().register(self) class Dog(Component): def started(self, *args): self.fire(bark()) def bark(self): print("Woof! I'm %s!" % name) # noqa class Bob(Dog): """Bob
""" channel = "bob" class Fred(Dog): """Fred""" channel = "fred" Pound().run()
PrefPy/opra
compsocsite/polls/migrations/0026_merge.py
Python
mit
330
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-06-29 17:46 from __future__ import unicode_lit
erals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('polls', '0025_questi
on_poll_algorithm'), ('polls', '0025_item_image'), ] operations = [ ]
beernarrd/gramps
gramps/plugins/docgen/rtfdoc.py
Python
gpl-2.0
21,776
0.002526
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2006 Donald N. Allingham # Copyright (C) 2007-2009 Brian G. Matherly # Copyright (C) 2009 Gary Burton # Copyright (C) 2010 Peter Landgren # Copyright (C) 2011 Adam Stein <adam@csh.rit.edu> # # This program is free software; you...
------- _CLICKABLE = r'''{\\field{\\*\\fldinst HYPERLINK "\1"}{\\fldrslt \1}}''' #------------------------------------------------------------------------ # # Functions # #------------------------------------------------------------------------ def twip
s(length_cm): """ RTF uses a unit called "twips" for its measurements. According to the RTF specification, 1 point is 20 twips. This routines converts centimeters to twips 2.54 cm/inch 72pts/inch, 20twips/pt """ return int(((length_cm/2.54)*72)+0.5)*20 #------------------------------------...
cmusatyalab/imagejfind
get-latest-imagej.py
Python
epl-1.0
1,202
0.001664
#!/usr/bin/python import os i
mport shutil import subprocess import urllib2 OUTPUT = 'ij-latest.zip' OUTPUT_BASEDIR = 'ImageJ' OUTPUT_JAR = os.path.join(OUTPUT_BASEDIR, 'ij.jar') URL = 'http://rsb.info.nih.gov/ij/' ZIPS = URL + 'download/zips/' JARS =
URL + 'download/jars/' VERSION_LIST = JARS + 'list.txt' UPGRADE_JAR = URL + 'upgrade/ij.jar' CHARS = ''.join(map(chr, range(ord('a'),ord('z')+1))) # remove any previous unpacked dir if os.path.exists(OUTPUT_BASEDIR): shutil.rmtree(OUTPUT_BASEDIR) # get path to latest zip vl = urllib2.urlopen(VERSION_LIST) url =...
damoxc/vsmtpd
test_smtp.py
Python
gpl-3.0
406
0.004926
import sys import smtplib def output((code, msg)): sys.stdout.write('%s %s\n' % (code, msg)) sys.stdout.flush() smtp = smtplib.SMTP('localhost', 2500) output(smtp.ehlo('moon.localdomain')) print sm
tp.esmtp_features output(smtp.mail(
'Damien Churchill <damoxc@gmail.com>')) output(smtp.rcpt('Damien Churchill <damoxc@damoxc.net>')) output(smtp.data('Subject: Testing\n\nTest')) output(smtp.quit())
Nethermaker/school-projects
intro/intro_challenge.py
Python
mit
3,681
0.002445
# Problem 1 # Write a function called switch_ends() that takes a string # and returns the string with the front and back letter switched # Ex: switch_ends('part') -> 'tarp' # switch_ends('abcdefg') -> 'gbcdefa' # switch_ends('dog') -> 'god' def switch_ends(string): first = string[0] last = string[-1] ...
his completely mathematically for a challen
ge, but # it might be easier if you turn the number into a string first. # Example: add_digits(12345) -> 15 # add_digits(5062) -> 13 # add_digits(10000000000001) -> 2 def add_digits(number): num = str(number) lst = list(num) new_list = [] for entry in lst: new_list.append(int(...
tuanavu/python-cookbook-3rd
src/10/making_separate_directories_import_under_a_common_namespace/bar-package/spam/grok.py
Python
mit
27
0
p
rint('bar-package grok!')
bhearsum/releasetasks
releasetasks/test/desktop/test_binary_transparency.py
Python
mpl-2.0
3,298
0.003335
import unittest from releasetasks.test.desktop import make_task_graph, do_common_assertions, \ get_task_by_name, create_firefox_test_args from releasetasks.test import generate_scope_validator, PVT_KEY_FILE, verify from voluptuous import Schema, truth class TestBinaryTransparency(unittest.TestCase): maxDiff ...
uires']) == sorted(requires) return validate_dependencies def test_common_assertions(self): do_common_assertions(self.graph) def test_task(self): verify(self.task, self.test_schema, self.generate_task_dependency_validator(), TestBinaryTransparency.not_allowed)
def test_graph(self): verify(self.graph, self.graph_schema)
samrussell/ryu
ryu/lib/packet/icmp.py
Python
apache-2.0
8,213
0
# Copyright (C) 2012 Nippon Telegraph and Telephone Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
_PORT_UNREACH_CODE = 3 ICMP_TTL_EXPIRED_CODE = 0 class icmp(packet_base.PacketBase): """ICMP (RFC 792) header encoder/decoder class. An instance has the following attributes at least. Most of them are same to the on-wire counterparts but in host byte order. __init__ takes the correspondig args in thi...
Type code Code csum CheckSum \ (0 means automatically-calculate when encoding) data Payload. \ Either a bytearray, or \ ryu.lib.packet.icmp.echo or \ ryu.lib.packet.icmp.dest_unreach or \ ...
M4gn4tor/mastercard-api-python
Services/moneysend/domain/options/updatemappingrequestoptions.py
Python
bsd-3-clause
116
0.008621
class UpdateMappingRequestOption
s(object): def __init__(self, mapping_id):
self.mapping_id = mapping_id
kbknapp/ConsoleMenu-py3x
examples/menu/opt3.py
Python
gpl-2.0
532
0.039474
#!/usr/bin/env python import subprocess short_name = 'Opt 3' disp_na
me = 'Option 3 Submenu' otype = 'Routine' need = ['need 1: ', 'need 2: ', 'need 3: '] answers = [] def run(): global answers while True: subprocess.call('clear') i = 0 while i < len(need): ans = input(need[i]) if validate(ans): answers.append(ans) i += 1 final = 'Doing something with ' for ...
a) print(final) input() return def validate(char): if char: return True return False
endlessm/chromium-browser
third_party/webgl/src/serve_localhost.py
Python
bsd-3-clause
1,473
0.002716
#! /usr/bin/env python3 # Invoke http.server to host a basic webserver on localhost /without/ caching. # Files served by http.server are usually cached by browsers, which makes testing and debugging # buggy. import http.server import os from functools import partial class NoCacheRequestHandler(http.server.SimpleHT...
bind', '-b', default='localhost', metavar='ADDRESS', help='Specify alternate bind address ' '[de
fault: localhost - pass \'\' if you want to serve remote clients]') parser.add_argument('--directory', '-d', default=os.getcwd(), help='Specify alternative directory ' '[default:current directory]') parser.add_argument('port', action='store', ...