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
audaciouscode/PassiveDataKit-Django
migrations/0069_auto_20190915_1605.py
Python
apache-2.0
600
0.001667
# pylint: skip-file # -*- coding: utf-8 -*- # Generated by Django 1.11.23 on 2019-09-15 20:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('passive_data_kit', '0068_remove_deviceissue_pl
atform_version'), ] operations = [ migrations.AlterField( model_name='deviceissue', name='state', field=models.CharField(choices=[('opened', 'Open
ed'), ('in-progress', 'In Progress'), ('resolved', 'Resolved'), ('wont-fix', "Won't Fix")], default='opened', max_length=1024), ), ]
jeor0980/TeamChampion
hatServer/config.py
Python
mit
60
0
S
ECRET_KEY = 'you-w
ill-never-guess' MONGO_DB = 'flask_test'
eeshangarg/zulip
zerver/data_import/slack.py
Python
apache-2.0
52,071
0.002016
import logging import os import random import secrets import shutil import subprocess import zipfile from collections import defaultdict from typing import Any, Dict, Iterator, List, Optional, Set, Tuple, Type, TypeVar import orjson import requests from django.conf import settings from django.forms.models import model...
slack_bot_name = user_profile["real_name_normalized"] elif "first_name" in user_profile: slack_bot_name = user_profile["first_name"]
else: raise AssertionError("Could not identify bot type") email = slack_bot_name.replace("Bot", "").replace(" ", "") + f"-bot@{domain_name}" if email in cls.duplicate_email_count: email_prefix, email_suffix = email.split("@") email_prefix += cls.duplicate_email_cou...
aroth-arsoft/arsoft-web-ddns
manage.py
Python
gpl-3.0
259
0
#!/usr/bin/env python3 import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "arso
ft.web.ddns.settings") from django.core.management import execute_fr
om_command_line execute_from_command_line(sys.argv)
kyleconroy/brushwagg
scrape.py
Python
mit
2,745
0
import requests import json import os import string from lxml import etree SITE_ROOT = "http://magiccards.info" SITE_MAP = "http://magiccards.info/sitemap.html" GET_CARD_ABILITIES = True def filename_encode(name): return ''.join([n for n in name if n in string.digits + string.letters]) def parse_sets(url): ...
_url).content) cardTables = cardhtml.findall(".//table") cardTable = cardTables[3] abilities = cardTable.find(".//b").text cards.app
end({ "number": no.text, "url": card_url, "image": image_url, "name": name.find("a").text, "type": ctype.text, "mana": mana.text, "rarity": rarity.text, "artist": artist.text, ...
adam704a/useful-scripts
move_tweets.py
Python
unlicense
853
0.021102
from pymongo import MongoClient import dateutil import dateutil.parser import datetime import slack import slack.chat slack.api_token = 'SLACK_KEY' c1 = MongoClient("SOURCE_MONGO_URL") d1 = c1.mj_tweets l1 = d1.mj_sample c2 = MongoClient("DESTINATION_MONGO_URL") d2 = c2.mj_sample l2 = d2.mj_sample sta
rt_time = datetime.datetime(2015, 6, 2) end_time = datetime.datetime(2015, 6, 24) counter = 1 slack.chat.post_message('mjsif_pipeline',"Tweet Mover launched.",username="Tweet Mover Utility",icon_emoji=':taxi:') for t in l1.find( {"created_at" : { "$lte" : end_time,
"$gte": start_time}},{'_id': False} ): try: l2.insert(t) counter += 1 except: pass if counter % 10000 == 0: slack.chat.post_message('mjsif_pipeline',str(counter) + " tweets moved",username="Date Mover Utility",icon_emoji=':taxi:')
M2IS/vendendo
landpage/urls.py
Python
gpl-2.0
166
0
from django.conf.urls import url fro
m . import views app_name = 'landpage' urlpatterns = [ url(r'^$', views.LandPageIn
dex.as_view(), name='landpage-index'), ]
tvtsoft/odoo8
addons/delivery/__init__.py
Python
agpl-3.0
170
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and lice
nsing details. import delivery import partn
er import sale import stock import models
dimagi/rapidsms-contrib-apps-dev
training/admin.py
Python
bsd-3-clause
215
0
#!/u
sr/bin/env python # vim: ai ts=4 sts=4 et sw=4 from django.contrib import admin from .models import * admin.site.register(MessageInWaiting) admin.site.register(ResponseInWaiting) admin.site.regi
ster(Template)
cognitect/transit-python
transit/read_handlers.py
Python
apache-2.0
3,818
0.003667
## Copyright 2014 Cognitect. 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...
urn transit_types.frozendict(pairs(cmap)) class IdentityHandler(object): @staticmethod def from_rep(i):
return i class SpecialNumbersHandler(object): @staticmethod def from_rep(z): if z == 'NaN': return float('Nan') if z == 'INF': return float('Inf') if z == '-INF': return float('-Inf') raise ValueError("Don't know how to handle: " + s...
JustasB/MitralSuite
Models/Migliore2014/gidfunc.py
Python
mit
103
0.019417
import params def mgid2glom(gid)
: return int((gid-params.gid_mitral_beg
in)/params.Nmitral_per_glom)
vlegoff/tsunami
src/primaires/scripting/actions/detruire_sortie.py
Python
bsd-3-clause
2,726
0.000735
#
-*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
ht notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specifi...
husarion/django-registration
registration/tests/urls.py
Python
bsd-3-clause
4,623
0.00411
""" URLs used in the unit tests for django-registration. You should not attempt to use these URLs in any sort of real or development environment; instead, use ``registration/backends/default/urls.py``. This URLconf includes those URLs, and also adds several additional URLs which serve no purpose other than to test tha...
_custom_disallowed', 'backend':
'registration.backends.default.DefaultBackend'}, name='registration_test_register_disallowed_url'), # Set up a pattern which will correspond to the # custom 'disallowed_url' above. url(r'^custom-disallowed/$', ...
jggatc/nexus
interface.py
Python
gpl-3.0
4,260
0.039437
from __future__ import division import env engine = env.engine import interphase interphase.init(engine) class MatrixInterface(interphase.Interface): def __init__(self, identity, matrix, control): self.matrix = matrix self.control = control interphase.Interface.__init__(self, identity, p...
5,175,200), control_list = ['Bootup'], tip_list = ['Nexus activate']) self.add( identity = 'Activate', control_type = 'control_toggle', position = (100,50), size = 'auto', font_color = (125,175,200), c
ontrol_list = ['Pause','Activate'], tip_list = ['Nexus pause','Nexus activate']) self.add( identity = 'DataProcessedTop', control_type = 'label', position = (60,44), size = (40,20), font_color = (125,175,200), control_list = ['0...
SabatierBoris/CecileWebSite
pyramidapp/tests/testexample.py
Python
gpl-2.0
407
0
# vim: set fileencoding=utf-8 : """ This is a example of a unittest module """ import unittest class TestExample(unitte
st.TestCase): """ Test of test """ def test_one(self): """ This is a example of a unittest """ self.assertFalse(False) def test_two(self): """ This is a example of a unittest """ self.assertTrue(True)
LukeM12/samba
buildtools/wafsamba/samba_bundled.py
Python
gpl-3.0
8,139
0.003686
# functions to support bundled libraries from Configure import conf import sys, Logs from samba_utils import * def PRIVATE_NAME(bld, name, private_extension, private_library): '''possibly rename a library to include a bundled extension''' # we now use the same private name for libraries as the public name. ...
me in conf.env.PRIVAT
E_LIBS) @conf def CHECK_PREREQUISITES(conf, prereqs): missing = [] for syslib in TO_LIST(prereqs): f = 'FOUND_SYSTEMLIB_%s' % syslib if not f in conf.env: missing.append(syslib) return missing @runonce @conf def CHECK_BUNDLED_SYSTEM_PKG(conf, libname, minversion='0.0.0', ...
Pardus-Ahtapot/GDYS
ahtapot-gkts/var/opt/ahtapot-gkts/developer/rule/models.py
Python
gpl-3.0
1,975
0.006643
#-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from datetime import datetime class Rule(mo
dels.Model): source = models.CharField(max_length=80, verbose_name="Kaynak", help_text="Kaynak IP veya FQDN Bilgisi Giriniz(Tek)") destination = models.CharField(max_length=80, verbose_name="Hedef", help_text="Hedef IP veya FQDN Bilgisi Giriniz(Tek)") destination_port = models.IntegerField(verbose_name=
"Hedef Port", help_text=u"Hedef Port Numarasını Giriniz(Tek)") protocol = models.CharField(max_length=80, verbose_name="Protokol", help_text=u"Protokol Bilgisini Giriniz(Tek)") time = models.IntegerField(verbose_name=u"Süre", help_text=u"Aktif Olacağı Süreyi Dakika Türünden Giriniz(Tek)") developer = models...
mordred-descriptor/mordred
mordred/FragmentComplexity.py
Python
bsd-3-clause
978
0
from __future__ import division from ._base import De
scriptor __all__ = ("FragmentComplexity",) class FragmentComplexity(Descriptor): r"""fragment complexity descriptor. .. math:: {\rm fragCpx} = \left| B^2 - A^2 + A \right| + \frac{H}{100} where :math:`A` is number of atoms, :math:`B` is number of bonds, :math:`H` is number of hetero...
@classmethod def preset(cls, version): yield cls() explicit_hydrogens = False def parameters(self): return () def __str__(self): return "fragCpx" def calculate(self): A = self.mol.GetNumAtoms() B = self.mol.GetNumBonds() H = sum(1 for a in self.mol...
GhalebKhaled/fb-bot-test
settings/local.py
Python
apache-2.0
105
0
from __f
uture__ import unicode_literals from .
base import * GI_APPLICATION = u'wsgi.local.application'
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
orcid_api_v3/models/affiliation_group_v30_rc1_invited_position_summary_v30_rc1.py
Python
mit
5,818
0.000516
# coding: utf-8 """ ORCID Member No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: Latest Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import si...
mmaryV30Rc1, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.
to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, AffiliationGroupV30Rc1InvitedPositionSummaryV30Rc1): return False return self._...
Xiaomi2008/Caffe_3D_FF
tools/convert_mat2levelDB.py
Python
bsd-2-clause
2,667
0.032996
import sys, getopt sys.path.insert(0, '/home/tzeng/space/Caffe_3D_FF/trunk/python') #sys.path.insert(0,'/home/tzeng/autoGenelable_multi_lables_proj/code/py-leveldb-read-only/build/lib.linux-x86_64-2.7') import numpy as np import hdf5storage import leveldb from leveldb import WriteBatch, LevelDB import os im...
t caffe_pb2 print os.path.dirname(caffe_pb2.__file__) #from caffe.proto import caffe_pb2 mat_file ='/home/tzeng/space/SegEM_project/data/train_segem.mat' #mat_file ='/home/tzeng/caffe_flx_kernel
/data/snems3d_train_RF8.mat' #mat_file ='/home/tzeng/caffe_flx_kernel/data/snems3d_test_pad_2_47_47.mat' #mat_file= '/home/tzeng/caffe_flx_kernel/data/snems3d_train_RF8_20Percent.mat' #mat_file= '/home/tzeng/caffe_flx_kernel/data/snems3d_predict_norm.mat' #snems3d_train_pad_4_47_47.mat' #mat_file ='/home/tzeng/caf...
tonyli71/designate
designate/tests/test_api/test_admin/extensions/test_reports.py
Python
apache-2.0
5,116
0
# coding=utf-8 # COPYRIGHT 2015 Rackspace # # Author: Betsy Luzader <betsy.luzader@rackspace.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/LICEN...
ords', response.json['counts'][0]) self.assertIn('tenants', response.json['counts'][0]) # Assert that they are all equal to 0 self.assertEqual(0, response.json['counts'][0]['zones']) self.assertEqual(0, response.json['counts'][0]['records']) self.assertEqual(0, response.json['co...
a domain and check the counts self.create_domain() response = self.client.get('/reports/counts') # Should be one domain self.assertEqual(1, response.json['counts'][0]['zones']) # Should be 1 NS and 1 SOA records self.assertEqual(2, response.json['counts'][0]['records']) ...
zeldin/libsigrokdecode
decoders/spiflash/pd.py
Python
gpl-3.0
19,082
0.002515
## ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2011-2016 Uwe Hermann <uwe@hermann-uwe.de> ## ## 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 t...
self.end_current_transaction() # Build dict mapping command keys to handler functions. Each # command in 'cmds' (defined in lists.py) has a
matching # handler self.handle_<shortname>. def get_handler(cmd): s = 'handle_%s' % cmds[cmd][0].lower().replace('/', '_') return getattr(self, s) self.cmd_handlers = dict((cmd, get_handler(cmd)) for cmd in cmds.keys()) def end_current_transaction(self): if s...
PapenfussLab/Srtools
bin/old/loadSolexa.py
Python
artistic-2.0
796
0.007538
#!/usr/bin/env python """ loadSolexa.py Author: Tony Papenfuss Date: Tue Jun 24 14:27:34 EST 2008
""" import os, sys from maq import * from useful import progressMessage oFilename = 'tmp/PlatySolexa.txt' if not os.path.exists(oFilename): oFile = open(oFilename, 'w') dataDir = '/Users/papenfuss/databases/platypus/venom/solexa/' for i,read in enumerate(MaqViewFile(os.path.join(dataDir, 'mapview.tx...
if (i % 1000)==0: progressMessage("# maq %s", i, 28395347) tokens = str(read).split('\t') tokens.append(i) print >> oFile, "|".join([str(x) for x in tokens]) oFile.close() progressMessage("# maq %s\n", i, 28395347) os.system("""sqlite3 alignedReads.db '.import "tmp/...
Spiderlover/Toontown
toontown/parties/DistributedPartyJukeboxActivityAI.py
Python
mit
549
0.010929
from direct.directnotify import DirectNotifyGlobal from toontown.parties.DistributedPar
tyJukeboxActivityBaseAI import DistributedPartyJukeboxActivityBaseAI import PartyGlobals class DistributedPartyJukeboxActivityAI(DistributedPartyJukeboxActivityBaseAI): notify = DirectNotifyGlobal.directNotify.newCategory("DistributedPartyJukeboxActivityAI")
def __init__(self, air, parent, activityTuple): DistributedPartyJukeboxActivityBaseAI.__init__(self, air, parent, activityTuple) self.music = PartyGlobals.PhaseToMusicData
be-cloud-be/horizon-addons
server-tools/base_export_manager/models/ir_exports.py
Python
agpl-3.0
2,147
0
# -*- coding: utf-8 -*- # Copyright 2015-2016 Jairo Llopis <jairo.llopis@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import _, api, fields, models from openerp.exceptions import ValidationError class IrExports(models.Model): _inherit = 'ir.exports' name =...
api.model def create(self, vals): """Check required values when creating the record. Odoo's export dialog populates ``resource``, while this module's new form populates ``model_id``. At least one of them is required to trigger the methods that fill up the other, so this should fail ...
one is missing. """ if not any(f in vals for f in {"model_id", "resource"}): raise ValidationError(_("You must supply a model or resource.")) return super(IrExports, self).create(vals)
obulpathi/bitcoinpy
bitcoinpy/mempool.py
Python
mit
952
0.026261
# MemPool.py # # Distributed under the MIT/X11 software license
, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import logging from lib.serialize import uint256_to_shortstr class MemPool(object): def __init__(self): self.pool =
{} # setup logging logging.basicConfig(level=logging.DEBUG) self.logger = logging.getLogger(__name__) def add(self, tx): tx.calc_sha256() hash = tx.sha256 hashstr = uint256_to_shortstr(hash) if hash in self.pool: self.log.write("MemPool.add(%s): already known" % (hashstr,)) return False if not t...
alexmogavero/home-assistant
homeassistant/components/device_tracker/unifi.py
Python
apache-2.0
3,400
0
""" Support for Unifi WAP controllers. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/device_tracker.unifi/ """ import logging import voluptuous as vol import homeassistant.helpers.config_validation as cv import homeassistant.loader as loader from homea...
otification') try: ctrl = Controller(host, username, password, port, version='v4', site_id=site_id, ssl_verify=verify_ssl) except APIError as ex: _LOGGER.error("Failed to connect to Unifi: %s", ex)
persistent_notification.create( hass, 'Failed to connect to Unifi. ' 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(ex), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) return False return UnifiSca...
nutils/nutils
nutils/topology.py
Python
mit
101,558
0.014435
# Copyright (c) 2014 Evalf # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, s...
nts the dimension of its elements, not that of the the space they are embedded in. The primary role of topologies is to form a domain
for :mod:`nutils.function` objects, like the geometry function and function bases for analysis, as well as provide tools for their construction. It also offers methods for integration and sampling, thus providing a high level interface to operations otherwise written out in element loops. For lower level operations to...
xavfernandez/pip
tests/data/src/pep518_twin_forkbombs_first-234/setup.py
Python
mit
143
0
from se
tuptools import setup setup(name='pep518_twin_forkbombs_first', version='234', py_modules=['pep518_twin_forkbombs_
first'])
edx-solutions/edx-platform
common/test/acceptance/fixtures/xqueue.py
Python
agpl-3.0
1,436
0.000696
""" Fixture to configure XQueue response. """ import json import requests from common.test.acceptance.fixtures import XQUEUE_STUB_URL class XQueueResponseFixtureError(Exception): """ Error occurred while configuring the stub XQueue. """ pass class XQueueResponseFixture(object): """ Confi...
n that contains the string `pattern`. Remember that there is one XQueue stub shared by all the tests; if possible, you should have tests use unique queue names to avoid conflict between tests running in parallel. """ self._pattern = pattern self._response_dict = ...
url = XQUEUE_STUB_URL + "/set_config" # Configure the stub to respond to submissions to our queue payload = {self._pattern: json.dumps(self._response_dict)} response = requests.put(url, data=payload) if not response.ok: raise XQueueResponseFixtureError( ...
svilaa/item_database
item_database/iitem_database/admin.py
Python
gpl-3.0
366
0.005464
from django.contrib import admin from iitem_database.models import Item,
ItemClass, Area, Creature, Drops, Found, UserItems, ItemReview admin.site.register(Item) admin.site.register(ItemClass) admin.site.register(Area) admin.site.register(Creature) admin.site.register(Drops) admin.site.register(Found) admin.site.register(UserItems) admin.site.regist
er(ItemReview)
facebookresearch/ParlAI
parlai/zoo/light_whoami/rpa_reranker.py
Python
mit
394
0
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is
licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ RPA Re-Ranker Model. """ from parlai.zoo.light_whoami.whoami_download import download_with_model_type def download(datapath): download_with_model_type(datapath,
'rpa_reranker', 'v1.0')
SyrakuShaikh/python
learning/a_byte_of_python/ds_reference.py
Python
gpl-3.0
712
0
print('Simple Assignment') shoplist = ['apple', 'mango', 'carrot', 'banana'] # mylist is just another name pointing to the same object! mylist = shoplist # I purchased the first item, so I remove it from the list del shoplist[0] print('shoplist is', shoplist) print('mylist is', mylist) # Notice that both shoplist and...
is', mylist) del mylist1[1]
print('shoplist is', shoplist) print('mylist is', mylist1)
dmcc/bllip-parser
python/tests/test_reranking_parser.py
Python
apache-2.0
68,004
0.003
# 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 t...
ssertRaises(ValueError, rrp.check_models_loaded_or_error, False) self.assertRaises(ValueError, rrp.load_parser_model, u'\u2602') self.assertRaises(ValueError, rrp.check_models_loaded_or_error, False) self.assertRaises(ValueError, rrp.load_reranker_model, u'\u2602', 'sec...
e/models/ec50spfinal/features.gz', u'\u2602') self.assertRaises(ValueError, rrp.check_models_loaded_or_error, True) self.assertRaises(ValueError, rrp.check_models_loaded_or_error, True) # tree function loading errors tree = Tree('(S1 (S (NP (DT This)) (VP (AUX ...
canvasnetworks/canvas
website/canvas/migrations/0163_auto__add_field_userinfo_avatar.py
Python
bsd-3-clause
21,325
0.007362
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'UserInfo.avatar' db.add_column('canvas_userinfo', 'avatar', self.gf('django.db.models.fiel...
: ('canvas.util.UnixTimestampField', [], {}) }, 'can
vas.category': { 'Meta': {'object_name': 'Category'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '140'}), 'founded': ('django.db.models.fields.FloatField', [], {'default': '1298956320'}), 'founder': ('django.db.models.fields.related.ForeignKey...
amiraliakbari/sharif-mabani-python
by-session/ta-921/j3/number1.py
Python
mit
267
0.007491
def devisors(n):
r = 0 i = 1 while i <= n: if n % i == 0: r += 1 i += 1 return r def is_prime(n): x = devisors(n) if x == 2: return True else: return False print i
s_prime(3)
ymoch/pyjpmesh
test/test_angle.py
Python
mit
2,197
0
""" Tests for jpmesh.angle. """ import unittest from jpmesh import Angle class TestAngle(unittest.TestCase): """Tests for jpmesh.Angle. """ def test_properties(self): """Test for properties. """ millisecond = 3600000 angle = Angle.from_millisecond(millisecond) se...
(self): """Test for operators. """ angle1 = Angle.from_millisecond(1.0) angle2 = Angle.from_millisecond(1.0) angle3 = Angle.from_millisecond(2.0) self.assertEqual( (angle1 + angle2).degree, angle1.degree + angle2.degree) self.assertEqual( (...
2) self.assertEqual((angle1 / 2.0).degree, angle1.degree / 2.0) self.assertEqual((+angle1).degree, +angle1.degree) self.assertEqual((-angle1).degree, -angle1.degree) self.assertEqual(abs(angle1).degree, abs(angle1.degree)) self.assertTrue(angle1 == angle2) self.assertFals...
mhorn71/StarbaseMini
ui/mainwindow.py
Python
gpl-2.0
30,116
0.002922
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mainwindow.ui' # # Created by: PyQt5 UI code generator 5.4.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWi...
selected { \n" " font: italic;\n" " color: green;\n" "}\n" "\n" "QToolBox::ta
b:!selected {\n" " color: black;\n" "}") self.toolBox.setObjectName("toolBox") self.UserCtrl = QtWidgets.QWidget() self.UserCtrl.setGeometry(QtCore.QRect(0, 0, 129, 521)) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) sizeP...
lektor/lektor-archive
lektor/devcli.py
Python
bsd-3-clause
3,718
0
import os import sys import click from .packages import get_package_info, register_package, publish_package from .cli import pass_context def ensure_plugin(): here = os.getcwd() if not os.path.isfile(os.path.join(here, 'setup.py')): raise click.UsageError('This command must be run in a ' ...
be unlocked by exporting the `LEKTOR_DEV=1` environment variable. """ @cli.command('shell', short_help='Starts a python shell.') @pass_context def shell_cmd(ctx): """Starts a Python shell in the context of a Lektor project. This is particularly useful for debugging plugins and to explore the API....
: the loaded project as object. - `env`: an environment for the loaded project. - `pad`: a database pad initialized for the project and environment that is ready to use. """ ctx.load_plugins() import code from lektor.db import F, Tree from lektor.builder import Builder banner = 'Py...
cloudysunny14/faucet
client/rest.py
Python
apache-2.0
8,791
0.002616
#!/usr/bin/env python # # Copyright 2014 cloudysunny14. # # 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...
headers["Content-type"] = "application/x-www-form-urlencoded" if hasattr(body, 'getvalue'): body = str(body.getvalue()) headers["Content-Length"] = len(body) for key, value in headers.items(): if isinstance(value, basestring) and '\n' in value: r...
(key, value)) try: urlopen = self.mock_urlopen if self.mock_urlopen else self.pool_manager.urlopen r = urlopen( method=method, url=url, body=body, headers=headers, preload_content=False ...
BYU-ODH/byu-hummedia-api
hummedia/test/test_vtt.py
Python
mpl-2.0
9,589
0.023777
import pytest import io import json import sys from .. import config from .. import vtt reload(sys) sys.setdefaultencoding('utf-8') def test_from_srt(ASSETS): f = io.BytesIO() vtt.from_srt(ASSETS + 'subs.srt', f) compare = open(ASSETS + 'subs.vtt', 'r') assert f.getvalue() == compare.read() def test_from_srt...
le.read() def test_upload_vtt_as_student_with_write_access(ASSETS, ACCOUNTS, app): app.login(ACCOUNTS["SUPERUSER"]) v = app.post('/video') data = json.loads(v.data) vid_pid = data[
'pid'] c = app.post('/collection', data=json.dumps({}), headers={'Content-Type': 'application/json'}) data = json.loads(c.data) col_pid = data['pid'] # attach video to collection membership = [{"collection":{"id":col_pid,"title":"Something"},"videos":[vid_pid]}] membership_result = app.post('/batch/video/...
dermoth/gramps
gramps/plugins/drawreport/drawplugins.gpr.py
Python
gpl-2.0
7,435
0.006187
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2009 Benny Malengier # # # 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...
--------------------------------- plg = newplugin() plg.id = 'descend_c
hart,BKI' plg.name = _("Descendant Chart") plg.description = _("Produces a graphical descendant chart") plg.version = '1.0' plg.gramps_target_version = MODULE_VERSION plg.status = STABLE plg.fname = 'descendtree.py' plg.ptype = REPORT plg.authors = ["Craig J. Anderson"] plg.authors_email = ["ander882@hotmail.com"] pl...
eduNEXT/edx-platform
lms/__init__.py
Python
agpl-3.0
959
0.003128
""" Celery needs to be loaded when the cms modules are so that task registration and discovery can work correctly. """ # We monkey patch Kombu's entrypoints listing because scanning through this # accounts for the majority of LMS/Studio startup time for tests, and we don't # use custom Kombu serializers (which is what...
ll, this is # pretty evil, and should be taken out when we update Celery to the next version # where it looks like this method of custom serialization has been removed. # # FWIW, this is identical behavior to what happens in Kombu if pkg_resources # isn't av
ailable. import kombu.utils kombu.utils.entrypoints = lambda namespace: iter([]) # This will make sure the app is always imported when Django starts so # that shared_task will use this app, and also ensures that the celery # singleton is always configured for the LMS. from .celery import APP as CELERY_APP # lint-amne...
edljk/Mosek.jl
deps/src/mosek/7/tools/examples/python/simple.py
Python
mit
1,730
0.015029
# # Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved. # # File: simple.py # # Purpose: Demonstrates a very simple example using MOSEK by # reading a problem file, solving the problem and # writing the solution to a file. # import mosek import sys def streamprinter(msg): sys.stdout.write (msg) ...
d problem data from the output file. task.putintparam (mosek.iparam.write_data_format, mosek.dataformat.op) task.putintparam (mosek.iparam.opf_write_solutions, mosek.onoffkey.on) task.putintparam (mosek.iparam.opf_write_hints, mosek.onoffkey.off) task.putintparam (mosek.iparam.o...
blem, mosek.onoffkey.off) task.writedata (sys.argv[2])
gizmag/django-arrow-field
arrow_field/model_fields.py
Python
mit
1,161
0
from __future__ import unicode_literals import arrow from django.db.models import DateTimeField, SubfieldBase from .form_fields import ArrowField as ArrowFormField class ArrowField(DateTimeField): __metaclass__ = SubfieldBase def to_python(self, value): if isinstance(value, arrow.Arrow): ...
lf._get_val_from_obj(obj) return '' if value is None else value.isoformat() def pre_save(self, model_instance, a
dd): if self.auto_now or (self.auto_now_add and add): value = arrow.utcnow() setattr(model_instance, self.attname, value) return value else: return super(ArrowField, self).pre_save(model_instance, add) def formfield(self, **kwargs): defaults =...
codeurimpulsif/PyMCS
console.py
Python
gpl-3.0
1,539
0.014945
#!/usr/bin/python # Console import sys, os, time, subprocess def MCS(): return subprocess.Popen(['python', 'mcs.py']) def color(text, color): if color == 0: color = "\033[0m" if color == 1: color = "\033[94m" if color == 2: color = "\033[92m" if color == 3: color = "\033[91m" if color == 4: ...
main.terminate() main.kill() main = MCS() if c
ommand == '5': if main.poll() == None: main.terminate() main.kill() if command == 'q': exit(0) if __name__ == "__main__": main()
Debetux/sr.ht
setup.py
Python
mit
300
0.066667
from distutils.core import setup setup( name = 'srht', packages = ['srht'], version = '1.0.0', description
= 'sr.ht services', author = 'Drew DeVault', author_email = 'sir@cmpwn.com', url = 'https://github.com/SirCmpwn/sr.ht', download_url = '', keywords = [], classifie
rs = [] )
sarielsaz/sarielsaz
share/rpcuser/rpcuser.py
Python
mit
1,118
0.005367
#!/usr/bin/env python2 # Copyright (c) 2015-2016 The Sarielsaz Core developers # Distributed under the MIT software license, see the accompa
nying # file COPYING or http://www.opensource.
org/licenses/mit-license.php. import hashlib import sys import os from random import SystemRandom import base64 import hmac if len(sys.argv) < 2: sys.stderr.write('Please include username as an argument.\n') sys.exit(0) username = sys.argv[1] #This uses os.urandom() underneath cryptogen = SystemRandom() #C...
larsonmp/security-system
src/service/rest/client.py
Python
lgpl-3.0
1,511
0.02912
from io import BytesIO from json import dumps from mimetypes import guess_all_extensions from os.path import join from requests import delete, get, post from tempfile import gettempdir def guess_extension(mimetype): #there's an oddity on raspbian wherein guess_extension is non-deterministic return sorted(guess_all_e...
id, sid=sid) response = get(url) extension = guess_ex
tension(response.headers['content-type']) filepath = join(gettempdir(), sid + extension) with open(filepath, 'wb') as fp: fp.write(BytesIO(response.content).read()) return filepath def get_all_snapshot_ids(self, cid=0): url = '{base_url}/camera/{cid:d}/snapshot'.format(base_url=self._base_url, cid=cid) ...
gminds/rapidnewsng
django/contrib/comments/admin.py
Python
bsd-3-clause
3,681
0.00326
from __future__ import unicode_literals from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.comments.models import Comment from django.utils.translation import ugettext_lazy as _, ungettext from django.contrib.comments import get_model from django.contrib.comments.views....
selected comment
s") def remove_comments(self, request, queryset): self._bulk_flag(request, queryset, perform_delete, lambda n: ungettext('removed', 'removed', n)) remove_comments.short_description = _("Remove selected comments") def _bulk_flag(self, request, queryset, action, done_message)...
IvanMalison/okcupyd
okcupyd/db/model/__init__.py
Python
mit
107
0
from .message import Message from .message_thread i
mport MessageThread from .
user import User, OKCupydUser
Bartzi/stn-ocr
mxnet/operations/disable_shearing.py
Python
gpl-3.0
1,178
0
import os import mxnet as mx # MXNET_CPU_WORKER_NTHREADS must be greater than 1 for custom op to work on CPU os.environ["MXNET_CPU_WORKER_NTHREADS"] = "2" class DisableShearing(mx.operator.CustomOp): def forward(self, is_train, req, in_data, out_data, aux): out = in_data[0].copy().asnumpy().reshape(-1,...
, 1, 0] = 0 self.assign(in_grad[0], req[0], mx.nd.array(grad.reshape(-1, 6))) @mx.operator.register("DisableShearing") class DisableShearingProp(mx.operator.CustomOpProp): def __init__(self): super(DisableShearingProp, self).__init__(need_top_grad=True) def list_arguments(self): retu...
f, in_shape): return [in_shape[0]], [in_shape[0]], [] def create_operator(self, ctx, shapes, dtypes): return DisableShearing()
F5Networks/f5-common-python
devtools/bin/create-test-list.py
Python
apache-2.0
4,268
0.002812
#!/usr/bin/env python """ Rules for *.py files * if the changed file is __init__.py, and there is a side-band test/ dir, then test the entire test/functional directory the reason for this is that the init files are usually organizing collections and those can affect many different apis if they break * if ...
-commit', help='Git commit to check', required=True) args = parser.parse_args() for product in ['iworkflow', 'bigip', 'bigiq']: d
etermine_files_to_test(product, args.commit)
SpectraLogic/ds3_python3_sdk
tests/helpersTests.py
Python
apache-2.0
12,900
0.003953
# Copyright 2021 Spectra Logic Corporation. 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. A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license" file ...
b_id, "", "job id was returned") # verify all the files
and directories are on the BP head_obj = client.head_object(ds3.HeadObjectRequest(bucket_name=bucket, object_name="does-not-exist")) self.assertEqual(head_obj.result, "DOESNTEXIST") for put_object in put_objects: head_obj = client.head_object(ds3.HeadObjectRequest(bucket_name=bucke...
HatPull/tornado-elasticsearch-proxy
es_proxy/tests/constants.py
Python
apache-2.0
648
0
SAMPLE_POLICIES
= [ { 'resources': { 'indices': ['kibana-int', ], }, 'users': ['*'], 'permissions': ['index_write', 'index_read'] }, { 'resources': { 'cluster': True
}, 'users': ['alan'], 'permissions': ['kibana_admin', ] }, { 'resources': { 'indices': ['joes_index', ], }, 'users': ['joe'], 'permissions': ['index_write', 'index_read'] }, { 'resources': { 'indices': ['*', ], }, ...
stackforge/python-openstacksdk
openstack/identity/v3/service.py
Python
apache-2.0
1,798
0
# Licensed under the Apache License, Version 2.0 (the "L
icense"); 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 # distrib
uted 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 openstack import resource class Service(resource.Resource): resource_ke...
steinnymir/RegAscope2017
test_scripts/GUI_test/PyQt5 Examples/inputDialogs.py
Python
mit
1,518
0.011199
import sys from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit from PyQt5.QtGui import QIcon class App(QWidget): def __init__(self): super().__init__() self.title = 'PyQt5 input dialogs - python
spot.com' self.left = 10 self.top = 10 self.width = 640 self.height = 480 self.initUI() def init
UI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.getInteger() self.getText() self.getDouble() self.getChoice() self.show() def getInteger(self): i, okPressed = QInpu...
boxeehacks/boxeehack
hack/boxee/skin/boxee/720p/scripts/boxeehack_settings.py
Python
mit
14,393
0.008893
import os import xbmc, xbmcgui, mc import ConfigParser import common available_providers = ['Addic7ed', 'BierDopje', 'OpenSubtitles', 'SubsWiki', 'Subtitulos', 'Undertexter'] # Set some default values for the subtitles handling def register_defaults(): subtitle_provider("get", "default") subtitle_provider("ge...
lacement = "Built-in" if replacement == "": replacement = "Off" return replacement def get_homeenabled(section): homeenabled = get_homeenabled_value().split(",") section = "%s" % section for item in homeenabled: item = item.split("|")[0] ...
nds","shows","movies","music"]: if section == "friends": types = ["Built-in", "Netflix", "Vudu", "Navi-X", "Spotify", "Grooveshark", "Pandora", "BBC iPlayer", "Revision3", "Crunchyroll", "Off"] if section == "shows": types = ["Built-in", "BBC iPlayer", "Revision3", "Crunchyroll",...
desion/tidy_page
tidypage/extractor.py
Python
mit
13,177
0.004707
#-*- coding: UTF-8 -*- from bs4 import BeautifulSoup import logging import sys import re from .cleaners import clean_tag from .cleaners import clean_spam import gzip log = logging.getLogger("tidypage.extractor") TEXT_TAG_COLLECTION = {"p":5, "span":4, "font":3, "i":2, "b":1, "pre": 1} REGEXES = { 'positiveRe': re...
- 1 cur_text_len = 0 i += 1 continue if cur_text_len == 0: tmp = i cur_text_len += block_set[i] i += 1 def text_weight(self, elem): content_score
= 1 long_text_line = 0 block_size = 3 inner_text = "" for string in elem.stripped_strings: if (self.is_foreign and len(string) > 100) or (not self.is_foreign and len(string) > 50): long_text_line += 1 inner_text += string else: ...
maoy/zknova
nova/scheduler/filters/io_ops_filter.py
Python
apache-2.0
1,650
0.001212
# Copyright (c) 2012 OpenStack, LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of t
he 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 expr
ess or implied. See the # License for the specific language governing permissions and limitations # under the License. from nova.openstack.common import cfg from nova.openstack.common import log as logging from nova.scheduler import filters LOG = logging.getLogger(__name__) max_io_ops_per_host_opt = cfg.IntOpt...
Distrotech/bzr
tools/package_mf.py
Python
gpl-2.0
2,892
0.000346
# Copyright (C) 2008 Canonical Ltd # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in ...
if not s
pecified, python standard library only is used. """ def __init__(self, path=None, debug=0, excludes=[], replace_paths=[]): if path is None: path = [os.path.dirname(os.__file__)] # only python std lib modulefinder.ModuleFinder.__init__(self, path, debug, excludes, repl...
chrisspen/django-feeds
djangofeeds/admin.py
Python
bsd-2-clause
7,712
0.006743
from datetime import date, timedelta from django.db.models import Q from django.contrib import admin from django.contrib.admin import FieldListFilter, ListFilter, SimpleListFilter from django.utils.translation import ( ungettext, ugettext_lazy as _ ) from django.http import HttpResponse, HttpResponseRedirect ...
aleListFilter, ) search_fields = ['feed_url', 'name'] readonly_fields = ( 'post_link', 'fresh',
) def lookup_allowed(self, *args, **kwargs): if conf.ALLOW_ADMIN_FEED_LOOKUPS: return True return super(FeedAdmin, self).lookup_allowed(*args, **kwargs) def post_link(self, obj=''): try: if not obj or not obj.id or not get_admin_changelist_url: ...
jeremiahyan/odoo
addons/link_tracker/models/mail_render_mixin.py
Python
gpl-3.0
3,440
0.00436
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re import markupsafe from werkzeug import urls, utils from odoo import api, models, tools class MailRenderMixin(models.AbstractModel): _inherit = "mail.render.mixin" # --------------------------------...
re.findall(tools.HTML_TAG_URL_REGEX, html): href = markupsafe.Markup(match[0]) long_url = match[1] label = (match[3] or '').strip() if not blacklist or not [s for s in blacklist if s in long_url] and not long_url.startswith(short_schema)
: create_vals = dict(link_tracker_vals, url=utils.unescape(long_url), label=utils.unescape(label)) link = self.env['link.tracker'].search_or_create(create_vals) if link.short_url: new_href = href.replace(long_url, link.short_url) ht...
dsm054/pandas
pandas/core/resample.py
Python
bsd-3-clause
67,558
0.000622
from __future__ import annotations import copy from datetime import timedelta from textwrap import dedent from typing import ( Callable, Hashable, Literal, final, no_type_check, ) import numpy as np from pandas._libs import lib from pandas._libs.tslibs import ( BaseOffset, IncompatibleFre...
def _get_binner_for_time(self):
raise AbstractMethodError(self) @final def _get_binner(self): """ Create the BinGrouper, assume that self.set_grouper(obj) has already been called. """ binner, bins, binlabels = self._get_binner_for_time() assert len(bins) == len(binlabels) bin_group...
blitzmann/Pyfa
gui/fitCommands/guiMetaSwap.py
Python
gpl-3.0
2,845
0.002109
import wx from service.fit import Fit import gui.mainFrame from gui import globalEvents as GE from .calc.fitRemoveImplant import FitRemoveImplantCommand from .calc.fitAddImplant import FitAddImplantCommand from .calc.fitRemoveBooster import FitRemoveBoosterCommand from .calc.fitAddBooster import FitAddBoosterCommand f...
elf, True, "Meta Swap") self.
mainFrame = gui.mainFrame.MainFrame.getInstance() self.sFit = Fit.getInstance() self.internal_history = wx.CommandProcessor() self.fitID = fitID self.itemID = itemID self.context = context self.data = [] fit = self.sFit.getFit(fitID) if context == 'fittin...
nickmckay/LiPD-utilities
Python/lipd/dataframes.py
Python
gpl-2.0
12,355
0.002266
import collections import pandas as pd from .regexes import re_pandas_x_num from .loggers import create_logger from .alternates import DATA_FRAMES from .misc import unwrap_arrays, match_arr_lengths logger_dataframes = create_logger("PDSlib") def _dotnotation_for_nested_dictionary(d, key, dots): """ Flatten...
n. Keep it as a chunk. dots[key] = d elif isinstance(d, dict): for k in d: _dotnotation_for_nested_dictionary(d[k], key + '.' + k if key else k, dots) elif isinstance(d, list) and \ not all(isinstance(item, (int, float
, complex, list)) for item in d): for n, d in enumerate(d): _dotnotation_for_nested_dictionary(d, key + '.' + str(n) if key != "" else key, dots) else: dots[key] = d return dots def create_dataframe(ensemble): """ Create a data frame from given nested lists of ensemble data...
foursquare/pants
src/python/pants/backend/docgen/targets/doc.py
Python
apache-2.0
4,885
0.007574
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals from pants.base.hash_utils import stable_json_hash from pants.base.payload import Payload...
ource file. Exactly one will be present. :param format: Page's format, ``md`` or ``rst``. By default, Pants infers
from ``source`` file extension: ``.rst`` is ReStructured Text; anything else is Markdown. :param links: Other ``page`` targets that this `page` links to. :type links: List of target specs :param provides: Optional "Addresses" at which this page is published. E.g., a wiki location. :type pr...
HeadsUpDisplayInc/mbed
tools/targets/REALTEK_RTL8195AM.py
Python
apache-2.0
10,067
0.003675
""" Realtek Semiconductor Corp. RTL8195A elf2bin script """ import sys, array, struct, os, re, subprocess import hashlib import shutil from tools.paths import TOOLS_BOOTLOADERS from tools.toolchains import TOOLCHAIN_PATHS from datetime import datetime # Constant Variables RAM2_RSVD = 0x00000000 RAM2_VER = 0x8195FFF...
6000 0x10006000 0x026bc 0x026bc RW 0x8 # LOAD 0x0026f0 0x30000000 0x30000000 0x06338 0x06338 RWE 0x4 segment_list = [] cmd = os.path.join(TOOLCHAIN_PA
THS['GCC_ARM'], 'arm-none-eabi-readelf') cmd = '"' + cmd + '"' + ' -l ' + image_elf for line in subprocess.check_output(cmd, shell=True, universal_newlines=True).split("\n"): if not line.startswith(" LOAD"): continue segment = line.split() if len(segment) != 8: c...
janchorowski/fuel
fuel/converters/dogs_vs_cats.py
Python
mit
4,138
0
import os import zipfile import h5py import numpy from PIL import Image from fuel.converters.base import check_exists, progress_bar from fuel.datasets.hdf5 import H5PYDataset TRAIN = 'dogs_vs_cats.train.zip' TEST = 'dogs_vs_cats.test1.zip' @check_exists(required_files=[TRAIN, TEST]) def convert_dogs_vs_cats(direct...
convert the
dogs_vs_cats dataset files. Parameters ---------- subparser : :class:`argparse.ArgumentParser` Subparser handling the `dogs_vs_cats` command. """ return convert_dogs_vs_cats
rahulunair/nova
nova/tests/functional/wsgi/test_secgroup.py
Python
apache-2.0
3,421
0
# Copyright 2015 Hewlett-Packard Development Company, L.P. # # 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 ...
_image_ref_parameter in imag
e: image_href = image[self._image_ref_parameter] else: image_href = image['id'] image_href = 'http://fake.server/%s' % image_href # We now have a valid imageId server[self._image_ref_parameter] = image_href # Set a valid flavorId flavor = sel...
avikivity/scylla
dist/docker/redhat/commandlineparser.py
Python
agpl-3.0
2,930
0.006826
import argparse def parse(): parser = argparse.ArgumentParser() parser.add_argument('--developer-mode', default='1', choices=['0', '1'], dest='developerMode') parser.add_argument('--experimental', default=0, choices=['0', '1']) parser.add_argument('--seeds', default=None, help="specify seeds - if left...
ault='1', choices=['0', '1'], dest='io_setup', help='Run I/O setup (i.e. iotune) at container startup. Defaults to 1.') parser.add_argument('--listen-address', default=None, dest='listenAddress') parser.add_argu
ment('--rpc-address', default=None, dest='rpcAddress') parser.add_argument('--broadcast-address', default=None, dest='broadcastAddress') parser.add_argument('--broadcast-rpc-address', default=None, dest='broadcastRpcAddress') parser.add_argument('--api-address', default=None, dest='apiAddress') parser.a...
bitmaintech/p2pool
p2pool/bitcoin/data.py
Python
gpl-3.0
10,333
0.007936
from __future__ import division import hashlib import random import warnings import p2pool from p2pool.util import math, pack import struct def hash256(data): return pack.IntType(256).unpack(hashlib.sha256(hashlib.sha256(data).digest()).digest()) def hash160(data): if data == '04ffd03de44a6e11b9917f3a29f944...
t, right=right))) for left, right in zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])] return hash_list[0] def calculate_merkle_link(hashes, index): # XXX optimize this hash_list = [(lambda _h=h: _h, i == index, []) for i, h in enumerate(hashes)] while len(hash_list) > ...
eft=_left(), right=_right()))), left_f or right_f, (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)], ) for (left, left_f, left_l), (right, right_f, right_l) in zip(hash_list[::2], hash_list[1::2] +...
askervin/gdbsearch
setup.py
Python
gpl-3.0
377
0.002653
#!/
usr/bin/env python from distutils.core import setup setup(name='gdbsearch', version='0.1', description='Search for interesting lines of code', author='Antti Kervinen', author_email='antti.kervinen@gmail.com', url='http://www.github.com/antti
.kervinen/gdbsearch', license='GNU General Public License', scripts=['gdbsearch'] )
sgarrity/bedrock
tests/pages/firefox/channel/ios.py
Python
mpl-2.0
590
0
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of
the MPL was not distributed with this #
file, You can obtain one at http://mozilla.org/MPL/2.0/. from selenium.webdriver.common.by import By from pages.firefox.base import FirefoxBasePage class ChannelIOSPage(FirefoxBasePage): URL_TEMPLATE = '/{locale}/firefox/channel/ios/' _testflight_button_locator = (By.CLASS_NAME, 'testflight-cta') @p...
rajashreer7/autotest-client-tests
linux-tools/prelink/prelink.py
Python
gpl-2.0
1,662
0.004813
#!/bin/python import os, subprocess import logging from autotest.client import test from autotest.client.shared import error, software_manager sm = software_manager.SoftwareManager() class prelink(test.test): """ Autotest module for testing basic functionality of prelink @author Athira Rajeev <atraj...
Popen(['./prelink.sh'], cwd="%s/prelink" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 except error.CmdError, e: self.nfail += 1 logging.error("Test Failed: %s", e) def postprocess(self): if self.nfai...
non-zero') raise error.TestError('\nTest failed') else: logging.info('\n Test completed successfully ')
voytekresearch/fakespikes
fakespikes/neurons.py
Python
mit
4,820
0.001245
# -*- coding: utf-8 -*- import numpy as np from numpy.random import RandomState from fakespikes.util import to_spikes from fakespikes.rates import constant class Spikes(object): """Simulates statistical models of neural spiking Params ------ n : int Number of neurons t : float Sim...
mask = ts > 0 ts = ts[mask] ns = ns[mask] spikes = to_spikes(ns, ts, self.t, self.n, self.dt) # Create baseline firing base = self.poisson(constant(self.times, a0)) spikes = base + spikes spikes[spikes > 1] = 1 return spikes
Captain-Coder/tribler
TriblerGUI/widgets/orderwidgetitem.py
Python
lgpl-3.0
1,786
0.003919
import datetime from PyQt5.QtWidgets import QTreeWidgetItem from TriblerGUI.utilities import prec_div class OrderWidgetItem(QTreeWidgetItem): """ This class represents a widget that displays an order. """ def __init__(self, parent, order, asset1_prec, asset2_prec): QTreeWidgetItem.__init__(se...
self.order = order order_time = datetime.datetime.fromtimestamp(int(order["timestamp"])).strftime('%Y-%m-%d %H:%M:%S') self.to
tal_volume = prec_div(order["assets"]["first"]["amount"], asset1_prec) self.traded_volume = prec_div(order["traded"], asset1_prec) self.price = float(self.total_volume) / float(prec_div(order["assets"]["second"]["amount"], asset2_prec)) self.setText(0, "%s" % order["order_number"]) self...
tchellomello/home-assistant
homeassistant/components/rfxtrx/cover.py
Python
apache-2.0
3,963
0.000252
"""Support for RFXtrx covers.""" import logging from homeassistant.components.cover import CoverEntity from homeassistant.const import CONF_DEVICES, STATE_OPEN from homeassistant.core import callback from . import ( CONF_AUTOMATIC_ADD, CONF_DATA_BITS, CONF_SIGNAL_REPETITIONS, DEFAULT_SIGNAL_REPETITION...
nvalid device: %s", packet_id) continue if not supported(event): continue device_id = get_device_id( event.device, data_bits=entity_info.get(CONF_DATA_BITS) ) if device
_id in device_ids: continue device_ids.add(device_id) entity = RfxtrxCover( event.device, device_id, entity_info[CONF_SIGNAL_REPETITIONS] ) entities.append(entity) async_add_entities(entities) @callback def cover_update(event, device_id): ""...
Petr-Kovalev/nupic-win32
py/regions/ImageSensorExplorers/ExhaustiveSweep.py
Python
gpl-3.0
11,962
0.007691
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have purchased from # Numenta, Inc. a separate commercial license for this software code, the # following terms and conditions apply: # # This pro...
ImageSensor takes care of the input validation. """ if image is None: filteredImages = [] for i in xrange(self.numImages): filteredImages.extend(self.getAllFilteredVersionsOfImage(i)) else: filteredImages = self.getAll
FilteredVersionsOfImage(image) return sum([self._getNumIterationsForImage(x[0]) for x in filteredImages]) def _firstSweepPosition(self): """ Go to the first sweep position for the current image and sweep direction. """ sbbox = self._getSweepBoundingBox(self.getFilteredImages()[0]) direction ...
associatedpress/datakit-data
tests/commands/test_push.py
Python
isc
1,702
0
from unittest import mock import pytest from conftest import create_project_config from datakit_data import Push @pytest.fixture(autouse=True) def initialize_data_configs(dkit_home, fake_project): project_configs = { 's3_bucket': 'foo.org', 's3_path': '2017/fake-project', 'aws_user_profi...
) def test_boolean_cli_flags(mocker): push_mock = mocker.patch( 'datakit_data.
commands.push.S3.push', autospec=True, ) parsed_args = mock.Mock() parsed_args.args = ['dry-run'] cmd = Push(None, None, 'data push') cmd.run(parsed_args) push_mock.assert_any_call( mock.ANY, 'data/', '2017/fake-project', extra_flags=['--dry-run'] )
SpectraLogic/samba
selftest/tests.py
Python
gpl-3.0
4,687
0.00064
#!/usr/bin/python # This script generates a list of testsuites that should be run as part of # the Samba test suite. # The output of this script is parsed by selftest.pl, which then decides # which of the tests to actually run. It will, for example, skip all tests # listed in selftest/skip or only run a subset during ...
thontestsuite("none", "samba.tests.registry") planpythontestsuite("none", "samba.tests.auth") planpythontestsuite("none", "samba.tests.getopt") planpythontestsuite("none", "samba.tests.secur
ity") planpythontestsuite("none", "samba.tests.dcerpc.misc") planpythontestsuite("none", "samba.tests.param") planpythontestsuite("none", "samba.tests.upgrade") planpythontestsuite("none", "samba.tests.core") planpythontestsuite("none", "samba.tests.provision") planpythontestsuite("none", "samba.tests.samba3") planpyth...
mrunge/openstack_horizon
openstack_horizon/dashboards/project/routers/ports/urls.py
Python
apache-2.0
949
0
# Copyright 2012, Nachi Ueno, NTT MCL, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # 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 django.conf.urls import patterns from django.conf.urls import url from openstack_horizon.dash...
tencentyun/python-sdk
python2/tencentyun/imageprocess.py
Python
mit
3,116
0.013479
# -*- coding: utf-8 -*- import os.path import time import urllib import json import requests from tencentyun import conf from .auth import Auth class ImageProcess(object): def __init__(self, appid, secret_id, secret_key, bucket): self.IMAGE_FILE_NOT_EXISTS = -1 self._secret_id,self._secret_key = ...
le ' + pfile + ' not exists', 'data':{}} i+=1 files['image['+str(i-1)+']']=(pfile, open(pfile,'r
b')) r = requests.post(url, headers=header, files=files) ret = r.json() return ret
struqt/invar
invar-example/target/generated-sources/example/python/TestDbMemberEntry.py
Python
mit
4,050
0.00669
#!/usr/bin/env python # -*- coding: utf-8 -*- # ===------------------------------* Python *------------------------------=== # THIS FILE IS GENERATED BY INVAR. DO NOT EDIT !!! # ===------------------------------------------------------------------------=== try: from cStringIO import StringIO except: ...
raise InvarError(498, 'Protoc read error: The value of \'hotfixExists\' is invalid.') #def read def write(w): w.writeUInt32(self._id) w.writeString(self._phone) w.writeString(se
lf._nickName) w.writeInt64(self._createTime) w.writeInt64(self._updateTime) if self._hotfix != None: w.writeUInt8(0x01) w.writeUInt32(len(self._hotfix)) for (k1,v1) in self._hotfix.items(): w.writeString(k1) w.writeString(v1) ...
kizza/CSS-Less-ish
tests/testfuncs.py
Python
mit
1,589
0.031466
import sys, re if sys.version_info < (3, 0): import testcase import modules.cssfuncs as funcs else: from . import testcase from ..modules import cssfuncs as funcs class TestFunctions(testcase.TestCase): title = "CSS Functions" def test_functions(self): self.set_text( self.input() ) self.text_equals( self....
0) * @gradient2 = linear-gradient(to top, #fff, #f00) * @gradient3 = linear-gradient(to bottom , #fff, #f00) */ """ def input(self): return self.vars()+""" h1 { @box-shadow; @transform; @transition; @gradient1; @gradient2; @gradient3; } """ def result(self): return self.vars()+""" h1 { -webk...
.deg); -webkit-transition: all 0.3s ease; transition: all 0.3s ease; background-image: -webkit-linear-gradient(bottom, #fff, #f00); background-image: linear-gradient(to top, #fff, #f00); background-image: -webkit-linear-gradient(bottom, #fff, #f00); background-image: linear-gradient(to top, #fff, #f0...
t10471/python
practice/src/design_pattern/Interpreter.py
Python
mit
2,299
0.005729
# -*- coding: utf-8 -*- import datetime import os #compsiteとcommandをあわせたような形 #ContextがhandlerでCommandが処理 class JobCommand(object): def execute(self, context): if context.getCurrentCommand() != 'begin': raise Exception('illegal command ' + str(context.getCurrentCommand())) command_list...
0000.0 max_size = 210000000.0 ratio = free_size / max_size * 100 print( 'Disk Free : %dMB (%.2f%%)' % (free_size / 1024 / 1024,
ratio)) elif current_command == 'date': print datetime.datetime.today().strftime("%Y/%m/%d") elif current_command == 'line': print '--------------------' else: raise Exception('invalid command [' + str(current_command) + ']') class Context(object): def _...
pytorch/vision
setup.py
Python
bsd-3-clause
20,786
0.002309
import distutils.command.clean import distutils.spawn import glob import os import shutil import subprocess import sys import torch from pkg_resources import parse_version, get_distribution, DistributionNotFound from setuptools import setup, find_packages from torch.utils.cpp_extension import BuildExtension, CppExtens...
ind_executable("conda") is_conda = conda is not None print(f"Running build on conda: {is_conda}") if is_conda: python_executable = sys.executable py_folder = os.path.dirname(python_executable)
if os.name == "nt": env_path = os.path.join(py_folder, "Library") else: env_path = os.path.dirname(py_folder) lib_folder = os.path.join(env_path, "lib") include_folder = os.path.join(env_path, "include") library_head...
loic/django
tests/gis_tests/inspectapp/models.py
Python
bsd-3-clause
713
0
from ..models i
mport models class AllOGRFields(models.Model): f_decimal = models.FloatField() f_float = models.FloatField() f_int = models.IntegerField() f_char = models.CharField(max_length=10) f_date = models.DateField() f_datetime = models.DateTimeField() f_time = models.TimeField() geom = models...
dels.PointField(dim=3) pointg = models.PointField(dim=3, geography=True) line = models.LineStringField(dim=3) poly = models.PolygonField(dim=3) class Meta: required_db_features = ['gis_enabled']
xbash/LabUNAB
11_diccionarios/0517_diccionarios3.py
Python
gpl-3.0
1,470
0.038095
#python27 #declaracion de diccionario agenda = {'Juan':12
3, 'Jose':456, 'Jorge':789, 'Juana':012, 'Joyce':345} def modificar(): print '...modificando dato de...' print '\n[1] Juan' print '\n[2] Jose' print '\n[3] Jorge' print '\n[4] Juanita' print '\n[5] Joyce' opcion = input('Ingresa la opcion') if opcion == 1: a = input('Ingresar un nuev...
co: ') if opcion == 4: d = input('Ingresar un nuevo numero telefonico: ') if opcion == 5: e = input('Ingresar un nuevo numero telefonico: ') ##el valor de la variable cambia por segun lo modificado agenda = {'Juan':a, 'Jose':b,'Jorge':c, 'Juanita':d, 'Joyce':e} def contacto(): print '......
riklaunim/django-custom-multisite
django/db/models/manager.py
Python
bsd-3-clause
8,241
0.001942
import copy from django.db import router from django.db.models.query import QuerySet, EmptyQuerySet, insert_query, RawQuerySet from django.db.models import signals from django.db.models.fields import FieldDoesNotExist def ensure_default_manager(sender, **kwargs): """ Ensures that a Model subclass contains a d...
e(*args, **kwargs) def in_bulk(self, *args, **kwargs): return self.get_query_set().in_bulk(*args, **kwargs) def iterator(s
elf, *args, **kwargs): return self.get_query_set().iterator(*args, **kwargs) def latest(self, *args, **kwargs): return self.get_query_set().latest(*args, **kwargs) def order_by(self, *args, **kwargs): return self.get_query_set().order_by(*args, **kwargs) def select_for_update(self...
makcedward/nlpaug
nlpaug/model/lang_models/machine_translation_transformers.py
Python
mit
3,112
0.001928
try: import torch from torch.utils import data as t_data from transformers import AutoTokenizer, AutoModelForSeq2SeqLM except ImportError: # No installation required if not using this function pass from nlpaug.model.lang_models import LanguageModels class MtTransformers(LanguageModels): def _...
all_translated_ids.append( translated_ids_batch.detach().cpu().numpy() ) all_translated_texts = [] for translated_ids_batch in all_translated_ids: translated
_texts = tokenizer.batch_decode( translated_ids_batch, skip_special_tokens=True ) all_translated_texts.extend(translated_texts) return all_translated_texts
DependencyWatcher/parser
dependencywatcher/parser/sbt.py
Python
apache-2.0
2,074
0.009643
from dependencywatcher.parser.parser import Parser from dependencywatcher.parser.pyparser import PyParser from pyparsing import * class SbtParser(PyParser): def __init__(self, source): super(SbtParser, self).__init__(source) vars = {} def store_var(st, locn, tokens): vars[toke...
oup(ArtifactIdentifier + Suppress(Literal("%")) + ArtifactIdentifier + Suppress(Literal("%")) + ScalaIdentifier) VarDependency.setParseAction(resolve_var) Dependency = Group(Artifac
tIdentifier + Suppress(Literal("%")) + ArtifactIdentifier + Suppress(Literal("%")) + VersionSpec) self.parser = VarDeclaration | VarDependency | Dependency self.parser.ignore(javaStyleComment) self.parser.setParseAction(self.defaultParseAction) def parse(self, dependencies): data = ...
111pontes/ydk-py
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_tunnel_l2tun_oper.py
Python
apache-2.0
488,131
0.020519
""" Cisco_IOS_XR_tunnel_l2tun_oper This module contains a collection of YANG definitions for Cisco IOS\-XR tunnel\-l2tun package operational data. This module contains definitions for the following management objects\: l2tp\: L2TP operational data l2tpv2\: l2tpv2 Copyright (c) 2013\-2016 by Cisco Systems, Inc. ...
n_oper.L2Tp.Sessions>` .. attribute:: tunnel_configurations List of tunnel IDs **type**\: :py:class:`TunnelConfigurations <ydk.models.cisco_ios_xr.Cisco_IOS_XR_tunnel_l2tun_oper.L2Tp.TunnelConfigurations>` .. attribute:: tunnels List of tunnel IDs **type**\: :py:class...
refix = 'tunnel-l2tun-oper' _revision = '2015-11-09' def __init__(self): self.classes = L2Tp.Classes() self.classes.parent = self self.counter_hist_fail = L2Tp.CounterHistFail() self.counter_hist_fail.parent = self self.counters = L2Tp.Counters() self.counters.pa...
CoderBounty/coderbounty
website/migrations/0006_auto_20151115_0005.py
Python
agpl-3.0
397
0
# -*- coding:
utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('website', '0005_auto_20151107_2021'), ] operations = [ migrations.AddField( model_name='issue', name='views', ...
jeremyplichta/pi-halloween
door.py
Python
mit
2,164
0.004159
import threading import logging from os import listdir from os.path import isfile, join import random import time import time import RPi.GPIO as G
PIO logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-10s) %(asctime)s %(message)s', ) class Door(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): threading.Thread.__init__...
self.closecallback = args[1] self.closedevent = args[2] self.closedcount = 0 self.gpio_door = kwargs['gpio_door'] self.shouldstop = threading.Event() self.kwargs = kwargs self.closed = True return def stop(self): self.shouldstop.set() ...
janusnic/21v-python
unit_13/qcombobox.py
Python
mit
796
0.023869
from PyQt4 import QtGui from PyQt
4 import QtCore from PyQt4.QtCore import pyqtSlot,SIGNAL,SLOT import sys class myMainWindow(QtGui.QMainWindow): @pyqtSlot(int) def onIndexChange(self, i): print i def main(): app = QtGui.QApplication(sys.argv) window = myMainWindow() palette = QtGui.QPalette() comboBox = ...
ox) comboBox.connect(comboBox,SIGNAL("currentIndexChanged(int)"), window,SLOT("onIndexChange(int)")) window.setWindowTitle('PyQt QComboBox CurrentIndexChange Example') window.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
timgrossmann/dailyProgrammer
Challenges/Python/decodeWebPage.py
Python
mit
698
0.012894
import requests, os from bs4 import BeautifulSoup url = 'http://www.nytimes.com' def extractArticles (url):
data = requests.get(url) soup = BeautifulSoup(data.text, 'html.parser') articles = [] for article in soup.find_all('arti
cle'): if article.find('h2') != None and article.find('h2').find('a') != None: heading = article.find('h2').find('a').get_text().strip() if heading != "": articles.append(heading) articles = sorted(list(set(articles))) f = open('./articles/headlines2.txt', 'w')...
stevepiercy/readthedocs.org
readthedocs/core/middleware.py
Python
mit
8,107
0.001357
import logging from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.core.cache import cache from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from django.http import Http404 from readthedocs.projects.models import Project, Domain log = logg...
for domain in domains: if domain.domain == host: request.slug = domain.project.slug request.urlconf = 'core.subdomain_urls' request.domain_object = True domain.count = domain.count + 1
domain.save() log.debug(LOG_TEMPLATE.format( msg='Domain Object Detected: %s' % domain.domain, **log_kwargs)) break if not hasattr(request, 'domain_object') and 'HTTP_X_RTD_SLUG' in request.META: ...
kevana/phonedusk-server
tests/test_models.py
Python
bsd-3-clause
1,682
0.001189
# -*- coding: utf-8 -*- """Model unit tests.""" import datetime as dt import pytest from phonedusk.user.models import User, Role from .factories import UserFactory @pytest.mark.usefixtures('db') class TestUser: def test_get_by_id(self): user = User('foo', 'foo@bar.com') user.save() retr...
= UserFactory(password="myprecious") db.session.commit() assert bool(user.username) assert bool(user.email) assert bool(user.created_at) assert user.is_admin is False assert user.active is True assert user.check_password('myprecious') def test_check_password...
arbaz123') is True assert user.check_password("barfoobaz") is False def test_full_name(self): user = UserFactory(first_name="Foo", last_name="Bar") assert user.full_name == "Foo Bar" def test_roles(self): role = Role(name='admin') role.save() u = UserFactory() ...