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
moment-of-peace/EventForecast
association_rule/event_frequent.py
Python
lgpl-3.0
1,535
0.001954
import os,
sys origin_dir = 'del_201304now/' new_dir = 'freq_event_state/' files = os.listdir(origin_dir) state_dir = {} country_dir = {} for file in files: with open(origin_dir + file) as f: event_dir = {} for line in f: tmp_content = line.split('\t') code = tmp_content[4] ...
ength == 3: state = tmp_loc[1] elif length == 2: state = tmp_loc[0] else: continue country = tmp_loc[length-1] if country not in country_dir: country_dir[country] = {} if state in country_dir[coun...
whd/python_moztelemetry
tests/test_spark.py
Python
mpl-2.0
5,208
0.002304
# 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/. import json import os from string import Template from uuid import uuid4 import pytest from moztelemetry.store import I...
pytest.mark.slow @pytest.mark.parametrize('filter_name,exact,wrong,start,end', test_data_for_range_match) def test_get_pings_by_range(test_store, mock_message_parser, spark_context, filter_name, exact, wrong, start, end): upload_ping(test_store, 'value1', **{filter_name: exact}) uplo...
et_pings(spark_context, **{filter_name: (start, end)}) assert pings.collect() == ['value1'] @pytest.mark.slow def test_get_pings_multiple_by_range(test_store, mock_message_parser, spark_context): upload_ping(test_store, 'value1', **{f[0]: f[1] for f in test_data_for_range_match}) upload_ping(test_store, ...
jokedurnez/RequiredEffectSize
SampleSize/filter_fMRI_terms.py
Python
mit
831
0.01444
# check for specific mention of fMRI-related terms # to filter out non-fMRI papers def filter_fMRI_terms(pmids,fmri_terms=['fMRI','functional MRI', 'functional magnetic resonance'],usemesh=False): """ return pmids that include fMRI-related terms in MESH keywords or abstract or title"""...
s(): if 'Magnetic Resonance Imaging' in pmids[pmid]['MeshTerms']:
goodkey=1 for t in fmri_terms: if pmids[pmid]['Abstract'][0].find(t)>-1: goodkey=1 if pmids[pmid]['Title'].find(t)>-1: goodkey=1 if goodkey: good_pmids[pmid]=pmids[pmid] return good_pmids
alxgu/ansible
lib/ansible/modules/cloud/amazon/aws_ses_identity_policy.py
Python
gpl-3.0
7,303
0.00356
#!/usr/bin/python # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: aws_ses_identity_policy s...
"state") if state == 'present': create_or_update_identity_policy(connection, module) else: delete_ide
ntity_policy(connection, module) if __name__ == '__main__': main()
pedrolegold/uforge-cli
src/uforgecli/commands/subscription/subscription.py
Python
apache-2.0
29,418
0.007614
__author__ = "UShareSoft" from texttable import Texttable from ussclicore.argumentParser import ArgumentParser, ArgumentParserError from ussclicore.cmd import Cmd, CoreGlobal from uforgecli.utils import org_utils from ussclicore.utils import printer from ussclicore.utils import generics_utils from uforgecli.utils.ufor...
f.api.Orgs(org.dbId).Subscriptions().Getall(Search=None) subscriptions = generics_utils.order_list_object_by(subscrip
tions.subscriptionProfiles.subscriptionProfile, "name") if subscriptions is None or len(subscriptions) == 0: printer.out("There is no subscriptions in [" + org.name + "] ") return 0 printer.out("List of subsc...
droundy/deft
papers/histogram/figs/gamma-multi-plot.py
Python
gpl-2.0
2,481
0.009674
from __future__ import division import numpy as np import matplotlib.pyplot as plt import sys, glob, matplotlib import colors matplotlib.rcParams['text.usetex'] = True matplotlib.rc('font', family='serif') filename = sys.argv[1] plt.figure(figsize=(5, 4)) print('starting!') try: for wl in glob.glob("data/gamma/%s...
plt.ylim(ymin=1e-10, ymax=1e1) plt.xlim(xmin=1e0, xmax=2e12) #print(avg_gamma) #print(ts) colors.loglog(ts, avg_gamma, sadname) if data.shape[1] > 2: max_avg_gamma = data[:, 2] min_avg_gamma = data[
:, 3] plt.fill_between(ts, min_avg_gamma, max_avg_gamma, edgecolor='none', linewidth=0, color=colors.color('sad'), alpha=0.1, zorder=-51) except: raise def gamma_sa(t, t0): return t0/np.maximum(t, t0) t0s = ['1e3',...
kernelci/kernelci-backend
app/utils/build/__init__.py
Python
lgpl-2.1
12,705
0
# Copyright (C) Collabora Limited 2017,2019 # Author: Guillaume Tucker <[email protected]> # Author: dcz-collabora <[email protected]> # # Copyright (C) Linaro Limited 2015,2016,2017,2018,2019 # Author: Matt Hart <[email protected]> # Author: Milo Casagrande <milo.casagrande@linaro....
= job_id): job_doc.id = job_id to_update = T
rue if job_doc.status != status: job_doc.status = status to_update = True no_git = all([ not job_doc.git_url, not job_doc.git_commit, not job_doc.git_describe, not job_doc.git_describe_v ]) no_compiler = all([ not job_doc.compiler, not j...
dridk/antibiobank
antibiobank/wsgi.py
Python
gpl-3.0
397
0.002519
""" WSGI confi
g for antibiobank project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "antibiobank.settings") from django.core.wsgi im...
_wsgi_application application = get_wsgi_application()
tinkerinestudio/Tinkerine-Suite
TinkerineSuite/python/Lib/power/linux.py
Python
agpl-3.0
8,180
0.002445
# coding=utf-8 """ Implements PowerManagement functions using /sys/class/power_supply/* See doc/linux for platform-specific details. """ __author__ = '[email protected]' import os import warnings from power import common POWER_SUPPLY_PATH = '/sys/class/power_supply' if not os.access(POWER_SUPPLY_PATH, os.R_OK...
""" @param supply_path: Path to power supply @return: True if ac is online. Otherwise False
""" with open(os.path.join(supply_path, 'status'), 'r') as status_file: return status_file.readline().strip() == 'Discharging' @staticmethod def get_battery_state(supply_path): """ @param supply_path: Path to power supply @return: Tuple (energy_full, energy_...
trea-uy/djangocms-plugin-image-gallery
image_gallerys/cms_plugins.py
Python
apache-2.0
1,027
0.000974
# coding: utf-8 import
re from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from .models import * from django.utils.translation import ugettext as _ from django.contrib im
port admin from django.forms import ModelForm, ValidationError class GalleryForm(ModelForm): class Meta: model = Gallery def clean_domid(self): data = self.cleaned_data['domid'] if not re.match(r'^[a-zA-Z_]\w*$', data): raise ValidationError( _("The name mu...
unnikrishnankgs/va
venv/lib/python3.5/site-packages/tensorflow/models/object_detection/core/losses.py
Python
bsd-2-clause
23,854
0.002893
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
tedSmoothL1LocalizationL
oss(Loss): """Smooth L1 localization loss function. The smooth L1_loss is defined elementwise as .5 x^2 if |x|<1 and |x|-.5 otherwise, where x is the difference between predictions and target. See also Equation (3) in the Fast R-CNN paper by Ross Girshick (ICCV 2015) """ def __init__(self, anchorwise_out...
nzbget/nzbget
tests/functional/parcheck/parcheck_opt2_test.py
Python
gpl-2.0
1,204
0.017442
nzbget_options = ['ParCheck=manual', 'ParQuick=yes', 'PostStrategy=sequential'] def test_parchecker_healthy(nserv, nzbget): hist = nzbget.download_nzb('parchecker2.nzb') assert hist['Status'] == 'SUCCESS/HEALTH' def test_parchecker_repair(nserv, nzbget): nzb_content = nzbget.load_nzb('parchecker2.nzb') nzb_conten...
'Status'] == 'WARNING/DAMAGED' def test_parchecker_middle(nserv, nzbget): nzb_content = nzbget.load_nzb('parchecker2.nzb') nzb_content = nzb_content.replace('<segment bytes="3
000" number="16">parchecker2/testfile.7z.001?16=45000:3000</segment>', '') hist = nzbget.download_nzb('parchecker.middle.nzb', nzb_content) assert hist['Status'] == 'WARNING/DAMAGED' def test_parchecker_last(nserv, nzbget): nzb_content = nzbget.load_nzb('parchecker2.nzb') nzb_content = nzb_content.replace('<segmen...
moosd/HomeAutomation
main.py
Python
gpl-2.0
1,574
0.014612
#!/usr/bin/env python import time import os from plugins import * import CustomHandlers # Light switch #try: # CapSwitch.CapSwitch(SerialEnumeration.find("capbutton1")) #except: # pass try: # Telephony services rotdial = RotaryDial.RotaryDial(SerialEnumeration.find("rotarydial")) # Handle telephon...
est.setParameter("temp", 144) #time.sleep(5) #test.setStatus(1) #test2.setStatus(1) #print test.getParameters() #b = 100 #while b > 1: # test.setParameter("brightness", b) # b = b-1 # time.sleep(0.1) #test.setParameter("color", 1) #test.setParameter("brightness", 100) #TestHandler() #TestSensor() while Tr...
KeyboardInterrupt: print '^C received, shutting down' os._exit(0)
jni/useful-histories
maree-faux-data.py
Python
bsd-3-clause
2,032
0.004429
# IPython log file with open('request.txt', mode='r') as fin: wells = [line.strip() for line in fin] wells plates = ['_'.join(well.split('_')[:2]) for well in wells] plates set.intersection(plates, os.listdir('/Volumes/King-Ecad-Screen-Tiffs2/tiffs/')) set.intersection(set(plates), set(os.listdir('/Volumes/K...
ic('pinfo', 'shutil.copyfile') len(plates) == len(set(plates)) for well in wells: plate = '_'.join(well.split('_')[:2]) if plate in avail: files = sorted(glob(os.path.join(hd
d, plate, well + '*'))) for file in files: shutil.copyfile(file, '.') print(f'copied: {os.path.basename(file)}') for well in wells: plate = '_'.join(well.split('_')[:2]) if plate in avail: files = sorted(glob(os.path.join(hdd, plate, well + '*'))) for...
marlboromoo/basinboa
basinboa/user/role.py
Python
mit
87
0.011494
#!/usr/
bin/env python """ role of player """ ROLE_ADMIN = 'admin' ROLE_USER = 'user'
FJFranklin/wifi-py-rpi-car-controller
noise/Noise/Visible.py
Python
mit
4,546
0.007259
import numpy as np from .Basis import Basis class Visible(object): def __init__(self, origin, window, target=None): self.origin = origin self.window = window self.target = target def crop_visible(self, visible): cropped_poly = self.window.crop_2D_poly(visible.window) ...
e = True for i in range(0, visible.window.count): dp = np.dot(visible.window.verts[i,:] - self.window.verts[s1,:], Bj) if Basis.is_strictly_positive(dp): all_outside = False if Basis.is_strictly_negative(dp): is_interior...
is_interior = False break v3D, count = visible.target.vertices() xy_o, z_o = self.target.plane.project(self.origin) for i in range(0, count): xy_i, z_i = self.target.plane.project(v3D[i,:]) zoi = z_o * z_i if printing: ...
jeremiah-c-leary/vhdl-style-guide
vsg/token/protected_type_declaration.py
Python
gpl-3.0
858
0
from vsg import parser class protected_keyword(parser.keyword): ''' unique_id = protected_type_declaration : protected_keyword ''' def __init__(self, sString): parser.keyword.__init__(self, sString) class end_keyword(parser.keyword): ''' unique_id = protected_type_declaration : end...
class protected_type_simple_name(parser.simple_name): ''' unique_id = protected_type_declaration : protected_type_simple_name ''' def __init__(self, sStri
ng): parser.simple_name.__init__(self, sString)
sakset/getyourdata
getyourdata/organization/tests.py
Python
mit
28,360
0.000388
from django.test import TestCase from django.contrib.auth.models import Permission, User from django.core.urlresolvers import reverse from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from getyourdata.te...
message=user_message, rating=user_rating ) @isDjangoTest() class OrganizationCreat
ionTests(TestCase): def setUp(self): self.auth_field1 = AuthenticationField.objects.create( name="some_number", title='Some number') def test_organization_with_valid_email_address_can_be_added(self): response = self.client.post( reverse("organization:new_orga...
airpoint/script.gb.wiz
downloader.py
Python
gpl-2.0
618
0.02589
import xbmcgui import urllib def download(url, dest, dp = None): if not dp: dp = xbmcgui.DialogProgress() dp.create("Elmore...Maintenance","Downloading & Copying File",' ', ' ') dp.update(0) urllib.urlretrieve(url,dest,lambda nb, bs, fs, url=url: _pbhook(nb,bs,fs,url,dp)) def _p...
rcent = min((numblocks*blocksize*100)/filesize, 100) dp.update(percent) except: percent = 100
dp.update(percent) if dp.iscanceled(): raise Exception("Canceled") dp.close()
coll-gate/collgate
server/accession/fixtures/sequences.py
Python
mit
661
0.00607
# -*- coding: utf-8; -*- # # @file sequences # @brief collgate # @author Frédéric SCHERMA (INRA UMR1095) # @date 2018-01-09 # @copyright Copyright (c) 2018 INRA/CIRAD # @license MIT (see LICEN
SE file) # @details def fixture(fixture_manager, factory_manager): acc_seq = "CREATE SEQUENCE IF NOT EXISTS accession_naming_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1;" bat_seq = "CREATE SEQUENCE IF NOT EXISTS batch_naming_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1...
ecute(acc_seq) cursor.execute(bat_seq)
stollcri/Research-Matrices
pgm/svd-pgm-avg.py
Python
mit
8,300
0.032289
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import argparse import numpy import math class Image: def __init__(self, matrix=[[]], width=0, height=0, depth=0): self.matrix = matrix self.width = width self.height = height self.depth = depth def set_width_and_height(self, width, height): self.w...
olumns which are all black become all white for x in xrange
(0, image.width): colnull = True for y in xrange(0, image.height): if int(image.matrix[y][x]) != 0: colnull = False if colnull: for y in xrange(0, image.height): image.matrix[y][x] = image.depth return image def process_svd(source_file_a, source_file_b, destination_file, kmin, kmax, rescale, co...
anushbmx/kitsune
kitsune/access/templatetags/jinja_helpers.py
Python
bsd-3-clause
786
0
import jinja2 from django_jinja import library from kitsune.access import utils as access @jinja2.contextfunction @library.global_function def has_perm(context, perm, obj): """ Check if the user has a permission on a specific object. Returns boolean. """ return access.has_perm(context['request']...
rship is determined by comparing perm_obj.field_name to the user in context. """
user = context['request'].user if user.is_anonymous(): return False return access.has_perm_or_owns(user, perm, obj, perm_obj, field_name)
hhstore/flask-annotated
sanic/sanic-0.1.9/sanic/__init__.py
Python
mit
116
0
from
.sanic import Sanic from .blueprints import Blueprint __version__ = '0.1
.9' __all__ = ['Sanic', 'Blueprint']
Phononic/Sean_Lubner_250HWs
hw10/hw10.py
Python
mit
8,297
0.013619
import os import sqlite3 from flask import Flask, render_template, request, url_for, redirect, send_from_directory from flask.ext.sqlalchemy import SQLAlchemy from werkzeug import secure_filename from pybtex.database.input import bibtex from string import punctuation, whitespace app = Flask(__name__) app.config['SQLAL...
ALLOWED_EXTENSIONS def is_bibtex(filename): """ returns True if the file is a bibtex file """ return filename.rsplit('.', 1)[1].lower() == 'bib' def parse_bibtex(bib_file_path_local, col_name): """ Parses a .bib file """ parser = bibtex.P
arser() bib_data = parser.parse_file(bib_file_path_local) def author2str(author): """ formats a Pybtex Person object into a string represntation """ return author.last()[0].strip('{}') + ", " + " ".join(author.bibtex_first()) gunk = punctuation + whitespace for tag, entry in bib_data.ent...
bllli/tsxyAssistant
app/templates/translate.py
Python
gpl-3.0
1,644
0.000717
# coding=utf-8 """html to jinja2首席挖洞官 将本目录/子目录下的html文件中使用到的 *静态文件* 的URL改为使用jinja2 + flask url_for渲染 href="css/base.css" -> href="{{ url_for("static", filename="css/base.css") }}" 挖洞前会在文件同目录做一个.bak后缀名的备份文件。 Usage: $ cd my_project $ python2 translate.py """ from __future__ import print_function import re im...
(filename): """备份 数据无价 谨慎操作 :type filename: str 文件名 """ if os.path.exists(filename + ".bak"): return # 如果已有备份文件 则不再重复生成备份文件 if os.path.isfile(filename): shutil.copy(filename, filename + ".bak") def rollback(): """回滚
暂时用不到 先不写了 """ pass def translate(filename): with open(filename, 'r+') as f: replaced = re.sub(r'(href|src)="(css|img|font|js)/(.*?)"', r'\g<1>="{{ url_for("static", filename="\g<2>/\g<3>") }}"', f.read()) f.seek(0) f.write(replaced) if __name__ == '_...
shaunstanislaus/sshuttle
src/firewall.py
Python
lgpl-2.1
29,513
0.002101
import errno import socket import select import signal import struct import compat.ssubprocess as ssubprocess import ssyslog import sys import os import re from helpers import log, debug1, debug3, islocal, Fatal, family_to_string, \ resolvconf_nameservers from fcntl import ioctl from ctypes import c_char, c_uint8, ...
ress family "%s" unsu
pported by tproxy method' % family_to_string(family)) table = "mangle" def ipt(*args): return _ipt(family, table, *args) def ipt_ttl(*args): return _ipt_ttl(family, table, *args) mark_chain = 'sshuttle-m-%s' % port tproxy_chain = 'sshuttle-t-%s' % port divert_chai...
ToonTownInfiniteRepo/ToontownInfinite
toontown/cogdominium/CogdoCraneGameSpec.py
Python
mit
1,302
0.004608
from toontown.co
ghq.SpecImports import * GlobalEntities = {1000: {'type': 'levelMgr', 'name': 'LevelMgr', 'comment': '', 'parentEntId': 0, 'modelFilename': 'phase_10/models/cogHQ/EndVault.bam'}, 1001: {'type': 'editMgr', 'name': 'EditMgr', 'parentEntId': 0, 'insertEntity': None,...
'removeEntity': None, 'requestNewEntity': None, 'requestSave': None}, 0: {'type': 'zone', 'name': 'UberZone', 'comment': '', 'parentEntId': 0, 'scale': 1, 'description': '', 'visibility': []}, 10001: {'type': 'cogdoCraneCogSettings', 'name': '<unnamed>', ...
cheral/orange3-text
orangecontrib/text/tests/test_newspaper.py
Python
bsd-2-clause
1,311
0.009916
import unittest import os import csv from orangecontrib.text.scraper import _get_info from unittest.mock import patch from contextlib import contextmanager import tempfile class MockUrlOpen: def __init__(self, filepath): self.data = [] with open(filepath, 'r') as f: reader=csv.reader(f...
self.url=row[4] try: next(f) except StopIteration: # Last empty line is sometimes missing pass def __call__(self, url): @contextmanager def cm(): yield self return cm() filename='article_c...
ch('urllib.request.urlopen', mock_urllib) class NewspaperTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.NamedTemporaryFile(delete=False) os.remove(self.tmp.name) self.cache_path = self.tmp.name def test_get_info(self): #checks whether article, title, date, author, url ...
glumu/django-redis-cluster
django_redis_cluster/__init__.py
Python
bsd-3-clause
425
0.011765
#coding:utf8 from django.core.cache import caches def get_cache(alias): return caches[alias] def get_redis_connection(alias='default', write=True): """ Helper used for obtain a
raw redis client. """ cache = get_cache(alias) if not hasattr(cache.client, 'get_client'): raise NotImplementedError("This backend does not supports this feature") return
cache.client.get_client(write)
werebus/dotfiles
bin/shorten_path.py
Python
mit
772
0.006477
#!/usr/bin/env python import sys import os import re try: path = sys.argv[1] length = int(sys.argv[2]) except: print >>sys.stderr, "Usage: $0 <path> <length>" sys.exit(1) path = re.sub(os.getenv('HOME'), '~', path) while len(path) > length: dirs = path.split("/"); # Find the longest directo...
h = 3 for i in range(len(dirs) - 1): if len(dirs[i]) > max
_length: max_index = i max_length = len(dirs[i]) # Shorten it by one character. if max_index >= 0: dirs[max_index] = dirs[max_index][:max_length-3] + ".." path = "/".join(dirs) # Didn't find anything to shorten. This is as good as it gets. else: break ...
matt77hias/Clipping
src/surfacearea.py
Python
gpl-3.0
2,427
0.005356
import numpy as np ############################################################################### ## Surface Area ## --------------------------------- ## Planar polygon ############################################################################### # Theorem of Green #------------------------------------------------...
p_v1 = p_vs[(j+nb_p_vs-1) % nb_p_vs] p
_v2 = p_vs[j] p_v3 = p_vs[(j+nb_p_vs+1) % nb_p_vs] area += p_v2[0] * (p_v3[1] - p_v1[1]) return 0.5 * abs(area) def _area3D(p_vs, n): area = 0.0 nb_p_vs = len(p_vs) ax = abs(n[0]) ay = abs(n[1]) az = abs(n[2]) if (ax > ay and ax > az): lca = 0 elif (ay > az): lca = 1 ...
mprinc/FeelTheSound
src/PoC/fft.py
Python
cc0-1.0
4,053
0.033062
#!/usr/bin/env python # 8 band Audio equaliser from wav file # import alsaaudio as aa # import smbus from struct import unpack import numpy as np import wave from time import sleep import sys ADDR = 0x20 #The I2C address of MCP23017 DIRA = 0x00 #PortA I/O direction, by pin. 0=output, 1=input DIR...
en('test_stereo_16000Hz_16bit_PCM.wav','r') #wavfile = wave.open('Media-Convert_test5_PCM_Stereo_VBR_8SS_44100Hz.wav','r') wavfile = wave.open('Media-Convert_test2_PCM_Mono_VBR_8SS_48000Hz.wav','r') sample_rate = wavfile.getframerate() no_channels = wavfile.getnchannels() chunk = 4096 # Use a multiple of 8 # out...
# Return power array index corresponding to a particular frequency def piff(val): return int(2*chunk*val/sample_rate) def print_intensity(matrix): levelFull = "||||||||"; levelEmpty = " "; levelStr = ""; for level in matrix: #level = 0; levelStr += levelFull[0: level] + levelEmpty [0...
ypflll/wiringX
python/examples/blink.py
Python
gpl-3.0
1,039
0.013474
#!/usr/bin/env python # Copyright (c) 2014 CurlyMo <[email protected]> # 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...
Y WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import s...
etup(); gpio.pinMode(gpio.PIN0, gpio.OUTPUT); print gpio.platform(); print gpio.I2CRead(0x10); try: while True: gpio.digitalWrite(gpio.PIN0, gpio.LOW); sleep(1); gpio.digitalWrite(gpio.PIN0, gpio.HIGH); sleep(1); except KeyboardInterrupt: pass
Fillll/reddit2telegram
reddit2telegram/channels/~inactive/r_haikuos/app.py
Python
mit
137
0.007299
#encodi
ng:utf-8 subreddit = 'haikuOS' t_channel = '@r_haikuos' def send_post(submission, r2t): return r2t.send_simple(submission)
caisq/tensorflow
tensorflow/contrib/autograph/pyct/static_analysis/cfg.py
Python
apache-2.0
15,704
0.005349
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
s
cfg_node.prev.add(head) self.current_leaves = [cfg_node] def build_cfg(self, node): """Build a CFG for a function. Implementation of building a CFG for dataflow analysis. See, e.g.: https://www.seas.harvard.edu/courses/cs252/2011sp/slides/Lec02-Dataflow.pdf Args: node: A function def...
delete/estofadora
estofadora/core/forms.py
Python
mit
1,354
0.00074
# conding: utf-8 from django import forms from .models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name', 'email', 'telephone', 'subject', 'description'] def clean(self): cleaned_data = super(ContactForm, self).clean() email = c...
s.update( {'class': 'form-control', 'placeholder': 'Nome completo'} ) self.fields['email'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Seu email'} )
self.fields['telephone'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Seu telefone com DDD'} ) self.fields['subject'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Assunto da mensagem'} ) self.fields['description'].widget.attrs....
Molecular-Image-Recognition/Molecular-Image-Recognition
code/rmgpy/quantity.py
Python
mit
30,455
0.005845
#!/usr/bin/env python # encoding: utf-8 ################################################################################ # # RMG - Reaction Mechanism Generator # # Copyright (c) 2002-2017 Prof. William H. Green ([email protected]), # Prof. Richard H. West ([email protected]) and the RMG Team ([email protected]) # # ...
: """ Return the conversion factor for converting a quantity to a given set of `units` from the SI equivalent units. """ return 1.0 / self.getConversionFactorToSI() ################################################################################ class ScalarQuantity(Units): ...
al quantity, with optional units and uncertainty information. The attributes are: =================== ======================================================== Attribute Description =================== ======================================================== `value` The numeric...
jgcobb3/growth-yield-batch
scripts/blm/climate_suitability/get_species_climate_combos.py
Python
bsd-3-clause
1,011
0.004946
#!/bin/python import sqlite3 import climquery if __name__ == "__main__": # RCPS = ['rcp45', 'rcp60', 'rcp85'] RCPS = ['rcp45', '
rcp85'] # CLIMATES = ['CCSM4', 'Ensemble', 'GFDLCM3', 'HadGEM2ES'] CLIMATES = ['Ensemble'] # YEARS = ['1990', '2030',
'2060', '2090'] YEARS = ['1990', '2060'] con = sqlite3.connect('/usr/local/apps/OR_Climate_Grid/Data/orclimgrid.sqlite') cur = con.cursor() table_query = """PRAGMA table_info(climattrs);""" cur.execute(table_query) result = cur.fetchall() species = [] for col in result: if co...
vitorfs/cmdbox
cmdbox/snippets/migrations/0004_auto_20160331_0959.py
Python
mit
592
0.001689
# -*- coding: utf-8 -*- # G
enerated by Django 1.9.4 on 2016-03-31 09:59 from __future__ import unicode_literals from django.db import m
igrations, models class Migration(migrations.Migration): dependencies = [ ('snippets', '0003_auto_20160331_0952'), ] operations = [ migrations.AlterField( model_name='snippet', name='description', field=models.TextField(blank=True, help_text='Give a br...
Hemisphere-Project/HPlayer2
profiles/_legacy/gadagne.py
Python
gpl-3.0
696
0
from core.engine import hplayer # PLAYER player = hplayer.addplayer('mpv', 'gadagne') # Interfaces player.addInterface('osc', 4000, 4001) player.addInterface('htt
p', 8080) # player.addInterface('gpio', [16,19,20,21,26]) # GADAGNE logic defaultFile = 'media0.mp4' push1File = 'media1.mp4' push2File = 'media2.mp4' push3File = 'media3.mp4' # Loop default file player.on('end', lambda: player.play(defaultFile)) # HTTP + GPIO events player.on(['push1', 'gpio20'], lambda: player.pla...
player.play(push3File)) fails = 5 # RUN hplayer.setBasePath("/home/pi/Videos/") hplayer.run()
heltonbiker/MapComplete
PyQt/SlippyMapOriginal.py
Python
mit
8,532
0.003868
#!/usr/bin/env python import sip sip.setapi('QVariant', 2) import math from PyQt4 import QtCore, QtGui, QtNetwork from lib.Point import Point from lib.tileOperations import * TDIM = 256 class LightMaps(QtGui.QWidget): def __init__(self, parent = None): super(LightMaps, self).__init__(parent) ...
lf.invalidate(); ############################ class TileDownloader(QtNetwork.QNetworkAccessManager): updated
= QtCore.pyqtSignal(QtCore.QRect) def __init__(self, parent=None): super(TileDownloader, self).__init__() self.parent = parent cache = QtNetwork.QNetworkDiskCache() cache.setCacheDirectory( QtGui.QDesktopServices.storageLocation (QtGui.QDesktopServices...
xguse/pyrad
pyrad/createfile.py
Python
gpl-3.0
3,821
0.011515
#!/usr/bin/env python2 import sys def main(version): output = """ ==** parameter inputs for pyRAD version %s **======================== affected step == ./ ## 1. Working directory (all) ./*.fastq.gz ## 2. Loc. of non-demultiplexed files (if not ...
mples in a final locus (s7) 3 ## 13. MaxSH: max inds with shared hetero site (s7) c88d6m4p3 ## 14. Prefix name for final output (no spaces) (s7) ==== optional params below this line ==========================
========= affected step == ## 15.opt.: select subset (prefix* only selector) (s2-s7) ## 16.opt.: add-on (outgroup) taxa (list or prefix*) (s6,s7) ## 17.opt.: exclude taxa (list or prefix*) (s7) ...
xinghalo/DMInAction
src/spider/BrandSpider/brand1.py
Python
apache-2.0
2,854
0.044697
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib import urllib2 import re import json class Spider: def __init__(self): self.url = 'http://brand.efu.com.cn/' self.user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36' self.h...
tr(line[0]) print output f.write(output) f.write("\n") break f.close() def resolveBrandContext(self,content): # [\s\S]+? try: pattern = re.compile('.*?<span class="sp-a">(.*?)</span>.*?<span class="sp-b">(.*?)</span>.*?') return re.findall(pattern,content) except: # ...
li><a title="(.*?)" href="(.*?)">.*?</a></li>.*?') return re.findall(pattern,content) except: # print '忽略解析首页出错问题' return [] def resolvePageContent(self,content,category): # pattern = re.compile('.*?<div class="lstPhotob"><div class="lstPa"><div class="lstPa-a"><a href="(.*?)" target="_blank" title="(.*...
brain-tec/server-tools
datetime_formatter/tests/test_best_matcher.py
Python
agpl-3.0
2,584
0
#
Copyright 2015, 2017 Jairo Llopis <[email protected]> # Copyright 2016 Tecnativa, S.L. - Vicent Cubells # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase from odoo.exceptions import UserError class BasicCase(TransactionCase): def setUp(self...
.setUp() self.langs = ("en_US", "es_ES", "it_IT", "pt_PT", "zh_CN") self.rl = self.env["res.lang"] for lang in self.langs: if not self.rl.search([("code", "=", lang)]): self.rl.load_lang(lang) def test_explicit(self): """When an explicit lang is used.""" ...
bjoernricks/kaizen
kaizen/phase/phase.py
Python
gpl-2.0
2,714
0.001474
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80: # kaizen - Continuously improve, build and manage free software # # Copyright (C) 2011 Björn Ricks <[email protected]> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as publishe...
name def __str__(self): return "Phase '%s' does not exist." % (self.name) class Phase(object): def __init__(self, name, value):
self.value = value self.name = name def __cmp__(self, other): if self.value < other.value: return -1 if self.value == other.value: return 0 if self.value > other.value: return 1 def __eq__(self, other): if not isinstance(other, Phase...
caspartse/QQ-Groups-Spider
vendor/pyexcel_io/constants.py
Python
mit
1,834
0.003272
""" pyexcel_io.constants ~~~~~~~~~~~~~~~~~~~ Constants appeared in pyexcel :copyright: (c) 2014-2017 by Onni Software Ltd. :license: New BSD License """ # flake8: noqa DEFAULT_NAME = 'pyexcel' DEFAULT_SHEET_NAME = '%s_sheet1' % DEFAULT_NAME DEFAULT_PLUGIN_NAME = '__%s_io_plugins
__' % DEFAULT_NAME MESSAGE_INVALID_PARAMETERS = "Invalid parameters" MESSAGE_ERROR_02 = "No content, file name. Nothing is given" MESSAGE_ERROR_03 = "cannot handle unknown content" MESSAGE_WRONG_IO_INSTANCE = "Wrong io instance is passed for your file format." MESSAGE_CANNOT_WRITE_STREAM_FORMATTER = "Cannot write cont...
type %s from stream" MESSAGE_CANNOT_WRITE_FILE_TYPE_FORMATTER = "Cannot write content of file type %s to file %s" MESSAGE_CANNOT_READ_FILE_TYPE_FORMATTER = "Cannot read content of file type %s from file %s" MESSAGE_LOADING_FORMATTER = "The plugin for file type %s is not installed. Please install %s" MESSAGE_EMPTY_ARRAY...
daj0ker/BinPy
BinPy/examples/source/ic/Series_7400/IC7443.py
Python
bsd-3-clause
1,225
0.001633
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <headingcell level=2> # Usage of IC 7443 # <codecell> from __future__ import print_function from BinPy import * # <codecell> # Usage of IC 7443: ic = IC_7443() print(ic.__doc__) # <codecell> # The Pin configuration is: inp = {8: 0, 12: 0, 13: 1, 14: 0, 15:...
n ic.drawIC() # <codecell> # Run the IC with the current configuration using -- print ic.run() -- # Note that the ic.run() returns a dict of pin configuration similar to print (ic.run()) # <codecell> # Seting the outputs to the current IC configuration using -- # ic.setIC(ic.run()) --\n ic.setIC(ic.run()) # Dr...
ll> # Seting the outputs to the current IC configuration using -- # ic.setIC(ic.run()) -- ic.setIC(ic.run()) # Draw the final configuration ic.drawIC() # Run the IC print (ic.run()) # <codecell> # Connector Outputs c = Connector() # Set the output connector to a particular pin of the ic ic.setOutput(1, c) pri...
LKajan/georef
djangoProject/georef/forms.py
Python
mit
642
0.003115
from django import forms from django.contrib.gis.forms import ModelForm as GeoModelForm,
BaseGeometryWidget from django.forms.models import inlineformset_factory from django.contrib.auth.models import User from georef.models import * class GCPForm(GeoModelForm): class Meta: model = GCP widgets = { 'ground': forms.HiddenInput(),
'image': forms.HiddenInput(), } class KuvaForm(forms.ModelForm): class Meta: model = Kuva fields = ['name', 'kuvaus', 'shootTime', 'shootHeight', 'tyyppi', 'tags'] GCPFormset = inlineformset_factory(Kuva, GCP, form=GCPForm, extra=0)
cgranade/qutip
qutip/tests/test_sparse.py
Python
bsd-3-clause
5,409
0.001294
import numpy as np from numpy.testing import run_module_suite, assert_equal, assert_almost_equal import scipy.sparse as sp from qutip.random_objects import (rand_dm, rand_herm, rand_ket) from
qutip.states import coherent from qutip.sparse import (sp_bandwidth, sp_permute, sp_reverse_permute, sp_profile, sp_one_norm, sp_inf_norm) from qutip.cy.spmath import zcsr_kron def _permu
tateIndexes(array, row_perm, col_perm): return array[np.ix_(row_perm, col_perm)] def _dense_profile(B): row_pro = 0 for i in range(B.shape[0]): j = np.where(B[i, :] != 0)[0] if np.any(j): if j[-1] > i: row_pro += (j[-1]-i) col_pro = 0 for j in range(B.sh...
factorlibre/odoo-addons-cpo
product_average_consumption_rules/model/res_config.py
Python
agpl-3.0
1,571
0
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). # © 2018 FactorLibre - Álvaro Marcos <[email protected]> from openerp import api, models, fields class ResConfig(models.TransientModel): _inherit = 'res.config.s
ettings' initial_date = fields.Date('Initial date') end_date = fields.Date('End date') added_locations = fields.Many2many( 'stock.location', string='Added locations to consumption') apply_to_calculation = fields.Boo
lean("Apply to calculation") @api.multi def set_values(self): super(ResConfig, self).set_values() Sudo = self.env['ir.config_parameter'].sudo() Sudo.set_param('initial_date', self.initial_date) Sudo.set_param('end_date', self.end_date) Sudo.set_param('added_locations', s...
Scalr/libcloud
libcloud/extra/drivers/google.py
Python
apache-2.0
6,824
0.002638
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
alse): """ Execute query and return result. Result will be chunked. Reference: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/query :param query: str. BQ query. Example: SELECT * FROM {billing_table} LIMIT 1 :param max_results: int. Page size :param timeo...
s whether to use BigQuery's legacy SQL dialect for this query. :return: dict which represent row from result """ request = '/queries' data = {'query': query, 'useLegacySql': use_legacy_sql, 'maxResults': max_results, 'timeoutMs': timeout_m...
msampathkumar/rms
app/old_views.py
Python
apache-2.0
709
0.011283
from flask import render_template from flask.ext.appbuilder.models.sqla.interface import SQLAInterface from flask.ext.appbuilder im
port ModelView from app import appbuilder, db """ Create your Views:: class MyModelView(ModelView): datamodel = SQLAInterface(MyModel) Next, register your Views:: appbuilder.add_view(MyModelView, "My View", icon="fa-folder-open-o", category="My Category", category_icon='fa-envelope') """ ...
late=appbuilder.base_template, \ appbuilder=appbuilder), 404 db.create_all()
robe16/kiosk.grandparent-message-board
src/config/cfg.py
Python
gpl-3.0
3,338
0.004793
import json import os import ast from datetime import datetime def get_json(): with open(os.path.join(os.path.dirname(__file__), 'config.json'), 'r') as data_file: data = json.load(data_file) return data def put_json(new_data): try: # try: new_data = ast.literal_eval(...
########################### # Axiscare ################################################################################################ def get_config_axiscare(): data = get_cfg_json() return data['axiscare'] def get_config_axiscare_url(): data = get_config_axiscare() return data['
url'] def get_config_axiscare_date(): data = get_config_axiscare() return data['dateReceived'] def put_config_axiscare_url(url): data = get_config_axiscare() data['config']['axiscare']['dateReceived'] = datetime.now().strftime('%Y-%m-%d') data['config']['axiscare']['url'] = url put_json(data...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/samba/dcerpc/drsuapi/DsReplicaNeighbourCtr.py
Python
gpl-2.0
866
0.008083
# encoding: utf-8 # module samba.dcerpc.drsuapi # from /usr/lib/python2.7/dist-packages/samba/dcerpc/drsuapi.so # by generator 1.135 """ drsuapi DCE/RPC """ # imports import dcerpc as __dcerpc import talloc as __talloc class DsReplicaNeighbourCtr(__talloc.Object): # no doc def __init__(self, *args, **kwargs)...
real signature unknown pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass array = property(lambda self: object(), lambda self, v: Non
e, lambda self: None) # default count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default reserved = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
scheib/chromium
third_party/tlslite/tlslite/utils/cryptomath.py
Python
bsd-3-clause
8,434
0.010197
# Authors: # Trevor Perrin # Martin von Loewis - python 3 port # Yngve Pettersen (ported by Paul Sokolovsky) - TLS 1.2 # # See the LICENSE file for legal information regarding use of this file. """cryptomath module This module has basic math/crypto code.""" from __future__ import print_function import os impor...
t] sieve = [x for x in sieve[2:] if x] return sieve sieve = makeSieve(1000) def isPrime(n, iterations=5, display=False): #Trial division with sieve for x in sieve: if x >= n: return True if n % x == 0: return False #Passed trial divisi
on, proceed to Rabin-Miller #Rabin-Miller implemented per Ferguson & Schneier #Compute s, t for Rabin-Miller if display: print("*", end=' ') s, t = n-1, 0 while s % 2 == 0: s, t = s//2, t+1 #Repeat Rabin-Miller x times a = 2 #Use 2 as a base for first iteration speedup, per HAC f...
kyokley/MediaViewer
mediaviewer/tests/views/test_signout.py
Python
mit
1,454
0
import mock from django.test import TestCase from mediaviewer.views.signout import signout class TestSignout(TestCase): def setUp(self): self.logout_patcher = mock.patch('mediaviewer.views.signout.logout') self.mock_logout = self.logout_patcher.start() self.addCleanup(self.logout_patcher...
ews.signout.setSiteWideContext') self.mock_setSiteWideContext = self.setSiteWideContext_patcher.start()
self.addCleanup(self.setSiteWideContext_patcher.stop) self.render_patcher = mock.patch('mediaviewer.views.signout.render') self.mock_render = self.render_patcher.start() self.addCleanup(self.render_patcher.stop) self.request = mock.MagicMock() def test_signout(self): ...
naturali/tensorflow
tensorflow/contrib/framework/python/ops/variables.py
Python
apache-2.0
22,660
0.005825
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
to check for suitability as a global step. If
None is given (the default), find a global step tensor. Returns: A tensor suitable as a global step, or `None` if none was provided and none was found. """ if global_step_tensor is None: # Get the global step tensor the same way the supervisor would. global_step_tensor = get_global_step(graph) ...
brahmastra2016/bleachbit
bleachbit/GUI.py
Python
gpl-3.0
36,930
0.000948
#!/usr/bin/env python # vim: ts=4:sw=4:expandtab # BleachBit # Copyright (C) 2008-2017 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3...
thread = threadin
g.Thread(target=func, args=args) thread.start() return wrapper class TreeInfoModel: """Model holds information to be displayed in the tree view""" def __init__(self): self.tree_store = gtk.TreeStore( gobject.TYPE_STRING, gobject.TYPE_BOOLEAN, gobject.TYPE_PYOBJECT, gobject.TY...
ChinaQuants/bokeh
bokeh/_legacy_charts/_builder.py
Python
bsd-3-clause
7,596
0.00237
"""This is the Bokeh charts interface. It gives you a high level API to build complex plot is a simple way. This is the Builder class, a minimal prototype class to build more chart types on top of it. """ #----------------------------------------------------------------------------- # Copyright (c) 2012 - 2014, Contin...
----- # Imports #----------------------------------------------------------------------------- from __future__ import absolute_import from ._chart import LegacyChart from ._data_adapter import DataAdapter from ..models.ranges import Range from ..
properties import Color, HasProps, Instance, Seq DEFAULT_PALETTE = ["#f22c40", "#5ab738", "#407ee7", "#df5320", "#00ad9c", "#c33ff3"] #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- d...
jokuf/hack-blog
posts/migrations/0008_auto_20170327_1923.py
Python
mit
469
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-27 19:23 from __future__ import unicode_literals from django.db import migra
tions, models class Migration(migrations.Migration): dependencies = [ ('posts', '0007_auto_20170327_1919'), ] operations = [ migrations.AlterField( model_name='post', name='image', field=models.ImageField(blank=True, null=True, upload_to=''),
), ]
archman/phantasy
phantasy/library/lattice/flame.py
Python
bsd-3-clause
43,973
0.003434
# encoding: UTF-8 """ Utility for generating a FLAME lattice from accelerator layout. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import re import logging import os.path from collections import OrderedDict i...
d in configuration: {}".format(option, value)) return value return defvalue def _get_config_float_default(self, option, defvalue): if self.config.has_default(option): value = self.config.getfloat_default(option) _LOGGER.debug("BaseLatticeFactory: '{}' found in co...
urn defvalue def _get_config_array_default(self, option, defvalue, conv=None, unpack=True): if self.config.has_default(option): value = self.config.getarray_default(option, conv=conv) if unpack and (len(value) == 1): value = value[0] _LOGGER.debug("BaseLa...
madisona/django-pseudo-cms
example/settings.py
Python
bsd-3-clause
3,794
0.000264
# Django settings for example project. import sys from os.path import
abspath, dirname, join PROJECT_DIR = abspath(dirname(__file__)) grandparent = abspath(join(PROJECT_DIR, '..')) for path in (
grandparent, PROJECT_DIR): if path not in sys.path: sys.path.insert(0, path) DEBUG = True ADMINS = ( # ('Your Name', '[email protected]'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': join(PROJECT_DIR, 'local.db'), } } ...
ajparsons/useful_inkleby
useful_inkleby/useful_django/models/__init__.py
Python
mit
162
0.024691
from .mixins import * from .flexi import * class FlexiBulkModel(
FlexiModel,EasyBu
lkModel,StockModelHelpers): class Meta: abstract = True
meletakis/collato
esn/actstream/urls.py
Python
gpl-2.0
2,399
0.005002
try: from django.conf.urls import url, patterns except ImportError: from django.conf.urls.defaults import url, patterns from actstream import feeds from actstream import views from django.contrib.auth.decorators import login_required urlpatterns = patterns('actstream.views', # Syndication Feeds url(r...
atom/$'
, feeds.AtomObjectActivityFeed(), name='actstream_object_feed_atom'), url(r'^feed/(?P<content_type_id>\d+)/(?P<object_id>\d+)/$', feeds.ObjectActivityFeed(), name='actstream_object_feed'), url(r'^feed/(?P<content_type_id>\d+)/atom/$', feeds.AtomModelActivityFeed(), name='actstream_model_...
Shuailong/Leetcode
solutions/first-unique-character-in-a-string.py
Python
mit
660
0
#!/usr/bin/env python # encoding: utf-8 """ first-unique-character-in-a-string.py Created by Shuailong on 2016-09-01. https://leetcode.com/problems/first-unique-character-in-a-string/. """ # 376 ms from collections
import Counter class Solution(object): def firstUniqChar(self, s): """ :typ
e s: str :rtype: int """ c = Counter(s) for i in range(len(s)): if c[s[i]] == 1: return i return -1 def main(): solution = Solution() print solution.firstUniqChar('leetcode') print solution.firstUniqChar('loveleetcode') if __name__ == '...
jmcanterafonseca/fiware-orion
test/acceptance/behave/components/common_steps/general_steps.py
Python
agpl-3.0
18,232
0.003189
# -*- coding: utf-8 -*- """ Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U This file is part of Orion Context Broker. Orion Context Broker is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation,...
API entry point request: /v2 ...") props = propertie
s_class.read_properties()[CONTEXT_BROKER_ENV] context.cb = CB(protocol=props["CB_PROTOCOL"], host=props["CB_HOST"], port=props["CB_PORT"]) context.resp = context.cb.get_base_request() __logger__.info("...Sent a API entry point request: /v2 correctly") @step(u'send a version request') def send_a_version_re...
cscanlin/Super-Simple-VLOOKUP-in-Python
python_vlookup/__init__.py
Python
mit
29
0
from python_vlookup import *
alisaifee/holmium.core
tests/support/cucumber/steps.py
Python
mit
823
0
from holmium.core import ( Page, Element, Locators, Elements, ElementMap, Section, Sections ) from holmium.core.cucumber import init_steps init_steps() class TestSection(Section): el = Element(Locators.NAME, "el") els = Elements(Locators.NAME, "els") elmap = ElementMap(Locators.NAME, "elmap") class ...
) elmap = ElementMap(Locators.NAME, "elmap") sections = TestSections(Locators.NAME, "sections") section = TestSection(Locators.NAME, "section") def do_stuff(self, a, b): return a + b def do_stuff_no_args(self): return True def do_stuff_var_args(self, *a
rgs, **kwargs): return args, kwargs
danirus/blognajd
blognajd/tests/test_sitemaps.py
Python
mit
1,817
0
from django.core.urlresolvers import reverse from django.test import TestCase as DjangoTestCase from blognajd.models import Story, SiteSettings from blognajd.sitemaps import StaticSite
map, StoriesSitemap class StaticSitemap1TestCase(DjangoTestCase): fixtures = ['sitesettings_tests.json'] def test_staticsitemap_items_disabled(self): sitesettings = SiteSettings.objects.get(pk=1) sitesettings.has_about_page = False sitesettings.has_projects_page = False sitese...
for i in StaticSitemap().items()], ['blog']) def test_staticsitemap_items_enabled(self): sitesettings = SiteSettings.objects.get(pk=1) sitesettings.has_about_page = True sitesettings.has_projects_page = True sitesettings.has_contact_page = True sitesettings.save() s...
hgiemza/DIRAC
WorkloadManagementSystem/JobWrapper/Watchdog.py
Python
gpl-3.0
39,322
0.028915
######################################################################## # File : Watchdog.py # Author: Stuart Paterson ######################################################################## """ The Watchdog class is used by the Job Wrapper to resolve and monitor the system resource consumption. The Watchdog...
pting to Initialize Watchdog for: %s' % ( self.systemFlag ) ) # Test control flags self.testWa
llClock = gConfig.getValue( self.section + '/CheckWallClockFlag', 1 ) self.testDiskSpace = gConfig.getValue( self.section + '/CheckDiskSpaceFlag', 1 ) self.testLoadAvg = gConfig.getValue( self.section + '/CheckLoadAvgFlag', 1 ) self.testCPUConsumed = gConfig.getValue( self.section + '/CheckCPUConsumedFlag',...
thopiekar/Uranium
tests/Math/TestPolygon.py
Python
lgpl-3.0
9,024
0.014738
# Copyright (c) 2017 Ultimaker B.V. # Uranium is released under the terms of the LGPLv3 or higher. from UM.Math.Polygon import Polygon from UM.Math.Float import Float import numpy import math import pytest pytestmark = pytest.mark.skip(reason = "Incomplete tests") class TestPolygon: def setup_method(self, metho...
tersect with a rotated square." }), ({ "polygon": [[15.0, 0.0], [25.0, 0.0], [25.0, 10.0], [15.0, 10.0]], "answer": None, "label": "Intersect Miss", "description": "Intersect with a polygon that doesn't intersect at all." }) ] ## Tests the polygon intersect function. # # Every test...
ametrised polygon with a base square of # 10 by 10 units at the origin. # # \param data The data of the test. Must include a polygon to intersect # with and a required answer. @pytest.mark.parametrize("data", test_intersect_data) def test_intersectsPolygon(self, data): p1 = Polygon...
kuralabs/flowbber
lib/flowbber/plugins/sinks/print.py
Python
apache-2.0
1,764
0
# -*- coding: utf-8 -*- # # Copyright (C) 2017-2018 KuraLabs S.R.L # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
using it. See :ref:`filter-sink-options` for more information. **Dependencies:** .. code-block:: sh pip3 install flowbber[prin
t] **Usage:** .. code-block:: toml [[sinks]] type = "print" id = "..." .. code-block:: json { "sinks": [ { "type": "print", "id": "...", "config": {} } ] } """ from flowbber.logging import print from flowb...
jdepoix/goto_cloud
goto_cloud/commander/public.py
Python
mit
33
0
from .commander import Com
mander
UCSD-PL/kraken
reflex/test/webserver/listener.py
Python
gpl-2.0
678
0.023599
#!/usr/bin/env python2.7 import msg, socket, time import uuid HOST_NAME = 'localhost' # !!!REMEMBER TO CHANGE THIS!!! PORT_NUMBER = 9000 # Maybe set this to 9000. def debug(s): print(" L: " + s) if __name__ == '__main__': msg.init() debug("Spawned")
s = socket.socket() try: s.bind((HOST_NAME, PORT_NUMBER)) print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER) while True: s.listen(0) (bs, addr) = s.accept() debug('Accepting: ' + str(addr)) msg.send(msg.LoginReq, 'default', ' ', str(uuid.uuid4()), bs, bs) ...
me.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
lfalcao/thumbor
vows/upload_api_vows.py
Python
mit
26,572
0.002032
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/globocom/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com [email protected] from os.path import abspath, join, dirname, exists import re from p...
es') self.base_uri = "/image" def get(self, path, headers): return self.fetch(path, method='GET', body=urllib.urlencode({}, doseq=True), headers=
headers, allow_nonstandard_methods=True) def post(self, path, headers, body): return self.fetch(path, method='POST', body=body, headers=headers, allow_nonstandard_methods=True) ...
mlperf/training_results_v0.7
Google/benchmarks/gnmt/implementations/gnmt-research-TF-tpu-v4-512/utils/vocab_utils.py
Python
apache-2.0
6,145
0.009276
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
ring tensor Returns: A tensor of shape words.shape + [bytes_per_word] containing byte versions of each word. """ bytes_per_word = DEFAULT_CHAR_MAXLEN with tf.device("/cpu:0"): tf.assert_rank(tokens, 1)
shape = tf.shape(tokens) tf.logging.info(tokens) tokens_flat = tf.reshape(tokens, [-1]) as_bytes_flat = tf.map_fn( fn=lambda x: _string_to_bytes(x, max_length=bytes_per_word), elems=tokens_flat, dtype=tf.int32, back_prop=False) tf.logging.info(as_bytes_flat) as_bytes...
kosugawala/jubatus-weather
python/jubaweather/main.py
Python
mit
2,275
0.024176
import argparse import yaml from jubatus.classifier.client import classifier from jubatus.classifier.types import * from jubaweather.version import get_version def parse_options(): parser = argparse.ArgumentParser() parser.add_argument( '-a', required = True, help = 'analyze data file (YAML)', ...
'avetemp', float(avetemp)], ['maxtemp', float(maxtemp)], ['mintemp', float(mintemp)], ['pressure', float(pressure)], ['humidity', float(humidity)] ] d = datum([], num_values) train_data = [[season, d]] # train client.train('', train_data) ...
ather") # anaylze with open(args.analyzedata, 'r') as analyzedata: weather = yaml.load(analyzedata) for k, v in weather.iteritems(): print str(k), "(", str(v['season']), ")" num_values = [ ['avetemp', float(v['avetemp'])], ['maxtemp', float(v['maxtemp'])], ['mintemp', fl...
paulmartel/voltdb
examples/metrocard/exportServer.py
Python
agpl-3.0
6,191
0.004361
#!/usr/bin/env python # This file is part of VoltDB. # Copyright (C) 2008-2016 VoltDB Inc. # # 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 limitatio...
iron, start_response): start_response('200 OK', [('Content-Type', 'text/html')])
return assembleTable() def exportRows(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) if "QUERY_STRING" in environ: row = parse_qs(environ["QUERY_STRING"]) processRow(row) return [] getFuncs = { "htmlRows" : htmlRows, "exportRows" : exportRows, ...
ksavenkov/recsys-001
recsys/dataset.py
Python
mit
6,782
0.008552
import csv from collections import defaultdict class DataIO: '''Responsible for reading data from whatever source (CSV, DB, etc), normalizing indexes for processing and writing results in denormalized form. Also it provides an access to translation dictionaries between external and internal i...
turn def translate_users(self, old_user_ids): '''Takes an array of original user ids and translates them into the normalized form ''' return [self.new_user_idx(i) for i in old_user_ids] def translate_items(self, old_item_ids):
'''Takes an array of original item ids and translates them into the normalized form ''' return [self.new_item_idx(i) for i in old_item_ids] def num_items(self): '''Number of different items in the dataset''' return len(self.__old_item_idx) def num_users(self): '...
ohmini/thaifoodapi
thaifood/models.py
Python
bsd-3-clause
6,666
0.00063
##-*-coding: utf-8 -*- from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Usage(models.Model): ip = models.CharField(max_length=50) method = models.CharField(max_length=3) path = models.CharField(max_length=100) params = models...
ู่อาหาร" verbose_name_plural = "กลุ่มหมวดหมู่อาหาร" db_table = 'food_type' @python_2_unicod
e_compatible class Ingredient(models.Model): name = models.CharField(max_length=100, unique=True) description = models.CharField(max_length=255, blank=True, null=True) calories = models.IntegerField(default=0) nutrient = models.ForeignKey(Nutrient, on_delete=models.SET_N...
hmgaudecker/econ-project-templates
{{cookiecutter.project_slug}}/.mywaflib/waflib/extras/fc_solstudio.py
Python
bsd-3-clause
1,642
0.028015
#! /usr/bin/env python # encoding: utf-8 # harald at klimachs.de import re from waflib import Utils from waflib.Tools import fc,fc_config,fc_scan from waflib.Configure import conf from waflib.Tools.compiler_fc import fc_compiler fc_compiler['linux'].append('fc_solstudio') @conf def find_solstudio(conf): """Find the...
t_os = conf.env['DEST_OS'] or Utils.unversioned_sys_platform() solstudio_modifier_func = getattr(conf, 'solstudio_modifier_' + dest_os, None) if solstudio_modifier_func: solstudio_modifier_func() @conf def get_solstudio_version(conf, fc): """Get the compiler version""" version_re = re.compile(r"Sun Fortran 95 *...
) else: match = version_re(err) if not match: conf.fatal('Could not determine the Sun Studio Fortran version.') k = match.groupdict() conf.env['FC_VERSION'] = (k['major'], k['minor']) def configure(conf): conf.find_solstudio() conf.find_ar() conf.fc_flags() conf.fc_add_flags() conf.solstudio_flags() conf...
codendev/rapidwsgi
src/mako/pygen.py
Python
gpl-3.0
10,042
0.008365
# pygen.py # Copyright (C) 2006, 2007, 2008, 2009, 2010 Michael Bayer [email protected] # # This module is part of Mako and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """utilities for generating and formatting literal Python code.""" import re, string from ...
self, text): self.stream.write(text) def write_indented_block(self, block): """print a line or lines of python which already contain indentation. The indentation of the total block of lines will be adjusted to that of the current indent level.""" se...
a series of lines of python.""" for line in lines: self.writeline(line) def writeline(self, line): """print a line of python, indenting it according to the current indent level. this also adjusts the indentation counter according to the content of...
plac-lab/TMIIaTest
Software/Control/src/fungen_ctrl.py
Python
mit
2,433
0.006165
#!/usr/bin/env python # -*- coding: utf-8 -*- ## @package fungen_ctrl # Control the function generator # from __future__ import print_function import time import os import sys import shutil import math # use either usbtmc or NI Visa try: import usbtmc except: import visa ## Rigol DG1022 class DG1022(object):...
time.sleep(0.5) amax = 16383 vals=[0 for i in xrange(np)] for i in xrange(np): if i<xp:
vals[i] = amax else: vals[i] = int(amax*(1-math.exp(-(i-xp)*alpha))) string = "DATA:DAC VOLATILE" for i in xrange(np): string += (",%d"% vals[i]) self._instr.write(string) time.sleep(1.0) self._instr.write("FUNC:USER VOLATIL...
ilmir-k/website-addons
website_sale_available_fake/controllers/__init__.py
Python
lgpl-3.0
66
0
# -*- cod
ing: utf-8 -*- from . import website_sale_available_fak
e
gillarkod/jira_extended
example.py
Python
mit
240
0
from
jira_extended import JIRA jira = JIRA( '<url>', basic_auth=( '<user>', '<password>', ), options={ 'extended_url': '<url>', } )
jira.search_issues('project = "PROJECT1"')[0].move('PROJECT2')
ipazc/oculus-crawl
test/crawler_tests.py
Python
gpl-3.0
172
0
import
unittest class CrawlTests(unittest.TestCase): def test_something(self): self.assertEqual(True, False) if __name__ == '__main__': unittest.main()
westernx/sgevents
sgevents/dispatcher/dispatcher.py
Python
bsd-3-clause
4,868
0.003903
import itertools import logging import os import threading import yaml from ..utils import get_adhoc_module from .callback import Callback from .context import Context from .qube import QubeCallback from .shell import ShellScript from .. import logs log = logging.getLogger('sgevents.dispatcher') # __name__ is ugly ...
andler.name)) handler.handle_event(self, envvars, event) except: log.exception('Error during %s %r' % (handler.__class__.__name__.low
er(), handler.name))
trevor/calendarserver
txdav/base/datastore/util.py
Python
apache-2.0
4,470
0.004474
# -*- test-case-name: txdav.caldav.datastore.test.test_file -*- ## # Copyright (c) 2010-2014 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apa...
f.cacheExpireSeconds = cacheExpireSeconds def set(self, key, value): return
super(QueryCacher, self).set(key, value, expireTime=self.cacheExpireSeconds) def delete(self, key): return super(QueryCacher, self).delete(key) def setAfterCommit(self, transaction, key, value): transaction.postCommit(lambda: self.set(key, value)) def invalidateAfterCommit(self, trans...
git-commit/iot-gatekeeper
gatekeeper/test_app.py
Python
mit
25
0.04
import bot
bo
t.run_bot()
Jameeeees/Mag1C_baNd
kekangpai/testCon/migrations/0011_auto_20160716_1025.py
Python
apache-2.0
1,103
0
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-07-16 10:25 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('test
Con', '0010_auto_20160713_1534'), ] operations = [ migrations.AddField( model_name='account_teacher', name='teacherName', field=m
odels.CharField(default='TeacherName', max_length=20), preserve_default=False, ), migrations.AddField( model_name='classinfo', name='classCode', field=models.CharField(default=0, max_length=10), preserve_default=False, ), migrat...
quattor/aquilon
lib/aquilon/worker/dbwrappers/search.py
Python
apache-2.0
3,147
0
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2017 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
pick out the first and # lock that. q2 = session.query(cls).order_by(attr).limit(1) if q2.count() == 1: attrval = q2.value(attr) # This is not particularly
pleasant: Oracle won't permit a # "FOR UPDATE" query where "ORDER BY" is given (ORA-02014); # constructing the allowable version of the query may not be # possible with SQLAlchemy. q2 = session.query(cls).filter(attr == attrval) session.execute(q2.with_for_up...
montimaj/ShaktiT_LLVM
llvm/utils/lit/lit/formats/shtest.py
Python
gpl-3.0
1,993
0.003011
from __future__ import absolute_import import os import lit.Test import lit.TestRunner from .base import TestFormat class ShTest(TestFormat): """ShTest is a format with one file per test. This is the primary format for regression tests as described in the LLVM testing guide: http://llvm.org/doc...
"""Yields test files matching 'suffixes' from the localConfig.""" source_path = testSuite.getSourcePath(path_in_suite) for filename in os.listdir(source_path): # Ignore dot files and excluded tests. if (filename.startswith('.') or filename in localConfig.exclu...
xt(filename) if ext in localConfig.suffixes: yield lit.Test.Test(testSuite, path_in_suite + (filename,), localConfig) def execute(self, test, litConfig): """Interprets and runs the given test file, and returns the result.""" ...
jmuckian/GodsAndMonsters
bin/char.py
Python
gpl-3.0
46,928
0.003111
import random import sys import pygame import string import re import xml.dom.minidom from pygame.locals import * from gamedata import * from menu import Menu class CreateCharacter: """Creates a new character for Gods & Monsters based on the rules defined in the Rule Book beginning on page 6. """ ...
# se
lf.chardata[ability][-1] is set to original value to # account for temporary increases or decreases (curses, # magic, etc). i = 0 for score in scores: scores[i] = [score, self.gamedata.ABIL_MODIFIERS[score][0], self.gamedata...
chaocodes/playlist-manager-django
manager/playlist/views.py
Python
mit
2,983
0.002011
from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.http import Http404, JsonResponse, HttpResponseForbidden from django.shortcuts import render, redirect, get_object_or_404 from .forms import PlaylistForm from .models import Playlist def form_data(user, f...
ction', False) if action: if action == 'delete': playlist.delete() elif action == 'update': form = PlaylistForm(request.POST, instance=playlist) if form.is_valid(): playlist = form.save() else: ...
laylist/form.html', data) return redirect('playlist:all', user_id) @login_required def edit_view(request, user_id, playlist_id): user = get_object_or_404(User, id=user_id) playlist = get_object_or_404(Playlist, id=playlist_id, user=user) # Check if playlist belongs to logged in user if request....
si618/pi-time
pi_time/pi_time/db.py
Python
gpl-3.0
39
0.025641
"
""Database access
code...twistar?"""
Stratoscale/pycommonlog
js/main.py
Python
apache-2.0
1,322
0.005295
import shutil import argparse import os import subprocess import SimpleHTTPServer import SocketServer import socket parser = argparse.ArgumentParser( description = 'Present summary of tests results in a webpage.' ) parser.add_argument("--root", default="logs.racktest") parser.add_argument("--whiteboxRoot", action="sto...
rowser", help="avoid openning the browser", action="store_true") parser.add_argument("--noServer", action="store_true") args = parser.parse_args() if args.whiteboxRoot: args.root = "logs.whiteboxtest" root = args.root reporterDir = os.path.join(root, "_reporter") originalReporterDir = "../pycommonlog/js" shutil.r...
reporterDir) class ReusingTCPServer(SocketServer.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) if not args.noServer: os.chdir(args.root) PORT = 8000 Handler = SimpleHTTPServer.SimpleHTTPRequ...
googleads/google-ads-python
google/ads/googleads/v9/errors/types/shared_set_error.py
Python
apache-2.0
1,240
0.000806
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Versi
on 2.0 (the "License"); # y
ou 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...
jrbl/invenio
modules/bibauthorid/lib/bibauthorid_prob_matrix.py
Python
gpl-2.0
4,586
0.004143
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2011, 2012 CERN. ## ## Invenio 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 opt...
l2): for bib1 in cl1.bibs: for bib2 in cl2.bibs: if bib1 in cached_bibs and bib2 in cached_bibs: val = old_matrix[bib1, bib2] if not val:
cur_calc += 1 check_for_cleaning(cur_calc) val = compare_bibrefrecs(bib1, bib2) else: opti += 1 if bconfig.DEBUG_C...
mailjet/mailjet-apiv3-python
mailjet_rest/__init__.py
Python
mit
189
0
#!/us
r/bin/env python # coding=utf-8 from mailjet_rest.client
import Client from mailjet_rest.utils.version import get_version __version__ = get_version() __all__ = (Client, get_version)
QANSEE/l10n-belgium
account_companyweb/wizard/__init__.py
Python
agpl-3.0
1,052
0
# -*- coding: utf-8 -*- # ############################################################################## # # Authors: Adrien Peiffer # Copyright (c) 2014 Acsone
SA/NV (http://www.acsone.eu) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program i...
ITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################...