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
samuelmasuy/Concordia-Schedule-to-Gcal
app/__init__.py
Python
gpl-2.0
448
0.002232
# -*- coding:
utf-8 -*- # =========================================================================== # # Copyright (C) 2014 Samuel Masuy. All rights reserved. # samuel.masuy@gmail.com # # =========================================================================== from flask import Flask # Declare app object app = Flask(__name...
bject('config') app.debug = True from app import views
stanford-mast/nn_dataflow
nn_dataflow/core/loop_enum.py
Python
bsd-3-clause
705
0.001418
""" $lic$ Copyright (C) 2016-2020 by Tsinghua
University and The Board of Trustees of Stanford University This program is free software: you can redistribute it and/or modify it under the terms of the Modified BSD-3 License as published by the Open Source Initiative. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; witho...
of the Modified BSD-3 License along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>. """ ''' Enum for loop types. ''' IFM = 0 OFM = 1 BAT = 2 NUM = 3
MidwestCommunications/django-askmeanything
askmeanything/migrations/0004_rmpub.py
Python
mit
4,171
0.010309
from south.db import db from django.db import models from askmeanything.models import * class Migration: def forwards(self, orm): "Write your forwards migration here" def backwards(self, orm): "Write your backwards migration here" models = { 'askmeanything....
True'}), 'open': ('django.db.models.fields.B
ooleanField', [], {'default': 'True', 'blank': 'True'}), 'question': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'askmeanything.response': { 'answer': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'id': ('django.db.models.fi...
thom-at-redhat/cfme_tests
cfme/tests/infrastructure/test_esx_direct_host.py
Python
gpl-2.0
3,626
0.001103
# -*- coding: utf-8 -*- """ Tests of managing ESX hypervisors directly. If another direct ones will be supported, it should not be difficult to extend the parametrizer. """ import pytest import random from cfme.infrastructure.provider import VMwareProvider from utils.conf import cfme_data, credentials from utils.net ...
nue host = random.choice(hosts) creds = credentials[host["credentials"]] ip_address = resolve_hostname(host["name"]) cred = VMwareProvider.Credential( principal=creds["username"], secret=creds["password"], verify_secret=creds["password"] ) ...
_data["name"] = host["name"] provider_data["hostname"] = host["name"] provider_data["ipaddress"] = ip_address provider_data["credentials"] = host["credentials"] provider_data.pop("host_provisioning", None) provider_data["hosts"] = [host] provider_data["discovery_range"] =...
hknyldz/pisitools
pisilinux/pisilinux/db/historydb.py
Python
gpl-3.0
4,426
0.004293
# -*- coding: utf-8 -*- # # Copyright (C) 2008, TUBITAK/UEKAE # # 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. # # Plea...
self, package, config_file): hist_dir = os.path.join(ctx.config.history_dir(), self.history.ope
ration.no, package) if os.path.isdir(config_file): os.makedirs(os.path.join(hist_dir, config_file)) return destdir = os.path.join(hist_dir, config_file[1:]) pisilinux.util.copy_file_stat(config_file, destdir); def update_repo(self, repo, uri, operation = None): ...
kiyukuta/chainer
chainer/links/connection/parameter.py
Python
mit
1,222
0
from chainer import cuda from chainer.functions.math import identity from chainer import link class Parameter(link.Link): """Link that just holds a parameter and returns it. .. deprecated:: v1.5 The parameters are stored as variables as of v1.5. Use them directly instead. Args: ar...
): super(Parameter, self).__init__() self.add_param('W', array.shape, dtype=array.dtype) self.W.data = array if isinstance(array, cuda.ndarray): self.to_gpu(cuda.get_device_from_array(array)) def __call__(self, volatile=
'off'): """Returns the parameter variable. Args: volatile (~chainer.Flag): The volatility of the returned variable. Returns: ~chainer.Variable: A copy of the parameter variable with given volatility. """ # The first identity creates a copy o...
sampadsaha5/sympy
examples/beginner/basic.py
Python
bsd-3-clause
336
0.008929
#!/usr/bin/env
python """Basic example Demonstrates how to create symbols and print some algebra operations. """ from sympy import Symbol, pprint def main(): a = Symbol('a') b = Symbol('b') c = Symbol('c') e = ( a*b*b + 2*b*a*b )**c print('') pprint(e) print('') if __name__ ==
"__main__": main()
kvasnyj/face_counter
counter.py
Python
gpl-3.0
2,444
0.003273
import cv2 import numpy as np import datetime as dt # constant faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') OPENCV_METHODS = { "Correlation": 0, "Chi-Squared": 1, "Intersection": 2, "Hellinger": 3} hist_limit = 0.6 ttl = 1 * 60 q_limit = 3 # init variables total_count = 0 pre...
total_delta = 0 stm = {} q = [] term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1) video_capture = cv2.VideoCapture(0) while True: for t in list(stm): # short term memory if (dt.datetime.now() - t).seconds > ttl: stm.pop(t, None) # Capture frame-by-frame ret, frame =...
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.2, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE ) count = len(faces) if len(q) >= q_limit: del q[0] q.append(count) isSame = Tr...
BlueHoleUEC/BlueHoleUEC
ans_main_t3.py
Python
mit
21,255
0.046417
# coding: utf-8 #!/usr/bin/env python #python のバージョン指定:python 3.5.0 #(条件)MeCabをpythonから利用することができる import sys import MeCab import re import pandas from PIL import Image #----外ファイルインポート---- import python_mecab import get_nlc import get_day_time import record import ans_main_t3 import add_q_main import main_t3 from k3...
result = result['data'] ans_title = result['title'] ans_when_day = result['when_day'] ans_when_time = result['when_time'] ans_where = result['where'] print('[' + str(count) + ']') rfs('title:' + str(ans_title)) rfs(str(ans_when_day) + '日の' + str(ans_when_time) + '開始です。') rfs('開催場所
:' + ans_where) elif category_ans == 'who': #print('category is who') result = result['data'] ans_title = result['title'] ans_name = result['who'] ans_when_time = result['when_time'] print('[' + str(count) + ']') rfs('title:' + str(ans_title)) rfs(ans_name + 'さん。') elif ...
willemneal/Docky
lib/pylint/test/functional/import_error.py
Python
mit
419
0.004773
""" Test that import errors are detected. """ # pylint: disable=invalid-name, unused-import, no-absolute-import import totally_missing # [import-error] try: import maybe_missing except ImportError: maybe_missing = None try: import maybe_missing_1 except (ImportError, SyntaxError): maybe_missing_1 = No...
e
MediaKraken/MediaKraken_Deployment
source/common/common_metadata_tv_intro.py
Python
gpl-3.0
1,725
0.001159
""" Copyright (C) 2016 Quinn D Granfor <spootdev@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but ...
common import common_logging_elasticsearch_httpx from . import common_network from . import common_string # http://www.tv-intros.com def com_tvintro_download(media_name): """ Try to grab intro from tvintro """ # TODO doe
sn't match the tvintro........base from theme data = BeautifulSoup(common_network.mk_network_fetch_from_url( 'http://www.tv-intros.com/' + media_name[0].upper() + '/' + common_string.com_string_title(media_name).replace(' ', '_') + ".html", None)).find(id="download_song") if data is not ...
abawchen/leetcode
tests/012.py
Python
mit
1,527
0.003929
import unittest import sys sys.path.append('./') solutions = __import__('solutions.012_integer_to_roman', fromlist='*') class Test012(unittest.TestCase): def test_intToRoman(self): s = solutions.Solution() self.assertEqual(s.intToRoman(1), "I") self.assertEqual(s.intToRoman(2), "II") ...
ertEqual(s.intToRoman(89), "LXXXIX") self.assertEqual(s.intToRoman(98), "XCVIII") self.assertEqual(s.int
ToRoman(99), "XCIX") self.assertEqual(s.intToRoman(316), "CCCXVI") self.assertEqual(s.intToRoman(400), "CD") self.assertEqual(s.intToRoman(499), "CDXCIX") self.assertEqual(s.intToRoman(894), "DCCCXCIV") self.assertEqual(s.intToRoman(1499), "MCDXCIX") self.a...
kdart/pycopia
QA/pycopia/smartbits/smartlib.py
Python
apache-2.0
8,204
0.005241
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # 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 ...
44 33 22 11 # XXX current interface uses pointers vfdData = ptrcreate("int",0,6) ptrset(vfdData, 0x11, 0) ptrset(vfdData, 0x22, 1) ptrset(vfdData, 0x33, 2) ptrset(vfdData, 0x44, 3) ptrset(vfdData, 0x55, 4) ptrset(vfdData, 0x66, 5) # Associate the data w
ith the VFD structure vfdstruct.Data = vfdData # will increment 5 times then repeat LSB of Source MAC will # follow 11 12 13 14 15 11 12 pattern vfdstruct.DataCount = 5 # send to config card HTVFD( HVFD_1, vfdstruct, h1, s1, p1) ptrfree(vfdData) def setTrigger(h1, s1, p1): """ setTrig...
MusculoskeletalAtlasProject/mapclient-src
mapclient/widgets/workflowgraphicsview.py
Python
gpl-3.0
10,128
0.002073
''' MAP Client, a program to generate detailed musculoskeletal models for OpenSim. Copyright (C) 2012 University of Auckland This file is part of MAP Client. (http://launchpad.net/mapclient) MAP Client is free software: you can redistribute it and/or modify it under the terms of the GNU General Publi...
lf.scene().selectedItems()) self._undoStack.push(command) event.accept() else: event.ignore() def contextMenuEvent(self, event): item = self.itemAt(event.pos()) if item and item.type() == Node.Type: item.showContextMenu(event.globalPos()) ...
t(self.mapToScene(event.pos())) if event.button() == QtCore.Qt.RightButton: event.ignore() elif item and item.type() == StepPort.Type: centre = item.boundingRect().center() self._connectSourceNode = item self._connectLine = ArrowLine(QtCore.QLineF(item.map...
glyph/flanker
tests/mime/message/create_test.py
Python
apache-2.0
10,627
0.000292
# coding:utf-8 from nose.tools import * from mock import * import email import json from base64 import b64decode from flanker.mime import create from flanker.mime.message import errors from flanker.mime.message.part import MimePart from email.parser import Parser from ... import * def from_python_message_test():...
чка с длинным именем и пробельчиками" message.append( create.text("plain", "Hello"), create.text("html", "<html>Hello</html>"),
create.binary( "image", "png", MAILGUN_PNG, filename, "attachment")) eq_(3, len(message.parts)) message2 = create.from_string(message.to_string()) eq_(3, len(message2.parts)) eq_("base64", message2.parts[2].content_encoding.value) eq_(MAILGUN_PNG, message2.parts[2].body) ...
SummerLW/Perf-Insight-Report
telemetry/telemetry/value/trace.py
Python
bsd-3-clause
4,564
0.008326
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import datetime import logging import os import random import shutil import StringIO import sys import tempfile from catapult_base import cloud_storage # p...
n self._serialized_file_handle def UploadToCloud(self, bucket): if self._temp_file is None: raise ValueError('Tried to upload nonexistent trace to Cloud Storage.') try: if self._serialized_file_handle: fh = self._serialized_file_handle else: fh = self._temp_file remote...
m-%d_%H-%M-%S'), random.randint(1, 100000), fh.extension)) self._cloud_url = cloud_storage.Insert( bucket, remote_path, fh.GetAbsPath()) sys.stderr.write( 'View generated trace files online at %s for page %s\n' % (self._cloud_url, self.page.url if self.page ...
drtoful/pyvault
tests/02_store_test.py
Python
bsd-3-clause
1,342
0.002981
import unittest import os from nose.tools import assert_true from nose.tools import assert_false from pyvault import PyVault from pyvault.backends.file import PyVaultFileBackend from pyvault.backends.ptree import PyVaultPairtreeBackend class VaultStore(unittest.TestCase): """ testing storing data into the va...
nt backends and their resulting files. """ def test_store_file(self): backend = PyVaultFileBackend("/tmp/_pyvault_file") vault = PyVault(backend) vault.unlock("passphrase", Fa
lse) assert_false(vault.is_locked()) vault.store("key", "secret") assert_true(os.path.isfile("/tmp/_pyvault_file/8335fa56d487562de248f47befc72743334051ddffcc2c09275f665454990317594745ee17c08f798cd7dce0ba8155dcda14f6398c1d1545116520a133017c09")) def test_store_ptree(self): backend =...
callowayproject/django-articleappkit
articleappkit/fields.py
Python
apache-2.0
1,369
0.002191
import datetime import os from django.db.models.fields.files import FileField from django.core.files.storage import default_storage from django.utils.encoding import force_unicode, smart_str class ModelUploadFileField(FileField): """ Makes the upload_to parameter optional by using the name of the model "...
callable(upload_to): self.generate_filename = upload_to kwargs['max_length'] = kwargs.get('max_length', 100) super(FileField, self).__init__(verbose_name, name, **kwargs) def get_directory_name(self): return os.path.normpath(force_unicode(datetime.datetime.now().strftime(smart...
return os.path.join(self.get_directory_name(), self.get_filename(filename))
pybursa/homeworks
o_shestakoff/hw5/hw5_tests.py
Python
gpl-2.0
953
0.001072
# -*- coding: utf8 -*- u""" Тесты на ДЗ#5. """ __author__ = "wowkalucky" __email__ = "wowkalucky@gmail.com" __date__ = "2014-11-17" import datetime from hw5_solution1 import Person def tests_for_hw5_solution1(): u"""Тесты задачи 1""" petroff = Person("Petrov", "Petro", "1952-01-02") ivanoff = Person(...
dir(ivanoff) assert "nickname" not in dir(petroff) assert "nickname" in dir(sydoroff) assert petroff.surname == "Petrov" assert petroff.first_na
me == "Petro" assert petroff.get_fullname() == "Petrov Petro" assert sydoroff.nickname == "Senya" assert petroff.birth_date == datetime.date(1952, 01, 02) assert isinstance(petroff.birth_date, datetime.date) assert petroff.get_age() == "62" print 'All is Ok!'
wojciechtanski/robotframework
src/robot/conf/settings.py
Python
apache-2.0
20,981
0.003146
# Copyright 2008-2015 Nokia Solutions and Networks # # 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 l...
n loggerhelper.LEVELS: raise DataError("Invalid log level '%s'" % log_level) if default not in loggerhelper.LEVELS: raise DataError("Invalid log level '%s'" % defa
ult) if not loggerhelper.IsLogged(log_level)(default): raise DataError("Default visible log level '%s' is lower than " "log level '%s'" % (default, log_level)) def _process_randomize_value(self, original): value = original.lower() if ':' in value: ...
zerolab/wagtail
wagtail/tests/demosite/migrations/0002_capitalizeverbose.py
Python
bsd-3-clause
318
0
#
-*- coding: utf-8 -*- from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('demosite', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='homepage', option
s={'verbose_name': 'homepage'}, ), ]
ivanhorvath/openshift-tools
ansible/roles/lib_openshift_3.2/library/oc_secret.py
Python
apache-2.0
37,290
0.002789
#!/usr/bin/env python # pylint: disable=too-many-lines # ___ ___ _ _ ___ ___ _ _____ ___ ___ # / __| __| \| | __| _ \ /_\_ _| __| \ # | (_ | _|| .` | _|| / / _ \| | | _|| |) | # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____ # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _| # | |) | (_) ...
(['--list-pods', '-o', 'json']) return self.openshift_cmd(cmd, oadm=True, o
utput=True, output_type='raw') #pylint: disable=too-many-arguments def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False): ''' perform oadm manage-node evacuate ''' cmd = ['manage-node'] if node: cmd.extend(node) ...
tiborsimko/analysis-preservation.cern.ch
tests/integration/test_delete_deposit.py
Python
gpl-2.0
7,407
0.00243
# -*- coding: utf-8 -*- # # This file is part of CERN Analysis Preservation Framework. # Copyright (C) 2017 CERN. # # CERN Analysis Preservation Framework 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...
},{ 'email': other_user.email, 'type': 'user', 'op':
'add', 'action': 'deposit-update' }] with app.test_client() as client: # give other user read/write access resp = client.post('/deposits/{}/actions/permissions'.format(deposit['_deposit']['id']), headers=auth_headers_for_user(owner) + json_headers, ...
BrandonBaucher/website-optimization
dummy_backend.py
Python
mit
1,866
0.009646
#!/usr/bin/env python # Reflects the requests from HTTP methods GET, POST, PUT, and DELETE # Written by Nathan Hamiel (2010) from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from optparse import OptionParser class RequestHandler(BaseHTTPRequestHandler): success = 0 total =0 def do_GET(self):...
('content-length') length = int(content_length[0]) if content_length else 0 # print(request_h#eaders) print(self.rfile.read(length)) """ r = self.rfile.read(length).split('=')[-1] print r if r == 'true': success += 1 total +=1 ...
print'' """ print("<----- Request End -----\n") self.send_response(200) do_PUT = do_POST do_DELETE = do_GET def main(): port = 8080 print('Listening on localhost:%s' % port) server = HTTPServer(('', port), RequestHandler) server.serve_forever() ...
rebost/django
django/contrib/gis/gdal/__init__.py
Python
bsd-3-clause
2,164
0.001386
""" This module houses ctypes interfaces for GDAL objects. The following GDAL objects are supported: CoordTransform: Used for coordinate transformations from one spatial reference system to another. Driver: Wraps an OGR data source driver. DataSource: Wrapper for the OGR data source object, supports OGR-su...
rt objects that depend on the GDAL library. The # HAS_GDAL flag will be set to Tr
ue if the library is present on # the system. try: from django.contrib.gis.gdal.driver import Driver from django.contrib.gis.gdal.datasource import DataSource from django.contrib.gis.gdal.libgdal import gdal_version, gdal_full_version, gdal_release_date, GEOJSON, GDAL_VERSION from django.contrib.gis.gda...
SINGROUP/pycp2k
pycp2k/classes/_restart14.py
Python
lgpl-3.0
665
0.003008
from pycp2k.inputsection import InputSection from ._each406 import _each406 class _restart14(InputSection): def __init__(self): InputSection.__init__(self)
self.Section_parameters = None self.Add_last = None self.Common_iteration_levels = None self.Filename = None self.Log_print_key = None self.EACH = _each406() self._name = "RESTART" self._keywords = {'Log_print_key': 'LOG_PRINT_KEY', 'Filename': 'FILENAME', '...
'Section_parameters']
bx5974/sikuli
sikuli-ide/sample-scripts/resize-app.sikuli/resize-app.py
Python
mit
380
0.018421
def resizeApp(app, dx, dy): switchApp(app) corner = find(Pattern("1273159241516.png").targetOffset(3,14)) dragDrop(corner, corner.getCenter().offset(dx, dy
)) resizeApp("Safari", 50,
50) # exists("1273159241516.png") # click(Pattern("1273159241516.png").targetOffset(3,14).similar(0.7).firstN(2)) # with Region(10,100,300,300): # pass # click("__SIKULI-CAPTURE-BUTTON__")
MuhammadSohaib/colorado-geology-geodjango
geology/geology/wsgi.py
Python
mit
1,562
0.00064
""" WSGI config for geology project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` ...
ction") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application a
pplication = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
RiskSense-Ops/CVE-2016-6366
extrabacon-2.0/versions/shellcode_asa821.py
Python
mit
4,530
0.003311
# # this file autogenerated, do not touch # vers = "asa821" my_ret_addr_len = 4 my_ret_addr_byte = "\x93\xf2\x2b\x09" my_ret_addr_snmp = "147.242.43.9" finder_len = 9 finder_byte = "\x8b\x7c\x24\x14\x8b\x07\xff\xe0\x90" finder_snmp = "139.124.36.20.139.7.255.224.144" preamble_len = 41 preamble_byte = "\xb8\...
a5\xa5\xff\xd0\x58\xc3" payload_nop_snmp =
"144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144...
docteurmicro50/xivo-provd-plugins
plugins/xivo-snom/common/common.py
Python
gpl-3.0
15,004
0.001333
# -*- coding: utf-8 -*- # Copyright (C) 2010-2015 Avencall # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This p...
orm_mac(raw_mac.decode('ascii')) class BaseSnomPgAssociator(BasePgAssociator): def __init__(self, models,
version): self._models = models self._version = version def _do_associate(self, vendor, model, version): if vendor == u'Snom': if version is None: # Could be an old version with no XML support return PROBABLE_SUPPORT assert version is...
immstudios/firefly
proxyplayer/videoplayer.py
Python
gpl-3.0
9,818
0.000204
#!/usr/bin/env python3 import functools from nxtools import logging, log_traceback from .utils import ( Qt, QWidget, QSlider, QTimer, QHBoxLayout, QVBoxLayout, QIcon, RegionBar, TimecodeWindow, get_navbar, ) try: from .mpv import MPV has_mpv = True except OSError: ...
eback(handlers=False) self.player = DummyPlayer() self.position = 0 self.duration = 0 self.mark_in = 0 self.mark_out = 0 sel
f.fps = 25.0 self.loaded = False self.duration_changed = False self.prev_position = 0 self.prev_duration = 0 self.prev_mark_in = 0 self.prev_mark_out = 0 # # Displays # self.mark_in_display = TimecodeWindow(self) self.mark_in_dis...
tdl/python-challenge
l12_imageEvilReal.py
Python
mit
3,202
0.010618
## image quickie! ## install PIL (Python Imaging Library) first. Supercool lib import Image ## from Pil ! fImageOrig = "C:\\evil1.jpg" im = Image.open(fImageOrig) print im.size, im.mode width, height = im.size ## get pixel list lpix = list(im.getdata()) def getEvenOdd(lpix, width, height): return getPixels(lp...
artcol return lpix[startcol::x] magicheight = 5 listsEven = range(magicheight) imagesEven = range(magicheight) for i in rang
e(magicheight): listsEven[i] = getAnXthPartHeight(l0, width/2, height, i, magicheight) imagesEven[i] = Image.new(im.mode, (width/2, height/magicheight)) imagesEven[i].putdata(listsEven[i]) imagesEven[i].save("c:\\evil_even_" + str(magicheight) + "_" + str(i) + ".jpg") listsOdd = range(magicheig...
GeoMop/GeoMop
src/ModelEditor/ui/panels/__init__.py
Python
gpl-3.0
218
0
""" Module with Qt widgets. """ from .debug_info import DebugPanelWidget from .error_
tab import ErrorWidget from .info_panel import InfoPanelPage from .tree import TreeWidget from .yaml_editor import YamlEdit
orWidget
davetcoleman/moveit
moveit_ros/planning_interface/test/python_move_group_ns.py
Python
bsd-3-clause
3,928
0.001527
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Willow Garage, Inc. # 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 cod...
s # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF ME...
IBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # ...
mozilla/firefox-flicks
vendor-local/lib/python/oauthlib/oauth1/rfc5849/__init__.py
Python
bsd-3-clause
41,842
0.001793
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals """ oauthlib.oauth1.rfc5849 ~~~~~~~~~~~~~~ This module is an implementation of various logic needed for signing and checking OAuth 1.0 RFC 5849 requests. """ import logging import sys import time try: import urlparse except ImportEr...
AC: sig = signature.sign_hmac_sha1(base_string, self.client_secret, self.resource_owner_secret) elif self.signature_method == SIGNATURE_RSA: sig = signature.sign_rsa_sha1(base_string, self.rsa_key) else: sig = signature.sign_plaintext(self.client_secre...
self.resource_owner_secret) logging.debug("Signature: {0}".format(sig)) return sig def get_oauth_params(self): """Get the basic OAuth parameters to be used in generating a signature. """ nonce = (generate_nonce() if self.nonce is None else self...
axlt2002/script.light.imdb.ratings.update
resources/support/tvdbsimple/base.py
Python
gpl-3.0
5,912
0.007781
# -*- coding: utf-8 -*- """ This module implements the base class of tvdbsimple. Handle automatically login, token creation and response basic stripping. [See Authentication API section](https://api.thetvdb.com/swagger#!/Authentication) """ import json import requests class AuthenticationError(Exception): """...
'GET', self._get_complete_url('refresh_token'), headers=self._headers) response.raise_for_status() jsn = response.json() if 'token' in jsn: from . import KEYS KEYS.API_TOKEN = jsn['token'] return KEYS.API_TOKEN return '' def...
""" Get the existing token or creates it if it doesn't exist. Returns the API token. If `forceNew` is true the function will do a new login to retrieve the token. """ from . import KEYS if not KEYS.API_TOKEN or forceNew: if not KEYS.API_KEY: ...
navin-bhaskar/NewsReader-on-Linkit7688
config.py
Python
bsd-2-clause
522
0.017241
#The audio card number to be used; use "aplay -l" output to determine the card number AUDIO_CARD_NUMBER = 1 # Define the IR/button input pin INP_PIN = 2 # Speed with which the converted text is to be spoken
TTS_SPEED = 70 # Config server to spawned ot not, set to false if you do not want the config server CONFIG_SERVER_SPAWN = True # Name of the file where the RSS links will be stored R
SS_LINKS_FILE = "links.txt" # A temp file to indicate that the RSS list has been updated NEW_LIST_FILE = ".changed.tmp"
apllicationCOM/youtube-dl-api-server
youtube_dl_server/youtube_dl/extractor/adobetv.py
Python
unlicense
4,630
0.001728
from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( parse_duration, unified_strdate, str_to_int, float_or_none, ISO639Utils, ) class AdobeTVIE(InfoExtractor): _VALID_URL = r'https?://tv\.adobe\.com/watch/[^/]+/(?P<id>[^/]+)' _TEST = { '...
_TEST = { # From https://helpx.adobe.com/acrobat/how-to/new-experience-acrobat-dc.html?set=acrobat--get-started--essential-beginners 'url': 'https://video.tv.adobe.com/v/2456/', 'md5': '43662b577c018ad707a63766462b1e87', 'info_dict': { 'id': '24
56', 'ext': 'mp4', 'title': 'New experience with Acrobat DC', 'description': 'New experience with Acrobat DC', 'duration': 248.667, }, } def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, vi...
lcamacho/airmozilla
airmozilla/main/context_processors.py
Python
bsd-3-clause
12,078
0
import datetime from django.conf import settings from django.db.models import Q from django.utils import timezone from django.core.cache import cache from funfactory.urlresolvers import reverse from airmozilla.main.models import ( Event, Channel, EventHitStats, most_recent_event ) from airmozilla.mai...
# used for things like {% if event.attr == Event.ATTR1 %} 'Event': Event, 'get_feed_data': get_feed_data, } def sidebar(request): #
none of this is relevant if you're in certain URLs def get_sidebar(): data = {} if not getattr(request, 'show_sidebar', True): return data # if viewing a specific page is limited by channel, apply that # filtering here too if getattr(request, 'channels', None):...
pdp10/sbpipe
sbpipe/utils/dependencies.py
Python
mit
3,141
0.001273
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2018 Piero Dalle Pezze # # 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 ...
ame)): return os.path.join(path, cmd_name) if os.path.exists(os.path.join(path, cmd_name + '.exe')): return os.path.join(path, cmd_name + '.exe') return None def is_py_package_installed(package): """ Utility checking whether a Python package is i
nstalled. :param package: a Python package name :return: True if it is installed, false otherwise. """ try: installed_packages = subprocess.Popen(['pip', 'list'], stdout=subprocess.PIPE, stderr=subproces...
ulfaslak/bandicoot
immutable/docs/conf.py
Python
mit
8,601
0.005813
# -*- coding: utf-8 -*- # # bandicoot documentation build configuration file, created by # sphinx-quickstart on Mon Apr 28 20:51:43 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
avicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin st
atic files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path...
cloudwatt/contrail-neutron-plugin
neutron_plugin_contrail/plugins/opencontrail/contrail_plugin.py
Python
apache-2.0
28,349
0.000106
# Copyright 2014 Juniper Networks. 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...
portbindings_base.PortBindingBaseMixin, external_net.External_net): supported_extension_aliases = ["security-group", "router", "port-security", "binding", "agent", "quotas", "external-net", ...
VIF_TYPES portbindings.__dict__['VIF_TYPE_VROUTER'] = 'vrouter' portbindings.VIF_TYPES.append(portbindings.VIF_TYPE_VROUTER) def _parse_class_args(self): """Parse the contrailplugin.ini file. Opencontrail supports extension such as ipam, policy, these extensions can be configured i...
google/llvm-propeller
llvm/utils/update_analyze_test_checks.py
Python
apache-2.0
6,940
0.010519
#!/usr/bin/env python3 """A script to generate FileCheck statements for 'opt' analysis tests. This script is a utility to update LLVM opt analysis test cases with new FileCheck patterns. It can either update all of the tests in the file or a single test function. Example usage: $ update_analyze_test_checks.py --opt=...
ommon.scrub_body, [], raw_tool_output, prefixes, func_dict, args.verbose, False, False) is_in_function = False is_in_function_start = False prefix_set = set([prefix for prefixes, _ in prefix_list for prefix in prefixes]) common.debug('Rewriting FileCheck prefixes:', str(prefix_set), file=sys....
if input_line == '': continue if input_line.lstrip().startswith(';'): m = common.CHECK_RE.match(input_line) if not m or m.group(1) not in prefix_set: output_lines.append(input_line) continue # Print out the various check lines here. c...
bheesham/servo
python/servo/bootstrap_commands.py
Python
mpl-2.0
12,893
0.002094
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your #...
exists(docs_dir): print("Rust docs already downloaded.", end=" ") print("Use |bootstrap-rust-docs --force| to download again.") ret
urn if path.isdir(docs_dir): shutil.rmtree(docs_dir) docs_name = self.rust_path().replace("rustc-", "rust-docs-") docs_url = ("https://static-rust-lang-org.s3.amazonaws.com/dist/rust-docs-nightly-%s.tar.gz" % host_triple()) tgz_file = path.join(rust_root,...
xswxm/nrf24-injection
utils/config.py
Python
gpl-3.0
8,406
0.022365
#!/usr/bin/env python2 ''' Author: xswxm Blog: xswxm.com This script will analyze the paylods/tasks assigned by the messager.py and output the result to display.py. It also stores most parameters, which are shared between different classes and scripts. ''' import sys sys.path.append("..") from array import array f...
msg = [] msg.append('----------------------------------SELECT TASKS----------------------------------') msg.append('You selected: {0} ({1} {2})'.format( ':'.join('{:02X}'.format(b) for b in device.address), device.vendor, device.model)) menu = range(2) msg.append('{0:<6}{1}'.format('No.', 'Task')) ...
her_msg(): global devices, deviceID, menu device = devices[deviceID] msg = [] msg.append('----------------------------------SELECT TASKS----------------------------------') msg.append('You selected: {0} ({1} {2})'.format( ':'.join('{:02X}'.format(b) for b in device.address), device.vendor, device.mod...
lukas-hetzenecker/home-assistant
tests/components/fritzbox/__init__.py
Python
apache-2.0
3,106
0
"""Tests for the AVM Fritz!Box integration.""" from __future__ import annotations from typing import Any from unittest.mock import Mock from homeassistant.components.fritzbox.const import DOMAIN from homeassistant.core import HomeAssistant from .const import ( CONF_FAKE_AIN, CONF_FAKE_MANUFACTURER, CONF_...
rue has_powermeter = False has_switch = False has_temperature_sensor = False has_thermostat = False present = True class FritzDeviceClimateMock(Fritz
DeviceBaseMock): """Mock of a AVM Fritz!Box climate device.""" actual_temperature = 18.0 alert_state = "fake_state" battery_level = 23 battery_low = True comfort_temperature = 22.0 device_lock = "fake_locked_device" eco_temperature = 16.0 fw_version = "1.2.3" has_alarm = False ...
zenoss/ZenPacks.community.VMwareESXMonitor
ZenPacks/community/VMwareESXMonitor/modeler/plugins/zenoss/snmp/Esx.py
Python
gpl-2.0
1,873
0.003203
########################################################################### # # This program is part of Zenoss Core, an open source monitoring platform. # Copyright (C) 2009, Zenoss Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License versi...
rtualHostMonitor.VirtualMachine' columns = { '.1': 'snmpindex', '.2': 'displayName', '.4': 'osType', '.5': 'memory', '.6': 'adminStatus', '.7': 'vmid', '.8': 'operStatus', } snmpGetTableMaps = ( GetTableMap('vminfo', '.1.3.6.1...
.2.1.1', columns), ) def process(self, device, results, log): log.info('processing %s for device %s', self.name(), device.id) getdata, tabledata = results table = tabledata.get("vminfo") rm = self.relMap() for info in table.values(): info['adminStatus'] = inf...
leppa/home-assistant
homeassistant/components/vlc_telnet/media_player.py
Python
apache-2.0
7,570
0.000132
"""Provide functionality to interact with the vlc telnet interface.""" import logging from python_telnet_vlc import ConnectionError as ConnErr, VLCTelnet import voluptuous as vol from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerDevice from homeassistant.components.media_player.const impor...
lume"]) / 500.0 else: self._volume = None if "state" in status: state = status["state"] if state == "playing": self._state = STATE_PLAYING elif state == "pa...
else: self._state = STATE_IDLE self._media_duration = self._vlc.get_length() self._media_position = self._vlc.get_time() info = self._vlc.info() if info: self._media_artist = info[0].get("artist") ...
samuelcolvin/pydantic
tests/test_create_model.py
Python
mit
6,429
0.001555
import pytest from pydantic import BaseModel, Extra, Field, ValidationError, create_model, errors, validator def test_create_model(): model = create_model('FooModel', foo=(str, ...), bar=123) assert issubclass(model, BaseModel) assert issubclass(model.__config__, BaseModel.Config) assert model.__name...
FooModel', foo=(str, ...), bar=(int, 123), __base__=BarModel) assert model.__fields__.keys() == {'foo', 'bar', 'x', 'y'} m = model(foo='a', x=4) assert m.dict
() == {'bar': 123, 'foo': 'a', 'x': 4, 'y': 2} def test_custom_config(): class Config: fields = {'foo': 'api-foo-field'} model = create_model('FooModel', foo=(int, ...), __config__=Config) assert model(**{'api-foo-field': '987'}).foo == 987 assert issubclass(model.__config__, BaseModel.Config...
bzzzz/cython
tests/run/pure_py.py
Python
apache-2.0
4,851
0.013193
import cython def test_sizeof(): """ >>> test_sizeof() True True True True True """ x = cython.declare(cython.bint) print(cython.sizeof(x) == cython.sizeof(cython.bint)) print(cython.sizeof(cython.char) <= cython.sizeof(cython.short) <= cython.sizeof(cython.int) <= cython.si...
(p_void, cython.NULL) c = my_declare(my_void_star, cython.NULL) d = cy.declare(cy.p_void, cython.NULL) ## CURRENTLY BROKEN - FIXME!! #return a == d, compiled == my_compiled return compiled == my_compiled ## CURRENTLY BROKEN
- FIXME!! ## MyStruct3 = typedef(MyStruct[3]) ## MyStruct4 = my_typedef(MyStruct[4]) ## MyStruct5 = cy.typedef(MyStruct[5]) def test_declare_c_types(n): """ >>> test_declare_c_types(0) >>> test_declare_c_types(1) >>> test_declare_c_types(2) """ # b00 = cython.declare(cython.bint, 0) b...
brunitto/python-runner
lib/stages/cairo_museum.py
Python
mit
1,374
0
"""cairo_museum.py""" from lib.stage import Stage class CairoMuseum(Stage): """Cairo Museum stage""" def desc(self): """Describe action""" action = """ After getting the first replicant, you call some old friends and some of them mentions something about a hippie woman that likes no jokes. ...
ef look(self): """Look action""" action = """ Everyone seens to be busy looking at the art, mainly the big statues, nothing suspicious, except for a different woman in the corner... """ self.console.simulate_typing(action) def talk(self): """Talk action""" action = """ You...
ping(action) def joke(self): """Joke action""" action = """ You tell a really good joke and an old mummy start laughing... """ self.console.simulate_typing(action) def fight(self): """Fight action""" action = """ You try to start a fight, but a camel holds you and tel...
Jverma/InfoR
InfoR/ProbabilitisticModels.py
Python
mit
5,245
0.045567
# -*- coding: utf-8 -*- # A search engine based on probabilitistic models of the information retrival. # Author - Janu Verma # email - jv367@cornell.edu # http://januverma.wordpress.com/ # @januverma import sys from pydoc import help import os from collections import defaultdict from math import log, sqrt impo...
x in queryWords: try: tf_x = tf[x] e
xcept: continue try: df_x = df[x] except: continue # inverse document frequency of the term. idf = log(n/df_x) # correction factor correction = float((k + 1)*(tf_x))/(k*(1-b) + b*(l/(l_av)) + (tf_x)) # total contribution contribution = idf * correction score += contribution ...
WZQ1397/automatic-repo
python/FileSystem/BTpanel/btclass/panelMysql.py
Python
lgpl-3.0
3,122
0.02675
#coding: utf-8 # +------------------------------------------------------------------- # | 宝塔Linux面板 # +------------------------------------------------------------------- # | Copyright (c) 2015-2016 宝塔软件(http://bt.cn) All rights reserved. # +------------------------------------------------------------------- # | Author...
_PASS,port = self.__DB_PORT,charset="utf8",connect_timeout=1) self.__DB_CUR = self.__DB_CONN.cursor() return True except MySQLdb.Error,e: self.__DB_ERR = e return False def execute(self,sql): #执行SQL语句返回受影响行 if not self.__Conn(): ret...
self.__Close() return result except Exception,ex: return ex def query(self,sql): #执行SQL语句返回数据集 if not self.__Conn(): return self.__DB_ERR try: self.__DB_CUR.execute(sql) result = self.__DB_CUR.fetchall() #将...
pegurnee/2015-01-341
projects/project1_mini_python/python_mini_project.py
Python
mit
412
0.002427
def at_len(the_list): """
Takes a list and returns the number of atomic elements (basic unit of data) of the list :param the_list: a list of elements :return: the number of atomic elements in the list """ count = 0 for each_elem in the_list: if isinstance(each_elem, list)
: count += at_len(each_elem) else: count += 1 return count
richard-shepherd/monopyly
monopyly/game/dice.py
Python
mit
436
0
import random class Dice(object): ''' Generates random numbers by rolling two 'dice'. The reason for this class existing is so that it ca
n be mocked and replaced with a deterministic version for testing. ''' def roll(self): ''' Returns two value: the rolls of the two dice. ''' roll1 = random.ra
ndint(1, 6) roll2 = random.randint(1, 6) return roll1, roll2
iambernie/hdf5handler
examples/opening.py
Python
mit
183
0.005464
#!/usr/bin/env python from hdf5handler import HDF5Handler handler = HDF5Handler('mydata.hdf5') handler.open() for i in range(100): handler
.put(i, 'numbers') handler.close()
nylas/sync-engine
migrations/versions/120_simplify_transaction_log.py
Python
agpl-3.0
688
0.002907
"""simpli
fy transaction log Revision ID: 8c2406df6f8 Revises:58732bb5d14b Create Date: 2014-08-08 01:57:17.144405 """ # revision identifiers, used by Alembic. revision = '8c2406df6f8' down_revision = '58732bb5d14b' from alembic import op from sqlalchemy.sql import text def upgrade(): conn = op.get_bind() conn.exec...
ction CHANGE public_snapshot snapshot LONGTEXT, CHANGE table_name object_type VARCHAR(20), DROP COLUMN private_snapshot, DROP COLUMN delta, ADD INDEX `ix_transaction_object_public_id` (`object_public_id`) ''')) def downgrade(): raise Exception()
tommy-u/enable
kiva/tests/drawing_tester.py
Python
bsd-3-clause
5,452
0.000183
import contextlib import os import shutil import tempfile import numpy from PIL import Image from kiva.fonttools import Font from kiva.constants import MODERN class DrawingTester(object): """ Basic drawing tests for graphics contexts. """ def setUp(self): self.directory = tempfile.mkdtemp() ...
.begin_path() self.gc.move_to(107, 204) self.gc.line_to(107, 104) self.gc.stroke_path() def test_rectangle(self): with self.draw_and_check(): self.gc.begin_path() self.gc.move_to(107, 104) self.gc.line_to(107,
184) self.gc.line_to(187, 184) self.gc.line_to(187, 104) self.gc.line_to(107, 104) self.gc.stroke_path() def test_rect(self): with self.draw_and_check(): self.gc.begin_path() self.gc.rect(0, 0, 200, 200) self.gc.stroke_pat...
jenshnielsen/basemap
examples/maskoceans.py
Python
gpl-2.0
1,922
0.021852
from mpl_toolkits.basemap import Basemap, shiftgrid, maskoceans, interp import numpy as np import matplotlib.pyplot as plt # example showing how to mask out 'wet' areas on a contour or pcolor plot. topodatin = np.loadtxt('etopo20data.gz') lonsin = np.loadtxt('etopo20lons.gz') latsin = np.loadtxt('etopo20lats.gz') #...
ill be masked) CS=m.contourf(x,y,topo,np.arange(-300,3001,50),cmap=plt.cm.jet,extend='both') #im=m.pcolormesh(x,y,topo,cmap=plt.cm.jet,vmin=-300,vmax=3000) # draw coastlines. m.drawcoastlines() plt.title('ETOPO data with marine areas masked (original grid)') fig=plt.figure() # interpolate topo data to higher resolutio...
ace(-90,90,nlats) lons, lats = np.meshgrid(lons, lats) x, y = m(lons, lats) topo = interp(topoin,lons1,lats1,lons,lats,order=1) # interpolate land/sea mask to topo grid, mask ocean values. topo = maskoceans(lons, lats, topo) # make contour plot (ocean values will be masked) CS=m.contourf(x,y,topo,np.arange(-300,3001,50...
freedesktop-unofficial-mirror/zeitgeist__zeitgeist
examples/python/find_events.py
Python
lgpl-2.1
1,009
0.011893
from gi.repository import Zeitgeist, GLib log = Zeitgeist.Log.get_default() mainloop = GLib.MainLoop() def on_events_received(log, result, data): events = log.find_events_finish(result) for i in xrange(events.size()): event = events.next_value() if event: print "Event id:", event.ge...
ist.Event() event.add_subject(subject) time_range = Zeitgeist.TimeRange.anytime (); log.find_events(time_range, [event], Zeitgeist.StorageState.ANY, 20, Zeitgeist.ResultType.MOST_RECENT_SUBJECTS, No...
eived, None) mainloop.run()
ggimenez/HomeworkDesigner.activity
template.activity/simpleassociation.py
Python
gpl-2.0
17,950
0.036331
#!/usr/bin/env python # -*- coding: utf-8 -*- import pygtk pygtk.require('2.0') import gtk import json from collections import namedtuple from array import * import pango import random from gettext import gettext as _ import copy ''' Scales ''' IMAGES_SCALE = [100, 100] LETTERS_SCALE = [100, 100] '''Color Selec...
llEventBoxs = [] self.exerciseCompleted = False if stateJson is None: self.optionsSelectionState = [] self.correspondencesSelectionState = [] self.currentOptionSelected = -1 self.lastOptionSelected = -1 self.currentCorrespondenceSelected = -1 self.lastCorresponde
nceSelected = -1 self.optionsList, self.correspondencesList = self.disorderCorrespondences(exercise.items) self.COLOURS_ASSOCIATION = COLOURS_ASSOCIATION else: self.optionsSelectionState = stateJson['optionsSelectionState'] self.correspondencesSelectionState = stateJson['correspondencesSelectio...
fos/fos-legacy
scratch/very_scratch/server/example7/webSocketServer.py
Python
bsd-3-clause
4,050
0.008889
#!/usr/bin/env python import sys import time import socket import threading import Queue import ConfigParser import logging as log from connection import * from connectionManager import * log.basicConfig(level=log.DEBUG, stream=sys.stderr) #Dynamically instantiate an instance of an Application-derive...
clientAddress = serverSocket.accept() try: log.info('Got client connection from %s' % (repr(clientAddress))) connection = Connection(clientSocket, clientAddress) log.info('Client %s requested %s application' % (repr(clientAddress), connection.Applicati...
requestedApp = applications[connection.ApplicationPath] log.info('Client %s requested app: %s ' % (repr(clientAddress), repr(requestedApp))) if requestedApp.AddClient(connection) == True: connectionManager.Ad...
dataxu/ansible
lib/ansible/modules/network/junos/junos_user.py
Python
gpl-3.0
11,343
0.001851
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
em['active']: user.set('active', 'active'
) else: user.set('inactive', 'inactive') if item['role']: SubElement(user, 'class').text = item['role'] if item.get('full_name'): SubElement(user, 'full-name').text = item['full_name'] if item.get('sshkey'): ...
nagyistoce/devide
modules/vtk_basic/vtkRecursiveDividingCubes.py
Python
bsd-3-clause
506
0.001976
# class generated by DeVIDE::createDeVIDEModuleFromVTKObject from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase import vtk clas
s vtkRecursiveDividingCubes(SimpleVTKClassModuleB
ase): def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkRecursiveDividingCubes(), 'Processing.', ('vtkImageData',), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
linearregression/luigi
luigi/parameter.py
Python
apache-2.0
20,682
0.003771
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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...
than a single value. Default: ``False``. A list has an implicit default value of ``[]``. :param bool is_bool: specify ``True`` if the parameter is a bool value. Defau
lt: ``False``. Bool's have an implicit default value of ``False``. :param bool significant: specify ``False`` if the parameter should not be treated as part of the unique identifier for a Task. An insignificant Parameter might ...
essamjoubori/girder
girder/utility/s3_assetstore_adapter.py
Python
apache-2.0
29,780
0.000269
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2014 Kitware 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 cop...
'], doc['service']) # Make sure we can write into the given bucket using boto conn = botoConnectS3(doc['botoConnect']) if doc.get('readOnly'): try: conn.get_bucket(bucket_name=doc['bucket'], validate=True) except Exception: logger.exception...
doc['bucket'], 'bucket') else: try: bucket = conn.get_bucket(bucket_name=doc['bucket'], validate=True) testKey = boto.s3.key.Key( bucket=bucket, name='/'.join( fi...
tseaver/google-cloud-python
containeranalysis/google/cloud/devtools/containeranalysis_v1/gapic/container_analysis_client.py
Python
apache-2.0
21,328
0.001688
# -*- coding: utf-8 -*- # # 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...
container_analysis_grpc_transport, ) from google.cloud.devtools.containeranalysis_v1.proto import containeranalysis_pb2_grpc from google.iam.v1
import iam_policy_pb2 from google.iam.v1 import options_pb2 from google.iam.v1 import policy_pb2 from grafeas import grafeas_v1 from grafeas.grafeas_v1.gapic.transports import grafeas_grpc_transport _GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( "google-cloud-containeranalysis" ).version class Conta...
nagyistoce/edx-XBlock
xblock/core.py
Python
apache-2.0
9,923
0.002721
""" Core classes for the XBlock family. This
code is in the Runtime layer, because it is authored once by edX and used by all runtimes. """ import inspect import pkg_resources import warnings from collections import defaultdict from xblock.exceptions import DisallowedFileError from xblock.fields import String, List, Scop
e from xblock.internal import class_lazy import xblock.mixins from xblock.mixins import ( ScopedStorageMixin, HierarchyMixin, RuntimeServicesMixin, HandlersMixin, XmlSerializationMixin, IndexInfoMixin, ViewsMixin, ) from xblock.plugin import Plugin from xblock.validation import Validation #...
razzius/PyClassLessons
instructors/course-2015/errors_and_introspection/project/primetester3.py
Python
mit
969
0.004128
""" For any given number, we only need to test the primes below it. e.g. 9 -- we need only test 1,2,3,5,7 e.g. 8 -- we need only test 1,2,3,5,7 for example, the number 12 has factors 1,2,3,6,12. We could find the six factor but we will find the two factor first. The definition of a composite number is that it is co...
e it will always have a prime as a factor. This prime test should have an index of all primes below i. """ total_range = 100000
0 primes = list() def prime_test(i): """ Cases: Return False if i is not prime Return True if i is prime Caveat: cannot test 1. Caveat 2: Cannot test 2. It is fortuitous that these tests both return true. """ for possible_factor in primes: if i % possible_factor == 0: ...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/gio/_gio/FileMonitorEvent.py
Python
gpl-2.0
785
0.007643
# encoding: utf-8 # module gio._gio # from /usr/lib/python2.7/dist-packages/gtk-2.0/gio/_gio.so # by generator 1.135 # no doc # imports import gio as __
gio import glib as __glib import gobject as __gobject import gobject._gobject as __gobject__gobject class FileMonitorEvent(__gobject.GEnum): # no doc def __init__(self, *args, **kwargs): # real signature unknown pass __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self:...
__enum_values__ = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, } __gtype__ = None # (!) real value is ''
mozman/ezdxf
examples/render/dimension_linear.py
Python
mit
24,851
0.000563
# Purpose: using DIMENSION horizontal, vertical and rotated # Copyright (c) 2018-2021, Manfred Moitzi # License: MIT License from typing import cast import math import pathlib import random import logging import ezdxf from ezdxf.tools.standards import setup_dimstyle from ezdxf.math import Vec3, UCS from ezdxf.entities...
e to use x: start point x y: start point y halign: horizontal text alignment
- "left", "right", "center", "above1", "above2", requires DXF R2000+ valign: vertical text alignment "above", "center", "below" oblique: angle of oblique extension line, 0 = orthogonal to dimension line """ dimattr = {} if oblique: ...
sandrafig/addons
stock_picking_reports/models/stock_picking.py
Python
agpl-3.0
179
0.005587
# -*- coding:
utf-8 -*- from openerp import models, fields, api class StockPicking(models.Model): _inherit = 'stock.picking' deliver = f
ields.Char(string="Deliver at")
rluch/InfoMine
infomine/comment.py
Python
mit
1,716
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module containing methods for comment preprocessing (cleaning) """ class Comment(object): """ Comment Entity. Besides getters and setters it handlers simple preprocessing methods """ def __init__(self, comment_string): self._comment = comme...
comment = value @property def author(self): r
eturn self._author @author.setter def author(self, value): self._author = value @property def gender(self): return self._gender @gender.setter def gender(self, value): self._gender = value @property def male_likes(self): return self._male_likes @m...
berkus/enso
enso/platform/win32/selection/HtmlClipboardFormat.py
Python
bsd-3-clause
9,263
0.014574
# Copyright (c) 2008, Humanized, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of ...
a special format for handling HTML. The basic problem that the special format is trying to solve is that the user can select an arbitrary chunk of formatted text that m
ight not be valid HTML. For instance selecting half-way through a bolded word would contain no </b> tag. The solution is to encase the fragment in a valid HTML document. You can read more about this at: http://msdn.microsoft.com/workshop/networking/clipboard/htmlclipboard.asp This module de...
rfguri/vimfiles
bundle/ycm/third_party/ycmd/third_party/JediHTTP/vendor/jedi/test/run.py
Python
mit
14,446
0.000692
#!/usr/bin/env python """ |jedi| is mostly being tested by what I would call "Blackbox Tests". These tests are just testing the interface and do input/output testing. This makes a lot of sense for |jedi|. Jedi supports so many different code structures, that it is just stupid to write 200'000 unittests in the manner of...
has a ``real`` property. Goto Definitions ++++++++++++++
++ Definition tests use the same symbols like completion tests. This is possible because the completion tests are defined with a list:: #? int() ab = 3; ab Goto Assignments ++++++++++++++++ Tests look like this:: abc = 1 #! ['abc=1'] abc Additionally it is possible to add a number which descri...
bozzzzo/quark
quarkc/test/test_parse.py
Python
apache-2.0
1,856
0.003233
# Copyright 2015 datawire. 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 agr...
import assert_file, maybe_xfail, is_excluded_file directory = os.path.join(os.path.dirname(__file__), "parse") files = [name for name in os.listdir(directory
) if name.endswith(".q")] paths = [os.path.join(directory, name) for name in files] @pytest.fixture(params=paths) def path(request): return request.param def test_parse(path): parse(path, is_excluded_file) def test_parse_builtin(): parse(os.path.join(directory, "empty-file.q"), lambda x: False) def pars...
precompiler/python-101
learning-python/ch03/ConditionalProgramming.py
Python
apache-2.0
413
0.002421
income = 15000 if income < 10000: taxCoefficient = 0.0 elif income < 30000: taxCoefficient = 0.2 elif income < 100000: taxCoefficient = 0.35 else: taxCoefficient = 0.45 print("Need to pay: "
, income * taxCoefficient, "in taxes") flag = False if flag: print("a") print("b") if fl
ag: print("c") print("d") orderAmount = 300 discount = 25 if orderAmount > 100 else 0 print(discount)
elizabethtweedale/HowToCode2
SuperSkill-08-Teacher/Teacher-Quiz.py
Python
gpl-3.0
3,594
0.010295
# Teacher Quiz - Python Code - Elizabeth Tweedale import csv, random def askName(): # askName function returns the name of the student print("Welcome to the Super Python Quiz!") yourName = input("What is your name? ") print ("Hello",str(yourName...
e questions to with open("SuperPythonQuiz.csv", mode="r", encoding="utf-8") as myFile: myQuiz = csv.reader(myFile) for row in myQuiz: questions.append(row) return questions def askQuestion(question,score):
# askQuestion prints the question and choices to the screen then checks the answer print(question[0]) # print the question - this is in the [0] position of the row for eachChoice in question[1:-1]: # print each choice ...
plotly/plotly.py
packages/python/plotly/plotly/graph_objs/scatter3d/marker/_line.py
Python
mit
24,077
0.000955
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Line(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "scatter3d.marker" _path_str = "scatter3d.marker.line" _valid_props = { "autocolorscale...
burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ...
egbertbouman/tribler-g
Tribler/Core/CacheDB/MetadataDBHandler.py
Python
lgpl-2.1
40,875
0.013187
# Written by Andrea Reale # see LICENSE.txt for license information from Tribler.Core.Subtitles.MetadataDomainObjects.SubtitleInfo import SubtitleInfo from Tribler.Core.Subtitles.MetadataDomainObjects.MetadataDTO import MetadataDTO from Tribler.Core.CacheDB.SqliteCacheDBHandler import BasicDBHandler import threading f...
" + SH_MD_FK_KEY + " IN " \ + "( SELECT + " + MD_ID_KEY+ " FROM " \ + METADATA_TABLE + " WHERE + "\ + MD_PUBLISHER_KEY + " = ?"\ + " AND " + MD_INFOHASH_KEY + " = ? );", "CLEANUP OLD HAVE": "DELETE FROM " + SUBTITLES_HAVE_TABLE \ ...
SH_PEER_ID_KEY + " NOT IN " \ + "( SELECT md." + MD_PUBLISHER_KEY + " FROM " \ + METADATA_TABLE + " AS md W
joeirimpan/trytond-invoice-payment-gateway
tests/__init__.py
Python
bsd-3-clause
414
0.002415
# -*- coding: utf-8 -*- import unittest import trytond.tests.test_tryton from test_invoice import TestInvoice def suite(): """ Define suite """ test_suite = trytond.tests.test_tryton.suite() test_suite.addTests([ unittest.TestLoader().loa
dTestsFromTestCase(TestInvoice), ]) return
test_suite if __name__ == '__main__': unittest.TextTestRunner(verbosity=2).run(suite())
bazz-erp/erpnext
erpnext/controllers/accounts_controller.py
Python
gpl-3.0
30,488
0.024829
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, erpnext from frappe import _, throw from frappe.utils import today, flt, cint, fmt_mone
y, formatdate, getdate from erpnext.setup.utils import get_exchange_rate from erpnext.accounts.utils import get_fiscal_years, validate_fiscal_year, get_account_currency from erpnext.utilities.transaction_base import TransactionBase from erpnext.contr
ollers.recurring_document import convert_to_recurring, validate_recurring_document from erpnext.controllers.sales_and_purchase_return import validate_return from erpnext.accounts.party import get_party_account_currency, validate_party_frozen_disabled from erpnext.exceptions import InvalidCurrency force_item_fields = (...
USGSDenverPychron/pychron
pychron/updater/branch_view.py
Python
apache-2.0
2,723
0.002571
# # =============================================================================== # # Copyright 2015 Jake Ross # # # # 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.apa...
kind='livemodal', # buttons=['OK', 'Cancel']) # return v # # # class ManageBran
chView(Controller): # def traits_view(self): # v = View( # VGroup( # VGroup(HGroup(UItem('branch', editor=EnumEditor(name='all_branches')), # # icon_button_editor('build_button', 'bricks', # # tooltip=...
Transkribus/TranskribusDU
TranskribusDU/util/geoTools.py
Python
bsd-3-clause
2,557
0.030504
from rtree import index import numpy as np #from shapely.prepared import prep import shapely def polygon2points(p): """ convert a polygon to a sequence of points for DS documents :param p: shapely.geometry.Polygon returns a string representing the set of points """ return ",".join(l...
union :param z1: polygon :param z2: polygon returns z1.intersection(z2) / z1.union(z2) """ assert z1.isvalid assert z2.isvalid return z1.intersection(z2) / z1.union(z2) def populateGeo(lZones:list(),lElements:list()): """ affect lElements i to lZones usi...
dPopulated = {} for pos, z in enumerate(lZones): # lIndElements.insert(pos, cell.toPolygon().bounds) # print (cell,cell.is_valid,cell.bounds) lIndElements.insert(pos, z.bounds) aIntersection = np.zeros((len(lElements),len(lZones)),dtype=float) for j,elt in enumerate(lElements): ...
miceno/django-categories
categories/tests/test_admin.py
Python
apache-2.0
1,919
0.001563
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import Client, TestCase from categories.models import Category class TestCategoryAdmin(Tes
tCase): def setUp(self): self.client = Client() def test_adding_parent_and_child(self): User.objects.create_superuser('testuser', 'testuser@example.com', 'password') self.client.login(username='testuser', password='password') url = reverse('admin:categories_category_add') ...
'alternate_title': '', 'alternate_url': '', 'description': '', 'meta_keywords': '', 'meta_extra': '', 'order': 0, 'slug': 'parent', '_save': '_save', } resp = self.client.post(url, data=data) self.asser...
novafloss/django-anysign
django_anysign/backend.py
Python
bsd-3-clause
5,255
0
"""Base material for signature backends.""" from django.urls import reverse class SignatureBackend(object): """Encapsulate signature workflow and integration with vendor backend. Here is a typical workflow: * :class:`~django_anysign.models.SignatureType` instance is created. It encapsulates the ba...
n case the backend does not support "signer view" feature. Default implementation returns ``anysign:signer``.
""" return '{ns}:signer'.format(ns=self.url_namespace) def get_signer_return_url(self, signer): """Return absolute URL where signer is redirected after signing. The URL must be **absolute** because it is typically used by external signature service: the signer uses external ...
cisco-openstack/tempest
tools/generate-tempest-plugins-list.py
Python
apache-2.0
4,796
0
#! /usr/bin/env python # Copyright 2016 Hewlett Packard Enterprise 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...
list)) # We have tempest plugins not only in 'openstack/' n
amespace but also the # other name spaces such as 'airship/', 'x/', etc. # So, we print all of them here. for project in found_plugins: print(project)
lessthanoptimal/PyBoof
examples/scene_recognition.py
Python
apache-2.0
2,120
0.00283
#!/usr/bin/env python3 import glob import numpy as np import pyboof as pb # Scene recognition is defined here as the problem where you wish to find multiple views of the same scene # In this example we will load a set of images that has sets of 3 related images. We will tell it to find the 5 # most similar images so ...
"error"])) # Display the results image_list = [(query_image, "Query")] for m in found_matche
s: image_list.append((pb.load_planar(m["id"], np.uint8), m["id"])) pb.swing.show_list(image_list, title="Query Results") input("Press any key to exit")
HimmelStein/lg-flask
models.py
Python
mit
578
0.00173
from app import db from sqlalchemy.dialects.postgresql import JSON class ChBible(db.Mo
del): __tablename__ = 'chbible' id = db.Column(db.Integer, primary_key=True) bbid = db.Column(db.String()) snt = db.Column(db.String()) snt_lg = db.Column(db.String()) snt_sdg = db.Column(db.String(
)) def __init__(self, bbid, snt, snt_lg, snt_sdg): self.url = bbid self.snt = snt self.snt_lg = snt_lg self.snt_sdg = snt_sdg def __repr__(self): return '<id {0}> <{1}> {2}\n'.format(self.id, self.bbid, self.snt)
sharkspeed/dororis
packages/python/flask/flask-dog-book/7-chapter/app/main/__init__.py
Python
bsd-2-clause
143
0.006993
#!/usr/bin/env pytho
n # -*- coding: utf-8 -*- from flask import Blueprint main = Blueprint('main', __name__) from . import views, erro
rs
BurtBiel/autorest
AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/setup.py
Python
mit
1,161
0
# coding=utf
-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause in...
uptools import setup, find_packages NAME = "autorestresourceflatteningtestservice" VERSION = "1.0.0" # To install the library, run the following # # python setup.py install # # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, ...
seewindcn/tortoisehg
src/tortoisehg/util/hgversion.py
Python
gpl-2.0
1,003
0.000997
# hgversion.py - Version information for Mercurial # # Copyright 2009 Steve Borho <steve@borho.org> # # This software may b
e used and distributed according to the terms of the # GNU General Public Licen
se version 2, incorporated herein by reference. import re try: # post 1.1.2 from mercurial import util hgversion = util.version() except AttributeError: # <= 1.1.2 from mercurial import version hgversion = version.get_version() testedwith = '3.6 3.7' def checkhgversion(v): """range check...
F483/bikesurf.org
apps/account/urls.py
Python
mit
928
0.017241
# -*- coding: utf-8 -*- # Copyright (c) 2012 Fabian Barkhau <fabian.barkhau@gmail.com> # License: MIT (see LICENSE.TXT file) from django.conf.urls import patterns, include, url from apps.common.urls import arg_id, arg_slug, arg_username L = arg_id(
"link_id") U = arg_username("username") urlpatterns = patterns("apps.account.views", url(r"^account/profile$", "profile"), url(r"^account/view/%s$" % U, "view"), url(r"^account/set_passport$", "set_passport", { "wizard" : False }), url(r"^account/edit$",
"edit", { "wizard" : False }), url(r"^account/link/create$", "link_create"), url(r"^account/link/delete/%s$" % L, "link_delete"), # this url because allauth url(r"^accounts/profile/$", "edit", { "wizard" : True }), url(r"^account/wiz/passport", "set_passport"...
smitchell556/cuttle
cuttle/__init__.py
Python
mit
137
0
#
-*- coding: utf-8 -*- """ Cuttle, the simple, extendable ORM. :license: MIT, see LICENSE for details. """ __versi
on__ = '0.9.0.dev'
release-monitoring/anitya
anitya/tests/lib/backends/test_npmjs.py
Python
gpl-2.0
9,246
0.000108
# -*- coding: utf-8 -*- # # Copyright © 2014-2019 Red Hat, Inc. # # This copyrighted materi
al is made available to anyone wishing to use, # modify, copy, or redistribute it subje
ct to the terms and conditions # of the GNU General Public License v.2, or (at your option) any later # version. This program is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY expressed or implied, including the # implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. ...
telefonicaid/fiware-cosmos-ambari
ambari-agent/src/main/python/ambari_agent/UpgradeExecutor.py
Python
apache-2.0
6,975
0.013333
#!/usr/bin/env python2.6 ''' 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 "Licens...
_major_ver, stack_minor_ver else: return None def execute_dir(self, command, basedir, dir, tmpout, tmperr): """ Executes *.py and *.pp files locat
ed in a given directory. Files a executed in a numeric sorting order. """ dirpath = os.path.join(basedir, dir) logger.info("Executing %s" % dirpath) if not os.path.isdir(dirpath): warnstr = "Script directory %s does not exist, skipping" % dirpath logger.warn(warnstr) result = { ...
bukosabino/btctrading
settings.py
Python
mit
422
0.004739
from datetime import date NTESTS = 1 PREV_DAYS = 10 PERCENT_UP = 0.01 PERCEN
T_DOWN = 0.01 PERIOD = 'Hourly' # [5-min, 15-min, 30-min, Hourly, 2-hour, 6-hour, 12-hour, Daily, Weekly] MARKET = 'bitstampUSD' # DATE START YEAR_START = 2011 MONTH_START = 9 DAY_START = 13 DATE_START = date(YEAR_START, MONTH_START, DAY_START) # DATE END DATE_END = date
.today() URL_DATA_BASE = 'http://bitcoincharts.com/charts/chart.json?'
yandex/mastermind
src/cocaine-app/sync/kazoo_impl/__init__.py
Python
gpl-2.0
8,087
0.002844
from contextlib import contextmanager import logging import os.path import traceback from kazoo.client import KazooClient from kazoo.exceptions import ( LockTimeout, NodeExistsError, NoNodeError, KazooException, ZookeeperError, ) from kazoo.retry import KazooRetry, RetryFailedError from mastermind....
ed_locks = [] result = tr.commit() for i, res in
enumerate(result): if isinstance(res, ZookeeperError): failed = True if isinstance(res, NodeExistsError): failed_locks.append(locks[i]) if failed_locks: holders = [] for f in failed_locks: # TODO: fetch all holders ...
Bakterija/mmplayer
mmplayer/kivy_soil/terminal_widget/plugins/_base.py
Python
mit
4,885
0
class PluginBase(object): name = '' doc = 'doc about this class' methods_subclass = {} def __init__(self, **kwargs): self.methods = { 'help': 'doc about help method', 'get_methods': 'doc about get_methods method' } self.methods.update(self.methods_subclas...
if b == -1 and c == -1: yes = True else: start = b if c != -1 and c < b: start = c a = x[:start].find('=') if a !=
-1: yes = True if yes: kwargs_found[x[:a]] = x[a+1:] remlist.append(i) for x in reversed(remlist): del args_found[x] return args_found, kwargs_found @staticmethod def get_from_locals_globals(term_system...
google-research/kubric
examples/shapenet.py
Python
apache-2.0
3,800
0.002368
# Copyright 2022 The Kubric Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
correct path.") # --- CLI arguments parser = kb.ArgumentParser() parser.set_defaults( frame_end=5, resolution=(512, 512), ) FLAGS = parser.parse_args() # --- Common setups & resources scene, rng, output_dir, scratch_dir = kb.setup(FLAGS) renderer = Blender(scene, scratch_dir, samples_per_p...
evr-like lights to the scene scene += kb.assets.utils.get_clevr_lights(rng=rng) scene.ambient_illumination = kb.Color(0.05, 0.05, 0.05) # --- Add shadow-catcher floor floor = kb.Cube(name="floor", scale=(100, 100, 1), position=(0, 0, -1)) scene += floor # Make the floor transparent except for catching shadows # Togeth...