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 |
|---|---|---|---|---|---|---|---|---|
TrivialBox/HackatonUPS2016 | helpfriends/login/urls.py | Python | mit | 114 | 0.008772 | from django.conf.urls import | url
from . import views
urlpatterns = [
url(r'^$', views.login, name='lo | gin'),
] |
rreimann/electron | script/upload.py | Python | mit | 8,894 | 0.011806 | #!/usr/bin/env python
import argparse
import errno
import hashlib
import os
import shutil
import subprocess
import sys
import tempfile
from io import StringIO
from lib.config import PLATFORM, get_target_arch, get_env_var, s3_config, \
get_zip_name
from lib.util import electron_gyp, execute, ge... | ffmpeg))
# Upload chromedriver and mksnapshot for minor version update.
if parse_version(args.version)[2] == '0':
chromedriver = get_zip_name('chromedriver', ELECTRON_VERSION)
upload_electron(github, release, os.path.join(DIST_DIR, chromedriver))
mksnapshot = get_zip_name('mksnapshot', ELECTRON_VERSION... | d PDBs to Windows symbol server.
run_python_script('upload-windows-pdb.py')
# Upload node headers.
run_python_script('create-node-headers.py', '-v', args.version)
run_python_script('upload-node-headers.py', '-v', args.version)
def parse_args():
parser = argparse.ArgumentParser(description='upload d... |
home-assistant/home-assistant | homeassistant/components/balboa/climate.py | Python | apache-2.0 | 5,803 | 0.001206 | """Support for Balboa Spa Wifi adaptor."""
from __future__ import annotations
import asyncio
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
FAN_HIGH,
FAN_LOW,
FAN_MEDIUM,
FAN_OFF,
HVAC_MO... | T)
if newtemp < self._client.tmin[self._client.TEMPRANGE_HIGH][scale]:
await self._client.change_temprange(self._client.TEMPRANGE_LOW)
await asyncio.sleep(SET_TEMPERATURE_WAIT)
await self._client.send_temp_change(newtemp)
async def async_set_preset_mode(self, preset_mode) ->... | lidate_mode_or_raise(preset_mode)
if preset_mode not in modelist:
raise ValueError(f"{preset_mode} is not a valid preset mode")
await self._client.change_heatmode(modelist.index(preset_mode))
async def async_set_fan_mode(self, fan_mode):
"""Set new fan mode."""
await sel... |
tobinjt/Flexget | flexget/plugins/operate/version_checker.py | Python | mit | 3,855 | 0.001556 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from past.builtins import basestring
import logging
from datetime import datetime
from sqlalchemy import Column, DateTime
from flexget import db_schema, plugin
from flexg... | e.now()
schema = {
'oneOf': [
{'type': 'boolean'},
{'type': 'string', 'enum': ['always', 'by_interval']},
{
'type': 'object',
'properties': {
'lookup': {'type': 'string', 'enum': ['always', 'by_interval']},
'check_for_dev_version': {'... | ,
},
'additionalProperties': False,
},
]
}
class VersionChecker(object):
"""
A plugin that checks whether user is running the latest flexget version and place a log warning if not.
Checks via interval to avoid hammering, default is 1 day.
Can accept boolean or ['al... |
EventTeam/beliefs | test_oop/__init__.py | Python | gpl-2.0 | 171 | 0.005848 | from test_oop import *
from beliefs.referent import *
i | mport sys
TaxonomyCell.initialize(sys.modules[__name__])
m = MusicalThing()
print m
t = TaxonomyC | ell()
t.to_dot()
|
JonTheBurger/python_class | chapter 3/lessons/default_arguments.py | Python | mit | 383 | 0.007833 | # Lesson 3
# If arguments n3 or later aren't provided by the caller, they'll use a default value instead
def add(n1, n2, n3=0, n4=0, n5=0, n6=0): | # (We'll learn a better way to do something like this later)
return n1 + n2 + n3 + n4 + n5 + n6
print(add(1, 2, 3, 4)) |
# We can explicitly fulfil arguments out of order by using "named parameters"
print(add(n2=1, n1=4, n6=3))
|
followthesheep/galpy | galpy/potential_src/PowerSphericalPotentialwCutoff.py | Python | bsd-3-clause | 6,813 | 0.011449 | ###############################################################################
# PowerSphericalPotentialwCutoff.py: spherical power-law potential w/ cutoff
#
# amp
# rho(r)= --------- e^{-(r/rc)^2}
# r^\alpha
###########... | radial force
HISTORY:
| 2013-06-26 - Written - Bovy (IAS)
"""
r= nu.sqrt(R*R+z*z)
return -self._mass(r)*R/r**3.
def _zforce(self,R,z,phi=0.,t=0.):
"""
NAME:
_zforce
PURPOSE:
evaluate the vertical force for this potential
INPUT:
R - Galactocen... |
wearehoods/django-model-publisher-ai | publisher_test_project/fixtures.py | Python | bsd-3-clause | 6,789 | 0.003535 |
import logging
import sys
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from cms.models import Page, PagePermission
from django_cms_tools.fixtures.pages import CmsPageCreator
# https://github.com/jed... | t("Delete %i users..." % qs.count())
qs.delete()
qs = Group.objects.all()
print("Delete %i user groups..." % qs.count())
qs.delete()
# all_permissions = [
# "%s.%s" % (entry.content_type, entry.codename)
# for entry in Permission.objects.all().order_by("content_type... | r=True, is_active=True)
try:
superuser = superuser_qs[0]
except IndexError:
print("\nERROR: No active superuser found!")
print("Please create one and run again!\n")
sys.exit(-1)
print("Use password from Superuser:", superuser)
encrypted_password = superuser.password
... |
gregdek/ansible | lib/ansible/modules/source_control/gitlab_group.py | Python | gpl-3.0 | 7,470 | 0.002544 | #!/usr/bin/python
# Copyright: (c) 2015, Werner Dijkerman (ikben@werner-dijkerman.nl)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | efore this group can be removed.")
else:
if self._module.check_mode:
self._module.exit_json(changed=True)
try:
group.delete()
except Exception as e:
| self._module.fail_json(msg="Failed to delete a group: %s " % e)
return True
def existsGroup(self, name):
"""When group/user exists, object will be stored in self.groupObject."""
groups = self._gitlab.groups.list(search=name)
if len(groups) == 1:
self.groupOb... |
satiros12/MassHydra | brute-gui.py | Python | mit | 4,425 | 0.011299 | import sys, psutil, subprocess, time
from PyQt4 import QtGui
global config
def kill(proc_pid):
try:
process = psutil.Process(proc_pid)
for proc in process.children(recursive=True):
proc.kill()
process.kill()
except Exception as e:
print "Can't kill process",proc_pid,... | n(config.server_control, "w") as WF:
WF.write("start")
elif(ts == "Stop"):
with open(config.server_control, "w") as WF:
WF.write("stop")
| elif (ts == "Log"):
with open(config.server_control, "w") as WF:
WF.write("log")
time.sleep(float(config.control_updateTime))
self.statusBar().showMessage(sender.text())
def closeEvent(self, event):
if self.id_process != None:
kill(self.id_process.... |
steveandroulakis/mytardis | tardis/tardis_portal/publish/publishservice.py | Python | bsd-3-clause | 2,367 | 0.008872 |
class PublishService():
def __init__(self, providers, experiment):
self.rc_providers = providers
self.experiment = experiment
self.provider = self._get_provider()
def _get_provider(self):
from tardis.tardis_portal.publish.provider.rifcsprovider import RifCsProvider... | module_name, klass_name = pmodule.rsplit('.', 1)
module = import_module(module_name)
except ImportError, e:
# TODO Show appropriate error msg
raise e
| # Create the Instance
try:
provider_class = getattr(module, klass_name)
provider = provider_class()
except AttributeError, e:
# TODO Show appropriate error msg
raise e
... |
katakumpo/nicepy | nicepy/__init__.py | Python | mit | 122 | 0 | from nicepy.assertions import *
from nicepy.decorators import *
from ni | cepy.shortcuts import *
from n | icepy.utils import *
|
coddingtonbear/python-myfitnesspal | myfitnesspal/__init__.py | Python | mit | 128 | 0 | from myfitnesspal.client import Client # noqa
__version__ = "1.16.6"
VERSIO | N = tuple(int(v) for v in __version__.split(" | ."))
|
idea4bsd/idea4bsd | python/helpers/py3only/docutils/parsers/rst/languages/fi.py | Python | apache-2.0 | 3,541 | 0.001412 | # -*- coding: utf-8 -*-
# $Id: fi.py 7119 2011-09-02 13:00:23Z milde $
# Author: Asko Soukka <asko.soukka@iki.fi>
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files ... | s.
"""
Finnish-language mappings for language-dependent features of
reStructuredText.
"""
__docformat__ = 'reStructuredText'
directives = {
# language-dependent: fixed
'huomio': 'attention',
'varo': 'caution',
'code (translation required)': 'code',
'vaara': 'danger',
| 'virhe': 'error',
'vihje': 'hint',
't\u00e4rke\u00e4\u00e4': 'important',
'huomautus': 'note',
'neuvo': 'tip',
'varoitus': 'warning',
'kehotus': 'admonition',
'sivupalkki': 'sidebar',
'aihe': 'topic',
'rivi': 'line-block',
'tasalevyinen': 'parsed-literal',
... |
aestrivex/bctpy | test/nbs_test.py | Python | gpl-3.0 | 779 | 0.001284 | from .load_samples import load_sample_group_dsi, load_sample_group | _fmri, load_sample_group_qball
import numpy as np
import bct
def test_nbs_dsi_qbi():
q = load_sample_group_qball()
d = load_sample_group_dsi()
_nbs_helper(q, d, .5, atol=0.3)
def test_nbs_paired_dsi_qbi():
pass
def test_nbs_dsi_fmri():
d = load_sample_group_dsi()
f = load_sample_group_fmri... | l=.05, thresh=.1, ntrials=25,
paired=False):
# comment
pval, _, _ = bct.nbs_bct(x, y, thresh, k=ntrials, paired=paired)
print(pval, expected_pval)
assert np.allclose(pval, expected_pval, atol=atol)
|
CDSP/generate_zips | generate_zips.py | Python | gpl-3.0 | 5,314 | 0.026177 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Execution example : python generate_zips.py "path/to/folder/to/zip" "path/to/csv/inventory/file" "survey_name"
#
# Libs
#
import csv, logging, os, sys, zipfile, zlib
#
# Config
#
log_folder = 'log'
log_level = logging.DEBUG
ignored_extensions = ['jp2', 'j2k', 'jpf', 'jpx', ... | path_separator + sys.argv[0].replace('.py', '.log')
log_file = os.path.join(log_folder, sys.argv[0].replace('.py', '.log'))
logging.basicConfig(filename = log_file, filemode = 'w', format = '%(asctime)s | %(levelname)s | %(message)s', datefmt = '%m/%d/%Y %I:%M:%S %p', level = log_level)
logging.info('Start')... | ordsbyid = {}
with open(inventory_file, 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
for x in spamreader :
if len(x) == 23 :
recordsbyid[x[1]] = x
# Create archive folder
zf_ol = zipfile.ZipFile(zip_online_folder_name, mode='w', compression=zipfile.ZIP_DEFLATED, ... |
DxCx/nzbToMedia | nzbToGamez.py | Python | gpl-3.0 | 2,702 | 0.011843 | #!/usr/bin/env python2
#
##############################################################################
### NZBGET POST-PROCESSING SCRIPT ###
# Post-Process to CouchPotato, SickBeard, NzbDrone, Mylar, Gamez, HeadPhones.
#
# This script sends the download to your automated media... | , 2, 3).
#
# Set the ionice scheduling class. 0 for none, 1 for real time, 2 for best-effort, 3 for idle.
#ionice_class=2
# ionice scheduling class data.
#
# Set the ionice scheduling class data. This defines the class data, if the class accepts an argument. For real time and best-effort, 0-7 is valid data.
#ionice_cl... | L MAC
#
# enter the mac address of the system to be woken.
#wolmac=00:01:2e:2D:64:e1
# Set the Host and Port of a server to verify system has woken.
#wolhost=192.168.1.37
#wolport=80
### NZBGET POST-PROCESSING SCRIPT ###
########################################################... |
gregvw/EPM-FCC-bulk | epm.py | Python | mit | 4,240 | 0.020755 | from __future__ import division
import itertools as it
import numpy as np
import scipy.linalg as sl
import matplotlib.pyplot as plt
import csv
import sys
from zdict import zdict
# hbar^2/2m in eV-Ang^2
hb2m0 = 3.807
# hcR_infty (eV per Rydberg)
Ry = 13.60569253
def mag2(V):
""" Return the magnitude squared of a ... | open('form_factors.csv','r'),delimiter=',')
param = [[entry.split()[0] for entry in row] for row in reader]
# Store form factors in dictionaries
VS = zdict()
VA = zdict()
a0 = None
# Read form factors and lattice constant from file
row = [p[0] for p in param].index(material)
for i in ... | bz = {r'$\Gamma$':np.array((0,0,0)),
r'X':np.array((0,1,0)),
r'L':np.array((1/2,1/2,1/2)),
r'W':np.array((1/2,1,0)),
r'U':np.array((1/4,1,1/2)),
r'K':np.array((3/4,3/4,0))}
# Follow this path through the Brillouin zone to construct
# the band diagram
pa... |
airbnb/streamalert | tests/unit/streamalert/apps/test_apps/test_aliyun.py | Python | apache-2.0 | 7,474 | 0.002141 | """
Copyright 2018-present Airbnb, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, sof... | 3T19:28:30Z'
},
{
'NextTo | ken': '100',
'RequestId': 'BBBBBBBBB',
'Events': [
{
'eventTime': '2018-06-24T19:29:00Z'
},
{
'eventTime': '2018-06-24T19:28:00Z'
}
],
... |
mven/gonzo.py | gonzo.py | Python | mit | 888 | 0.023649 | # GONZO: A PYTHON SCRIPT TO RECORD PHP ERRORS INTO MONGO
# Michael Vendivel - vendivel@gmail.com
import subprocess
import datetime
from pymongo import MongoClient
# where's the log file
filename = '/path/to/php/logs.log'
# set up mongo client
client = MongoClient('mongo.server.address', 27017)
# w | hich DB
db = client.logs
# which Collection
php_logs = db.php_logs
# open a subprocess to tail (and follow) the log file
f = subprocess.Popen(['tail','-f',filename],\
stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# continue to read the file and record lines into mongo
while True:
# read line by line
line = f.st... | # insert the document into the Collection
post_id = php_logs.insert(post)
# output the line for visual debugging (optional)
print line |
Vito2015/pyextend | pyextend/core/thread/multiprocessTask.py | Python | gpl-2.0 | 6,887 | 0.001452 | #!/usr/bin/env python
# coding: utf-8
"""
multiprocessTask.py
~~~~~~~~~~~~~~~~~~~
a multiprocess model of producer/consumer
task = Task(work_func, 1, 3, counter=0, a='', callback=cb)
results | = task.run()
for i in xrange(26):
lines = ["%d" % i] * random.randint(10, 20)
task.put(lines)
task.finish()
"""
import os
impor | t time
from multiprocessing import Pool as ProcessPool, Manager, cpu_count
__all__ = ['Producer', 'Consumer', 'Task']
class Callable(object):
def __call__(self, *args, **kwargs):
raise NotImplementedError('%s not callable' % self)
def run(self, *args, **kwargs):
raise NotImplementedError('%... |
meliora000/eb_django_app | django_eb/users/migrations/0001_initial.py | Python | mit | 796 | 0.001256 | # -*- coding: utf-8 -*-
# Generated by Django 1. | 9 on 2015-12-30 01:33
from __future__ import unicode_literals
from django.db import migrations, models
class Mig | ration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='USER',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', mode... |
mpeuster/son-emu | examples/performance_measurements/osm_component_startup.py | Python | apache-2.0 | 3,883 | 0.000258 | #!/usr/bin/env python2
# Copyright (c) 2019 Erik Schilling
# 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 ... | ime.time()
lcm.start()
lcm_started = time.time()
| writer.writerow({
'other': other_end - start,
'zookeeper': zookeeper_started - other_end,
'kafka': kafka_started - zookeeper_started,
'mongo': mongo_started - kafka_started,
'nbi': nbi_started - mongo_started,
'ro_db'... |
googleads/googleads-python-lib | examples/adwords/v201809/advanced_operations/add_ad_customizer.py | Python | apache-2.0 | 8,193 | 0.006713 | #!/usr/bin/env python
#
# Copyright 2016 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 requir... | t2': 'Only {=%s.Price}' % feed_name,
'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name,
'finalUrls': ['http://www.exam | ple.com'],
}
# We add the same ad to both ad groups. When they serve, they will show
# different values, since they match different feed items.
operations = [{
'operator': 'ADD',
'operand': {
'adGroupId': adgroup,
'ad': expanded_text_ad
}
} for adgroup in adgroup_ids]
... |
pubs/pubs | tests/test_queries.py | Python | lgpl-3.0 | 9,022 | 0.001331 | # coding: utf8
from __future__ import unicode_literals
import unittest
import dotdot
from pubs.query import (AuthorFilter, CitekeyFilter, FieldFilter,
YearFilter, _query_block_to_filter,
get_paper_filter, InvalidQuery)
from pubs.paper import Paper
import fixtures
doe... | ilter('doe', case_sensitive=True)(doe_paper))
self.assertTrue(AuthorFilter('dOe', case_sensitive=False)(doe_paper))
def test_match_not_first_author(self):
self.assertTrue(A | uthorFilter('motwani')(page_paper))
def test_do_not_match_first_name(self):
self.assertFalse(AuthorFilter('lawrence')(page_paper))
class TestCitekeyFilter(unittest.TestCase):
def test_fails_if_no_citekey(self):
no_citekey = doe_paper.deepcopy()
no_citekey.citekey = ''
self.as... |
esilgard/BreastMR | fhcrc_pathology/Pathologist.py | Python | apache-2.0 | 744 | 0.005376 | '''author@esilgard'''
#
# Copyright (c) 2014-2016 Fred Hutchinson Cancer Research Center
#
# Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
#
from OneFieldPerReport import OneFieldPerReport
import glo | bal_strings as gb
class Pathologist(OneFieldPerReport):
''' extract the name of the pathologist who initially signed the report '''
__version__ = 'Pathologist1.0'
def __init__(self):
super(Pathologist, self).__init__()
self.field_name = 'Pathologist'
self.regex = r'\n([A-Za-z\'\-,. ... | self.table = gb.PATHOLOGY_TABLE
self.value_type = 'match'
|
eusoubrasileiro/fatiando_seismic | fatiando/geothermal/climsig.py | Python | bsd-3-clause | 7,793 | 0 | r"""
Modeling and inversion of temperature residuals measured in wells due to
temperature perturbations in the surface.
Perturbations can be of two kinds: **abrupt** or **linear**.
Forward modeling of these types of changes is done with functions:
* :func:`~fatiando.geothermal.climsig.abrupt`
* :func:`~fatiando.geot... | t** for the
amplitude and age of the change. The available inversion solvers are:
* :class:`~fa | tiando.geothermal.climsig.SingleChange`: inverts for the
parameters of a single temperature change. Can use both abrupt and linear
models.
----
"""
from __future__ import division
import numpy
import scipy.special
from ..inversion.base import Misfit
from ..constants import THERMAL_DIFFUSIVITY_YEAR
def linear(... |
wcmitchell/insights-core | insights/client/auto_config.py | Python | apache-2.0 | 7,561 | 0.000265 | """
Auto Configuration Helper
"""
import logging
import os
import requests
from urlparse import urlparse
from constants import InsightsConstants as constants
from cert_auth import rhsmCertificate
from connection import InsightsConnection
from config import CONFIG as config
logger = logging.getLogger(__name__)
APP_NAM... | = config['proxy']
config['proxy'] = proxy
config['base_url'] = hostname + '/r/insights'
if not verify_connectivity():
logger.warn("Could not auto configure, | falling back to static config")
logger.warn("See %s for additional information",
constants.default_log_file)
config['base_url'] = saved_base_url
if proxy is not None:
if saved_proxy is not None and saved_proxy.lower() == 'none':
saved_proxy = None... |
operatorequals/gatheros | gatheros/editor/cmd_interface.py | Python | bsd-3-clause | 3,370 | 0.07092 | import cmd
import json
import termcolor
from struct_manager import createEmptyCommandGroup, createEmptyStruct, createEmptyCommand
from populator import populateDict
class EditorShell ( cmd.Cmd ) :
def __init__ ( self, file ) :
cmd.Cmd.__init__(self)
self.file = file
# self.struct = json.load ( self.file )
... | _edit_command( self, line ) :
if not line :
print "Need a 'command identifier' "
return
line = line.strip()
toks = line.split()
ident = toks[0]
for gname, group in self.st | ruct['CommandGroups'].iteritems() :
try :
comm = group['Commands'][ident]
break
except :
pass
if not comm :
print "Identifier '%s' doesn't exist" % comm
return
populateDict( comm, False )
def do_edit_group( self, line ) :
if not line :
print "Need a 'command identifier' "
return
... |
wallarelvo/racer | racer/roadmap.py | Python | apache-2.0 | 539 | 0 |
import networkx as nx
class Roadmap(nx.Graph):
def __init__(self, gd, max_dist, *args, **kwarg | s):
self.gd = gd
self.max_dist = max_dist
nx.Graph.__init__(self, *args, **kwargs)
def insert(self, sample):
self.gd.insert(sample)
for smpl in self.gd.get_nearest(sample):
if smpl == sample:
continue
if smpl.dist_to(sample) <= self.ma... | )
def make(*args, **kwargs):
return Roadmap(*args, **kwargs)
|
loopCM/chromium | chrome/test/functional/media/audio_tools.py | Python | bsd-3-clause | 6,222 | 0.010125 | #!/usr/bin/env python
# Copyright (c) 2012 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.
"""Audio tools for recording and analyzing audio.
The audio tools provided here are mainly to:
- record playing audio.
- remove si... | Exception("Mono recording not supported on Windows yet!")
duration = time.strftime('%H:%M:%S', time.gmtime(self._duration))
cmd = [_AUDIO_RECORDER, '/FILE', self._output_file, '/DURATION',
duration]
# This is needed to run SoundR | ecorder.exe on Win-64 using Python-32 bit.
ctypes.windll.kernel32.Wow64DisableWow64FsRedirection(
ctypes.byref(ctypes.c_long()))
else:
num_channels = 1 if self._record_mono else 2
cmd = [_AUDIO_RECORDER, '-d', self._duration, '-f', 'dat', '-c',
str(num_channels), self._outpu... |
thinkasoft/ProyectoRD-dev | l10n_ve_withholding_islr/__init__.py | Python | agpl-3.0 | 1,587 | 0.002522 | #!/usr/bin/python
# -*- encoding: utf-8 -*-
###########################################################################
# Module Written to OpenERP, Open Source Management Solution
# Copyright (C) OpenERP Venezuela (<http://openerp.c | om.ve>).
# All Rights Reserved
###############Credits######################################################
# Coded by: Humberto Arocha <hbto@vauxoo.com>
# María Gabriela Quilarque <gabriela@vauxoo.com>
# Javier Duran <javier@vauxoo.com>
# Planified by: Nhomar ... | da, C.A. http://heladosgilda.com.ve
# Audited by: Humberto Arocha humberto@openerp.com.ve
#############################################################################
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publish... |
sahat/bokeh | examples/plotting/cloud/candlestick.py | Python | bsd-3-clause | 853 | 0.009379 |
from math import pi
import pandas as pd
from bokeh.sampledata.stocks import MSFT
from bokeh.plotting import *
df = pd.DataFrame(MSFT)[:50]
df['date'] = pd.to_datetime(df['date'])
mids = (df.open + df.close)/2
spans = abs(df.close-df.open)
inc = df.close > df.open
dec = df.open > df.close
w = 12*60*60*1000 # half d... | date[dec], mids[dec], w, spans[dec], fill_color="#F2583E", line_co | lor="black")
curplot().title = "MSFT Candlestick"
xaxis().major_label_orientation = pi/4
grid().grid_line_alpha=0.3
# open a browser
show()
|
cn-app-registry/cnr-server | appr/api/config.py | Python | apache-2.0 | 545 | 0 | from __future__ import absolute_import, division, print_function
import os
class Config(object):
""" Default configuration """
DEBUG = False
APPR_URI = os.getenv('APPR_URI', "http://localhost:5000")
class ProductionConfig(Config):
""" Production configuration """
APPR_URI = "ht | tp://localhost:5000"
APPR_BACKEND = 'false'
class DevelopmentConfig(Config):
""" Development configuration """
DEBUG = True
# APPR_URI = 'https://api.appr.sh'
APPR_URI = os.getenv('APPR_URI', "http://loc | alhost:5000")
|
NickSanzotta/WiFiSuite | wifisuite/helpers/macchange.py | Python | mit | 1,617 | 0.019171 | # Module: macchanger.py
# Description: Wrapper for built-in linux tool macchanger.
# Author: Nick Sanzotta/@Beamr
# Version: v 1.09252017
try:
import os, sys, time
from subprocess import Popen, PIPE
from theme import *
except Exception as e:
print('\n [!] MACCHANGE - Error: ' % (e))
sys.exit(1)
def macRandom(int... | ue('*') + 'New MAC Address: %s' % (p2.communicate()[0].rstrip('\n')))
def macManual(interface, macaddress):
wirelessInt = str(interface.get_ifname())
p1 = Popen(["ifconfig " + wirelessInt + " | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'"], shell=True, stdout=PIPE)
print(normal('i') + 'Current MAC Address... | r -m ' + macaddress + ' ' + wirelessInt + ' > /dev/null')
os.system('ifconfig ' + wirelessInt + ' up')
p2 = Popen(["ifconfig " + wirelessInt + " | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'"], shell=True, stdout=PIPE)
print(blue('*') + 'New MAC Address: %s' % (p2.communicate()[0].rstrip('\n')))
|
swesterfeld/beast | yapps2_deb/yapps2.py | Python | lgpl-2.1 | 4,135 | 0.006288 | #!/usr/bin/env python2
#
# Yapps 2 - yet another python parser system
# Copyright 1999-2003 by Amit J. Patel <amitp@cs.stanford.edu>
#
# This version of Yapps 2 can be distributed under the
# terms of the MIT open source license, either found in the LICENSE file
# included with the Yapps distribution
# <http://theory.... | parser
f = s.find(DIVIDER)
if f >= 0: s, postparser = s[:f], '\n\n'+s[f+len(DIVIDER):]
# Create the parser and scanner and parse the text
scanner = grammar.ParserDescriptionScanner(s, filename=inputfilena | me)
if preparser: scanner.del_line += preparser.count('\n')
parser = grammar.ParserDescription(scanner)
t = runtime.wrap_error_reporter(parser, 'Parser')
if t is None: return 1 # Failure
if preparser is not None: t.preparser = preparser
if postparser is not None: t.postparser = postparser
... |
nbateshaus/chem-search | inchi-split/splitter.py | Python | bsd-3-clause | 9,306 | 0.016548 |
import re
from collections import namedtuple
# this is almost a validating expression, it could certainly be simpler by just using [^/]* inside the groups
chargeDef = r"(/q[\-\+0-9;\*mMnNi]*)?"
protonationDef = r"(/p[\-\+0-9,;]*)?"
isotopeDef = r"(/i[\-\+0-9,;HDT]*(?:/h[0-9HDT]+)*)?"
stereoBondDef=r"(/b[\-\+0-9,\?\*;... | otopes
From: O=C([18O])/C=C/C(=[18O])O
>>> tpl = extractLayers('InChI=1/C4H3O4/c5-3(6)1-2-4(7)8/h1-2H,(H,5,6)/b2-1+/i5+2,7+2/f/h5H/i6+2,7+2')
>>> tpl.isotope
'i5+2,7+2'
>>> tpl.fixedh_isotope
'i6+2,7+2'
Fixed Hs causes stereo_bond
From: F[C@H](Cl | )/C=C/C=C(/CC(O)=N)CC(=O)N
>>> tpl = extractLayers('InChI=1/C9H12ClFN2O2/c10-7(11)3-1-2-6(4-8(12)14)5-9(13)15/h1-3,7H,4-5H2,(H2,12,14)(H2,13,15)/b3-1+/t7-/m0/s1/f/h12,14H,13H2/b3-1+,6-2-,12-8?')
>>> tpl.fixedh
'f/h12,14H,13H2'
>>> tpl.fixedh_stereo_bond
'b3-1+,6-2-,12-8?'
Fixed Hs causes stereo... |
alimon/oeqa2 | oeqa2/test/decorator/__init__.py | Python | mit | 1,356 | 0.007375 | # Copyright (C) 2016 Intel Corporation
# Released under the MIT license (see COPYING.MIT)
from functools import wraps
class OETestDecorator(object):
case = None # Reference of OETestCase decorated
attrs = None # Attributes to be loaded by decorator implementation
d | ef __init__(self, *args, **kwargs):
if not self.attrs:
return
for idx, attr in enumerate(self.attrs):
attr_type = self.attrs[attr]
if attr in kwargs:
value = kwargs[attr]
else:
value = args[idx]
value_type = t... | _type:
class_name = self.__class__.__name__
raise TypeError("%s decorator attr %s expects argument %s"\
" received %s." % (class_name, attr, attr_type,
value_type))
setattr(self, attr, value)
def __call__(self, func):
... |
djrscally/eve-wspace | evewspace/POS/models.py | Python | gpl-3.0 | 7,280 | 0.003846 | # Eve W-Space
# Copyright (C) 2013 Andrew Austin and other contributors
#
# 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... | not, see <http://www.gnu.org/licens | es/>.
from django.db import models
from core.models import Type, Location
from API.models import CorpAPIKey
from core.models import Corporation, Alliance
from Map.models import System
import csv
from django.contrib.auth.models import User
import pytz
class POS(models.Model):
"""Represents a POS somewhere in space... |
mrcslws/nupic.research | packages/backprop_structure/src/nupic/research/frameworks/backprop_structure/networks/alexnet_kwinners.py | Python | agpl-3.0 | 5,250 | 0 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2019, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should | have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
from collections import OrderedDict
from functools import partial
from torch import nn
... |
vlas-sokolov/pyspeckit | pyspeckit/spectrum/models/astropy_models.py | Python | mit | 1,575 | 0.008889 | try:
from astropy.models import ParametricModel,Parameter,_convert_input,_convert_output
import numpy as np
class PowerLawModel(ParametricModel):
param_names = ['scale', 'alpha']
def __init__(self, scale, alpha, param_dim=1):
self._scale = Parameter(name='scale', val=scale, mcl... | s)**(-params[1]))
def noderiv(self, params, xvals, yvals):
deriv_dict = {
'scale': ((xvals)**(-params[1])),
'al | pha': params[0]*((xvals)**(-params[1]))*np.log(xvals)}
derivval = [deriv_dict[par] for par in self.param_names]
return np.array(derivval).T
def __call__(self, x):
"""
Transforms data using this model.
Parameters
--... |
csparpa/pyowm | pyowm/utils/measurables.py | Python | mit | 7,259 | 0.000276 | #!/usr/bin/env python
# -*- coding: utf-8 -*-"""
# Temperature conversion constants
KELVIN_OFFSET = 273.15
FAHRENHEIT_OFFSET = 32.0
FAHRENHEIT_DEGREE_SCALE = 1.8
# Wind speed conversion constants
MILES_PER_HOUR_FOR_ONE_METER_PER_SEC = 2.23694
KM_PER_HOUR_FOR_ONE_METER_PER_SEC = 3.6
KNOTS_FOR_ONE_METER_PER_SEC = 1.943... | nd degree
result[key] = value * KM_P | ER_HOUR_FOR_ONE_METER_PER_SEC
else:
result[key] = value
return result
def metric_wind_dict_to_knots(d):
"""
Converts all the wind values in a dict from meters/sec
to knots
:param d: the dictionary containing metric values
:type d: dict
:returns: a dict with the same ke... |
aaronsw/watchdog | import/parse/punch.py | Python | agpl-3.0 | 1,090 | 0.008257 | from decimal import Decimal
import re
import web
r_row = re.compile(r'<tr>(.*?)</tr>', re.S)
r_td = re.compile(r'<td v[^>]+>([^<]*)</td>')
r_member = re.compile(r'member=([^"]+)">([^<]+)<')
def fixdec(d):
d = d.strip()
return Decimal(d) and Decimal(d)/100
def parse_doc(d):
for row in r_row.findall(d):
... | [1])
s.progressiveall = fixdec(out[3])
s.name = membername.decode('iso-8859-1')
yield s
def parse | _all():
d = file('../data/crawl/punch/house.html').read()
for x in parse_doc(d): yield x
d = file('../data/crawl/punch/senate.html').read()
for x in parse_doc(d): yield x
if __name__ == "__main__":
import tools
tools.export(parse_all()) |
galaxy-ctf/milky-way | milkyway/management/commands/load_chals.py | Python | agpl-3.0 | 1,410 | 0 | from django.core.management.base import BaseCommand
from milkyway.models import Challenge, Hint, Category, Flag
import yaml
class Command(BaseCommand):
help = 'Load data from yaml file'
def add_arguments(self, parser):
parser.add_argument('dataset', type=str)
def handle(self, *args, **options):
... | tegory = Category.objects.create(
name=cat['name'],
description=cat['desc']
)
for chal in cat['chals']:
chal_data = {
'id': chal['id'],
'name': chal['n | ame'],
'description': chal['desc'],
'value': chal['value'],
'category': category,
'lesson': chal.get('lesson', ''),
}
c = Challenge.objects.create(**chal_data)
for hint in chal['hints']:
... |
HaebinShin/tensorflow | tensorflow/contrib/metrics/python/metrics/classification.py | Python | apache-2.0 | 2,307 | 0.002167 | # 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... | se ValueError('Labels should have integer or string dtype. '
| 'Given: %s' % str(labels.dtype))
if not labels.dtype.is_compatible_with(predictions.dtype):
raise ValueError('Dtypes of predictions and labels should match. '
'Given: predictions (%s) and labels (%s)' %
(str(predictions.dtype), str(labels.dtype)))
with ops... |
trabacus-softapps/openerp-8.0-cc | openerp/service/server.py | Python | agpl-3.0 | 32,015 | 0.003155 | #-----------------------------------------------------------
# Threaded, Gevent and Prefork Servers
#-----------------------------------------------------------
import datetime
import errno
import logging
import os
import os.path
import platform
import psutil
import random
import resource
import select
import signal
im... | imeout=0)
mask = pyinotify.IN_MODIFY | pyinotify.IN_CREATE # IN_MOVED_FROM, IN_MOVED_TO ?
for path in openerp.tools.config.options["addons_path"].split(','):
_logger.info('Watching addons fold | er %s', path)
self.wm.add_watch(path, mask, rec=True)
def process_data(self, files):
xml_files = [i for i in files if i.endswith('.xml')]
addons_path = openerp.tools.config.options["addons_path"].split(',')
for i in xml_files:
for path in addons_path:
... |
qedsoftware/commcare-hq | corehq/apps/dump_reload/sql/filters.py | Python | bsd-3-clause | 1,812 | 0.002208 | from abc import ABCMeta, abstractmethod
import six
from django.db.models import Q
from dimagi.utils.chunked import chunked
class DomainFilter(six.with_metaclass(ABCMeta)):
@abstractmethod
def get_filters(self, domain_name):
"""Return a list of filters. Each filter will be applied to a queryset indep... | _name)
for chunk in chunked(usernames, 500):
filter = Q() |
for username in chunk:
filter |= Q(username__iexact=username)
yield filter
class UserIDFilter(DomainFilter):
def __init__(self, user_id_field, include_web_users=True):
self.user_id_field = user_id_field
self.include_web_users = include_web_users
def ge... |
ox-it/humfrey | humfrey/update/transform/upload.py | Python | bsd-3-clause | 2,982 | 0.001341 | from __future__ import with_statement
import datetime
import logging
import pytz
import rdflib
from django.conf import settings
from humfrey.update.transform.base import Transform
from humfrey.update.uploader import Uploader
from humfrey.sparql.endpoint import Endpoint
from humfrey.utils.namespaces import NS
logge... | %r", input)
extension = input.r | split('.', 1)[-1]
try:
serializer = self.formats[extension]
except KeyError:
logger.exception("Unrecognized RDF extension: %r", extension)
raise
graph = rdflib.ConjunctiveGraph()
graph.parse(open(input, 'r'),
format=serializer,
... |
eljost/pysisyphus | tests_staging/test_mullerbrownpot.py | Python | gpl-3.0 | 6,681 | 0.002994 | #!/usr/bin/env python3
import copy
import matplotlib.pyplot as plt
import numpy as np
import pytest
from pysisyphus.plotters.AnimPlot import AnimPlot
from pysisyphus.calculators.MullerBrownPot import MullerBrownPot
#from pysisyphus.calculators.MullerBrownSympyPot import MullerBrownPot
from pysisyphus.cos.NEB import ... | ts() | :
kwargs = copy.copy(KWARGS)
convergence = {
"rms_force_thresh": 2.8,
}
kwargs["convergence"] = convergence
szts_energy = SimpleZTS(get_geoms(), param="energy")
opt = run_cos_opt(szts_energy, SteepestDescent, **kwargs)
assert(opt.is_converged)
assert(opt.cur_cycle == 15)
re... |
amicojeko/YouCantTouchThis | sendemail.py | Python | gpl-3.0 | 2,259 | 0.009296 | # coding=utf-8
# Copyright (C) 2014 Stefano Guglielmetti
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This prog... | l mail send
server = 'smtp.gmail.com:587'
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
assert type(send_to)==list
assert typ | e(files)==list
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for f in files:
part = MIMEBase('application', "octet-stream")
part.set_payload(... |
david415/tahoe-lafs | src/allmydata/test/test_configutil.py | Python | gpl-2.0 | 3,451 | 0.00058 | import os.path
from twisted.trial import unittest
from allmydata.util import configutil
from allmydata.test.no_network import GridTestMixin
from ..scripts import create_node
from .. import client
class ConfigUtilTests(GridTestMixin, unittest.TestCase):
def test_config_utils(self):
self.basedir = "cli/C | onfigUtilTests/test-config-utils"
self.set_up_grid(oneshare=True)
tahoe_cfg = os.path.join(self.get_clientdir(i=0), "tahoe.cfg")
# test that at least one option was read correctly
config = configutil.get_config(tahoe_cfg)
self.failUnlessEqual(config.get("node", "nickname"), "cli... | # test that set_config can mutate an existing option
configutil.set_config(config, "node", "nickname", "Alice!")
configutil.write_config(tahoe_cfg, config)
config = configutil.get_config(tahoe_cfg)
self.failUnlessEqual(config.get("node", "nickname"), "Alice!")
# test that ... |
ianyh/heroku-buildpack-python-opencv | vendor/.heroku/lib/python2.7/idlelib/EditorWindow.py | Python | mit | 66,031 | 0.001817 | import sys
import os
import re
import imp
from Tkinter import *
import tkSimpleDialog
import tkMessageBox
import webbrowser
from idlelib.MultiCall import MultiCallCreator
from idlelib import idlever
from idlelib import WindowList
from idlelib import SearchDialog
from idlelib import GrepDialog
from idlelib import Repla... | entation is stored inside the python framework
dochome = os.path.join(sys.prefix,
'Resources/Engli | sh.lproj/Documentation/index.html')
dochome = os.path.normpath(dochome)
if os.path.isfile(dochome):
EditorWindow.help_url = dochome
if sys.platform == 'darwin':
# Safari requires real file:-URLs
EditorWindow.help_url = 'file... |
robinandeer/chanjo | tests/test_calculate.py | Python | mit | 2,295 | 0 | """Test calculate module"""
from chanjo.store.models import Sample
def test_mean(populated_db):
"""Test for calculating mean coverage"""
# GIVEN a database loaded with 2 samples
assert Sample.query.count() == 2
# WHEN calculating mean values across metrics
query = populated_db.mean()
# THEN t... | limited to that sample
results = query.all()
assert len(results) == 1
result = results[0]
assert result[0] == sample_id
def test_gene(populated_db):
"""Test for calculating gene metrics"""
# GIVEN a database populated with a single sample
assert Sample.query.count() == 2
# WHEN calcula... |
# THEN the results should add up to a single row
results = query.all()
assert len(results) == 2
result = results[0]
assert result[0] == 'sample'
assert result[-1] == gene_id
def test_sample_coverage(populated_db):
"""Test for OMIM coverage"""
# GIVEN a database populated with two samp... |
sergev/vak-opensource | languages/python/simtrace.py | Python | apache-2.0 | 3,176 | 0.007557 | #!/usr/bin/python
# -*- encoding: utf-8 -*-
#
# Print the sequence of function calls from the Imperas trace file.
#
import sys, string, subprocess, bisect
if len(sys.argv) != 3:
print "Usage: simtrace file.trace vmunix.elf"
sys.exit (1)
# Extract the list of symbols from the binary executable.
nm_command = su... | :
word = line.split()
if len(word) > 0 and word[0] == "---":
if pc > max_addr and len(word) == 6 and | word[1] == "I/O" and \
word[2] == "Read" and word[5] == "U4STA":
# Skip bootloader timeout
continue
# Print i/o events.
print line.strip()
continue
if len(word) > 1 and word[0] == "Info" and word[1] == "(MIPS32_EXCEPT)":
# Print exceptions.
... |
nastya/droidbot | droidbox_scripts/droidbox_compatible.py | Python | mit | 24,119 | 0.006468 | # I have to modify droidbox scripts to let it work with droidbot
# This is a compatible version which generate a report with the same format of original DroidBox
__author__ = 'yuanchun'
################################################################################
# (c) 2011, The Honeynet Project
# Author: Patrik La... | ysis.")
sys.exit(1)
# Execute the application
call(["adb", "logcat", "-c"])
ret = call(['monkeyrunner', 'monkeyrunner.py', apk_name,
package_name, main_activity], stderr=None,
cwd=os.path.dirname(os.path.realpath(__file__)))
if (ret =... | tivity %s..." % main_activity)
# By default the application has not started
self.applicationStarted = 0
stringApplicationStarted = "Start proc %s" % package_name
# Open the adb logcat
if self.adb is None:
self.adb = Popen(["adb", "logcat", "DroidBox:W", "dalvikvm:W"... |
sintrb/urlimg | img/funs.py | Python | gpl-2.0 | 2,541 | 0.006528 | # -*- coding: UTF-8 -*
'''
Created on 2015年1月18日
@author: RobinTang
'''
try:
import Image, ImageDraw, ImageFont, ImageFilter
except:
pass
try:
from PIL import Image, ImageDraw, ImageFont, ImageFilter
except:
pass
import StringIO
filters = {
('blur', ImageFilter.BLUR, '模糊滤镜'),
('contour', Imag... |
path = os.path.abspath(file_name)
except:
path = ''
font = ImageFont.truetype(os.path.join(path, "font.ttf"), size)
return font
def fitto(src, dw=360, dh=200):
dst = Image.new("RGBA", (dw, dh), (255, 255, 255, 0))
sw = src.siz | e[0]
sh = src.size[1]
kw = float(sw) / float(dw)
kh = float(sh) / float(dh)
w, h = 0, 0
if kw > kh:
w, h = int(dw), int(sh / kw)
else:
w, h = int(sw / kh), int(dh)
nsrc = src.resize((w, h),)
x = (dw - w) / 2
y = (dh - h) / 2
dst.paste(nsrc, (x, y, x + w, y + h))
... |
drptbl/webium | webium/settings.py | Python | apache-2.0 | 251 | 0 | from selenium.webdriver import Firefox
from selenium.webdriver.common.by import By
driver_class = | Firefox
implicit_timeout = 30
wait_timeout = 30
default_search_type = By.ID
try:
from local_webium_settings import *
except ImportError:
pass | |
jzorrof/eve | eve/tests/methods/patch.py | Python | bsd-3-clause | 25,507 | 0 | from bson import ObjectId
import simplejson as json
from eve.tests import TestBase
from eve.tests.test_settings import MONGO_DBNAME
from eve.tests.utils import DummyEvent
from eve import STATUS_OK, LAST_UPDATED, ID_FIELD, ISSUES, STATUS, ETAG
from eve.methods.patch import patch_internal
class TestPatch(TestBase):
... | tTrue(test_item in db_value)
d | ef test_patch_list(self):
field = "alist"
test_value = ["a_string", 99]
changes = {field: test_value}
r = self.perform_patch(changes)
db_value = self.compare_patch_with_get(field, r)
self.assertEqual(db_value, test_value)
def test_patch_dict(self):
field = "l... |
jhajek/euca2ools | euca2ools/commands/ec2/describebundletasks.py | Python | bsd-2-clause | 2,642 | 0 | # Copyright 2009-2013 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of condi | tions and | the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS... |
servee/django-servee-oldcontrib | oldcontrib/media/document/forms.py | Python | bsd-3-clause | 190 | 0.010526 | from django import forms
from oldcontrib.media.document.models import Document
class Document | Upload(forms.ModelForm):
class Meta:
model = Document
| fields = ('document',) |
TeamProxima/predictive-fault-tracker | board/board_manager.py | Python | mit | 2,638 | 0.003412 | import json
import socket
from comms_manager import CommsManager
from constants import *
class BoardManager:
def __init__(self, args):
self.server_address = (args.IP, args.PORT)
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(15)
self.sock.connec... | humidity, temperature = self.cm.take_single_sample()
packet = json.dumps({'scores': {'temperature': temperature,
'humidity': humidity}})
self.sock.send(packet)
resp = self.sock.recv(1024)
| if resp:
resp = json.loads(resp)
if resp['response'] == -1:
self.cm.send_sms(
message='There is a temperature problem at station 2. For detailed'
' info siemenshackathon://scheme.ne... |
cacahootie/deckmaster | deckmaster/app/process_site.py | Python | mit | 4,475 | 0.007374 | """Process `site.json` and bower package tools."""
import os
import json
import subprocess
from functools import partial
import importlib
import sys
from flask import Flask, render_template, g, redirect, current_app
from gitloader import git_show
from import_code import import_code
try:
from app import app
exce... | t element in the config for local vs bower components."""
local, bower = process_local(deps), process_bowe | r(deps)
retval = {}
for tag in local:
retval[tag] = local[tag] + bower[tag]
return retval
def process_route(route):
if not route.get('view'):
def route_handler(revid = None, path = None):
g.revid = revid
try:
return render_template(
... |
wkrzemien/Pilot | Pilot/tests/Test_Pilot.py | Python | gpl-3.0 | 4,260 | 0.006103 | """ Test class for Pilot
"""
# pylint: disable=protected-access, missing-docstring, invalid-name, line-too-long
# imports
import unittest
import json
import stat
import sys
import os
import shutil
from Pilot.pilotTools import PilotParams
from Pilot.pilotCommands import CheckWorkerNode, ConfigureSite, NagiosProbes
... | 'cetype2': ['d', 'f']},
'CommandExtensions': 'TestExtension1,TestExtension2',
'NagiosProbes': 'Nagios1,Nagios2',
'NagiosPutURL': 'https://127.0.0.2/',
... | }
},
'CEs': {'grid1.example.com': {'GridCEType': 'cetype1', 'Site': 'site.example.com'}},
'DefaultSetup': 'TestSetup'},
fp)
def tearDown(self):
for fileProd in [
'pilot.json',
'Nagios1... |
DryRun/seizures | code/dataIO.py | Python | gpl-3.0 | 3,438 | 0.041303 | import scipy.io
import scipy.signal
import os
import sys
import matplotlib
import pandas as pd
import numpy as np
import random
# Load a matlab file into a data panel
# subject = Patient_N or Dog_N
# segment_type = interictal, ictal, or test
# downsample = True or False
# train_fraction = 0 < # <1, fraction of data to... | files[i][0:qp] + (10-len(files[i][files[i].rfind('_')+1:]) )*'0' + files[i][qp:] )
#print len(files), len(files2)
t = {key:value for key, value in zip(files2,files)}
files2 = t.keys()
files2.sort()
f = [t[i] for i in files2]
j = 0
for i in f:
seg = i[i.rfind('_')+1 : i. | find('.mat')] # Number of segment, e.g. Dog_1_interictal_segment_250.mat => 250
segtype = i[i[0:i.find('_segment')].rfind('_')+1: i.find('_segment')] # Type of segment: ictal, interictal, test
d = scipy.io.loadmat(dir+i)
if j==0:
cols = range(len(d['channels'][0,0]))
cols = cols +['time']
if segtype == ... |
xlqian/navitia | source/jormungandr/jormungandr/exceptions.py | Python | agpl-3.0 | 5,255 | 0.001713 | # Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public tr... | ned using
# twitter @navitia
# channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
# https://groups.google.com/d/forum/navitia
# www.navitia.io
from __future__ import absolute_import, print_function, unicode_literals, division
from flask import request
from werkzeug.exceptions import HTTPExceptio... | ound", "DeadSocketException", "ApiNotFound", "InvalidArguments"]
def format_error(code, message):
error = {"error": {"id": code, "message": message}, "message": message}
return error
class RegionNotFound(HTTPException):
def __init__(self, region=None, lon=None, lat=None, object_id=None, custom_msg=None)... |
srkunze/xcache | setup.py | Python | mit | 573 | 0 | #!/usr/bin/env python
from __future__ import unicode_literals
from setuptools import setup
setup(
name='xcache',
version='0.2',
description='clean caches when needed',
author='Sven R. Kunze',
author_email='srkunze@mail.de',
url='https:/ | /github.com/srkunze/xcache',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Program | ming Language :: Python',
],
py_modules=['xcache'],
install_requires=[],
)
|
pombredanne/1trillioneuros | webapp/currency/migrations/0001_initial.py | Python | gpl-3.0 | 1,131 | 0.006189 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Currency'
db.create_table(u'currency_currency', (
('iso_code', self.gf('django.d... | te_signal(u'currency', ['Currency'])
def backwards(self, orm):
# Deleting model 'Currency'
db.delete_table(u'currency_currency')
models = {
u'currency.currency': {
'Meta': {'object_name': 'Currency'},
| 'iso_code': ('django.db.models.fields.CharField', [], {'max_length': '3', 'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '120'}),
'rate': ('django.db.models.fields.FloatField', [], {}),
}
}
complete_apps = ['currency'] |
uw-it-aca/spacescout_web | spacescout_web/tests.py | Python | apache-2.0 | 152 | 0 | from d | jango.utils import unittest
from spacescou | t_web.test.not_found import NotFound404Test
from spacescout_web.test.url_filtering import URLFiltering
|
kisel/trex-core | scripts/astf/param_tcp_rxbufsize_8k.py | Python | apache-2.0 | 1,298 | 0.006163 | from trex_astf_lib.api import *
# IPV6 tunable example
#
# ipv6.src_msb
# ipv6.dst_msb
# ipv6.enable
#
class Prof1():
def __init__(self):
pass
def get_profile(self, **kwargs):
# ip generator
ip_gen_c = ASTFIPGenDist(ip_range=["16.0.0.0", "16.0.0.255"], distribution="seq")
... | ange=["48.0.0.0", "48.0.255.255"], distribution="seq")
ip_gen = ASTFIPGen(glob=ASTFIPGenGlobal(ip_offset="1.0.0.0"),
dist_client=ip_gen_c,
dist_server=ip_gen_s)
c_glob_info = ASTFGlobalInfo()
c_glob_info.tcp.rxbufsize = 8*1024
c_glob... | b_info.tcp.rxbufsize = 8*1024
s_glob_info.tcp.txbufsize = 8*1024
return ASTFProfile(default_ip_gen=ip_gen,
# Defaults affects all files
default_c_glob_info=c_glob_info,
default_s_glob_info=s_glob_info,
... |
stvstnfrd/edx-platform | lms/djangoapps/discussion/django_comment_client/tests/test_utils.py | Python | agpl-3.0 | 78,549 | 0.002928 | # pylint: skip-file
import datetime
import json
import sys
from unittest import mock
from unittest.mock import Mock, patch
import ddt
import pytest
from django.test import RequestFactory, TestCase
from django.urls import reverse
from edx_django_utils.cache import RequestCache
from opaque_keys.edx.keys import CourseK... | self):
ret = utils.has_forum_access('student', self.course_id, 'Student')
assert ret
ret = utils.has_forum_access('not_a_student', self.course_id, 'Student')
assert not ret
ret = utils.has_forum_access('s | tudent', self.course_id, 'NotARole')
assert not ret
@ddt.ddt
class CoursewareContextTestCase(ModuleStoreTestCase):
"""
Base testcase class for courseware context for the
comment client service integration
"""
def setUp(self):
super().setUp()
self.course = CourseFactory.crea... |
eteq/ginga | ginga/colors.py | Python | bsd-3-clause | 48,361 | 0.000186 | #
# colors.py -- color definitions
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import re
color_dict = {
'aliceblue': (0.9411764705882353, 0.9725490196078431, 1.0... | 627451, 0.803921568627451),
'cyan4': (0.0, 0.5450980392156862, 0.5450980392156862),
'darkblue': (0.0, 0.0, 0.5450980392156862),
'darkcyan': (0.0, 0.5450980392156862, 0.5450980392156862),
'darkgoldenrod': (0.7215686274509804,
0.5254901960784314,
| 0.043137254901960784),
'darkgoldenrod1': (1.0, 0.7254901960784313, 0.058823529411764705),
'darkgoldenrod2': (0.9333333333333333,
0.6784313725490196,
0.054901960784313725),
'darkgoldenrod3': (0.803921568627451,
0.5843137254901961,
... |
MostlyOpen/odoo_addons | myo_base/__openerp__.py | Python | agpl-3.0 | 1,788 | 0 | # -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
#
# 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
#... | gory': 'Generic Modules/Others',
'license': 'AGPL-3',
'website': 'http://mostlyopen.org',
'depends': ['base'],
'data': [
'security/base_security.xml',
'views/base_menu_view.xml',
'views/groupings_menu_view.xml',
'views/agro_menu_view.xml',
'vi | ews/community_menu_view.xml',
'views/health_menu_view.xml',
'views/insurance_menu_view.xml',
'views/pharmacy_menu_view.xml',
'views/mfmng_menu_view.xml',
'views/res_users_view.xml',
],
'demo': [],
'test': [],
'init_xml': [],
'test': [],
'update_xml': [],
... |
m101/lfipwn | core/techniques/LFIDataURI.py | Python | agpl-3.0 | 1,128 | 0.018617 | from core.techniques.LFIExec import LFIExec
from base64 import b64encode
class LFIDataURI (LFIExec):
files_exec = [
# input
{ 'path' : '', 'type' : 'data_uri' },
]
# find LFI code execution path
def check (self):
return super(LFIDataURI, self)._check (prepare_check_data_uri)
... | i (lfi, cmd):
purl = lfi.pattern_url[:]
payload_exec = '<?php echo "' + lfi.tag_start_exec + '"; system ($_GET["cmd"]); echo "' + lfi.t | ag_end_exec + '"; ?>'
payload = 'data:text/plain;base64,{0}&cmd={1}'.format (b64encode (payload_exec), cmd)
# payload = 'data:text/plain,{0}&cmd={1}'.format (payload_exec, cmd)
url = purl.replace (lfi.payload_placeholder, payload)
return url
|
frreiss/tensorflow-fred | tensorflow/python/keras/engine/deferred_sequential_test.py | Python | apache-2.0 | 8,563 | 0.003503 | # Copyright 2020 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... | ilt)
self.assertTrue(model._is_graph_network)
self.assertLen(model.layer | s, 2)
self.assertLen(model.weights, 2)
model.add(keras.layers.Dense(2))
self.assertTrue(model.built)
self.assertTrue(model._is_graph_network)
self.assertLen(model.layers, 3)
self.assertLen(model.weights, 4)
@keras_parameterized.run_all_keras_modes(always_skip_v1=True)
def test_feature_extra... |
ryantierney513/capirca | tests/lib/cisco_test.py | Python | apache-2.0 | 23,978 | 0.001877 | # Copyright 2008 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/licens | es/LICENSE-2.0
#
# unless required by applicable law or agreed to i | n writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unittest for cisco acl rendering module."""
from ... |
neno1978/pelisalacarta | python/main-classic/channels/trailertools.py | Python | gpl-3.0 | 26,400 | 0.005538 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta 4
# Copyright 2015 tvalacarta@gmail.com
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#
# Distributed under the terms of GNU General Public License v3 (GPLv3)
# http://www.gnu.org/licenses/gpl-3.0.html
# --... | = platformtools.dialog_input(default=item.contentTitle, heading=config.get_localized_string(30112))
if texto is not None:
if item.extra == "abandomoviez":
return abandomoviez_search(item.clone(contentTitle=texto, page="", year=""))
el | if item.extra == "youtube":
return youtube_search(item.clone(contentTitle=texto, page=""))
elif item.extra == "filmaffinity":
return filmaffinity_search(item.clone(contentTitle=texto, page="", year=""))
elif item.extra == "jayhap":
return jayhap_search(item.clone(cont... |
CodeTengu/jokekappa | tests/test_core.py | Python | mit | 127 | 0 | # coding: u | tf-8
import unittest
import jokekappa
class VoidTest(unittest.TestCase):
def test_ | void(self):
pass
|
simleo/openmicroscopy | components/tools/OmeroWeb/omeroweb/webclient/show.py | Python | gpl-2.0 | 37,362 | 0.00008 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2014 University of Dundee & Open Microscopy Environment.
# All rights reserved.
#
# 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 Foun... | .request = request
self.menu = menu
path = self.request.GET.get('path', '').split('|')[-1]
self._add_if_supported(path)
show = self.request.GET.get('show', '')
for path in show.split('|'):
self._add_if_supported(path)
def _add_if_supported(self, path):
... | dds a path to the initially selected list if it is supported."""
m = self.PATH_REGEX.match(path)
if m is None:
return
object_type = m.group('object_type')
key = m.group('key')
value = m.group('value')
if key is None:
key = 'id'
if object_ty... |
menren/openshift-ansible | utils/src/ooinstall/cli_installer.py | Python | apache-2.0 | 31,431 | 0.003213 | # TODO: Temporarily disabled due to importing old code into openshift-ansible
# repo. We will work on these over time.
# pylint: disable=bad-continuation,missing-docstring,no-self-use,invalid-name,no-value-for-parameter
import click
import os
import re
import sys
from ooinstall import openshift_ansible
from ooinstall ... | ided')
return path
# if not os.path.exists(path)):
# raise click.BadParameter("Path \"{}\" doesn't exist".format(path))
def is_valid_hostname(hostname):
if not hostname or len(hostname) > 255:
return False
if hostname[-1] == ".":
hostname = hostname[:-1] # strip exactly one dot... | m the right, if present
allowed = re.compile(r"(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
return all(allowed.match(x) for x in hostname.split("."))
def validate_prompt_hostname(hostname):
if '' == hostname or is_valid_hostname(hostname):
return hostname
raise click.BadParameter('"{}" appears t... |
grollins/foldkin | foldkin/simple/__init__.py | Python | bsd-2-clause | 27 | 0 | f | rom simple_model import | *
|
ah-anssi/SecuML | SecuML/core/DimensionReduction/Algorithms/Projection/Itml.py | Python | gpl-2.0 | 1,021 | 0 | # SecuML
# Copyright (C) 2016 ANSSI
#
# SecuML 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.
#
# SecuML is distributed in the hope t... |
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# with SecuML. If not, see <http://www.gnu.org/licenses/>.
import metric_learn
import numpy as np
from .SemiSupervisedProjection import Sem... | t__(self, conf):
SemiSupervisedProjection.__init__(self, conf)
self.projection = metric_learn.itml.ITML_Supervised()
def setProjectionMatrix(self):
self.projection_matrix = np.transpose(
self.pipeline.named_steps['projection'].transformer())
|
Stub-O-Matic-BA/stubo-app | stubo/model/db.py | Python | gpl-3.0 | 23,064 | 0.002688 | """
:copyright: (c) 2015 by OpenCredo.
:license: GPLv3, see LICENSE for more details.
"""
from pymongo import MongoClient, DESCENDING, ASCENDING
import logging
from bson.objectid import ObjectId
from stubo.utils import asbool
from stubo.model.stub import Stub
import hashlib
import time
import motor
import os
... | except Exception as ex1:
log.debug("Could not get PRE STUB nModified key, result returned: %s. Error: %s" % (result, ex1))
except Exception as ex:
log.debug("Could not update scenario pre stub, got error: %s" % ex)
response['Pre stubs changed'] = 0
try:
... | nged'] = result['nModified']
except KeyError:
# older versions of mongodb returns 'n' instead of 'nModified'
response['Scenarios changed'] = result['n']
except Exception as ex1:
log.debug("Could not get SCENARIO nModified key, result returned: %s. ... |
tferreira/Flask-Redis | application/models.py | Python | mit | 170 | 0 | # from index import db
# class MyObject():
| # def __init__(self):
# pass
# @staticmethod
# def get_something(arg1, arg2):
# return something
| |
CorySpitzer/FizzBuzz | everest/FizzBuzz.py | Python | mit | 175 | 0.091429 | n = 1
while n <= 100:
if (n % 3 == 0 and n % 5 | == 0):
print "FizzBuzz"
elif (n % 3 == 0) | :
print "Fizz"
elif (n % 5 == 0):
print "Buzz"
else:
print n
n += 1 |
LeonNie52/dk-plus | test files/params.py | Python | gpl-3.0 | 13,072 | 0.008415 | """
The parameters class. It is initialized with the vehicle's attributes at time of construction
but it is constantly updated through attribute listeners after calling the add_listeners() function
These parameters can provide the basic info for a future collision avoidance scheme.
Any functions that can refer to th... | def decorated_gps_callback(self, attr_name, value):
network.vehicle_params.gps_fix = value.fix_type
network.vehicle_params.gps_sat = value.satellites_visible
network.vehicle_params.gps_eph = value.eph
network.vehicle_params.gps_epv = value.epv
print 'GP... | params.gps_eph, \
'\nEPV: ', network.vehicle_params.gps_epv
#Set altitude offboard
#return: True/False
@vehicle.on_attribute('set_altitude_target_global_int')
def decorated_set_global_altitude_callback(self, attr_name, value):
network.vehicle_params.set_global_... |
pygeo/pycmbs | pycmbs/benchmarking/models/cmip5.py | Python | mit | 20,505 | 0.003755 | # -*- coding: utf-8 -*-
"""
This file is part of pyCMBS.
(c) 2012- Alexander Loew
For COPYING and LICENSE details, please refer to the LICENSE file
"""
from cdo import Cdo
from pycmbs.data import Data
import tempfile as tempfile
import copy
import glob
import os
import sys
import ast
import numpy as np
from pycmbs.be... | s
else:
filename1 = custom_path + self.get_raw_filename(varname, **kwargs)
if filename1 is None:
print_log(WARNING, 'No valid model input data')
return None
force_calc = False
if self.start_time is N | one:
raise ValueError('Start time needs to be specified')
if self.stop_time is None:
raise ValueError('Stop time needs to be specified')
#/// PREPROCESSING ///
cdo = Cdo()
s_start_time = str(self.start_time)[0:10]
s_stop_time = str(self.stop_time)[0:10]
... |
metaml/nupic.core | ci/travis/deploy-wheel-to-s3.py | Python | agpl-3.0 | 1,831 | 0.0071 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013-5, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and condition... |
def upload(artifactsBucket, wheelFileName, wheelPath):
key = Key(artifactsBucket)
key.key = "%s/%s" % (RELEASE_FOLDER, wheelFileName)
print "Uploading %s to %s/%s..." % (wheelFileName, BUCKET, RELEASE_FOLDER)
key.set_contents_from_filename(wheelPath)
def run(wheelPath):
wheelFileName = os.path.basename(wh... | run(wheelPath)
|
j5shi/Thruster | pylibs/test/test_nis.py | Python | gpl-2.0 | 1,215 | 0.003292 | from test import test_support
import unittest
nis = test_support.import_module('nis')
class NisTests(unittest.TestCase):
def test_maps(self):
try:
maps = nis.maps()
except nis.error, msg:
# NIS is probably not active, so this test isn't useful
self.sk... | mapping = nis.cat(nismap)
for k, v in mapping.items():
if not k:
continue
if nis.match(k, nismap) != v:
self.fail("NIS match failed for key `%s' in map `%s'" % (k, nismap))
else:
# just test th... | break
def test_main():
test_support.run_unittest(NisTests)
if __name__ == '__main__':
test_main()
|
the13fools/Bokeh_Examples | glyphs/anscombe.py | Python | bsd-3-clause | 3,251 | 0.021839 | from __future__ import print_function
import numpy as np
import pandas as pd
from bokeh.browserlib import view
from bokeh.document import Document
from bokeh.embed import file_html
from bokeh.glyphs import Circle, Line
from bokeh.objects import (
ColumnDataSource, Glyph, Grid, GridPlot, LinearAxis, Plot, Range1d
... | II', 'xii', 'yii')
III = make_plot('III', 'xiii', 'yiii')
IV = make_plot('IV', 'xiv', 'yiv')
grid = GridPlot(children=[[I, II], [III, IV]], plot_width=800)
doc = Document( )
doc.add(grid)
if __name__ == "__main__": |
filename = "anscombe.html"
with open(filename, "w") as f:
f.write(file_html(doc, INLINE, "Anscombe's Quartet"))
print("Wrote %s" % filename)
view(filename)
|
atodorov/anaconda | pyanaconda/modules/payloads/source/source_base_interface.py | Python | gpl-2.0 | 1,817 | 0.001101 | #
# Base object of all payload sources.
#
# Copyright (C) 2019 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is ... | nc.
#
from abc import ABCMeta
from dasbus.server.interface import dbus_interface
from dasbus.typing import * # pylint: disable=wildcard-import
from pyanaconda.modules.common.base.base_template import ModuleInterfaceTemplate
from pyanaconda.modules.common.constants.interfaces import PAYLOAD_SOURCE
@dbus_interface(PA... | CMeta):
"""Base class for all the payload source module interfaces.
This object contains API shared by all the sources. Everything in this object has
to be implemented by a source to be used.
"""
@property
def Type(self) -> Str:
"""Get the type of this source.
Possible values ... |
falkTX/Cadence | src/shared_settings.py | Python | gpl-2.0 | 12,056 | 0.004728 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Common/Shared code related to the Settings dialog
# Copyright (C) 2010-2018 Filipe Coelho <falktx@falktx.com>
#
# 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 Softw... | r
# any later version.
#
# This program 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 PARTICUL | AR PURPOSE. See the
# GNU General Public License for more details.
#
# For a full copy of the GNU General Public License see the COPYING file
# ------------------------------------------------------------------------------------------------------------
# Imports (Global)
if True:
from PyQt5.QtCore import pyqtSlo... |
lluxury/P_U_S_A | 8_OS_Soup/code/dispatch1.py | Python | mit | 297 | 0.016835 | #!/usr/bin/env python
import subprocess
"""
A ssh based command dispatch system
"""
machines = ["10.0.1.40",
"10.0.1.50",
"10.0.1.51",
"10.0.1.60",
"10.0.1.80"]
cmd = "python /src/fing | erprint.py"
for machine in machines:
subprocess.call("ssh root@%s %s" % (machine, cmd), shell=True)
| |
vslavik/poedit | scripts/extract-fileviewer-mappings.py | Python | mit | 3,349 | 0.008361 | #!/usr/bin/env python3
# Update plural forms expressions from the data collected by Unicode Consortium
# (see http://www.unicode.org/cldr/charts/supplemental/language_plural_rules.html),
# but from a JSON version by Transifex folks
import os.path
import sys
import urllib.request
import re
import gettext
import json
i... | :
BLACKLIST = set([
'glsl', 'nginx', 'apacheconf', 'matlab', 'opencl', 'puppet', 'reason', 'renpy',
'plsql', 'sql', 'tex',
])
# ...and extensions:
BLACKLIST_EXT = | set([
'spec', 'pluginspec', 'ml',
])
MARKER_BEGIN = "// Code generated with scripts/extract-fileviewer-mappings.py begins here"
MARKER_END = "// Code generated with scripts/extract-fileviewer-mappings.py ends here"
prism_langs = json.loads(urllib.request.urlopen(PRISM_COMPONENTS_URL).read().decode('utf-8'))... |
Danielhiversen/home-assistant | homeassistant/components/lutron_caseta/device_trigger.py | Python | apache-2.0 | 8,121 | 0.000739 | """Provides device triggers for lutron caseta."""
from __future__ import annotations
from typing import Any
import voluptuous as vol
from homeassistant.components.automation import (
AutomationActionType,
AutomationTriggerInfo,
)
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHE... | omationTriggerInfo,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
device = get_button_device_by_dr_id(hass, config[CONF_DEVICE_ID])
schema = DEVICE_TYPE_SCHEMA_MAP.get(device["type"])
valid_buttons = DEVICE_TYPE_SUBTYPE_MAP.get(device["type"])
config = schema(c | onfig)
event_config = {
event_trigger.CONF_PLATFORM: CONF_EVENT,
event_trigger.CONF_EVENT_TYPE: LUTRON_CASETA_BUTTON_EVENT,
event_trigger.CONF_EVENT_DATA: {
ATTR_SERIAL: device["serial"],
ATTR_BUTTON_NUMBER: valid_buttons[config[CONF_SUBTYPE]],
ATTR_ACTION... |
jhanley634/testing-tools | problem/weblog/prefix/ip_addr.py | Python | mit | 5,425 | 0.00129 |
# Copyright 2020 John Hanley.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribut... | return None # We can keep going.
| else:
return NotImplemented # Prohibit further processing.
def __eq__(self, other):
return self._invalid(other) or (self.ip.addr, self.masklen) == (other.ip.addr, other.masklen)
def __lt__(self, other):
return self._invalid(other) or (self.ip.addr, self.masklen) < (other.ip.addr,... |
Samnsparky/cdibase | prog_code/controller/enter_data_controllers_test.py | Python | gpl-3.0 | 28,902 | 0.001799 | """Automated tests for entering CDI forms manually.
Copyright (C) 2014 A. Samuel Pottinger ("Sam Pottinger", gleap.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 of the Licens... | SSION_NUM,
TEST_TOTAL_NUM_SESSIONS,
3,
TEST_ITEMS_EXCLUDED,
TEST_PERCENTILE,
TEST_EXTRA_CATEGORIES,
0,
TEST_LANGUAGES,
TEST_NUM_LANGUAGES,
'standard',
constants.EXPLICIT_FALSE,
False
)
TEST_EXPECTED_WORD_ENTRIES = {
| 'cat_1_word_1': 1,
'cat_1_word_2': 0,
'cat_1_word_3': 1,
'cat_2_word_1': 0,
'cat_2_word_2': 1,
'cat_2_word_3': 0
}
class EnterDataControllersTests(unittest.TestCase):
def setUp(self):
self.app = cdibase.app
self.app.debug = True
self.__callback_called = False
de... |
zxytim/pynojo | pynojo/model/_ext_type.py | Python | gpl-3.0 | 2,330 | 0.003863 | # $File: _ext_type.py
# $Date: Wed Feb 22 15:04:06 2012 +0800
#
# Copyright (C) 2012 the pynojo development team <see AUTHORS file>
#
# Contributors to this file:
# Kai Jia <jia.kai66@gmail.com>
#
# This file is part of pynojo
#
# pynojo is free software: you can redistribute it and/or modify
# it under the terms ... | ABILITY 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 pynojo. If not, see <http://www.gnu.org/licenses/>.
#
"""Extra SQLAlchemy ORM types"""
__all__ = ['JSONEncodeDict']
import cjson
fr... | r
class JSONEncodeDict(TypeDecorator):
"""Represents an mutable python *dict* as a json-encoded string."""
# pylint: disable=W0223
impl = String
def process_bind_param(self, value, dialect):
if value is not None:
value = cjson.encode(value)
if len(value) > self.length:... |
jlinn/pylastica | pylastica/query/matchall.py | Python | apache-2.0 | 180 | 0.005556 | __author__ = 'Joe Linn'
from . import abstract
c | lass MatchAll(abstract.AbstractQuery):
def __init__(self):
| super(MatchAll, self).__init__()
self._params = {}
|
gkioxari/RstarCNN | lib/attr_data_layer/layer.py | Python | bsd-2-clause | 5,647 | 0.000708 | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
# --------------------------------------------------------
# R*CNN
# Wri... | meter string, which must be valid YAML
layer_params = yaml.load(self.param_str_)
self._num_classes = layer_params['num_classes']
self._name_to_top_map = {
'data': 0,
'rois': 1,
'labels': 2}
# data blob: holds a batch of N images, each with 3 channel... | # (n, x1, y1, x2, y2) specifying an image batch index n and a
# rectangle (x1, y1, x2, y2)
top[1].reshape(1, 5)
# labels blob: holds labels for each attribute
top[2].reshape(1, self._num_classes)
def forward(self, bottom, top):
"""Get blobs and copy them into this ... |
xodus7/tensorflow | tensorflow/contrib/lite/python/lite_test.py | Python | apache-2.0 | 45,063 | 0.003107 | # Copyright 2018 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... | 0]['dtype'])
self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())
self.assertEqual((0., 0.), output_details[0]['quantization'])
def testQuantization(self):
in_tensor_1 = array_ops.placeholder(
shape=[1, 16, 16, 3], dtype=dtypes.float32, name='inputA')
in_tensor_2 = array_ops.... | t_with_min_max_args(
in_tensor_1 + in_tensor_2, min=0., max=1., name='output')
sess = session.Session()
# Convert model and ensure model is not None.
converter = lite.TocoConverter.from_session(
sess, [in_tensor_1, in_tensor_2], [out_tensor])
converter.inference_type = lite_constants.QU... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.