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
endlessm/chromium-browser
tools/perf/benchmarks/speedometer2.py
Python
bsd-3-clause
2,350
0.008936
# Copyright 2017 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. """Apple's Speedometer 2 performance benchmark. """ import os import re from benchmarks import press from core import path_util from telemetry import ben...
_SPEEDOMETER_DIR) ps.AddStory(speedometer2_pages.Speedometer2Story(ps, should_filter_suites, filtered_suite_names, self.enable_smoke_tes
t_mode)) return ps @classmethod def AddBenchmarkCommandLineArgs(cls, parser): parser.add_option('--suite', type="string", help="Only runs suites that match regex provided") @classmethod def ProcessCommandLineArgs(cls, parser, args): if args.suite: try: if not sp...
rwth-ti/gr-ofdm
python/ofdm/qa_moms_ff.py
Python
gpl-3.0
1,256
0.007962
#!/usr/bin/env python # # Copyright 2014 Institute for Theoretical Information Technology, # RWT
H Aachen University # www.ti.rwth-aachen.de # # This 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, or (at your option) # any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th...
Gaurang033/Selenium2Library
src/Selenium2Library/keywords/_browsermanagement.py
Python
apache-2.0
28,305
0.004911
import os.path from robot.errors import DataError from robot.utils import secs_to_timestr, timestr_to_secs from selenium import webdriver from selenium.common.exceptions import NoSuchWindowException from Selenium2Library import webdrivermonkeypatches from Selenium2Library.utils import BrowserCache from Selenium2Libr...
rnet Explorer | | googlechrome | Google Chrome | | gc | Google Chrome | | chrome | Google Chrome | | opera | Opera | | phantomjs | PhantomJS | | htmlunit | HTMLUnit | | htmlunitwithjs | HTMLU...
t support | | android | Android | | iphone | Iphone | | safari | Safari | | edge | Edge | Note, that you will encounter strange behavior, if you open multiple Internet Explorer browser instances. That...
deepmind/enn
enn/experiments/neurips_2021/base.py
Python
apache-2.0
2,522
0.00912
# python3 # pylint: disable=g-bad-file-header # Copyright 2021 DeepMind Technologies Limited. 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...
==================
========== """Base classes for GP testbed.""" import abc from typing import Any, Dict, NamedTuple, Optional import chex import dataclasses import typing_extensions # Maybe this Data class needs to be a tf.Dataset class Data(NamedTuple): x: chex.Array y: chex.Array @dataclasses.dataclass class PriorKnowledge: ...
morissette/devopsdays-hackathon-2016
venv/lib/python2.7/site-packages/boto3/resources/model.py
Python
gpl-3.0
20,675
0.000048
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
property def params(self): """ Get a list of auto-filled parameters for this request. :type: list(:py:class:`Parameter`) """ params = [] for item in self._definition.get('params', []): params.appen
d(Parameter(**item)) return params class Parameter(object): """ An auto-filled parameter which has a source and target. For example, the ``QueueUrl`` may be auto-filled from a resource's ``url`` identifier when making calls to ``queue.receive_messages``. :type target: string :param t...
yddgit/hello-python
network/tcp_client.py
Python
apache-2.0
1,642
0.003584
#!/usr/bin/env python # -*- coding: utf-8 -*- # 创建一个基于TCP连接的Socket import socket # 创建一个socket # AF_INET指定使用IPv4协议,要使用IPv6则指定为AF_INET6 # SOCK_STREAM指定使用面向流的TCP协议 # 此时,Socket对象创建成功,但还没有建立连接 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 建立连接,参数是一个tuple,包含地址和端口号 s.connect(('www.baidu.com', 80)) # TCP连接创建的是双向通道,...
in ['Michael', 'Tracy', 'Sarah']: s.send(data) # 发送数据 print s.re
cv(1024) s.send('exit') s.close()
ypu/tp-qemu
qemu/tests/live_snapshot.py
Python
gpl-2.0
3,334
0
import time import logging from autotest.client.shared import error from virttest import utils_test from generic.tests import file_transfer def run(test, params, env): """ live_snapshot test: 1). Create live snapshot during big file creating 2). Create live snapshot when guest reboot 3). Check if ...
"snapshot_nam
e") format = params.get("snapshot_format", "qcow2") vm.monitor.live_snapshot(device, snapshot_name, format) logging.info("Check snapshot is created ...") snapshot_info = str(vm.monitor.info("block")) if snapshot_name not in snapshot_info: logging.error(snapshot_info)...
Bachmann1234/hn-tldr
constants.py
Python
apache-2.0
586
0
import os TOP_STORIES_KEY = b'top_30' TITLE = 'title' URL = 'url' BODY = 'body' SENTENCES = 'sentences' HACKER_NEWS_ID = 'hn_id' TEXT = 'text' DATE_FOUND = 'date_found' AYLIEN_ID = 'AYLIENID' AYLIEN_KEY = 'AYLIENKEY' REDIS_HOST = 'REDIS_HOST' REDIS_PORT = 'REDIS_PORT' REDIS_PASS = 'REDIS_PASS' def
get_environment(): return { AYLIEN_ID: os.environ.get(AYLIEN_ID), AYLIEN_KEY: os.environ.get(AYLIEN_KEY), REDIS_HOST: os.environ.get(REDIS_HOST), R
EDIS_PORT: int(os.environ.get(REDIS_PORT), 0), REDIS_PASS: os.environ.get(REDIS_PASS), }
owainkenwayucl/utils
src/fortwrangler.py
Python
mit
6,251
0.007359
#!/usr/bin/env python3 # Fortwrangler is a tool that attempts to resolve issues with fortran lines over standard length. # Global libraries import sys # Global variables # Strings inserted for continuation CONTINUATION_ENDLINE = "&\n" CONTINUATION_STARTLINE = " &" # Line length settings MIN_LENGTH = len(CONTI...
R.write("Error - you cannot both write output to a separate file and writ
e it in place.\n") sys.exit(1) else: if args.o != None: outfile = open(args.o, 'w') output = outfile if args.c: for a in args.files: check_file(a, maxlength=maxlength, report=output) elif args.i != None: import os ...
jatchley/OSU-Online-CS
325/Final Project/Final.py
Python
mit
4,765
0.004617
#********************************************************************** # CS 325 - Project Group 9 # Joshua Atchley # Aalon Cole # Patrick Kilgore # # Project - Solving the Travelling Salesman Problem with Approximation # # Algorithm - Simulated Annealing as described in: # Hansen, Per Brinch, "Simulated An...
cal Reports. Paper 170. # http://surface.syr.edu/eecs_techreports/170 #********************************************************************** import math import sys import time import random from timeit import default_timer as timer class City: def __init__(self, numbe
r, xc, yc): self.cNum = number self.x = xc self.y = yc def distanceTo(self, endpoint): xdiff = endpoint.x - self.x ydiff = endpoint.y - self.y dist = math.sqrt(xdiff*xdiff + ydiff*ydiff) return int(round(dist)) def tourLength(tourArray): n = len(tourArra...
banga/powerline-shell
test/repo_stats_test.py
Python
mit
687
0
import unittest from powerline_shell.utils import RepoStats class RepoStatsTest(unittest.TestCase): def setUp(self): self.repo_stats = RepoStats() self.repo_stats.changed = 1 self.repo_stats.conflicted = 4 def test_dirty(self):
self.assertTrue(self.repo_stats.dirty) def test_simple(self): self.assertEqual(self.repo_stats.new, 0) def test_n_or_empty__empty(self): self.assertEqual(self.repo_stats.n_or_empty("changed"), u"") def test_n_or_empty__n(self): self.assertEqual(self.repo_stats.n_or_empty("confli...
1)
Dru89/2do
project_2do/wsgi.py
Python
mit
399
0
""" WSGI config for project_2do 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.8/howto/deployment/wsgi/ ""
" import os from django.core.wsgi import get_wsgi_application os.environ.setdef
ault("DJANGO_SETTINGS_MODULE", "project_2do.settings") application = get_wsgi_application()
lizardsystem/lizard-security
lizard_security/admin.py
Python
gpl-3.0
5,909
0
# (c) Nelen & Schuurmans. GPL licensed, see LICENSE.txt # -*- coding: utf-8 -*- """ Lizard-security's ``admin.py`` contains two kinds of model admins: - Our own model admins to make editing data sets, permission mappers and user groups easier. - ``SecurityFilteredAdmin`` as a base class for admins of models that u...
nagers']: if manager not in members: members.append(manager) self.cleaned_data['members'] = members return self.cleaned_data class UserGroupAdmin(admin.ModelAdmin): """Custom admin for user groups: show manager/membership info directly. User groups are also filtere...
del = UserGroup form = UserGroupAdminForm list_display = ('name', 'manager_info', 'number_of_members') search_fields = ('name', ) filter_horizontal = ('managers', 'members') def queryset(self, request): """Limit user groups to those you manage. The superuser can edit all user group...
JohanComparat/pySU
spm/bin_SMF/create_table_snr.py
Python
cc0-1.0
8,566
0.025683
import astropy.io.fits as fits import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as p import numpy as n import os import sys from scipy.stats import scoreatpercentile as sc from scipy.interpolate import interp1d survey = sys.argv[1] z_min, z_max = 0., 1.6 imfs = ["Chabrier_ELODIE_", "Chabrier_MILES_",...
path.join( os.environ['OBS_REPO'], 'SDSS', '26', 'catalogs', "FireFly.fits" ) path_2_eboss_cat = os.path.join( os.environ['OBS_REPO'], 'SDSS', 'v5_10
_0', 'catalogs', "FireFly.fits" ) # OPENS THE CATALOGS print("Loads catalog") if survey =='deep2': deep2_dir = os.path.join(os.environ['OBS_REPO'], 'DEEP2') path_2_deep2_cat = os.path.join( deep2_dir, "zcat.deep2.dr4.v4.LFcatalogTC.Planck13.spm.fits" ) catalog = fits.open(path_2_deep2_cat)[1].data if survey =='s...
sanctuaryaddon/sanctuary
script.module.liveresolver/lib/liveresolver/resolvers/playwire.py
Python
gpl-2.0
1,286
0.01944
# -*- coding: utf-8 -*- import re,urlparse,json from liveresolver.modules import client from BeautifulSoup import BeautifulSoup as bs import xbmcgui def resolve(url): try: result = client.request(url) html = result result = json.loads(result) try: f4m=res...
dialog = xbmcgui.Dialog() index = dialog.select('Select bitrate', choices) if index>-1:
return links[index] return except: return
Awesomecase/Speedtest
speedtest_sendtest/__init__.py
Python
gpl-3.0
71
0
__all__ = ["speedtest_
exceptions", "
speedtest"] from . import sendtest
julien6387/supervisors
supvisors/client/subscriber.py
Python
apache-2.0
6,689
0.001196
#!/usr/bin/python # -*- coding: utf-8 -*- # ====================================================================== # Copyright 2016 Julien LE CLEACH # # 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 Lice...
e.INFO, fmt='%(asctime)s %(levelname)s %(message)s\n', rotating=True, maxbytes=10 * 1024 * 1024, backups=1, stdout=True): """ Return a Supervisor logger. """ logger = loggers.getLogger(loglevel) if stdout: loggers.handle_stdout(logger, fmt) loggers.handle_file...
ckups) return logger class SupvisorsEventInterface(threading.Thread): """ The SupvisorsEventInterface is a python thread that connects to **Supvisors** and receives the events published. The subscriber attribute shall be used to define the event types of interest. The SupvisorsEventInterface requ...
williechen/DailyApp
12/py201501/Ch01_03/__init__.py
Python
lgpl-3.0
62
0.020833
#-*-
coding
: utf-8 -*- ''' 留下最後 N 個項目 '''
universalcore/unicore.comments
unicore/comments/service/tests/test_schema.py
Python
bsd-2-clause
9,303
0
import uuid from datetime import datetime from unittest import TestCase import pytz import colander from unicore.comments.service.models import ( COMMENT_MAX_LENGTH, COMMENT_CONTENT_TYPES, COMMENT_MODERATION_STATES, COMMENT_STREAM_STATES) from unicore.comments.service.schema import ( Comment, Flag, Banned...
data[key] = value.hex elif isinstance(value, dict): data[key] = value.copy() else: data[key] = unicode(value) comment_data = comment_model_data.copy() flag_data = flag_model
_data.copy() banneduser_data = banneduser_model_data.copy() streammetadata_data = streammetadata_model_data.copy() for data in (comment_data, flag_data, banneduser_data, streammetadata_data): simple_serialize(data) class CommentTestCase(TestCase): def test_deserialize(self): schema = Comment().bind(...
mathemage/h2o-3
h2o-py/tests/testdir_parser/pyunit_parquet_parser_simple.py
Python
apache-2.0
999
0.008008
from __future__ import print_function import sys sys.path.insert(1,"../../") import h2o from tests import pyunit_utils def parquet_parse_simple(): """ Tests Parquet parser by comparing the summary of the original csv frame with the h2o parsed Parquet frame. Basic use case of importing files with auto-dete...
ssed. Otherwise, an exception will be thrown. """ csv = h2o.import_file(path=pyunit_utils.locate("smalldata/airlines/AirlinesTrain.csv.zip")) parquet = h2o.import_file(path=pyunit_utils.locate("smalldata/parser/parquet/airlines-simple.snappy.parquet")) csv.summary() csv_summary = h2o.frame(csv.fra...
rquet_summary) if __name__ == "__main__": pyunit_utils.standalone_test(parquet_parse_simple) else: parquet_parse_simple()
scott-w/pyne-django-tutorial
chatter/chatter/base/migrations/0001_initial.py
Python
mit
799
0.001252
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
, serialize=False, auto_created=True, primary_key=True)), ('content', models.CharField(max_length=200)), ('created', models.DateTimeField(auto_now_add=True)), ('user', models.ForeignKey(to=settings.AU
TH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), ]
rawkintrevo/sharky
mysharky/writers.py
Python
apache-2.0
2,074
0.047734
from multiprocessing import Process, Pipe,Value, Queue from time import sleep, clock from solr import Solr #### EVERY connection must be a class with a .commit() method. #### Starbase and solr already have these. If you want to make #### a csv method, you need to define it as a custom class. #### #### commit(...
ntion, but i
t #### needs to be there. class SharkyWriterConnection(): def __init__(self, name): self.name= name def establishConnection(self): # Expected Parameters () pass def setEstablishConnectionFn(self, fn): self.establishConnection= fn def processMessage(self, message, target_queue): # Expected Paramete...
chromium/chromium
tools/perf/contrib/leak_detection/page_sets.py
Python
bsd-3-clause
10,066
0.001987
# Copyright 2017 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 py_utils from telemetry import story as story_module from telemetry.page import page as page_module from telemetry.page import shared_page_state clas...
s://www.theverge.com/', 'https://www.nlm.nih.gov/', 'https://archive.org/', 'https://www.udemy.com/', 'https://answers.yahoo.com/', # TODO(crbug.com/985552): Memory dump fails flakily.
# 'https://www.goodreads.com/', 'https://www.cricbuzz.com/', 'http://www.goal.com/', 'http://siteadvisor.com/', 'https://www.patreon.com/', 'https://www.jw.org/', 'http://europa.eu/', 'https://translate.google.com/', 'https://www.epicgames.com/', 'http://www.reve...
NicLew/CS360-Practive-CI-Testing
unittestExample.py
Python
gpl-2.0
1,699
0.030606
#!/usr/bin/python3 ################################ # File Name: unittestExample.py # Author: Chadd Williams # Date: 10/20/2014 # Class: CS 360 # Assignment: Lecture Examples # Purpose: Demonstrate unit tests ################################ # adapted from https://docs.python.org/3/library/unittest.html # pytho...
sort() self.assertEqual(self.theList, list(range(self.listSize))) def test_append(self): """ make sure append works correctly """ self.theList.append(self.listSize+1) self.assertEqual(self.theList[-1], self.listSize+1) def test_exceptions(self): """test some exceptions """ # theList does not con...
# theList DOES contain 1. # remove will not raise the expected exception self.assertRaises(ValueError, self.theList.remove, 0)"""
rsoumyassdi/nuxeo-drive
nuxeo-drive-client/nxdrive/wui/conflicts.py
Python
lgpl-2.1
3,320
0.001506
''' Created on 10 mars 2015 @author: Remi Cattiau ''' from nxdrive.logging_config import get_logger from nxdriv
e.wui.dialog import WebDialog, WebDriveApi from nxdrive.wui.translator import Translator from PyQt4 import QtCore log = get_logger(__name__) class WebConflictsApi(WebDriveApi): def __init__(self, application, engine, dlg=None): super(WebConflictsApi, self).__init__(application, dlg) self._manager...
@QtCore.pyqtSlot(result=str) def get_errors(self): return super(WebConflictsApi, self).get_errors(self._engine._uid) @QtCore.pyqtSlot(result=str) def get_conflicts(self): return super(WebConflictsApi, self).get_conflicts(self._engine._uid) @QtCore.pyqtSlot(int) def resolve_with_loc...
varunarya10/python-openstackclient
openstackclient/identity/v2_0/ec2creds.py
Python
apache-2.0
5,662
0
# Copyright 2012 OpenStack Foundation # Copyright 2013 Nebula Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """Identity v2 EC2 Credentials action implementations""" import loggin
g import six from cliff import command from cliff import lister from cliff import show from openstackclient.common import utils from openstackclient.i18n import _ # noqa class CreateEC2Creds(show.ShowOne): """Create EC2 credentials""" log = logging.getLogger(__name__ + ".CreateEC2Creds") def get_pars...
MingfeiPan/leetcode
string/6.py
Python
apache-2.0
526
0.015209
import functools class Solution: d
ef convert(self, s: str, numRows: int) -> str: if numRows == 1: return s ret = [[] for _ in range(numRows)] pattern = numRows*2 - 2 for i in range(len(s)): if i % pattern < numRows: ret[i % pattern].append(s[i]) else: ...
ret[pattern - (i % pattern)].append(s[i]) return functools.reduce(lambda a, b : a + b ,[''.join(c) for c in ret])
stryder199/RyarkAssignments
Assignment2/ttt/archive/_old/other/echo_io.py
Python
mit
750
0.042667
import question_template game_type = 'input_output' source_language = 'C' parameter_list = [ ['$x0','string'],['$x1','string'],['$x2','string'], ['$y0','string'],['$y1','string'],['$y2','string'] ] tuple_list = [ ['echo_io_forward_',['a','b','c',None,None,None]], ] global_code_template = '''\ d #include &lt;s...
stion_template(game_type,source_language, parameter_list,tuple_list,global_code_template,main_code_template, argv_templat
e,stdin_template,stdout_template)
gcobos/rft
config.py
Python
agpl-3.0
673
0.002972
# Author: Drone import web from app.helpers import utils from app.helpers import formatting projectName = 'Remote Function Trainer' listLimit = 40 # connect to database db
= web.database(dbn='mysql', db='rft', user='root', passwd='1234') t = db.transaction() #t.commit() # in development debug error messages and reloader web.config.debug = False # in develpment template caching is set to false cache = False # template global functions globals = utils.get_all_
functions(formatting) # set global base template view = web.template.render('app/views', cache=cache, globals=globals) # in production the internal errors are emailed to us web.config.email_errors = ''
achalddave/simple-amt
reject_assignments.py
Python
mit
970
0.016495
import argparse, json import simpleamt if __name__ == '__main__': parser = argparse.ArgumentParser(parents=[simpleamt.get_parent_parser()]) args = parser.parse_args() mtc = simpleamt.get_mturk_connectio
n_from_args(args) reject_ids = [] if args.hit_ids_file is None: parser.error('Must specify --hit_ids_file.') with open(args.hit_ids_file, 'r') as f: hit_ids = [line.strip() for line in f] for hit_id in hit_ids: for a in mtc.get_assignments(hit_id): reject_ids.append(a.AssignmentId) pr...
r(args.sandbox))) print 'Continue?' s = raw_input('(Y/N): ') if s == 'Y' or s == 'y': print 'Rejecting assignments' for idx, assignment_id in enumerate(reject_ids): print 'Rejecting assignment %d / %d' % (idx + 1, len(reject_ids)) mtc.reject_assignment(assignment_id, feedback='Invalid results...
iulian787/spack
var/spack/repos/builtin/packages/mariadb-c-client/package.py
Python
lgpl-2.1
3,917
0.007148
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class MariadbCClient(CMakePackage): """MariaDB turns data into structured information in a wide ...
46a2e8b116ea21b04ece24b5a70712c3e96') version('2.3.5', sha256='2f3bf4c326d74284debf7099f30cf3615f7978d1ec22b8c1083676688a76746f') version('2.3.4', sha256='8beb0513da8a24ed2cb47836564c8b57045c3b36f933362f74b3676567c13abc') version('2.3.3', sha256='82a5710134e7654b9cad58964d6a25ed91b3dc1804ff51e8be2def0032914...
version('2.3.1', sha256='6ab7e1477ae1484939675a3b499f98148980a0bd340d15d22df00a5c6656c633') version('2.3.0', sha256='37faae901ca77bd48d2c6286f2e19e8c1abe7cac6fb1b128bd556617f4335c8a') version('2.2.3', sha256='cd01ce2c418382f90fd0b21c3c756b89643880efe3447507bf740569b9d08eed') version('2.2.2', sha256='93f56ad...
usc-isi-i2/etk
etk/data_extractors/htiExtractors/unicode_decoder.py
Python
mit
22,630
0.068714
### @author Rishi Jatia import json import re import string def decode_unicode(data, replace_boo=True): # dictionary which direct maps unicode values to its letters dictionary = {'0030':'0','0031':'1','0032':'2','0033':'3','0034':'4','0035':'5','0036':'6','0037':'7','0038':'8','0039':'9','0024':'$','0040':'@',...
ata,unicode_str,' ') elif uni in hearts: retval+=' *hearts* ' if replace_boo: data=string.replace(data,unicode_str,' *hearts* ') else: data=string.replace(data,unicode_str,' ') elif uni in dictionary: retval+=dictionary[uni] data=string.replace(data,unicode_str,dict...
ni]) elif uni[0:3]=='004' or uni[0:3]=='005': #replacing unicodes for digits and before that, replacing hexadecimals with their numerical value last_dig=uni[3:] if last_dig in hex_dict: last_dig=int(hex_dict[last_dig]) else: last_dig=int(last_dig) second_last_dig= int(u...
royveshovda/pifog
source/piclient/doorpi/door_runner.py
Python
apache-2.0
4,850
0.003093
import json import time import settings from shared import common from datetime import datetime from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient import logging handler = None pin_door1 = 11 #BCM17 pin_door2 = 12 # BCM18 pin_door1_led = 13 # BCM27 pin_door2_led = 15 # BCM22 def init(): global handler ...
else: return False, old_state else: return False, old_state def set_led_state(door1_state, door2_state): handler.set_state(pin_door1_led, door1_state) handler.set_state(pin_door2_led, door2_state) def start(): shadow, client = common.setup_aws_shadow_client(settings.aws_endp...
settings.aws_private_key, settings.aws_certificate, settings.device_name) JSONPayload = '{"state":{"reported":{"connected":"true"}}}' client.shadowUpdate(JSONPayload, customSh...
batpad/osmcha-django
osmchadjango/changeset/migrations/0023_userdetail_contributor_uid.py
Python
gpl-3.0
441
0
# -*- coding: ut
f-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('changeset', '0022_auto_20160222_2358'), ] operations = [ migrations.AddField( model_name='userdetail', name='contrib...
), ]
Kwentar/Dream-Crusher
app/main_views.py
Python
apache-2.0
2,225
0.001348
from flask import Blueprint, render_template, g, request, jsonify from time import gmtime, strftime from flask_login import login_required, current_user from app.models import Month, DreamDay, Dream import datetime main_module = Blueprint('main', __name__, template_folder='templates') @main_module.route('/old') @lo...
(Dream(title="be better than yesterday")) month.dreams.append(Dream(title="collect all pokemons")) month.dreams.append(Dream(title="learn to fly")) g.user.months.append(month) g.user.save() return rende
r_template('index.html', current_n_month=current_n_month) @main_module.route('/add_half_hour', methods=['POST']) @login_required def add_half_hour(): dream_id = request.form['dream_id'] curr_month = g.user.get_current_month() curr_dream = next(x for x in curr_month.dreams if str(x.id_) == dream_id) cu...
openhealthalgorithms/openhealthalgorithms
OHA/helpers/converters/LengthConverter.py
Python
apache-2.0
1,483
0
import abc from OHA.helpers.converters.BaseConverter import BaseConverter __author__ = 'indrajit' __email__ = 'eendroroy@gmail.com' class LengthConverter(BaseConverter): def __init__(self, _va
lue, _from=None, _to=None): super(LengthConverter, self).__init__(_value, _from, _to) def _supported_units(self): return ['ft', 'in', 'm', 'cm'] @abc.abstractmethod def _default_from_unit(sel
f): raise NotImplementedError('method not implemented') @abc.abstractmethod def _default_to_unit(self): raise NotImplementedError('method not implemented') def _convert(self): if self._from == self._to: return self._value elif self._to == 'm' and self._from == '...
kishori82/MetaPathways_Python.3.0
utilities/extract_flat_files.py
Python
mit
7,627
0.023994
#!/usr/bin/python """This script run the pathologic """ try: import optparse, sys, re, csv, traceback from optparse import OptionGroup import pickle import math from libs.python_modules.taxonomy.LCAComputation import * import operator from os import path, _exit, remove, rename import logging....
resultLines = p
ythonCyc.getFlatFiles() StopPathwayTools() try: if False: pythonCyc = startPathwayTools(options.sample_name.lower(), options.ptoolsExec, True) pythonCyc.setDebug() # disable pathway debug statements printf("INFO\tExtracting the reaction list from ePGDB " + options.sample_name + ...
mozaik-association/mozaik
mozaik_mass_mailing_access_rights/__manifest__.py
Python
agpl-3.0
625
0
# Copyright 2021 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Mozaik Mass Mailing Access Rights", "summary": """ New group: Mass Mailing Manager. Managers can edit and unlink mass mailings.""", "version": "14.0.1.0.0", "license": "AGPL-3", "author": "ACSONE SA/NV", ...
mailing", ], "data": [ "security/groups.xml", "security/ir.model.access.csv", "views/mailing_mailing.xml", "views/mail_template.xml", ], "demo": [], }
johan--/Geotrek
geotrek/tourism/migrations/0022_auto__add_field_touristiceventtype_pictogram__add_field_touristicconte.py
Python
bsd-2-clause
14,288
0.006859
# -*- coding: utf-8 -*- from south.db import db from south.v2 import SchemaMigration from django.conf import settings class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'TouristicEventType.pictogram' db.add_column('t_b_evenement_touristique_type', 'pictogram', ...
gth': '256', 'null': 'True', 'db_column': "'email'", 'blank': 'True'}), 'geom': ('django.contrib.gis.db.models.fields.PointField', [], {'srid': str(settings.SRID), 'null': 'True', 'spatial_index': 'False', 'db_column': "'geom'", 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [],...
ull': 'True', 'db_column': "'commune'", 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '256', 'db_column': "'nom'"}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'db_column': "'telephone'", 'blank': 'True'}), ...
tomachalek/kontext
lib/mailing.py
Python
gpl-2.0
2,086
0.000479
# Copyright (c) 2016 Czech National Corpus # # 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; version 2 # dated June, 1991. # # This program is distributed in the hope that it will be useful, # b...
ed 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA...
t import MIMEText import logging import settings def smtp_factory(): """ Create a new SMTP instance with some predefined stuff :return: """ username = settings.get('mailing', 'auth_username') password = settings.get('mailing', 'auth_password') port = settings.get_int('mailing', 'smtp_port'...
DataDog/gunicorn
tests/requests/valid/004.py
Python
mit
164
0
request = { "method": "GET", "uri": uri(
"/silly"), "version": (1, 1), "headers": [ ("AAAAAAAAAAAAA", "++++++++++")
], "body": b"" }
rainwoodman/fastpm-python
fastpm/tests/test_state.py
Python
gpl-3.0
600
0.005
from fastpm.state import StateVector, Matter, Baryon, CDM, NCDM from runtests.mpi import MPITest from nbodykit.cosmo
logy import Planck15 as cosmo import numpy BoxSize = 100. Q = numpy.zeros((100, 3)) @MPITest([1, 4]) def test_create(comm): matter = Matter(cosmo, BoxSize, Q, comm) cdm = CDM(cosmo, BoxSize, Q, comm) cdm.a['S'] = 1.0 cdm.a['P'] = 1.0 baryon = Baryon(cosmo, BoxSize, Q, comm) baryon.
a['S'] = 1.0 baryon.a['P'] = 1.0 state = StateVector(cosmo, {'0': baryon, '1' : cdm}, comm) state.a['S'] = 1.0 state.a['P'] = 1.0 state.save("state")
tfroehlich82/django-propeller
manage.py
Python
mit
819
0.001221
#!/usr/bin/env python import os import
sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_propeller_demo.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is reall...
ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractLimostnWordpressCom.py
Python
bsd-3-clause
380
0.028947
def extractLimostnWordpressCom(item):
''' Parser for 'limostn.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None if "The Outcast" in item['tags']: return buildReleaseMessageWithType(item, "The Outcast", vol, chp, frag=frag, postfix=...
eturn False
GFibrizo/TPS_7529
TDA Grafo/Dijkstra.py
Python
apache-2.0
1,960
0.003061
from grafo import Digraph from CaminoMinimo import CaminoMinimo import heapq class Dijkstra(CaminoMinimo): def __init__(self, grafo, origen, destino): CaminoMinimo.__init__(self, grafo, origen, destino) self.dist_heap = [] #heapq.heapify(self.dist_heap) for i in xrange(self.grafo.V...
cia_actual, None return heapq.heappop(heap) graph = Digraph(8) graph.add_edge(0, 1, 1) # 1 -- graph.add_edge(0, 2, 3) # 3 graph.add_edge(2, 3, 1) # 1 graph.add_edge(3, 4, 1) # 1 graph.add_edge(1, 4, 1) # 4 graph.add_edge(1, 2, 1) # 1 graph.add_edge(4, 5, 5) # 2 graph.add_edge(5,...
ph.add_edge(6, 7, 1) # 1 search = Dijkstra(graph, 0, 7) print search.camino(7) print search.distancia(7)
craws/OpenAtlas
openatlas/util/changelog.py
Python
gpl-2.0
26,790
0.000037
versions = { '7.1.1': ['2022-03-04', { 'fix': { '1649': 'Minor label error in model image', '1650': 'Obsolete database version in install SQL'}}], '7.1.0': ['2022-02-15', { 'feature': { '1506': 'Update CIDOC CRM to 7.1.1', '1285': 'Improved value t...
ditional output format RDFS', '1551': 'API: Relation type adaptions, adding relationDescription', '1561': 'Refactor'}, 'fix': { '1557': 'Save buttons blocked by map', '1580': 'H
idden error messages for reference systems', '1570': 'API: Wrong type signature in OpenApi'}}], '6.4.1': ['2021-08-11', { 'fix': { '1559': 'Installation problem because of missing upload folder'}}], '6.4.0': ['2021-08-10', { 'feature': { '1280': 'Picture Previ...
harikishen/addons-server
src/olympia/devhub/tests/test_cron.py
Python
bsd-3-clause
1,566
0
import datetime import os from django.conf import settings from olympia.amo.tests import TestCase from olympia.addons.models import Addon from olympia.devhub.cron import update_blog_posts from olympia.devhub.tasks import convert_purified from olympia.devhub.
models import BlogPost class TestRSS(TestCase): def test_rss_cron(self): url = os.path.join( settings.ROOT, 'src', 'olympia', 'devhub', 'tests', 'rss_feeds', 'blog.xml') settings.DEVELOPER_BLOG_URL = url update_blog_posts() assert BlogPost.objects.count(...
= 'Test!' assert bp.date_posted == datetime.date(2011, 6, 10) assert bp.permalink == url class TestPurify(TestCase): fixtures = ['base/addon_3615'] def setUp(self): super(TestPurify, self).setUp() self.addon = Addon.objects.get(pk=3615) def test_no_html(self): sel...
mfnch/pyrtist
pyrtist/gui/dox/dox.py
Python
lgpl-2.1
2,729
0.009894
# Copyright (C) 2011, 2012 by Matteo Franchin # # This file is part of Pyrtist. # # Pyrtist is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 2.1 of the License, or # (at your optio...
warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Pyrtist. If not, see <http://www.gnu.org/licenses/>. import os import re import fnmatch f...
og_msg, set_log_context from tree import DoxType, DoxProc, DoxInstance, DoxTree from context import Context import builder class Dox(object): def __init__(self): self.file = None self.tree = DoxTree() self.context = Context() def log(self, msg, show_hdr=False): hdr = "" if show_hdr and self.f...
sosguns2002/interactive-mining
interactive-mining-3rdparty-madis/madis/src/functions/vtable/timeslidingwindow.py
Python
gpl-3.0
6,001
0.0025
""" .. function:: timeslidingwindow(timewindow, timecolumn) -> query results Returns the query input results annotated with the window id as an extra column. The following arguments can be passed as parameters: timewindow: It can be a numeric value that specifies the time length of the window (in seconds). timecol...
1:00 1 | 12.05.2010 00:02:00 1 | 12.05.2010 00:03:00 1 | 12.05.2010 00:04:00 >>> table1(''' ... "12.05.2010 00:00:00" ... "12.05.2010 00:01:00" ... "12.05.2010 00:01:00"
... "12.05.2010 00:02:00" ... "12.05.2010 00:03:00" ... "12.05.2010 00:04:00" ... "12.05.2010 00:05:00" ... ''') ... ''') >>> sql("timeslidingwindow timewindow:120 timecolumn:0 select * from table1") wid | a ------------------------- 0 | 12.05.2010 00:00:00 0 | 12.05.2010 0...
ahuarte47/QGIS
tests/src/python/test_qgsvectorfilewriter.py
Python
gpl-2.0
49,644
0.002397
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsVectorFileWriter. .. note:: 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. "...
rc, errmsg = QgsVectorFileWriter.writeAsVectorFormat(ml, file
name, 'utf-8', crs, 'GPKG') # open the resulting geopackage vl = QgsVectorLayer(filename + '.gpkg', '', 'ogr') self.assertTrue(vl.isValid()) # test values idx = vl.fields().indexFromName('fldlonglong') self.assertEqual(vl.getFeature(1).attributes()[idx], 2262000000) ...
knuu/competitive-programming
atcoder/dp/edu_dp_o.py
Python
mit
818
0.002445
import sys import ctypes def popcount(N): if sys.platform.startswith('linux'): libc = ctypes.cdll.LoadLibrary('libc.so.6') return
libc.__sched_cpucount(ctypes.sizeof(ctypes.c_long), (ctypes.c_long * 1)(N)) elif sys.platform == 'darwin': libc = ctypes.cdll.LoadLibrary('libSystem.dylib') return libc.__popcountdi2(N) else: assert(False) def main
(): N = int(input()) mod = 10 ** 9 + 7 A = [[int(x) for x in input().split()] for _ in range(N)] dp = [0] * (1 << N) dp[0] = 1 for state in range(1 << N): dp[state] %= mod i = popcount(state) for j in range(N): if (state >> j & 1) == 0 and A[i][j]: ...
alfateam123/Teca
tests/test_utils.py
Python
mit
902
0.001109
import teca.utils as tecautils import teca.ConfigHandler as tecaconf impor
t unittest class TestFileFilter(unittest.TestCase): def setUp(self): self.conf = tecaconf.ConfigHandler( "tests/test_data/configuration.json", {"starting_path": "tests/test_data/images"} ) self.files_list = [ "foo.doc", "yukinon.jpg", "c...
self.assertTrue("foo.doc" not in tecautils.filterImages(self.files_list, self.conf)) self.assertTrue("yukinon.jpg" in tecautils.filterImages(self.files_list, self.conf)) ...
l33tdaima/l33tdaima
local_packages/binary_tree.py
Python
mit
1,599
0.001251
from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, val: int = 0, left: "TreeNode" = None, right: "TreeNode" = None): self.val = val self.left = left self.right = right @classmethod def serialize(cls, root: "TreeNode") -> str: """...
__ == "__main__": tests = [ "#", "1,#,#", "1,2,#,#,#", "1,#,2,#,#", "1,2,#,#,3,#,#", "1,2,#,#,3,4,5,#,#,#,#", ] for t in tests: actual = TreeNode.serialize(TreeNode.deserialize(t)) print("serialize(deserialize
) ->", actual) assert t == TreeNode.serialize(TreeNode.deserialize(t))
fireeye/flare-floss
floss/api_hooks.py
Python
apache-2.0
14,484
0.001105
# Copyright (C) 2017 FireEye, Inc. All Rights Reserved. import contextlib import envi import viv_utils class ApiMonitor(viv_utils.emulator_drivers.Monitor): """ The ApiMonitor observes emulation and cleans up API function returns. """ def __init__(self, vw, function_index): viv_utils.emulat...
) self._heap_addr = 0x96960000 MAX_ALLOCATION_SIZE = 10 * 1024 * 1024 def _allocate_mem(self, emu, size): size = round(size, 0x1000) if size > self.MAX_ALLOCATION_SIZE: size = self.MAX_ALLOCATION_SIZE va = self._heap_addr self.d("RtlAllocateHeap: mapping %s ...
eap allocation]", b"\x00" * (size + 4)) emu.writeMemory(va, b"\x00" * size) self._heap_addr += size return va def hook(self, callname, driver, callconv, api, argv): # works for kernel32.HeapAlloc if callname == "ntdll.RtlAllocateHeap": emu = driver hh...
lebauce/artub
bike/parsing/pathutils.py
Python
gpl-2.0
5,507
0.005084
# -*- coding: iso-8859-1 -*- # # Bicycle Repair Man - the Python Refactoring Browser # Copyright (C) 2001-2006 Phil Dawes <phil@phildawes.net> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # A some of this code is ...
files: list.extend(getFilesForName(file)) return list # try to find module or package name = getPathOfModuleOrPackage(name,[]) if not name: return[] if os.path.isdir(
name): # find all python files in directory list = [] os.path.walk(name, _visit_pyfiles, list) return list elif os.path.exists(name) and not name.startswith("."): # a single file return [name] return [] def _visit_pyfiles(list, dirname, names): """ Helper fo...
fermat618/pida
pida-plugins/quickopen/quickopen.py
Python
gpl-2.0
7,589
0.003031
# -*- coding: utf-8 -*- """ :copyright: 2005-2008 by The PIDA Project :license: GPL 2 or later (see README/COPYING/LICENSE) """ # stdlib import os.path # gtk import gtk, gobject # PIDA Imports # core from kiwi.ui.objectlist import Column from pida.core.service import Service from pida.core.features impor...
ult(accept=True) else: return Result(accept=True) project = self.svc.boss.cmd('project', 'get_current_project') if not project: return for result in project.indexer.query(do_filter): self.olist.append(result) return False ...
def on_olist__key_press_event(self, widget, event): if event.keyval == gtk.keysyms.Escape and self.pane.get_params().detached: self.can_be_closed() def on_filter_keypress(self, widget, event): if event.keyval == gtk.keysyms.Tab and len(self.olist): gcall(self.olist.grab_f...
lfblogs/aiopy
aiopy/required/aiohttp/web_ws.py
Python
gpl-3.0
8,998
0
__all__ = ('WebSocketResponse', 'MsgType') import asyncio import warnings from . import hdrs from .errors import HttpProcessingError, ClientDisconnectedError from .websocket import do_handshake, Message, WebSocketError from .websocket_client import MsgType, closedMessage from .web_exceptions import ( HTTPBadReque...
type(data)) self._writer.send(data, binary=True) @asyncio.coroutine def wait_closed(self): # pragma: no cover warnings.warn( 'wait_closed() coroutine is deprecated. use close() instead', DeprecationWarning) return (yield from self.close...
elf): if self._eof_sent: return if self._resp_impl is None: raise RuntimeError("Response has not been started") yield from self.close() self._eof_sent = True @asyncio.coroutine def close(self, *, code=1000, message=b''): if self._writer is None: ...
isislab/CTFd
tests/test_plugin_utils.py
Python
apache-2.0
7,989
0.001377
#!/usr/bin/env python # -*- coding: utf-8 -*- from CTFd.plugins import ( bypass_csrf_protection, get_admin_plugin_menu_bar, get_user_page_menu_bar, override_template, register_admin_plugin_menu_bar, register_admin_plugin_script, register_admin_plugin_stylesheet, register_plugin_asset, ...
csrf_protection( bypass_csrf_protection_test_route ) with app.test_client() as client: r = client.post("/login") output = r.get_data(as_text=True) assert r.
status_code == 200 assert output == "Success" destroy_ctfd(app) def test_challenges_model_access_plugin_class(): """ Test that the Challenges model can access its plugin class """ app = create_ctfd() with app.app_context(): from CTFd.plugins.challenges import get_chal_clas...
sketchfab/io_object_mu
import_mu.py
Python
gpl-2.0
15,783
0.003485
# vim:ts=4:et # ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This prog...
ype = 'FREE' if i > 0: dist = (key.time - curve.keys[i - 1].time) / 3
dx, dy = dist * fps, key.tangent[0] * dist * mult else: dx, dy = 10, 0.0 fc.keyframe_points[i].handle_left = x - dx, y - dy if i < len(curve.keys) - 1: dist = (curve.keys[i + 1].time - key.time) / 3 dx, dy = dist * fps, key.tangent[1] * dist * mult ...
mazelife/django-scaffold
docs/settings.py
Python
bsd-3-clause
698
0
# A very basic settings file that allows Sphinx to build # the docs (this is becuase autodoc is used). import os import sys sys.path.insert(0, os.getcwd()) sys.path.insert(0, os.path.join(os.getcwd(), os.pardir)) SITE_ID = 303 DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = {"default": { "NAME": ":memory:", "...
th', 'django.contrib.contenttypes'
, 'django.contrib.sessions', 'django.contrib.sites', 'scaffold', ) SECRET_KEY = "NULL" SCAFFOLD_EXTENDING_APP_NAME = "scaffold" SCAFFOLD_EXTENDING_MODEL_PATH = "scaffold.models.BaseSection"
rishig/zulip
zerver/tests/test_docs.py
Python
apache-2.0
24,048
0.002828
# -*- coding: utf-8 -*- import os import subprocess import ujson from django.conf import settings from django.test import TestCase, override_settings from django.http import HttpResponse from typing import Any, Dict, List from zproject.settings import DEPLOY_ROOT from zerver.lib.integrations import INTEGRATIONS from...
]) for integration in INTEGRATIONS.keys(): url = '/integrations/doc-html/{}'.format(integration) self._test(url, '', doc_html_str=True) def test_integration_pages_open_graph_metadata(self) -> None: url = '/integrations/doc/github'
title = '<meta property="og:title" content="Connect GitHub to Zul
ujjwal96/mitmproxy
mitmproxy/io/db.py
Python
mit
1,107
0.000903
import sqlite3 import os from mitmproxy.io import protobuf class DBHandler: """ This class is wrapping up connection to SQLITE DB. """ def __init__(self, db_path, mode='load'): if mode == 'write': if os.path.isfile(db_path): os.remove(d
b_path) self.db_path = db_path self._con = sqlite3.connect(self.db_path) self._c = self._con.cursor() self._create_db() def _create_db(self): with self._con: self._co
n.execute('CREATE TABLE IF NOT EXISTS FLOWS(' 'id INTEGER PRIMARY KEY,' 'pbuf_blob BLOB)') def store(self, flows): blobs = [] for flow in flows: blobs.append((protobuf.dumps(flow),)) with self._con: self._co...
valesi/electrum
gui/kivy/uix/dialogs/wallets.py
Python
gpl-3.0
1,677
0.001193
from kivy.app import App from kivy.factory import Factory from kivy.properties import ObjectProperty from kivy.lang import Builder from elect
rum.i18n import _ from electrum.util import base_units import os from label_dialog import LabelDialog Builder.load_string(''' #:import os os <WalletDialog@Popup>: title: _('Wallets') id: popup path: '' BoxLayout: orientation: 'vertical' FileChooserListView: id: wallet_selec...
*.*' path: os.path.dirname(app.wallet.storage.path) size_hint_y: 0.6 Widget size_hint_y: 0.1 GridLayout: cols: 2 size_hint_y: 0.1 Button: size_hint: 0.1, None height: '48dp' text: _('C...
tobiz/OGN-Flight-Logger_V3
flogger_email_msg.py
Python
gpl-3.0
1,212
0.012376
import smtplib import base64 from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEBase import MIMEBase from email import encoders from __bui
ltin__ import file import flogger_settings import os import datetime def email_msg(sender, receiver, msg, date, settings): # print "Send take off msg" if settings.FLOGGER_TAKEOFF_EMAIL != "y" and settings.FLOGGER_TAKEOFF_EMAIL != "Y": # Don't send take off email msg return # body = "Msg from...
, date) print body msg = MIMEMultipart() msg.attach(MIMEText(body, 'plain')) fromaddr = sender toaddr = receiver msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = body server = smtplib.SMTP(settings.FLOGGER_SMTP_SERVER_URL, settings.FLOGGER_SMTP_SERVER_PORT) ...
RPGOne/Skynet
pytorch-master/torch/legacy/nn/ParallelCriterion.py
Python
bsd-3-clause
1,404
0.001425
import torch from .Criterion import Criterion from .utils import recursiveResizeAs, recursiveFill, recursiveAdd class ParallelCriterion(Criterion): def __init__(self, repeatTarget=False): super(ParallelCriterion, self).__init__() self.criterions = [] self.weights = [] self.gradInp...
rget = repeatTarget def add(self, criterion, weight=1): self.criterions.append(criterion) self.weights.append(weight) return self def updateOutput(self, input, target): self.output = 0 for i, criterion in enumerate(self.criterions): current_target = target i...
t += self.weights[i] * criterion.updateOutput(input[i], current_target) return self.output def updateGradInput(self, input, target): self.gradInput = recursiveResizeAs(self.gradInput, input)[0] recursiveFill(self.gradInput, 0) for i, criterion in enumerate(self.criterions): ...
fountainment/FountainEngineImproved
fountain/render/convert_shader.py
Python
mit
396
0.007576
#!/usr/bin/env python import sys def convert_str(infile, outfile): f = open(infile, 'r') lines = f.readlines() f.close()
f = open(outfile, 'w') f.writelines(['"%s\\n"\n' % i.rstrip() for i in lines]) f.close() def main(): convert_str('fountain.vert', 'fountain.vert.inc') convert_str('fountain.frag', 'fountain.frag.inc') if
__name__ == '__main__': main()
Vagab0nd/SiCKRAGE
lib3/imdb/parser/http/searchCompanyParser.py
Python
gpl-3.0
2,406
0.001247
# Copyright 2008-2018 Davide Alberani <da@erlug.linux.it> # 2008-2018 H. Turgut Uyar <uyar@tekir.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 2 of the License,...
RCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of th
e GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module provides the classes (and the instances) that are used to parse the results of a search for a given company. For example, when searchin...
races1986/SafeLanguage
CEM/families/i18n_family.py
Python
epl-1.0
6,800
0.000294
# -*- coding: utf-8 -*- __version__ = '$Id: 7e07cc8b51fa2cdfb23c34c8652adf4a94003dc8 $' import family # The Wikimedia i18n family class Family(family.Family): def __init__(self):
family.Family.__init__(self) self.name = 'i18n' self.langs = { 'i18n': 'translatewiki.net', } self.namespaces[4] = { '_default': [u'Project'], } self.namespaces[5] = { '_default': [u'Project talk'], } self.namespaces[6...
'_default': [u'File talk'], } self.namespaces[90] = { '_default': [u'Thread'], } self.namespaces[91] = { '_default': [u'Thread talk'], } self.namespaces[92] = { '_default': [u'Summary'], } self.namespaces[93]...
fake-name/IntraArchiveDeduplicator
Tests/Test_db_BKTree_Compare.py
Python
bsd-3-clause
1,765
0.026062
import unittest import time import pprint import logging import scanner.logSetup as logSetup import pyximport print("Have Cython") pyximport.install() import dbPhashApi class TestCompareDatabaseInterface(unittest.TestCase): def __init__(self, *args, **kwargs): logSetup.initLogging() super().__init__(*args,...
load() def dist_check(self, distance, dbid, phash): qtime1 = time.time() have1 = self.tree.ge
tWithinDistance_db(phash, distance=distance) qtime2 = time.time() qtime3 = time.time() have2 = self.tree.getIdsWithinDistance(phash, distance=distance) qtime4 = time.time() # print(dbid, have1) if have1 != have2: self.log.error("Mismatch!") for line in pprint.pformat(have1).split("\n"): self.log...
Lukasa/spdypy
test/test_api.py
Python
mit
368
0
# -*- coding: utf-8 -*- """ test/test_api ~~~~~~~~~ Tests of the top-level SPDYPy API. These will be relatively sparse for the m
oment. """ # Nasty little path hack. import sys sys.path.append('.') class TestAPI(object): """ Tests for the top-level spdypy API. """ def test_can_import_spdypy_on_py_33(self): import spdypy assert Tr
ue
SauloAislan/ironic
ironic/api/app.py
Python
apache-2.0
3,844
0
# -*- encoding: utf-8 -*- # Copyright © 2012 New Dream Network, LLC (DreamHost) # 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....
pp, audit_map_file=CONF.audit.audit_map_file, ignore_req_list=CONF.audit.ignore_req_list ) except (EnvironmentError, OSError, audit_middleware.PycadfAuditApiConfigError) as e: raise exception.InputFileError( file_name=CONF.a...
F.auth_strategy == "keystone": app = auth_token.AuthTokenMiddleware( app, dict(cfg.CONF), public_api_routes=pecan_config.app.acl_public_routes) # Create a CORS wrapper, and attach ironic-specific defaults that must be # included in all CORS responses. app = IronicCORS(app, C...
cwoebker/pen
pen/__init__.py
Python
bsd-3-clause
182
0
# -*- coding: utf-8 -*- """ pen: terminal notes """ __title__ = 'pen'
__author__ = 'cwoebker' __version__ = '0.4.2' __license__ = 'BSD' __copyright__ = '© 2013-2018 C
ecil Wöbker'
elena/dev-parse
posts/migrations/0002_auto__add_field_post_posts.py
Python
bsd-2-clause
3,048
0.007874
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migrat
ion(SchemaMigration): def fo
rwards(self, orm): # Adding field 'Post.posts' db.add_column(u'posts_post', 'posts', self.gf('django.db.models.fields.PositiveIntegerField')(default=0), keep_default=False) def backwards(self, orm): # Deleting field 'Post.posts' db.delete...
tima/ansible
lib/ansible/modules/network/aci/aci_interface_policy_leaf_policy_group.py
Python
gpl-3.0
15,589
0.003207
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Bruno Calogero <brunocalogero@hotmail.com> # 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_...
t of the leaf policy group to be created. a
liases: [ lldp_policy_name ] stp_interface_policy: description: - Choice of stp_interface_policy to be used as part of the leaf policy group to be created. aliases: [ stp_interface_policy_name ] egress_data_plane_policing_policy: description: - Choice of egress_data_plane_policing_policy to be used as ...
wdbm/media_editing
media_editing.py
Python
gpl-3.0
2,382
0.010915
# -*- coding: utf-8 -*- """ ################################################################################ # # # media_editing # # ...
# #
# ################################################################################ """
PC-fit-Christian-Rupp/serverstatepage
code/testroutine/dm_server.py
Python
mit
1,222
0.047463
import os import enums class dm_server: def __init__ (self, Name, Ip, statistics, Os = None): self.__name = Name self.__ip = Ip self.__services = [] self.__statistics = statistics if Os: self.__os = Os else: self.__os = None def addService (self, Service): self.__services.append(Service) def ...
checkOs(self): pass def __checkVersionMac(self): pass def __checkVersionLinux(self): pass def __checkVersionWin(self): pass def getOs(self): return self.__os def getVersion(self): pass def getList(self): return self.__services def getState(self): return self.__state def getName(self): ...
__name def getIp(self): return self.__ip def getStatistic(self): return self.__statistic
DoubleNegativeVisualEffects/gaffer
python/GafferUI/Slider.py
Python
bsd-3-clause
14,206
0.062509
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted ...
ex( self ) : return self.__selectedIndex def selectedIndexChangedSignal( self ) : signal = getattr( self, "_selectedIndexChangedSignal", None ) if signal is None : signal = GafferUI.WidgetSignal() self._selectedIndexChangedSignal = signal return signal ## Determines whether or not positions m...
self.__sizeEditable = editable def getSizeEditable( self ) : return self.__sizeEditable ## Sets a size after which no more positions can # be removed. def setMinimumSize( self, minimumSize ) : self.__minimumSize = minimumSize def getMinimumSize( self ) : return self.__minimumSize ## May ...
ryfx/modrana
core/configs.py
Python
gpl-3.0
6,907
0.00304
# -*- coding: utf-8 -*- #---------------------------------------------------------------------------- # ModRana config files handling #---------------------------------------------------------------------------- # Copyright 2012, Martin Kolman # # This program is free software: you can redistribute it and/or modify # i...
upgradeCount += 1 except Exception: log.exception("upgrading config file: %s failed", config) if upgradeCount: log.info("%d configuration files upgraded", upgradeCount) else: log.info("no configuration files needed upgrade") def loadA...
f.loadMapConfig() self.loadUserConfig() def getUserConfig(self): return self.userConfig def loadUserConfig(self): """load the user oriented configuration file.""" path = os.path.join(self.modrana.paths.getProfilePath(), "user_config.conf") try: config = Con...
archives-new-zealand/archwayimportgenerator
libs/unicodecsv.py
Python
gpl-3.0
7,077
0.001559
# -*- coding: utf-8 -*- import sys import csv from itertools import izip # https://pypi.python.org/pypi/unicodecsv # http://semver.org/ VERSION = (0, 9, 4) __version__ = ".".join(map(str, VERSION)) pass_throughs = [ 'register_dialect', 'unregister_dialect', 'get_dialect', 'list_dialects', 'field_...
w.writerow({'name': u'Willam ø. Unicoder', 'place': u'éSpandland'}) >>> f.seek(0) >>> r = DictReader(f, fieldnames=['name', 'place']) >>> print r.next() == {'name': 'Cary Grant', 'place': 'hollywood'} True >>> print r.next() == {'name': 'Na
than Brillstone', 'place': u'øLand'} True >>> print r.next() == {'name': u'Willam ø. Unicoder', 'place': u'éSpandland'} True """ def __init__(self, csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', encoding='utf-8', errors='strict', *args, **kw...
uploadcare/pyuploadcare
tests/functional/ucare_cli/test_update_webhook.py
Python
mit
484
0
import pytest from tests.functional.ucare_cli.helpers import arg_namespace from pyuploadcare.ucare_cli.commands.update_webhook import update_webhook @pyte
st.mark.vcr def test_update_webhooks(capsys, uploadcare): update_webhook( arg_namespace( "update_webhook 865715 --deactivate " "--target_url=https://webhook.site/updated" ),
uploadcare, ) captured = capsys.readouterr() assert '"is_active": false' in captured.out
plaid/plaid-python
plaid/model/link_token_create_request_update.py
Python
mit
6,717
0.000447
""" The Plaid API The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from plaid.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal...
raised if the wrong type is input.
Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the...
gamesun/MyTerm-for-WangH
GUI.py
Python
bsd-3-clause
16,544
0.001572
#!/usr/bin/env python # -*- coding: UTF-8 -*- # # generated by wxGlade 0.6.8 (standalone edition) on Tue Jan 14 10:41:03 2014 # import wx import wx.grid # begin wxGlade: dependencies # end wxGlade # begin wxGlade: extracode # end wxGlade class MyFrame(wx.Frame): def __init__(self, *args, **kwd...
reateGrid(50, 9) self.grid_csv.SetRowLabelSize(25) self.grid_c
sv.SetColLabelSize(21) self.button_1.SetMinSize((-1, 20)) self.button_2.SetMinSize((-1, 20)) self.button_3.SetMinSize((-1, 20)) self.button_4.SetMinSize((-1, 20
harry-ops/opencloud
webvirtcloud/networks/views.py
Python
gpl-2.0
4,905
0.001427
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse from computes.models import Compute from networks.forms import AddNetPool from vrtManager.network import wvmNetwork, wv...
onseRedirec
t(reverse('network', args=[compute_id, data['name']])) else: for msg_err in form.errors.values(): error_messages.append(msg_err.as_text()) conn.close() except libvirtError as lib_err: error_messages.append(lib_err) return render(reques...
gabegaster/connectedness
experiment.py
Python
mit
748
0.022727
import numpy as np from itertools import combinations, imap from timer import show_progress from connectedness
import is_connected def brute_main(): for N in show_progress(xrange(4,1000)): print N,brute(N) def brute(N): return sum(is_connected(s) for s in combinations(xrange(N),3)) def mu(N,k=3): data = [is_connected(np.random.choice(N, k, replace=False)) for _ in xrange(10**3)
] return np.mean(data) def bootstrap(N,k=3): data = [mu(N,k) for _ in xrange(10)] return np.mean(data), (max(data)-min(data))/2 def boot_main(): for N in show_progress(xrange(10,10**3)): print ",".join(map(str,[N]+list(bootstrap(N,k=int(N**.5))))) if __name__=="__main__": boot_main()
lssfau/walberla
tests/field/codegen/JacobiKernel.py
Python
gpl-3.0
1,066
0.00469
import numpy as np import pystencils as ps from pystencils_walberla import CodeGeneration, generate_sweep with CodeGeneration() as ctx: # ----- Stencil 2D - created by specifying weights in nested list -------------------------- src, dst = ps.fields("src, src_tmp: [2D]", layout='fzyx') stencil = [[1.11, 2...
nc(): dst[0, 0, 0] @= (3 * src[1, 0, 0] + 4 * src[-1, 0, 0] + 5 * src[0, 1, 0] + 6 * src[0, -1, 0]
+ 7 * src[0, 0, 1] + 8 * src[0, 0, -1]) / 33 generate_sweep(ctx, 'JacobiKernel3D', kernel_func, field_swaps=[(src, dst)])
pengkobe/leetcode
questions/Palindrome_Number.py
Python
gpl-3.0
1,166
0.014315
# -*- coding: utf-8 -*- # 本题难度:★ # 不使用额外储存空间,判断一个整数是否为回文数字。例如: # -22 -> false # 1221 -> true # 1221221 -> true # 1234321 -> true # 234 -> false # 需要注意的是: # 考虑负数 # 不允许使用额外储存空间,比如将数字转换成字符串 # 反转数字需要考虑溢出问题 # 参考答案:https://github.com/barretlee/daily-algorithms/blob/master/answers/7.md import math def Palindrome_Number(nu...
else: return False; return True; print(Palindrome_Number(10)) print(Palindrome_Number(1)) print(Palindrome_Number(-22)) print(Palindrome_Number(1221)) print(Palindrome_Number(1221221)) print(Palind
rome_Number(1234321)) print(Palindrome_Number(234))
spulec/moto
tests/test_es/test_server.py
Python
apache-2.0
352
0
import json
import sure # noqa # pylint: disable=unused-import import moto.server as server def test_es_list(): backend = server.create_backend_app("es") test_client = backend.test_client() resp = test_client.get("/2015-01-01/domain") resp.status_code.should.equal(200) json.loads(resp.data
).should.equals({"DomainNames": []})
jonathanf/infosalud
visit/visit.py
Python
agpl-3.0
3,450
0.002319
# # Copyright (C) 2014 Jonathan Finlay <jfinlay@riseup.net> # # 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 la...
context: :return: """ if consulting_room: consulroom_obj = self.pool.get('consulting.room') duration = consulroom_obj.browse(cr, uid, consulting_room, context=context)[0].duration else: duration = 0.0 vals = { 'value': { ...
'name': fields.char('Identifier'), 'starts': fields.datetime('Start date'), 'duration': fields.float('Duration', help='Duration in minutes'), 'patient_id': fields.many2one('patient', 'Patient'), 'consultingroom_id': fields.many2one('consulting.room...
bigvat/vat
common.py
Python
apache-2.0
3,323
0.040024
#!/usr/bin/env python #-*- coding: ascii -*- from __future__ import print_function import sys import platform def copy_to_dst(src_name, dst_dir): print("Copy %s to %s" % (src_name, dst_dir)) import shutil shutil.copy(src_name, dst_dir) #cfg, address_model=32/64, version_type=debug/release; def getEnvInfo(address...
iler_name = "vc" compiler_version = 10 elif "vc9" == cfg: generator = "Visual Studio 9 2008" compiler_name = "vc" compiler_version = 9 elif "vc8" == cfg: generator = "Visual Studio 8 2005" compiler_name = "vc" compiler_version = 8 elif "mingw" == cfg:
generator = "MinGW Makefiles" compiler_name = "gcc" compiler_version = 0 elif "gcc" == cfg: generator = "Unix Makefiles" compiler_name = "gcc" compiler_version = 0 else: print("Wrong compiler configuration\n") sys.exit(1) # prepare file suffix if "win32" == plat: bat_suffix = "bat" dll_suffix =...
erinspace/osf.io
website/project/views/drafts.py
Python
apache-2.0
13,819
0.003329
import functools import httplib as http import itertools from operator import itemgetter from dateutil.parser import parse as parse_date from django.core.exceptions import ValidationError from django.db.models import Q from django.utils import timezone from flask import request, redirect import pytz from framework.d...
t_schema_or_fail = lambda query: get_or_http_error(RegistrationSchema, query) autoload_draft = functools.partial(autoload, DraftRegistration, 'draft_id', 'draft') def must_be_branched_from_node(func): @autoload_draft @must_be_valid_project @functools.wraps(func) def wrapper(*args, **kwargs): no...
e HTTPError(http.GONE) if not draft.branched_from._id == node._id: raise HTTPError( http.BAD_REQUEST, data={ 'message_short': 'Not a draft of this node', 'message_long': 'This draft registration is not created from the given nod...
deafhhs/adapt
clients/migrations/0018_merge.py
Python
mit
297
0
# -*- coding: utf-8 -*- from __f
uture__ import unicode_literals from django.db import migrations, models class
Migration(migrations.Migration): dependencies = [ ('clients', '0017_auto_20151025_1240'), ('clients', '0015_auto_20151025_1209'), ] operations = [ ]
rackerlabs/horizon
openstack_dashboard/dashboards/admin/projects/urls.py
Python
apache-2.0
1,755
0.00057
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # no...
t IndexView from openstack_dashboard.dashboards.admin.projects.views \ import ProjectUsageView from openstack_dashboard.dashboards.admin.projects.views \ import UpdateProjectView urlpatterns = patterns('', url(r'^$', IndexView.as_view(), name='index'), url(r'^create$', CreateProjectView.as_view(), nam...
age/$', ProjectUsageView.as_view(), name='usage'), url(r'^(?P<tenant_id>[^/]+)/create_user/$', CreateUserView.as_view(), name='create_user'), )
hanlind/nova
nova/conf/cells.py
Python
apache-2.0
15,948
0.003386
# Copyright 2015 OpenStack Foundation # 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 requ...
c task run. """), # TODO(sfinucan): Add min parameter cfg.IntOpt("instance_
update_num_instances", default=1, help=""" Instance update num instances On every run of the periodic task, nova cells manager will attempt to sync instance_updated_at_threshold number of instances. When the manager gets the list of instances, it shuffles them so that multiple nova-cells services do no...
kvar/ansible
lib/ansible/modules/cloud/amazon/aws_codecommit.py
Python
gpl-3.0
6,565
0.00198
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Shuang Wang <ooocamel@icloud.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_versi...
ciated with the repository." returned: when state is present type: str sample: "268342293637" arn: description: "The Amazon Resource Name (ARN) of the repository." returned: when state is present type: str sample: "arn:aws:codecommit:ap-northeast-1:268342293637:username" ...
description: "The URL to use for cloning the repository over HTTPS." returned: when state is present type: str sample: "https://git-codecommit.ap-northeast-1.amazonaws.com/v1/repos/reponame" clone_url_ssh: description: "The URL to use for cloning the repository over SSH." returned:...
mattmillr/utaka
src/exceptions/BadRequestException.py
Python
apache-2.0
11,951
0.038407
#Copyright 2009 Humanitarian International Services Group # #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...
rgument', 'ArgumentValue' : argValue, 'ArgumentName' : argName}) class InvalidArgumentAuthorizationException(InvalidArgumentException): def __init__(self, argValue): headerPrefix = str(Config.get('authentication', 'prefix')) Invali
dArgumentException.__init__(self, argValue, 'Authorization', ("Authorization header is invalid. Expected " + headerPrefix + " AccessKeyId:signature")) class InvalidArgumentAuthorizationSpacingException(InvalidArgumentException): def __init__(self, argValue): InvalidArgumentException.__init__(self, argValue, 'Author...
niespodd/flyer_generator
main.py
Python
mit
2,191
0.006846
# Script Name : main.py # Author : Shy Ruparel # Created : September 8 2015 # Pulls in data from "data.csv" which is 2 columns wide # Uses a base image as the background # Uses the data - school name, and venue address - # and prints onto the base image # and saves every image as a .PNG fro...
, fill="white") draw.text(((W-wAddress)/2,((H-hAddress)/2)+hVenue+125), addressDetails,font=address, fill="white") # Save out the image filename = 'output/' + venueName.strip() + '.png'
filename = filename.replace (" ", "_") print filename im.save(filename,'PNG')
SciLifeLab/scilifelab
scripts/xls2ped.py
Python
mit
751
0
""" Convert Excel document (.xls) delivered from MAF to a ped.txt file. """ import argpa
rse import csv import xlrd def main(xls_file, out_file, sheet_name): with xlrd.open_workbook(xls_file) as workbook: worksheet = workbook.sheet_by_name(sheet_name) with open(out_file, 'w') as fh: c = csv.write
r(fh, delimiter='\t') for row in range(worksheet.nrows): c.writerow(worksheet.row_values(row)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('xls_file') parser.add_argument('out_file') parser.add_argument('--sheet_name', default='HaploVie...
leppa/home-assistant
homeassistant/components/pilight/binary_sensor.py
Python
apache-2.0
6,144
0.000488
"""Support for Pilight binary sensors.""" import datetime import logging import voluptuous as vol from homeassistant.components import pilight from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorDevice from homeassistant.const import ( CONF_DISARM_AFTER_TRIGGER, CONF_NAME, CONF...
} ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up Pilight Binary Sensor.""" disarm = config.get(CONF_DISARM_AFTER_TRIGGER) if disarm: add_entities( [ PilightTriggerSensor(
hass=hass, name=config.get(CONF_NAME), variable=config.get(CONF_VARIABLE), payload=config.get(CONF_PAYLOAD), on_value=config.get(CONF_PAYLOAD_ON), off_value=config.get(CONF_PAYLOAD_OFF), rs...
insomnia-lab/calibre
setup/extensions.py
Python
gpl-3.0
24,319
0.005222
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import textwrap, os, shlex, subprocess, glob, shutil from distutils import sysconfig ...
ension('msdes', ['calibre/utils/msdes/msdesmodule.c', 'calibre/utils/msdes/des.c'], headers=['calibre/utils/msdes/spr.h', 'calibre/utils/msdes/d3des.h'], inc_dirs=['calibre/utils/msdes']), Extension('cPalmdoc', ...
'calibre/ebooks/djvu/bzzdecoder.c'], inc_dirs=(['calibre/utils/chm'] if iswindows else []) # For stdint.h ), Extension('matcher', ['calibre/utils/matcher.c'], headers=['calibre/utils/icu_calibre_utils.h'], libraries=icu_libs, lib_dirs=icu_lib_dirs, cflags=icu_cf...
guorendong/iridium-browser-ubuntu
tools/metrics/rappor/PRESUBMIT.py
Python
bsd-3-clause
1,156
0.007785
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for rappor.xml. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details on the presubmit API built ...
h() if (input_api.basename(p) == 'rappor.xml' and input_api.os_path.dirname(p) == input_api.PresubmitLocalPath()): cwd = input_api.os_path.dirname(p) exit_code = input_api.subprocess.call( ['python', 'pretty_print.py', '--presubmit'], cwd=cwd) if exit_code != 0: return [o...
angeOnUpload(input_api, output_api): return CheckChange(input_api, output_api) def CheckChangeOnCommit(input_api, output_api): return CheckChange(input_api, output_api)