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 |
|---|---|---|---|---|---|---|---|---|
dcoetzee/questionvault | src/questionvault/apps/questions/views.py | Python | unlicense | 1,602 | 0.004994 | import pdb
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template import RequestContext
from django import forms
from models import Question, Answer
from forms import QuestionForm, AnswerFormSet
# view handling groked from http://stackoverflow.com/questions/18755909... | :
question = Question()
question_form = QuestionForm(request.POST, instance=question)
answer_formset = AnswerFormset(request.POST, instance=question)
|
# Check these separately to avoid short-circuiting
question_valid = question_form.is_valid()
answer_valid = answer_formset.is_valid()
if question_valid and answer_valid:
question_form.save()
answer_formset.save()
return HttpResponse("... |
rohitranjan1991/home-assistant | homeassistant/components/gree/switch.py | Python | mit | 5,377 | 0.000186 | """Support for interface with a Gree climate systems."""
from __future__ import annotations
from homeassistant.components.switch import SwitchDeviceClass, SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher impor... | GreeFreshAirSwitchEntity(GreeEntity, SwitchEntity):
"""Representation of the fresh air mode state of the device."""
def __init__(self, coordinator):
"""Initialize the Gree device."""
super().__init__(coordinator, "Fresh Air")
@property
def device_class(self):
"""Return the clas... | lass.SWITCH
@property
def is_on(self) -> bool:
"""Return if the state is turned on."""
return self.coordinator.device.fresh_air
async def async_turn_on(self, **kwargs):
"""Turn the entity on."""
self.coordinator.device.fresh_air = True
await self.coordinator.push_st... |
umitproject/site-status | agent/__init__.py | Python | agpl-3.0 | 1,867 | 0.012855 | #!/usr/bin/env python
# -*- coding: ut | f-8 -*-
##
## Author: Adriano Monteiro Marques <adriano@umitproject.org>
##
## Copyright (C) 2011 | S2S Network Consultoria e Tecnologia da Informacao LTDA
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU Affero General Public License as
## published by the Free Software Foundation, either version 3 of the
## License, or (at your option) any later version.
#... |
mikeckennedy/python_bytes_show_notes | tools/otter_ai_to_our_format.py | Python | mit | 1,657 | 0 | import os
import sys
def main():
if len(sys.argv) != 2:
print("Usage: Pass the file name for the source transcript txt file.")
sys.exit(-1)
file = sys.argv[1]
out_file = os.path.expanduser(
os.path.join(
'~/Desktop',
os.path.basename(file)
)
)
... | ric() for p in parts)
def get_time_text( | line: str) -> str:
if ':' not in line:
raise Exception(f"Text doesn't seem to be a time: {line}")
parts = line.split(':')
hour_text = "0"
min_text = "0"
sec_text = "0"
if len(parts) == 3:
hour_text = parts[0].strip()
min_text = parts[1].strip()
sec_text = parts... |
toumorokoshi/web-transmute | transmute_core/frameworks/flask/__init__.py | Python | mit | 87 | 0 | from transmute_core import *
from .rout | e import route
from .swagger import add_s | wagger
|
di-unipi-socc/DockerFinder | storage/crawl_officials.py | Python | apache-2.0 | 3,338 | 0.003295 | import requests
import json
DOCKER_HUB = "https://hub.docker.com"
FILE_SAVE_TAGS="officials_images_tags.json"
FILE_SAVE="officials_images.json"
def pull_officials():
payload = {'page': 1, 'page_size': 100}
count = 0
try:
res = requests.get(DOCKER_HUB+"/v2/repositories/library",params=payload)
... | ls():
count = get_count_tags(name)
print("{} tags {}".format(name, count))
| count_total += count
print("{} total tags".format(count_total))
count_all_tags()
|
open-homeautomation/home-assistant | tests/components/camera/test_local_file.py | Python | apache-2.0 | 2,135 | 0 | """The tests for local file camera component."""
import asyncio
from unittest import mock
# Using third party package because of a bug reading binary data in Python 3 | .4
# https://bugs.python.org/issue23004
from mock_open import MockOpen
from homeassistant.bootstrap import setup_component
from tests.common import mock_http_component
import logging
@asyncio.coroutine
def test_loading_file(hass, test_client):
"""Test that it loads image from disk."""
@mock.patch('os.path.i... | up platform inside callback."""
assert setup_component(hass, 'camera', {
'camera': {
'name': 'config_test',
'platform': 'local_file',
'file_path': 'mock.file',
}})
yield from hass.loop.run_in_executor(None, setup_platform)
client ... |
UmSenhorQualquer/pyforms | utils/deploy-pypi.py | Python | mit | 2,402 | 0.011657 | import os
import xmlrpc.client
from subprocess import Popen, PIPE
import shutil
pypi = xmlrpc.client.ServerProxy('https://pypi.org')
DIRECTORIES_TO_SEARCH_FORM = [
os.path.join('.'),
os.path.join('pyforms-web'),
os.path.join('pyforms-web', 'orquestra'),
os.path.join('pyforms-gui'),
os.path.join('... | en(b):
return -1
elif len(a)<len(b):
return 1
return 0
for dir_name in | DIRECTORIES_TO_SEARCH_FORM:
dir_path = os.path.abspath(dir_name)
print('---', dir_path)
if not os.path.isdir(dir_path): continue
setup_filepath = os.path.join(dir_path, 'setup.py')
if not os.path.isfile(setup_filepath): continue
os.chdir(dir_path)
version = Popen(["python", setup_filepath... |
rainwoodman/mpi4py_test | runtests/mpi/__init__.py | Python | bsd-2-clause | 69 | 0 | from .t | ester import Tester, MPITest, MPIWorld, nompi, MPITestFixtu | re
|
JonnoFTW/htm-models-adelaide | engine/metrics.py | Python | agpl-3.0 | 2,087 | 0.003833 | from sklearn.utils import check_array
import numpy as np
def geh(y_true, y_pred, axis=0):
return np.sqrt(2*np.power(y_pred - y_true, 2)/(y_pred + y_true)).mean(axis=axis)
def mean_absolute_percentage_error(y_true, y_pred):
"""
Use of this metric is not recommended; for illustration only.
See other re... | bsolute_percentage_error
def rmse(y_true, y_pred, axis=0):
r | eturn np.sqrt(((y_pred - y_true) ** 2).mean(axis=axis))
def MASE(training_series, testing_series, prediction_series):
"""
Computes the MEAN-ABSOLUTE SCALED ERROR forecast error for univariate time series prediction.
See "Another look at measures of forecast accuracy", Rob J Hyndman
parameters:
... |
yorvic/.vim | bundle/python-mode/pylibs/ropevim.py | Python | gpl-3.0 | 14,770 | 0.000203 | """ropevim, a vim mode for using rope refactoring library"""
import glob
import os
import tempfile
import re
from ropemode import decorators
from ropemode import environment
from ropemode import interface
import vim
# Gobal var to be able to shutup output
_rope_quiet = False
class VimUtils(environment.Environment)... | completion(proposal)
for proposal in values)
def _command(self, command, encode=False):
if encode:
command = command.encode(self._get_encoding())
vim.command(command)
def ask_completion(self, prompt, values, starting=None):
if self.get('vim_completi... | d 'i' in call('mode()'):
proposals = self._update_proposals(values)
col = int(call('col(".")'))
if starting:
col -= len(starting)
self._command(u'call complete({0}, [{1}])'.format(col, proposals),
encode=True)
return N... |
SavinaRoja/npyscreen2 | npyscreen2/widgets/input_handler.py | Python | gpl-3.0 | 6,709 | 0.005068 | # -*- coding: utf-8 -*-
import curses
from functools import wraps
import logging
log = logging.getLogger('npyscreen2.widgets.input_handler')
__all__ = ['exit_edit_method', 'InputHandler']
def exit_edit_method(func):
"""
This functions serves as a decorator for Widget methods intended to end the
edit l... |
"""
@wraps(func)
def wrapper(self, inpt=None):
self.editing = False
self.how_exited = func(self, inpt)
return wrapper
class InputHandler(object):
"""
An object that can handle user input
"""
def handle_input(self, inpt):
"""
Returns True if input has b... | methods in self.complex_handlers (if any),
which is an array of form (test_func, dispatch_func).
If test_func(input) returns true, then dispatch_func(input) is called.
Check to see if parent can handle. No further action taken after that
point.
"""
log.debug('handle_inp... |
iotaledger/iota.lib.py | iota/transaction/types.py | Python | mit | 2,751 | 0.001454 | from iota.crypto import FRAGMENT_LENGTH
from iota.exceptions import with_context
from iota.types import Hash, TryteString, TrytesCompatible
__all__ = [
'BundleHash',
'Fragment',
'TransactionHash',
'TransactionTrytes',
'Nonce'
]
class BundleHash(Hash):
"""
An :py:class:`TryteString` (:py:c... | ` representation of a Transaction.
:raises ValueError: if ``trytes`` is longer than 2673 trytes in length.
"""
LEN = 2673
"""
Len | gth of a transaction in trytes.
"""
def __init__(self, trytes: TrytesCompatible) -> None:
super(TransactionTrytes, self).__init__(trytes, pad=self.LEN)
if len(self._trytes) > self.LEN:
raise with_context(
exc=ValueError('{cls} values must be {len} trytes long.'.form... |
t184256/soundcontrol | nanopad2/test.py | Python | gpl-3.0 | 3,864 | 0.009576 | #!/usr/bin/python
import pypm, sys, time
DEV_NAME = 'nanoPAD2 MIDI 1'
OUT_NAME = 'fs'
#OUT_NAME = 'MIDI IN'
#OUT_NAME = 'Synth input port (20116:0)'
FIRST_NOTE = 24 + 4 # E, not C
SECOND_NOTE = FIRST_NOTE + 5
PADS1 = range(51, 35, -2)
PADS2 = range(50, 34, -2)
shorten_bools = lambda bool_list: ''.join(('0' if b else... | ME, 'found at number', out_num
midi_in = pypm.Input(dev_num)
#midi_out = pypm.Output(pypm.GetDefaultOutputDeviceID(), 0)
midi_out = pypm.Output(out_num, 0)
def noteon(chan, note, vel):
midi_out.Write([[[0x90 + chan, note, vel], pypm.Time()]])
def noteoff(chan, note):
| midi_out.Write([[[0x80 + chan, note, 0], pypm.Time()]])
def press(chan, base_note, vel):
noteon(chan, base_note, vel)
noteon(chan, base_note - 7, vel / 3)
noteon(chan, base_note + 7, vel / 4)
noteon(chan, base_note + 12, vel / 5)
def release(chan, base_note):
noteoff(chan, base_note)
noteon... |
Japanuspus/Site-in-a-Dropbox | app/test/dbtools.py | Python | mit | 7,523 | 0.015951 | from __future__ import absolute_import
from __future__ import with_statement
import os.path
import re
from datetime import datetime
import logging
import pickle
import copy
import subprocess
import zipfile
import functools
import traceback
import dropbox.auth
import dropbox.client
from oauth import oauth
import dropb... | """
from google.appengine.api import users
from siteinadropbox import models, controller
owner = users.User('fake@halwe.dk')
site = models.Site.get_or_insert(key_name=models.Site.the_key_name,
| owner = owner,
owner_id = 'abekat',
dropbox_access_token = 'oauth_token_secret=fakesecret&oauth_token=vc1okyqpio7irgy',
dropbox_base_dir=base_dir,
... |
tiagochiavericosta/edx-platform | common/djangoapps/student/tests/test_microsite.py | Python | agpl-3.0 | 3,772 | 0.002121 | """
Test for User Creation from Micro-Sites
"""
from django.test import TestCase
from student.models import UserSignupSource
import mock
import json
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
FAKE_MICROSITE = {
"SITE_NAME": "openedx.localhost",
"university": "fakeu... | .client.post(self.url, self.params)
self.assertEqual(response.status_code, 200)
self.asse | rtGreater(len(UserSignupSource.objects.filter(site='openedx.localhost')), 0)
def test_user_signup_from_non_micro_site(self):
"""
test to create a user form the non-microsite. The record should not be saved
in the UserSignupSource Table
"""
response = self.client.post(self.ur... |
necaris/embedded-js-in-python-example | guestbook/render_react.py | Python | mit | 5,801 | 0 | import time
import json
import logging
import PyV8
from .utils import absolute_path_in_app, ORMEncoder
log = logging.getLogger(__name__)
JSX_TRANSFORMER_PATH = absolute_path_in_app(
"static/js/JSXTransformer-0.11.1.js")
REACT_LIB_PATH = absolute_path_in_app(
"static/js/react-with-addons-0.11.1.min.js")
d... | ed source.
Also compile it into a PyV8 object and c | reate an extension to
embed in future PyV8 contexts.
"""
log.debug("Transforming JSX for %r", path)
if "lib/jsx" in PyV8.JSExtension.extensions:
log.debug("JSX extension already loaded")
else:
with open(JSX_TRANSFORMER_PATH) as jsxf:
jsx_transformer_js = jsxf.read()
... |
Pexego/alimentacion | performance_calculation/stock.py | Python | agpl-3.0 | 1,773 | 0.005085 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2004-2012 Pexego Sistemas Informáticos All Rights Reserved
| # $Marta Vázquez Rodríguez$ <marta@pexego.es>
#
# This program is free software: you c | an redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WA... |
kevinmcain/graal | mx/commands.py | Python | gpl-2.0 | 58,280 | 0.005988 | #
# commands.py - the GraalVM specific commands
#
# ----------------------------------------------------------------------------------------------------
#
# Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free ... | lation with tiered system (i.e., client + server), Graal omitted
'client-nograal' : None, # all compilation with client compiler, Graal omitted
'original' : None, # default VM copied from bootstrap JDK
}
""" The VM that will be run by the 'vm' command and built by default by the 'build' command.
This can b... | nt. """
_vm = None
""" The VM builds that will be run by the 'vm' command - default is first in list """
_vmbuildChoices = ['product', 'fastdebug', 'debug', 'optimized']
""" The VM build that will be run by the 'vm' command.
This can be set via the global '--vmbuild' option.
It can also be temporarily set by ... |
xia2/xia2 | src/xia2/cli/npp.py | Python | bsd-3-clause | 2,064 | 0 | from __future__ import annotations
import math
import sys
from iotbx.reflection_file_reader import any_reflection_file
from scitbx.array_family import flex
import xia2.Handlers.Streams
from xia2.Toolkit.NPP import npp_ify
def npp(hklin):
reader = any_reflection_file(hklin)
intensities = [
ma
... | e. variances derived from SIGI column
merger = intensities.merge_equivalents(use_internal_variance=False)
mult = merger.redundancies().data()
i | mean = merger.array()
unique = imean.indices()
iobs = imean.data()
# scale up variance to account for sqrt(multiplicity) effective scaling
variobs = (imean.sigmas() ** 2) * mult.as_double()
all = flex.double()
cen = flex.double()
for hkl, i, v, m in zip(unique, iobs, variobs, mult):
... |
KarrLab/kinetic_datanator | datanator/schema_2/transform_metabolites_meta.py | Python | mit | 13,372 | 0.005459 | from datanator_query_python.util import mongo_util
from datanator_query_python.config import config
class TransformMetabolitesMeta(mongo_util.MongoUtil):
def __init__(self, MongoDB=None,
db=None,
username=None,
password=None,
... | ty["description"] = obj.get("description")
entity["related"] = []
if obj["pathways"] is None:
return entity
pathways = obj["pathways"]["pat | hway"]
if isinstance(pathways, list):
for path in pathways:
related = {"description": path.get("name"),
"namespace": "kegg_map_id",
"value": path.get("kegg_map_id")}
entity["related"].append(related)
... |
denovator/myfriki | app/settings.py | Python | apache-2.0 | 354 | 0.002825 | # -*- coding: | utf-8 -*-
class Config(object):
SECRET_KEY = "asdfjlsadjflkjlwkqjerljlasdjfl"
debug = False
class Production(Config):
debug = True
CSRF_ENABLED = False
ADMIN = "seunghojung0114@gmail.com"
SQLALCHEMY_DATABASE_URI = "mysql+gaerdbms:///flaskr?instance=mochafac:flaskr-instance"
migra | tion_directory = "migrations"
|
plaidfluff/dreamcatcher | dc_common/model.py | Python | apache-2.0 | 3,153 | 0.007295 | # model.py - Peewee database model
from peewee import *
from playhouse.migrate import migrate
from config import database, migrator
import datetime
database.connect()
def atomic():
''' To run a bunch of stuff within a transaction; e.g.:
with model.atomic() as xact:
foo
bar
baz
... | ema | version, generic global config, etc.) '''
key = CharField(unique=True)
int_value = IntegerField(null=True)
string_value = CharField(null=True)
@staticmethod
def update_schema(check_update,from_version):
''' Hook for migrating schemata, e.g. table names '''
return 0
''' Some sample... |
lig/picket_classic | settings/local_sample.py | Python | gpl-3.0 | 890 | 0.008989 | # Django settings for wapzap project.
from dist import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
#('Firstname Lastname', 'admin@example.com'),
)
MANA | GERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(PROJECT_ROOT, 'local.db'), # Or path to database file if using sqlite3.
| 'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used wit... |
brucework/demo | src/python/hello/func_default.py | Python | gpl-3.0 | 113 | 0.035398 | #File | name: func_default.py
def say(message, times = 1):
pri | nt message * times
say('Hello')
say('World', 5)
|
BraveToasterStudio/django-notes | docs/conf.py | Python | bsd-3-clause | 6,470 | 0.006801 | # -*- coding: utf-8 -*-
#
# django-notes documentation build configuration file, created by
# sphinx-quickstart on Wed May 13 10:34:42 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
... | y = ''
# Else, today_fmt is used as the format for a strftime ca | ll.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_... |
sernaleon/charlie | Others/BlocklyProbatinas/hello/www/build.py | Python | apache-2.0 | 14,864 | 0.007535 | #!/usr/bin/python
# Compresses the core Blockly files into a single JavaScript file.
#
# Copyright 2012 Google Inc.
# http://blockly.googlecode.com/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the Licen... | altime[\\/]realtime.js', add_dependency)
add_dependency = re.sub('([\\/])' + re.escape(m.gro | up(1)) +
'([\\/]realtime[\\/])', '\\1" + dir + "\\2', add_dependency)
f.write(add_dependency + '\n')
provides = []
for dep in calcdeps.BuildDependenciesFromFiles(self.search_paths):
if not dep.filename.startswith(os.pardir + os.sep): # '../'
provides.extend(dep.provides)
provides... |
elainenaomi/sciwonc-dataflow-examples | sbbd2016/experiments/1-postgres/3_workflow_full_10files_primary_nosh_nors_annot_with_proj_3s/pegasus.bDkvI/pegasus-4.6.0/lib/python2.7/dist-packages/Pegasus/tools/kickstart_parser.py | Python | gpl-3.0 | 21,415 | 0.005183 | #!/usr/bin/env python
"""
Pegasus utility functions for pasing a kickstart output file and return wanted information
"""
##
# Copyright 2007-2010 University Of Southern California
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.... | ion
#return buffer[:end]
def is_invocation_record(self, buffer=''):
"""
Returns True if buffer contains an invocation record.
"""
if buffer.find("<invocation") == -1:
return False
return True
def is_task_record(self, buffer=''):
"""
... | return True
return False
def is_clustered_record(self, buffer=''):
"""
Returns True if buffer contains a clustered record.
"""
if ( buffer.find("[seqexec-summary") != -1 or buffer.find( "[cluster-summary" ) != -1):
return True
return False
def start... |
madmax983/h2o-3 | h2o-py/h2o/h2o_model_builder.py | Python | apache-2.0 | 4,406 | 0.050159 | """
*** Deprecated Model Builder functionality ***
Supports functional algorithm calls found in the top-level h2o module.
Current modeling is performed via estimator fitting (see estimators sub module for details)
"""
from connection import H2OConnection
from frame import H2OFrame
from job import H2OJob... | build(x,y,vx,vy,algo,offsets,weights,fold_column,kwargs):
if x is None: raise ValueError("Missing features")
x =_check_frame(x,y,y)
vx=_check_frame(vx,vy,y)
if offsets | is not None: x,vx=_check_col(x,vx,kwargs["validation_frame"],offsets)
if weights is not None: x,vx=_check_col(x,vx,kwargs["validation_frame"],weights)
if fold_column is not None: x,vx=_check_col(x,vx,kwargs["validation_frame"],fold_column)
kwargs['training_frame']=x.frame_id
if vx is not None: kwargs['v... |
native2k/lvbRequester | lvbRequester/lvbRequester.py | Python | bsd-3-clause | 9,165 | 0.002619 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import object
import requests
import types
from datetime import datetime, timedelta
from pprint import pformat
import urllib.request, urllib.parse, urllib... | s.
"""
params = self._getStationParams(station, self._defParseDatetime(time))
# log.debug('PARAMS: %s' % (params, ))
data = requests.post(self.URL['station'], data=params, headers=self.HEADER)
if data.status_code == 200:
# log.debug('BODY: %s' % (data.text))
... | raise Exception('Unable to retrieve data error: %s' % data.status_code)
@classmethod
def _getStationParams(self, stop, time):
""" build paramter structure for station request """
res = [
'results[5][5][function]=ws_info_stop&results[5][5][data]=[',
'{"name":"res... |
silvermagic/jhbuild | jhbuild/versioncontrol/hg.py | Python | gpl-2.0 | 4,401 | 0.001591 | # jhbuild - a tool to ease building collections of source packages
# Copyright (C) 2001-2006 James Henstridge
# Copyright (C) 2007 Marco Barisione <marco@barisione.org>
#
# hg.py: some code to handle various Mercurial operations
#
# This program is free software; you can redistribute it and/or modify
# it under the... | def get_revision_id(self):
# Return the id of the tip, see bug #313997.
try:
hg = Popen(['hg', 'ti', '--template', '{node}'], stdout=PIPE,
cwd=self.srcdir)
except OSError as e:
raise CommandError(str(e))
return hg.stdout.read().strip()
... | return self.get_revision_id()
register_repo_type('hg', HgRepository)
|
uniflex/module_wifi_gnuradio | gr_scripts/uniflex_wifi_transceiver.py | Python | mit | 8,326 | 0.008768 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Uniflex Wifi Transceiver
# Generated: Fri Mar 10 14:35:04 2017
##################################################
import os
import sys
sys.path.append(os.environ.get('GRC_HIER_PATH',... | turn self.rx_gain
def set_rx_gain(self, rx_gain):
self.rx_gain = rx_gain
self | .uhd_usrp_source_0.set_normalized_gain(self.rx_gain, 0)
def get_lo_offset(self):
return self.lo_offset
def set_lo_offset(self, lo_offset):
self.lo_offset = lo_offset
self.uhd_usrp_source_0.set_center_freq(uhd.tune_request(self.freq, rf_freq = self.freq - self.lo_offset, rf_freq_policy... |
titansgroup/python-phonenumbers | python/phonenumbers/re_util.py | Python | apache-2.0 | 1,426 | 0.000701 | """Additional regular expression utilities, to make it easier to sync up
with Java regular expression code.
>>> import re
>>> from .re_util import fullmatch
>>> from .util import u
>>> | string = 'abcd'
>>> r1 = re.compile('abcd')
>>> r2 = re.compile('bc')
>>> r3 = re.compile('abc')
>>> fullmatch(r1, string) # doctest: +ELLIPSIS
<...SRE_Match object...>
>>> fullmatch(r2, string)
>>> fullmatch(r3, | string)
>>> r = re.compile('\\d{8}|\\d{10,11}')
>>> m = fullmatch(r, '1234567890')
>>> m.end()
10
>>> r = re.compile(u('[+\uff0b\\d]'), re.UNICODE)
>>> m = fullmatch(r, u('\uff10'))
>>> m.end()
1
"""
import re
def fullmatch(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, return... |
capitalone/cloud-custodian | tools/c7n_gcp/c7n_gcp/resources/spanner.py | Python | apache-2.0 | 5,796 | 0.00069 | # Copyright 2019 Capital One Services, LLC
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from c7n.utils import type_schema
from c7n_gcp.actions import MethodAction, SetIamPolicy
from c7n_gcp.provider import resources
from c7n_gcp.query import QueryResourceManager, TypeInfo, ChildTypeInf... | = "spanner.googleapis.com/Database"
@staticmethod
def get(client, resource_info):
return client.execute_command(
'get', {
'name': resource_info['resourceName']}
)
SpannerDatabaseInstance.action_registry.register('set-iam-policy', SetIamPolic... | tanceDropDatabase(MethodAction):
"""The action is used for databases deleting.
GCP action is https://cloud.google.com/spanner/docs
/reference/rest/v1/projects.instances.databases/dropDatabase.
:Example:
.. code-block:: yaml
policies:
- name: gcp-spanner-instance-databases-d... |
bostonlink/nwmaltego | nw_threat_2_file_attachment.py | Python | gpl-3.0 | 2,405 | 0.003742 | #!/usr/bin/env python
# Copyright (C) 2012 nwmaltego Developer.
# This file is part of nwmaltego - https://github.com/bostonlink/nwmaltego
# See the file 'LICENSE' for copying permission.
# Netwitness Threat to Filename Maltego transform
# Author: David Bressler (@bostonlink)
import sys
import urllib2, urllib, json
f... | Name="risk" DisplayName="Threat Name">%s</Field>
<Field Name="ip" DisplayName="IP Address">%s</Field>
<Field Name="metaid1" DisplayName="Meta id1">%s</Field>
<Field Name="metaid2" DisplayName="Meta id2">%s</Field>
<Field Name="type" Display... | </AdditionalFields>
</Entity>""" % (value, risk_name, ip, d['id1'], d['id2'], d['type'], d['count'])
file_list.append(value)
# Maltego transform XML footer
trans_footer = """ </Entities>
</MaltegoTransformResponseMessage>
</MaltegoMessage> """
print trans_footer |
vivisect/synapse | synapse/tests/test_lib_trees.py | Python | apache-2.0 | 1,092 | 0.002747 |
from synapse.tests.common import *
import synapse.lib.trees as s_trees
class TreeTest(SynTest):
def test_lib_tree_interval(self):
ivals = (
((-30, 50), {'name': 'foo'}),
((30, 100), {'name': 'bar'}),
((80, 100), {'name': 'baz'}),
)
itree = s_trees.Int... | r', 'baz'])
# test an exact overlap on max
names = [ival[1].get('name') for ival in itree.get(100)] |
self.eq(names, ['bar', 'baz'])
self.eq(itree.get(-31), [])
self.eq(itree.get(101), [])
self.eq(itree.get(0xffffffff), [])
|
dstufft/warehouse | warehouse/migrations/versions/56e9e630c748_add_fuzzystrmatch.py | Python | apache-2.0 | 846 | 0 | # 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 a | t
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin | g, 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.
"""
Add fuzzystrmatch
Revision ID: 56e9e630c748
Revises: e82c... |
edx/edxanalytics | src/util/playback.py | Python | agpl-3.0 | 1,385 | 0.01083 | import logging, logging.handlers
import sys
logging.handlers.HTTPHandler('','',method='GET')
logger = logging.getLogger('simple_example')
# http_handler = logging.handlers.HTTPHandler('127.0.0.1:9022', '/event', method='GET')
http_handler = logging.handlers.HTTPHandler('127.0.0.1:9999', '/httpevent', method='GET')
... | , pickle, struct, time, re
# from codecs import BOM_UTF8
# from stat import ST_DEV, ST_INO, ST_MTIME
# import queue
# try:
# import threading
# except ImportError: #pragma: no cover
# threading = None
# import http.client, urllib.parse
# port = 9022
# method = "GET"
# host = "127.0.0.1"
# url = "/"
# h = htt... | HTTPConnection(host)
# url = url + "?%s" % (sep, data)
# for item in lines:
# data = urllib.parse.urlencode(record)
# h.putrequest(method, url)
# h.putheader("Host", host)
# if method == "POST":
# h.putheader("Content-type",
# "application/x-www-form-urlencoded")
# ... |
gnublet/py_explorations | sklearn/exercise_02_sentiment.py | Python | mit | 4,170 | 0.003118 | """Build a sentiment analysis / polarity model
Sentiment analysis can be casted as a binary text classification problem,
that is fitting a linear classifier on features extracted from the text
of the user messages so as to guess wether the opinion of the author is
positive or negative.
In this examples we will use a ... | sting set and store it in a variable
# named y_predicted
y_predicted = grid_search.predict(docs_test)
# Print the classification report
print(metrics.classification_report(y_test, y_predicted,
target_names=dataset.target_names))
# Print and | plot the confusion matrix
cm = metrics.confusion_matrix(y_test, y_predicted)
print(cm)
# import matplotlib.pyplot as plt
# plt.matshow(cm)
# plt.show()
#new--
# Predict the result on some short new sentences:
sentences = [
u'Wow! this movie was amazing. I was impressed by the in-depth... |
douwekiela/nncg-negation | acl17/models.py | Python | mit | 13,191 | 0.005231 | from __future__ import print_function
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence
#from torchtext import vocab
class Vocabulary(object):... | squeeze(3).expand(batch_size, self.first_dim,
self.second_dim, self.out_dim)
input2_expanded = input2.unsqueeze(1).unsqueeze(3).expand(batch_size, self.first_dim,
self.second_dim, ... | f.out_dim)
weights_expanded = self.weights.unsqueeze(0).expand(batch_size, self.first_dim,
self.second_dim, self.out_dim)
output = (weights_expanded*input1_expanded*input2_expanded).sum(1).sum(2)
return output.squeeze(1).squeeze(1)
... |
rnavarro/Py-Post | vendors/yenc-0.3.1/examples/ydecode_Decoder.py | Python | mit | 2,936 | 0.044619 | #!/usr/bin/env python
##=============================================================================
#
# Copyright (C) 2003, 2004 Alessandro Duca <alessandro.duca@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as publis... | ad_crc = trail_crc = ""
if len(sys.argv) > 1:
file_in = open(sys.argv[1],"r")
else:
file_in = sys.stdin
while 1:
line = file_in.readline()
if line.startswith("=ybegin "):
try:
name, size = NAME_RE.match(line).group(1), int(SIZE_RE.match(line | ).group(1))
m_obj = CRC32_RE.match(line)
if m_obj:
head_crc = m_obj.group(1)
except re.error, e:
sys.stderr.write("err-critical: malformed =ybegin header\n")
sys.exit(1)
break
elif not line:
sys.stderr.write("err-critical: no valid =ybegin header found\n")
sys.exit(1)
file_out = open... |
Kromey/fbxnano | prosodyauth/utils.py | Python | mit | 1,032 | 0.005814 | from django.middleware.csrf import rotate_token
from prosodyauth.models import User, AnonymousUser
from prosodyauth.prosody.backend import ProsodyBackend
SESSION_KEY = '_prosodyauth_user_id'
def login(request, user):
try:
user_id = request.session[SESSION_KEY]
if user.pk != user_id:
... | uest.session.cycle_key()
request.session[SESSION_KEY] = user.pk
request.u | ser = user
rotate_token(request)
def logout(request):
request.session.flush()
request.user = AnonymousUser()
def get_user(request):
user = None
try:
user_id = request.session[SESSION_KEY]
except KeyError:
pass
else:
backend = ProsodyBackend()
user = backend... |
bblacey/FreeCAD-MacOS-CI | src/Mod/Path/PathScripts/nc/hpgl2dv.py | Python | lgpl-2.1 | 580 | 0.015517 | # hpgl2dv.py
#
# Copyright (c) 2009, Dan Heeks
# This program is released under the BSD | license. See the file COPYING for details.
#
# This is the same as the hpgl2d machine, but uses units of 0.25mm instead of 0.0 | 1mm
import nc
import hpgl2d
class Creator(hpgl2d.Creator):
def init(self):
hpgl2d.Creator.init(self)
def imperial(self):
self.units_to_mc_units = 101.6 # multiplier from inches to machine units
def metric(self):
self.units_to_mc_units = 4 # multiplier from mm to ma... |
Applied-GeoSolutions/gips | gips/__init__.py | Python | gpl-3.0 | 1,365 | 0.00293 | #!/usr/bin/env python
################################################################################
# GIPS: Geospatial Image Processing System
#
# AUTHOR: Matthew Hanson
# EMAIL: matt.a.hanson@gmail.com
#
# Copyright (C) 2014-2018 Applied Geosolutions
#
# This program is free software; you can redist... | /or modify
# it under the terms of the GNU General Public License as published by
# the Free Softwa | re Foundation; either version 3 of the License, or
# (at your option) 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 PARTICULAR PURPOSE. See the
# GNU General Publi... |
alxgu/ansible | lib/ansible/modules/identity/ipa/ipa_service.py | Python | gpl-3.0 | 6,566 | 0.001219 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# 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',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = | '''
---
module: ipa_service
author: Cédric Parent (@cprh)
short_description: Manage FreeIPA service
description:
- Add and delete an IPA service using IPA API
options:
krbcanonicalname:
description:
- principal of the service
- Can not be changed as it is the unique identifier.
required: true
ali... |
ray-project/ray | rllib/agents/impala/tests/test_vtrace.py | Python | apache-2.0 | 15,359 | 0.001172 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | tch_size = 15
num_actions = 3
clip_rho_threshold = None # No clipping.
clip_pg_rho_threshold = None # No clipping.
space = Box(-1.0, 1.0, (seq_len, batch_size, num_actions))
| action_space = Box(
0,
num_actions - 1,
(
seq_len,
batch_size,
),
dtype=np.int32,
)
space_w_time = Box(
-1.0,
1.0,
(
seq_len,
batch_size,
... |
jason-neal/eniric | tests/test_legacy.py | Python | mit | 3,783 | 0.001057 | import numpy as np
import pytest
from astropy import units as u
from hypothesis import given, strategies as st
from eniric.atmosphere import Atmosphere
from eniric.legacy import RVprec_calc_masked, RVprec_calc_weights_masked, mask_clumping
def test_RV_prec_masked(test_spec):
"""Test same precision results betwee... | rec_calc_masked(wav_masked, flux_masked, mask=None)
rv_ma | sked = RVprec_calc_masked(wav, flux, mask)
assert rv_masked.value == rv_chunks.value
assert isinstance(rv_masked, u.Quantity)
assert rv_masked.unit == u.m / u.s
@given(st.lists(st.booleans(), min_size=5, max_size=300))
def test_mask_clumping_of_mask(mask):
"""Masking mask show return all ones."""
... |
liangwang/m5 | src/arch/x86/isa/insts/general_purpose/flags/push_and_pop.py | Python | bsd-3-clause | 2,420 | 0 | # Copyright (c) 2007-2008 The Hewlett-Packard Development Company
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware imp... | L,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY | , OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Gabe Black
microcode = '''
def macroop PUSHF {
.adjust_env oszIn64Override
rflags t1
stupd t1, ss, [1, t0, rsp], "-env.stackSize", dataSize=... |
snahelou/awx | awx/main/tests/functional/api/test_activity_streams.py | Python | apache-2.0 | 7,308 | 0.003147 | import mock
import pytest
from awx.api.versioning import reverse
from awx.main.middleware import ActivityStreamMiddleware
from awx.main.models.activity_stream import ActivityStream
from awx.main.access import ActivityStreamAccess
def mock_feature_enabled(feature):
return True
@pytest.fixture
def activity_strea... | nization.admin_role'
@mock.patch('awx.api.views.feature_enabled', new=mock_feature_enabled)
@pytest.mark.django_db
def test_rbac_stream_user_roles(activity_stream_entry, organization, org_admin, settings):
settings.ACTIVITY_STREAM_ENABLED = True
assert activity_stream_entry.user.first() == org_admin
asser... | relationship_type == 'awx.main.models.organization.Organization.admin_role'
@pytest.mark.django_db
@pytest.mark.activity_stream_access
@mock.patch('awx.api.views.feature_enabled', new=mock_feature_enabled)
def test_stream_access_cant_change(activity_stream_entry, organization, org_admin, settings):
settings.ACTIV... |
dopsi/flairstats | flairstats/fetchbot.py | Python | mit | 5,308 | 0.00471 | from praw import Reddit
import json
import os
import time
import datetime
from .tools import storage
from .tools import display
class FetchBot:
"""Bot to fetch the subreddit data."""
def __init__(self, user_agent, subreddit, data_file):
"""Basic constructor"""
self._user_agent = user_agent
... | ta_file)):
os.makedirs(os.path.dirname(self._data_file))
with open(self._data_file, 'w') as df:
json.dump(self._data, df)
def fetch(self):
"""Fetching function"""
self._fetch(self._praw.get_comments(self._subreddit, limit=500), 'comments')
self._fetch(self._p... | function"""
is_first = True
storage.dict_check_key(self._data[key], 'first', float(round(time.time())))
try:
new_creation_limit = self._data[key]['last']
except:
self._data[key]['last'] = new_creation_limit = 0
for it in submissions:
if is... |
alias-org/alias | alias/semantics/extensions/extension_stable.py | Python | gpl-3.0 | 188 | 0.010638 | import alias as al
def extension_stable(af):
p | ref = al.extension_preferred(af)
stab = []
for p in pref:
if p == af.argsU(p):
| stab.append(p)
return stab |
nilsFK/py-privatekonomi | py_privatekonomi/tests/dataset/avanza/sample1.py | Python | mit | 6,015 | 0.026824 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
test_data = [
{
"Transaction" : {
"transaction_date" : "2015-01-08",
"amount" : -1286.75,
"security_amount" : 4.0726,
"security_rate" : 413.68
},
"Account" : ... | },
"Currency" : {
"code" : "SEK"
},
"SecurityProvider" : {
"name" : "Aktiefond #3"
},
"TransactionType" : {
"name" : "Köp | "
},
"TransactionData" : {
"ISIN" : "SE0000000007",
"courtage" : 70.50
}
},
{
"Transaction" : {
"transaction_date" : "2014-10-28",
"amount" : -862.99,
"security_amount" : 8.7321,
"security_rate" : 213.35
... |
Arabidopsis-Information-Portal/jbrowse | tests/selenium_tests/welcome_page_test.py | Python | lgpl-2.1 | 247 | 0.020243 | import unittest
from jbrowse_selenium import JBrowseTest
class WelcomePageTest( JBrowseTest, unittest.Te | stCase ):
data_dir = 'nonexisten | t'
def test_volvox( self ):
self.assert_element('//div[contains(@class,"fatal_error")]/h1')
|
riga/order | order/util.py | Python | bsd-3-clause | 11,655 | 0.003089 | # coding: utf-8
"""
Helpful utilities.
"""
__all__ = [
"ROOT_DEFAULT", "typed", "make_list", "multi_match", "flatten", "to_root_latex",
"join_root_selection", "join_numexpr_selection", "class_id", "args_to_kwargs", "DotAccessProxy",
]
import os
import functools
import types
import re
import fnmatch
import ... | The member name can be configured by setting *name*. If *setter* (*deleter*) is *True* (the
default), a setter (deleter) method is booked as well. Prior to updating the membe | r when the
setter is called, *fparse* is invoked which may implement sanity checks.
"""
def __init__(self, fparse=None, setter=True, deleter=True, name=None):
self._args = (setter, deleter, name)
# only register the property if fparse is set
if fparse is not None:
self.... |
addiks/gmattermost | src/Controller/IndicatorController.py | Python | gpl-3.0 | 1,064 | 0.00282 |
from gi.repository import AppIndicator3 as appindicator
class IndicatorController:
__application = None # Application
__indicator = None # appindicator.Indicator
def __init__(self, application):
# Gtk.Builder
self.__gladeBuilder = application.createGladeBuilder('indicator')
sel... | m):
self.__application.showTeamsLi | stWindow(True, False)
|
spreadflow/spreadflow-core | spreadflow_core/script.py | Python | mit | 7,764 | 0.002962 | """
Provides utility functions for spreadflow config script.
"""
import inspect
from spreadflow_core.component import Compound
from spreadflow_core.dsl.stream import AddTokenOp, SetDefaultTokenOp
from spreadflow_core.dsl.parser import ComponentParser
from spreadflow_core.dsl.tokens import \
AliasToken, \
Comp... | ctx.tokens.extend(operations)
return process
def Chain(name, *procs, **kw): # pylint: disable=C0103
"""
Forms a chain of the given components by connecting the default input port
to the default output port of its prede | cessor.
"""
ctx = Context.top()
template = ChainTemplate(chain=procs)
parser = ComponentParser()
operations = list(parser.divert(template.apply()))
process = parser.get_component()
operations.append(AddTokenOp(LabelToken(process, name)))
operations.append(AddTokenOp(AliasToken(process... |
evrom/genitag | controllers/site_root/login.py | Python | gpl-2.0 | 2,373 | 0.000421 | from bottle import request, redirect
from passlib.hash import pbkdf2_sha256
from libraries.template import view
from sqlalchemy import exc
from sqlalchemy.sql import select
from libraries.regex import email as EmailRegex,\
username as UsernameRegex
from libraries.database import users, engine as db
from libraries.f... | f EmailRegex.match(form.loginname.data):
| result = conn.execute(
select([
users.c.id,
users.c.pbkdf2,
users.c.emailverified]).where(
users.c.email == form.loginname.data))
elif UsernameRegex.match(... |
nena1/OxwallDigest | launch.py | Python | gpl-2.0 | 12,682 | 0.003391 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "marko"
import sys, os, datetime, smtplib, json
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import codecs
from collections import OrderedDict
import traceback
import sqlalchemy
from sqlalchemy import and_
import jinja2... | last=comment.create_stamp,
url="%s/blogs/%s" % (configuration.url_prefix, blog_post.id)
)
else:
blog_post_comments[title].append(comment.user.username, comment.create_stamp)
# Digest comments to events
| event_comments = OrderedDict()
for comment in session.query(Comment).filter(
and_(Comment.create_stamp >= seconds_since_epoch(interval_begin),
Comment.create_stamp < seconds_since_epoch(interval_end))).order_by(Comment.create_stamp):
if comment.comment_entity.active != 1 or... |
nagyistoce/edx-platform | lms/envs/devstack.py | Python | agpl-3.0 | 7,127 | 0.00435 | """
Specific overrides to the base prod settings to make development easier.
"""
from .aws import * # pylint: disable=wildcard-import, unused-wildcard-import
# Don't use S3 in devstack, fall back to filesystem
del DEFAULT_FILE_STORAGE
MEDIA_ROOT = "/edx/var/edxapp/uploads"
DEBUG = True
USE_I18N = True
TEMPLATE_DEB... | CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC",
}
# Skip enrollment start date filtering
SEARCH_SKIP_ENROLLMENT_START_DATE_FIL | TERING = True
########################## Shopping cart ##########################
FEATURES['ENABLE_SHOPPING_CART'] = True
FEATURES['STORE_BILLING_INFO'] = True
FEATURES['ENABLE_PAID_COURSE_REGISTRATION'] = True
FEATURES['ENABLE_COSMETIC_DISPLAY_PRICE'] = True
########################## Third Party Auth #############... |
bkpathak/HackerRank-Problems | python/graphs/rainfall_challenge.py | Python | mit | 1,071 | 0.003735 | """
The problem definition is here:
http://codereview.stackexchange.com/questions/38500/rainfall-challenge
The implementaion here uses union-find data structures.
"""
class Basin(object):
"""
This class tracks the sink for each basin and number of cells that belongs
to the basin.
"""
def __init__... | cture.
"""
class Cell(object):
"""
Keep tracks of to which basin the cell belongs to.
"""
def __init__(self):
self.to_basin = None
def find_basin():
"""
This is find operation of UNION-FIND data structure.
"""
class Topography(object):
"""
Run thro... | """
Find the number of basin in the data.
"""
for
|
kansanmuisti/kamu | profiler/middleware.py | Python | agpl-3.0 | 2,022 | 0.001978 | try:
import cProfile as profile
except ImportError:
import profile
import pstats
from io import StringIO
from django.conf import settings
class P | rofilerMiddleware(object):
"""
Simple profile middleware to profile django views. To run it, add ?prof to
the URL like this:
http://localhost:8000/view/?pr | of
Optionally pass the following to modify the output:
?sort => Sort the output by a given metric. Default is time.
See http://docs.python.org/2/library/profile.html#pstats.Stats.sort_stats
for all sort options.
?count => The number of rows to display. Default is 100.
This is adapted... |
iceihehe/easy-note | app/validators.py | Python | mit | 329 | 0 | # -*- coding: utf-8 -*-
import re
# from flask_restful import inputs
# objectid = inputs.regex('^[0-9a-z]{24}$')
def objectid(value):
message = 'ciao'
if n | ot value:
return None
pattern = re.comp | ile('^[0-9a-z]{24}$')
if not pattern.match(value):
raise ValueError(message)
return value
|
senarvi/theanolm | theanolm/training/adadeltaoptimizer.py | Python | apache-2.0 | 3,644 | 0.001098 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""A module that implements the ADADELTA optimi | zer.
"""
import numpy
import theano.tensor as tensor
fro | m theanolm.backend import Parameters
from theanolm.training.basicoptimizer import BasicOptimizer
class AdadeltaOptimizer(BasicOptimizer):
"""ADADELTA Optimization Method
ADADELTA optimization method has been derived from AdaGrad. AdaGrad
accumulates the sum of squared gradients over all time, which is use... |
leeping/mdtraj | tests/test_rmsd.py | Python | lgpl-2.1 | 6,778 | 0.000738 | ##############################################################################
# MDTraj: A Python Library for Loading, Saving, and Manipulating
# Molecular Dynamics Trajectories.
# Copyright 2012-2013 Stanford University and the Authors
#
# Authors: Robert McGibbon
# Contributors:
#
# MDTraj is free software: y... | get_fn('traj.h5'), stride=10)
# don't center t1, and use it without precentered
# explicitly center t2, and use *with* precentered
t2_a.center_coordinates()
t2_b.center_coordinates()
for parallel in [True, False]:
for i in range(t1_b.n_frames):
ref = np.zeros(t1_a.n_fram | es)
for j in range(t1_a.n_frames):
ref[j] = rmsd_qcp(t1_a.xyz[j], t1_b.xyz[i])
val1 = md.rmsd(t1_a, t1_b, i, parallel=parallel, precentered=False)
val2 = md.rmsd(t2_a, t2_b, i, parallel=parallel, precentered=True)
eq(ref, val1, decimal=3)
eq(v... |
rueckstiess/dopamine | experiments/api.py | Python | gpl-3.0 | 5,317 | 0.007711 | from dopamine.experiments.experiment import Experiment, ExperimentException
import numpy as np
import types
class APIExperiment(Experiment):
def runEpisode(self, reset=True):
""" resets the environment in a random state, then creates rollouts until
the environment and its adapters signals the ... | pisodeFinished(episodeFinished)
# while the resulting episodeFinished is False, loop over interactions
while not episodeFinished:
self.interact()
episodeFinished = self.environment.episodeFinished()
for adapter in self.adapters_:
... | .newEpisode()
self.numEpisodes += 1
def evaluateEpisodes(self, count, reset=True, exploration=False, visualize=True):
""" executes the original Experiment.runEpisode() function during evaluation. """
self.funcRunEpisode = self.runEpisode
self.runEpisode = types.MethodTy... |
SUSE/teuthology | teuthology/task/proc_thrasher.py | Python | mit | 2,404 | 0.002496 | """
Process thrasher
"""
import logging
import gevent
import random
import time
from teuthology.orchestra import run
log = logging.getLogger(__name__)
class ProcThrasher:
""" Kills and restarts some number of the specified process on the specified
remote
"""
def __init__(self, config, remote, *pr... | self.remote = remote
# config:
self.num_procs = self.config.get("num_procs", 5)
self.rest_period = self.config.get("rest_period", 100) # seconds
self.run_time = self.config.get("run_time", 1000) # seconds
def log(self, msg):
"""
Local log wrapper
"""
... | Start thrasher. This also makes sure that the greenlet interface
is used.
"""
if self.greenlet is not None:
return
self.greenlet = gevent.Greenlet(self.loop)
self.greenlet.start()
def join(self):
"""
Local join
"""
self.greenle... |
arrabito/DIRAC | WorkloadManagementSystem/DB/TaskQueueDB.py | Python | gpl-3.0 | 51,921 | 0.01067 | """ TaskQueueDB class is a front-end to the task queues db
"""
__RCSID__ = "$Id"
import random
from DIRAC import gConfig, gLogger, S_OK, S_ERROR
from DIRAC.WorkloadManagementSystem.private.SharesCorrector import SharesCorrector
from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations
from DIRAC.Core... | maxCPUSegments = self.__defaultCPUSegments
| break
last = cpuS
except BaseException:
maxCPUSegments = self.__defaultCPUSegments
# Map to a segment
for cpuSegment in maxCPUSegments:
if cpuTime <= cpuSegment:
return cpuSegment
return maxCPUSegments[-1]
def _checkTaskQueueDefinition(self, tqDefDict):
"""
... |
jcurbelo/networkx | examples/algorithms/blockmodel.py | Python | bsd-3-clause | 3,014 | 0.022893 | #!/usr/bin/env python
# encoding: utf-8
"""
Example of creating a block model using the blockmodel function in NX. Data used is the Hartford, CT drug users network:
@article{,
title = {Social Networks of Drug Users in {High-Risk} Sites: Finding the Connections},
volume = {6},
shorttitle = {Social Networks of Drug ... | in BM.nodes()]
edge_width=[(2*d['weight']) | for (u,v,d) in BM.edges(data=True)]
# Set positions to mean of positions of internal nodes from original graph
posBM={}
for n in BM:
xy=numpy.array([pos[u] for u in BM.node[n]['graph']])
posBM[n]=xy.mean(axis=0)
ax=fig.add_subplot(212)
nx.draw(BM,posBM,node_size=node_size,width=edge_... |
Bioto/Huuey-python | huuey/hue/scenes/__init__.py | Python | mit | 24 | 0.041667 | fr | om .scene impor | t Scene |
srfraser/services | src/shipit_code_coverage/shipit_code_coverage/cli.py | Python | mpl-2.0 | 2,004 | 0 | # -*- coding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# Licens | e, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import absolute_import
import click
from cli_common.click import taskcluster_options
from cli_common.log import init_logger
from cli_common.taskcluster import get_secrets
from shipi... | VISION')
@click.option(
'--cache-root',
required=True,
help='Cache root, used to pull changesets'
)
def main(revision,
cache_root,
taskcluster_secret,
taskcluster_client_id,
taskcluster_access_token,
):
secrets = get_secrets(taskcluster_secret,
... |
zsloan/genenetwork2 | wqflask/tests/wqflask/show_trait/testSampleList.py | Python | agpl-3.0 | 642 | 0 | import unittest
im | port re
from unittest import mock
from wqflask.show_trait.SampleList import natural_sort
class TestSampleList(unittest.TestCase):
def test_na | tural_sort(self):
"Sort the list into natural alphanumeric order."
characters_list = ["z", "f", "q", "s", "t", "a", "g"]
names_list = ["temp1", "publish", "Sample", "Dataset"]
sorted_list_a = natural_sort(characters_list)
sorted_list_b = natural_sort(names_list)
self.ass... |
alangwansui/mtl_ordercenter | openerp/addons/001_mrp/__init__.py | Python | agpl-3.0 | 301 | 0.003322 | # -*- coding: utf-8 -*-
##############################################################################
# 'author': 'Wu | lf Chow',
# 'date' : 2012-7-5
# 'maile' : <alangwansui at | gmail.com>
##############################################################################
import mrp_production_new
|
OwenSawyer/PiBot | Pi Driver.py | Python | mit | 3,775 | 0.050331 |
from pubnub import Pubnub
import json,time
try:
import RPi.GPIO as GPIO
except RuntimeError:
print "Error importing RPi.GPIO! This is probably because you need superuser privileges. You can achieve this by using 'sudo' to run your script"
#Setup GPIO
GPIO.setmode(GPIO.BOARD)
#Setup PubNub
pubnub = Pubnub... | pubnub.publish(pubnubChannelN | ame, respmsg)
elif(command['req'] == 'right'):
if(right):
respstring = 'right stop'
forward = False
backward = False
left = False
right = False
gpiostop()
else:
right = True
respstring = 'right'
GPIO.output(19, True)
GPIO.output(22, False)
GPIO.out... |
erikabarros/naguil | backend/appengine/routes/account.py | Python | mit | 1,088 | 0.001838 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from config.templa | te_middleware import TemplateResponse
from gaecookie.decorator import no_csrf
from gaepermission.decorator import login_required
from pytz import common_timezones
import settings
from tekton import router
from tekton.gae.middleware.redirect import RedirectResponse
from gaepermission.decorator import login_not_required
... | equired
@no_csrf
def edit(_logged_user, name, user_locale, timezone):
if name:
_logged_user.name = name
_logged_user.locale = user_locale
_logged_user.timezone = timezone
_logged_user.put()
return RedirectResponse('/')
@login_not_required
@no_csrf
def index(_logged_user):
_logged_user.... |
sbg/sevenbridges-python | sevenbridges/models/compound/price_breakdown.py | Python | apache-2.0 | 733 | 0 | from sevenbridges.meta.resource import Resource
from sevenbridges.meta.fields import StringField
class Breakdown(Resource):
"""
Breakdown resource contains price breakdown by storage and computation.
"""
storage = StringField(read_only=True)
computation = StringField(read_only=True)
data_trans... | 'computation={s | elf.computation}>'
)
|
botswana-harvard/bcpp-subject | bcpp_subject/models/model_mixins/__init__.py | Python | gpl-3.0 | 523 | 0 | from .circumcision_model_mixin import CircumcisionModelMixin
from .crf_model_mixin import CrfModelManager, CrfModelMixin
# CrfModelMixinNonUniqueVisit
from .detailed_sexual_history_mixin i | mport DetailedSexualHistoryMixin
from .hiv_testing_supplemental_mixin import HivTestingSupplementalMixin
from .mobile_test_model_mixin import MobileTestModelMixin
from .pregnancy_model_mixin import PregnancyModelMixin
from .search_slug_model_mixin import SearchSlugModelMixin
from .sexual_partner_model_mixin import Sexu... | |
nanobox-io/nanobox-adapter-libcloud | nanobox_libcloud/utils/output.py | Python | mit | 612 | 0.009804 | import typing
from flask import json
FlaskHeaders = typing.Union[typing.List[typing.Tuple[str, str]], typing.Dict[str, str]]
FlaskResponse = typing.Tuple[str, int, FlaskHeaders]
def success(data, status=200) -> FlaskResponse:
return json.dumps(data, indent=2), status, [("Con | tent-Type", "application/json")]
def failure(message, status=400) -> FlaskResponse:
return json.dumps({"errors": ([message]\
if hasattr(message, | 'strip') else message if hasattr(message, 'split')\
else repr(message))}, indent=2),\
status,\
[("Content-Type", "application/json")]
|
dhp-denero/LibrERP | report_aeroo/ctt_languages/tr_TR/currencies/trl.py | Python | agpl-3.0 | 623 | 0.004831 | #!/usr/bin/python
# -*- coding: utf8 -*-
from report_aeroo.ctt_objects import ctt_currency
class trl(ctt_currency):
def _init_currency(self):
self.language = u'tr_TR'
self.code = u'TRL'
self.fractions = 100
self.cur_singular = u' Lira'
# default plural form for currency
... | actions
| self.frc_plural = u' kuruş'
# grammatical genders: f - feminine, m - masculine, n -neuter
self.cur_gram_gender = 'm'
self.frc_gram_gender = 'm'
trl()
|
sasha-gitg/python-aiplatform | google/cloud/aiplatform_v1beta1/services/index_service/transports/grpc_asyncio.py | Python | apache-2.0 | 16,914 | 0.00136 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | :`google.auth.default`.
channel (Optional[aio.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint | (Optional[str]): Deprecated. The mutual TLS endpoint.
If provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from
``client_cert_source`` or application default SSL credentials.
client_cert_source (... |
gmimano/commcaretest | corehq/apps/app_manager/tests/test_success_message.py | Python | bsd-3-clause | 3,754 | 0.003729 | from StringIO import StringIO
from django.test import TestCase
from django.test.client import Client
from corehq.apps.app_manager.models import Application, APP_V1, Module
from corehq.apps.app_manager.success_message import SuccessMessage
from corehq.apps.domain.shortcuts import create_domain
from corehq.apps.users.mod... | _id
couch_user.first_name = self.first_name
couch_user.last_name = self.last_name
| couch_user.save()
self.sm = SuccessMessage(self.message, userID, tz=self.tz)
c = Client()
app = Application.new_app(self.domain, "Test App", application_version=APP_V1)
app.add_module(Module.new_module("Test Module", "en"))
form = app.new_form(0, "Test Form", "en")
fo... |
eunchong/build | third_party/sqlalchemy_0_7_1/sqlalchemy/sql/util.py | Python | bsd-3-clause | 24,702 | 0.003765 | # sql/util.py
# Copyright (C) 2005-2011 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from sqlalchemy import exc, schema, util, sql, types as sqltypes
from sqlalchemy.util impo... | # evaluate callables
if callable(value):
value = value()
v.append(value)
visitors.traverse(clause, {}, {'bindparam':visit_bindparam})
return v
def _quote_ddl_expr(eleme | nt):
if isinstance(element, basestring):
element = element.replace("'", "''")
return "'%s'" % element
else:
return repr(element)
def expression_as_ddl(clause):
"""Given a SQL expression, convert for usage in DDL, such as
CREATE INDEX and CHECK CONSTRAINT.
Converts bind p... |
Yubico/yubioath-desktop-dpkg | yubioath/gui/controller.py | Python | gpl-3.0 | 14,732 | 0 | # Copyright (c) 2014 Yubico AB
# All rights reserved.
#
# 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 program... | f.cred.oath_type == TYPE_HOTP
def calculate(self):
window = get_active_window()
dialog = QtGui.QMessageBox(window)
dialog.setWindowTitle(m.touch_title)
dialog.setStandardButtons(QtGui.QMessageBox.NoButton)
d | ialog.setIcon(QtGui.QMessageBox.Information)
dialog.setText(m.touch_desc)
timer = None
def cb(code):
if timer:
timer.stop()
dialog.accept()
if isinstance(code, Exception):
QtGui.QMessageBox.warning(window, m.error,
... |
hughperkins/kgsgo-dataset-preprocessor | thirdparty/future/src/libfuturize/fixer_util.py | Python | mpl-2.0 | 16,007 | 0.002436 | """
Utility functions from 2to3, 3to2 and python-modernize (and some home-grown
ones).
Licences:
2to3: PSF License v2
3to2: Apache Software License (from 3to2/setup.py)
python-modernize licence: BSD (from python-modernize/LICENSE)
"""
from lib2to3.fixer_util import (FromImport, Newline, is_import,
... | for which a node (an import_stmt) has scope
The purpose of this is for a call to _find() on each of them
"""
# import_name / import_from are small_stmts
assert node.type in _import_stmts
test = node.next_sibling
# A small_stmt can only be followed by a SEMI or a NEWLINE.
while test.type == ... | nly be followed by a small_stmt or a NEWLINE
if nxt.type == token.NEWLINE:
break
else:
yield nxt
# A small_stmt can only be followed by either a SEMI or a NEWLINE
test = nxt.next_sibling
# Covered all subsequent small_stmts after the import_stmt
# Now to c... |
Kortemme-Lab/protein_feature_analysis | ProteinFeatureAnalyzer/features/RamachandranFeature.py | Python | mit | 8,582 | 0.015731 | import os
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import Bio.PDB as PDB
from sklearn import svm
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import KernelDensity
from sklearn.model_selection import GridSearchCV
from sklear... | lt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), Z.max(), 20), cm | ap=plt.cm.Blues_r)
#plt.contourf(xx, yy, Z, levels=np.linspace(0, Z.max()), colors='orange')
plt.contourf(xx, yy, Z_pred, levels=[0.9, 1.1], colors='orange')
# Draw the density estimation
if self.de:
Z = self.de.score_samples(transformed_data)
Z = Z.reshape(xx.shape)
plt.c... |
planbcoin/planbcoin | test/functional/p2p-segwit.py | Python | mit | 90,174 | 0.003271 | #!/usr/bin/env python3
# Copyright (c) 2016 The PlanBcoin developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test segwit transactions and blocks on P2P network."""
from test_framework.mininode import *
from test_framewo... | stFramework
from test_framework.util import *
from test_framework.script import *
from test_framework.blocktools import create_block, create_coinbase, add_witness_commitment, get_witness_script, WITNESS_COMMITMENT_ | HEADER
from test_framework.key import CECKey, CPubKey
import time
import random
from binascii import hexlify
# The versionbit bit used to signal activation of SegWit
VB_WITNESS_BIT = 1
VB_PERIOD = 144
VB_ACTIVATION_THRESHOLD = 108
VB_TOP_BITS = 0x20000000
MAX_SIGOP_COST = 80000
# Calculate the virtual size of a wit... |
gangadharkadam/tailorerp | erpnext/support/doctype/support_ticket/support_ticket.py | Python | agpl-3.0 | 8,287 | 0.033064 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from erpnext.utilities.transaction_base import TransactionBase
from frappe.utils import now, extract_email_id
import json
import reque... | cket)
if isinstance(support_ticket, li | st):
for comm in support_ticket:
self.del_keys(comm)
def del_keys(self, support_ticket):
frappe.errprint(type(support_ticket))
del support_ticket['name']
del support_ticket['creation']
del support_ticket['modified']
del support_ticket['company']
def tenent_based_ticket_creation(self, support_tick... |
lanking520/Digital_China | backup1.py | Python | mit | 22,145 | 0.011063 | import cookielib
import urllib2
import urllib
import jso | n
import time
#Default Settings for a system to keep cookies, please add it before testing
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_op | ener(opener)
# Let the single cookie system override the current openurl
#Cookies Info
def INITCOOKIES():
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
def COOKIE_TO_FILE(filename):
cookie = cookielib.MozillaCookieJar(filename)
... |
KunihikoKido/aws-lambda-es-suggest | lambda_function.py | Python | mit | 2,422 | 0 | # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import re
import json
import boto3
import logging
import pystache
import unicodedata
from elasticsearch import Elasticsearch
import settings
logger = logging.getLogger(__name__)
logger.setLevel(settings.LOG_LEVEL)
class Event(dict):
... | }
return pystache.render(settings.QUERY_TEMPLATE, context)
def lambda_handler(event, context):
event = Event(event)
client = Elasticsearch(eve | nt.host)
try:
response = client.search(
index=event.index, doc_type=event.doc_type, body=event.body)
except Exception as e:
logger.error(e)
return {'items': []}
logger.debug(response)
items = {'items': response['aggregations']['keywords']['buckets']}
logger.debu... |
jsirois/pex | docs/conf.py | Python | apache-2.0 | 8,585 | 0.000466 | # -*- coding: utf-8 -*-
#
# pex documentation build configuration file, created by
# sphinx-quickstart on Fri Jul 25 15:16:37 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All c... | red prefixes for module index sorting.
# modindex_common_pr | efix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
try:
import sphin... |
HongxuChen/dotfiles | Linux/_gdb/gdb_printer/libstdcxx/v6/printers.py | Python | mit | 40,117 | 0.004612 | # Pretty-printers for libstc++.
# Copyright (C) 2008-2014 Free Software Foundation, Inc.
# 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) ... | return 'empty __gnu_cxx::slist'
return '__gnu_cxx::slist'
class StdSlistIteratorPrinter:
"Print __gnu_cxx::slist::iterator"
def __init__(self, typename, val):
self.val = val
def to_string(self):
nodetype = find_type(self.val.type, '_Node')
nodetype = nodetype.strip_t... | )['_M_data']
class StdVectorPrinter:
"Print a std::vector"
class _iterator:
def __init__ (self, start, finish, bitvec):
self.bitvec = bitvec
if bitvec:
self.item = start['_M_p']
self.so = start['_M_offset']
self.finish = fin... |
hzlf/openbroadcast.org | website/tools/tagging_extra/widgets.py | Python | gpl-3.0 | 986 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.forms.widgets import TextInput
from django.template import loader
from django.utils.safestring import mark_safe
class TagAutocompleteWidget(TextInput):
# TODO: template_name supported from django 1.11
template_name = "tagging/forms/w... | ef render(self, name, value, attrs=None):
print(self.__dict__)
tpl = loader.get_template(self.template_name)
context = {
"ct": self.instance.get_ct() if self.instance else None,
"instance": self.instance,
"name": name,
"value": value,
"... | options,
}
return mark_safe(tpl.render(context))
|
jbedorf/tensorflow | tensorflow/python/compiler/tensorrt/test/lru_cache_test.py | Python | apache-2.0 | 2,912 | 0.004121 | # 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... |
name="conv")
bias = constant_op.constant(
np.random.randn(1, 10, 10, 1), dtype=dtypes.float32)
x = math_ops.add(x, bias)
x = nn.relu(x)
x = array_ops.identity(x, name="output")
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names... | input_name],
input_dims=input_dims,
output_names=[output_name],
expected_output_dims=expected_output_dims)
def ExpectedEnginesToBuild(self, run_params):
"""Return the expected engines to build."""
return ["TRTEngineOp_0"]
def ShouldRunTest(self, run_params):
return (run_params.... |
tommy-u/chaco | chaco/tools/tests/range_selection_test_case.py | Python | bsd-3-clause | 1,955 | 0 | import unittest
import numpy as np
from chaco.array_plot_data import ArrayPlotData
from chaco.plot import Plot
from chaco.tools.range_selection import RangeSelection
from enable.testing import EnableTestAssistant
class RangeSelectionTestCase(EnableTestAssistant, unittest.TestCase):
def test_selecting_mouse_lea... | rer.bounds[0] - 1
high_y = low_y + renderer.bounds[1] - 1
cx = 5
cy = 5
bounds = (
(low_x - | 1, low_y),
(high_x + 1, low_y),
(low_x, low_y - 1),
(low_x, high_y + 1),
)
for x, y in bounds:
self.mouse_down(tool, x=cx, y=cy)
self.mouse_leave(tool, x=x, y=y... |
UIKit0/friture | friture/delay_estimator.py | Python | gpl-3.0 | 13,695 | 0.00146 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009 Timoth?Lecomte
# This file is part of Friture.
#
# Friture is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# Friture is distribu... | er to get a normalized cross-correlation at the end)
d0 -= d0.mean()
d1 -= d1.mean()
# Hann window to mitigat | e non-periodicity effects
window = numpy.hanning(len(d0))
# compute the cross-correlation
D0 = rfft(d0 * window)
D1 = rfft(d1 * window)
D0r = D0.conjugate()
G = D0r * D1
# G = (G==0.)*1e-30 + (G<>0.)*G
# W = 1. # frequency unweighted
# W = 1./numpy.abs(G) # "PHAT"
absG = numpy.a... |
allenai/document-qa | docqa/trainer.py | Python | apache-2.0 | 27,581 | 0.002574 | import os
import pickle
import shutil
import time
from datetime import datetime
from os.path import exists, join, relpath
from threading import Thread
from typing import List, Union, Optional, Dict, Tuple
import numpy as np
import tensorflow as tf
from tensorflow.python.training.adadelta import AdadeltaOptimizer
from ... | tf.get_collection(tf.GraphKeys.SUMMARIES)])
else:
summary_tensor = tf.summary.tensor_summary("loss", loss)
train_objective = loss
regularizers = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
if len(regularizers) > 0:
regularization_loss = tf.add_n(regularizers, name="regula... |
if train_params.regularization_weight is not None:
train_objective = train_objective + regularization_loss * train_params.regularization_weight
else:
train_objective = train_objective + regularization_loss
else:
regularization_loss = None
opt = train_params.opt.... |
ravenac95/virtstrap | virtstrap-core/virtstrap/log.py | Python | mit | 6,365 | 0.000943 | """
virtstrap.log
-------------
Provides a central logging facility. It is used to record log info
and report both to a log file and stdout
"""
import sys
import logging
import traceback
CLINT_AVAILABLE = True
try:
from clint.textui import puts, colored
except:
# Clint is still not stable enough yet to just i... | # Do nothing
logging_level = level
else:
raise TypeError('Invalid logging level. Must be string or int %s'
% str(level))
return logging_level
class VirtstrapLogger(object):
"""Custom logger for use with virtstrap
It'll allow the logger to store logged data before a lo... | r
def add_handler(self, handler):
self._handlers.append(handler)
log_lines = self._log_lines
for level, message in log_lines:
self.log(level, message, new_line=False)
self._log_lines = []
def debug(self, message, **kwargs):
self.log('debug', message, **kwarg... |
creemerica/wetransfer-upload | wetransfer/__init__.py | Python | mit | 27 | 0.037037 | from main im | port WeTransfe | r |
FreakJoe/cryptolockpy | cryptolock/exceptions.py | Python | mit | 1,180 | 0.008475 | """Defines exceptions specific to this project"""
class CryptoBaseException(Exception):
"""Base exception to be inherited by other exceptions"""
def __init__(self, value):
"""Set the exception's message and cause"""
self.value = value
def __str__(self):
"""Return a string represe... | ed when an invalid key is supplied for encryption or decryption"""
pass
class CryptoInvalidMessageException(Exception):
"""Exception raised when an invalid message is supplied for decryption"""
pass
class CryptoFalseKeyException(Exception):
" | ""Exception raised when a false key is supplied for decryption"""
pass
class BinaryFileException(Exception):
"""Exception raised when a false key is supplied for decryption"""
pass
class InvalidFileException(Exception):
"""Exception raised when an invalid file is supplied for adding or reading"""
... |
Rogentos/rogentos-anaconda | installclasses/lxde.py | Python | gpl-2.0 | 2,674 | 0.005236 | #
# xfce.py
#
# Copyright (C) 2010 Fabio Erculiani
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is... | od.startswith(productName):
return True
return False
def versionMatches(self, oldver):
try:
oldVer = float(oldver)
newVer = float(productVersion)
except ValueError:
return True
return n | ewVer >= oldVer
def __init__(self):
BaseInstallClass.__init__(self)
|
Hasimir/brython | www/src/Lib/encodings/cp1251.py | Python | bsd-3-clause | 13,668 | 0.020778 | """ Python Character Mapping Codec cp1251 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1251.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def d... | MARK
'\u2026' # 0x85 -> HORIZONTAL ELLIPSIS
'\u2020' # 0x86 -> DAGGER
'\u2021' # 0x87 -> DOUBLE DAGGER
'\u20ac' # 0x88 -> EURO SIGN
'\u2030' # 0x89 -> PER MILLE SIGN
'\u0409' # 0x8A -> CYRILLIC CAPITAL LETTER LJE
'\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOT... | LLIC CAPITAL LETTER KJE
'\u040b' # 0x8E -> CYRILLIC CAPITAL LETTER TSHE
'\u040f' # 0x8F -> CYRILLIC CAPITAL LETTER DZHE
'\u0452' # 0x90 -> CYRILLIC SMALL LETTER DJE
'\u2018' # 0x91 -> LEFT SINGLE QUOTATION MARK
'\u2019' # 0x92 -> RIGHT SINGLE QUOTATION MARK
'\u201c' # 0x9... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.