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 |
|---|---|---|---|---|---|---|---|---|
cyanobacterium/Cyanos-Planet-Factory | deploy.py | Python | gpl-3.0 | 7,423 | 0.034353 | #!/usr/bin/python3
import sys, os, shutil
from os import path
from urllib.request import pathname2url
import subprocess
from subprocess import call
import sys
import re
import zipfile
import config
os.chdir(config.root_dir)
SUPPORTED_OPERATING_SYSTEMS = ('windows_x64', 'linux_x64', 'mac')#, 'linux-arm32', 'linux-ar... | en(path.join(imag | e_dir, 'launch_%s.sh' % config.module_title),'w') as fout:
fout.write('#!/bin/sh\ncd "`dirname "$0"`"\n./bin/launch\n')
# package images
named_dir = path.join(config.deploy_image_dir, release_OS, config.module_title)
zip_file = path.join(config.deploy_image_dir, '%s_%s.zip' % (config.module_title, release_OS))... |
kirillmorozov/youbot_control | scripts/client_gui.py | Python | bsd-2-clause | 32,532 | 0.000486 | #!/usr/bin/python2
# -*- coding: utf-8 -*-
"""Client GUI to control youBot robot."""
import Tkinter as tk
import ttk
import tkMessageBox
import rospyoubot
from math import radians, degrees
class MainApplication(ttk.Frame):
u"""Основное окно приложения."""
def __init__(self, parent, *args, **kwargs):
... | JointControl(self, 1)
self.a1_joint.grid(row=0, columnspan=2, sticky='nswe')
self.a2_joint = | JointControl(self, 2)
self.a2_joint.grid(row=1, columnspan=2, sticky='nswe')
self.a3_joint = JointControl(self, 3)
self.a3_joint.grid(row=2, columnspan=2, sticky='nswe')
self.a4_joint = JointControl(self, 4)
self.a4_joint.grid(row=3, columnspan=2, sticky='nswe')
self.a5_j... |
tdryer/netscramble | netscramble/easing.py | Python | bsd-3-clause | 1,458 | 0.004115 | """Animation easing functions using cubic bezier curves."""
def _cubic_bezier_parametric(t, p0, p1, p2, p3):
"""Return (x, y) on cubic bezier curve for t in [0, 1]."""
return tuple([
pow(1 - t, 3) * p0[i] +
3 * pow(1 - t, 2) * t * p1[i] +
3 * (1 - t) * pow(t, 2) * p2[i] +
pow(t,... | rn r_y
elif difference < 0:
return _cubic_bez | ier(x, p0, p1, p2, p3, start=midpoint, end=end)
else:
return _cubic_bezier(x, p0, p1, p2, p3, start=start, end=midpoint)
def cubic_bezier(x, x1, y1, x2, y2):
"""Return y for given x on cubic bezier curve with given control points.
This is similar to the CSS3 cubic-bezier function. The curve alway... |
Phrozyn/MozDef | tests/alerts/test_nsm_scan_address.py | Python | mpl-2.0 | 4,726 | 0.00127 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Copyright (c) 2017 Mozilla Corporation
from positive_alert_test_case import PositiveAlertTestCase
from negative_alert_... |
"severity": "NOTICE",
"tags": ['nsm', 'bro', 'addressscan'],
"summary": "Addr | ess scan from 10.99.88.77 (mock.mozilla.org)",
'notify_mozdefbot': False
}
test_cases = []
test_cases.append(
PositiveAlertTestCase(
description="Positive test with default event and default alert expected",
events=AlertTestSuite.create_events(default_event, 5),
... |
dongguangming/python-phonenumbers | python/phonenumbers/pb2/__init__.py | Python | apache-2.0 | 2,788 | 0.004304 | """Translate python-phonenumbers PhoneNumber to/from protobuf PhoneNumber
Examples of use:
>>> import phonenumbers
>>> from phonenumbers.pb2 import phonenumber_pb2, PBToPy, PyToPB
>>> x_py = phonenumbers.PhoneNumber(country_code=44, national_number=7912345678)
>>> print x_py
Country Code: 44 National Number: 79123456... | ro
False
>>> y_py = PBToPy(y_pb)
>>> print y_py
Country Code: 44 National Number: 7912345678
>>> x_pb = PyToPB(x_py)
>>> print str(x_pb).strip()
country_code: 44
national_number: 7912345678
>>> x_py == y_py
True
>>> x_pb == y_pb
True
>>> # Explicitly set the field to its default
>>> y_pb.italian_leading_zero = y_pb.ita... | Py(numpb):
"""Convert phonenumber_pb2.PhoneNumber to phonenumber.PhoneNumber"""
return PhoneNumber(numpb.country_code if numpb.HasField("country_code") else None,
numpb.national_number if numpb.HasField("national_number") else None,
numpb.extension if numpb.HasField... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractAhgashonixnoveltranslationWordpressCom.py | Python | bsd-3-clause | 592 | 0.032095 |
def extractAhgashonixnoveltranslationWordpressCom(item):
'''
Parser for 'ahgashonixnoveltranslation.wordpres | s.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, na | me, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
manthey/girder | girder/cli/__init__.py | Python | apache-2.0 | 358 | 0 | from click_plugins imp | ort with_plugins
from pkg_resources import iter_entry_points
import click
@with_plugins(iter_entry_points('girder.cli_plugins'))
@click.group(help='Girder: data management platform for the web.',
context_settings=dict(help_option_names=['-h', | '--help']))
@click.version_option(message='%(version)s')
def main():
pass
|
cuckoobox/cuckoo | cuckoo/data/analyzer/android/modules/packages/apk.py | Python | mit | 851 | 0.001175 | # Copyright (C) 2014-2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox | - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
# Originally contributed by Check Point Software Technologies, Ltd.
import logging
from lib.api.adb import dump_droidmon_logs, execute_sample, install_sample
from lib.common.abstrac | ts import Package
log = logging.getLogger(__name__)
class Apk(Package):
"""Apk analysis package."""
def __init__(self, options={}):
super(Apk, self).__init__(options)
self.package, self.activity = options.get("apk_entry", ":").split(":")
def start(self, path):
install_sample(path... |
Mangara/ArboralExplorer | lib/Cmpl/pyCmpl/lib/pyCmpl/CmplInstance.py | Python | apache-2.0 | 7,151 | 0.05286 | #***********************************************************************
# This code is part of pyCMPL
#
# Copyright (C) 2013
# Mike Steglich - Technical University of Applied Sciences
# Wildau, Germany
#
# pyCMPL is a project of the Technical University of
# Applied Sciences Wildau and the Institute f... | d + "\" type=\"cmplData\">\n")
#self.__instStr.write(b64encode(self.__cmplDataList[d]))
self.__instStr.write(escape(self.__cmplDataList[d]))
self.__instStr.write("\n")
self.__instStr.write("</file>\n")
self.__instStr.write("</problemFiles>\n")
self.__instStr.write("</CmplInstance>\n")
... | tanceStr ******
#*********** writeCmplInstance **********
def writeCmplInstance(self, folder, instStr):
if os.path.exists(folder) == False:
raise CmplException("Path <"+self.__cmplServerPath+"> doesn't exist.")
instDom = dom.parseString(instStr)
if instDom.firstChild.nodeName!="CmplInstance":
... |
chrisbay/library.kdhx.org | library/jinja2.py | Python | gpl-3.0 | 1,663 | 0.004811 | from django.contrib.staticfiles.storage import staticfiles_storage
from django.contrib.contenttypes.models import ContentType
from django.core.urlreso | lvers import reverse
from jinja2 import Environment
from albums.models import Album, Artist, RecordLabel
def get_spotify_search_url(term):
return 'https://open.spotify.com/search/results/'+term
def get_entity_url(watson_obj):
content_type = ContentType.objects.get(app_label=watson_obj.content_type.app_label,... | ntent_type.model)
obj_class = content_type.model_class()
url = ''
if obj_class == Album:
url = reverse('albums:album-detail', args=[watson_obj.object_id_int])
elif obj_class == Artist:
url = reverse('albums:albums-by-artist', args=[watson_obj.object_id_int])
elif obj_class == RecordL... |
evernym/zeno | plenum/test/req_drop/test_req_drop_on_prepare_phase_primary.py | Python | apache-2.0 | 3,979 | 0.001257 | import pytest
from plenum.test.helper import sdk_send_random_requests
from stp_core.loop.eventually import eventually
from plenum.common.messages.node_messages import Prepare, Commit
from plenum.test.delayers import delay
from plenum.test.propagate.helper import recvdRequest, recvdPropagate, \
sentPropagate, recvd... | def check_prepares_and_commits_received():
# Node should have received all delayed Prepares and Commits for master instance
assert len(recvdPrepareForInstId(lagged_node, 0)) == 3
assert len(recvdCommitForInstId(lagged_node, 0)) == 3
timeout = howlong * 2
looper | .run(eventually(check_prepares_and_commits_received, retryWait=.5, timeout=timeout))
def check_ledger_size():
# The request should be eventually ordered
for n in txnPoolNodeSet:
assert n.domainLedger.size - initial_ledger_size == 1
looper.run(eventually(check_ledger_size, retryWait... |
wxgeo/geophar | wxgeometrie/param/modules.py | Python | gpl-2.0 | 3,148 | 0.00446 | # -*- coding: utf-8 -*-
######################################
#
# Détection des modules
#
######################################
#
# WxGeometrie
# Dynamic geometry, graph plotter, and more for french mathematic teachers.
# Copyright (C) 2005-2013 Nicolas Pourcelot
#
# This program is free software; yo... | es modules (répertoire '%s') !" % _modules_dir)
modules = []
descriptions_modules = {}
modules_actifs = dict.fromkeys(modules, False)
for nom in modules_par_defaut:
| modules_actifs[nom] = True
def _key(nom):
# les modules activés par défaut apparaissent en premier,
# les autres sont classés par ordre alphabétique.
key = [1000000, nom]
if nom in modules_par_defaut:
key[0] = modules_par_defaut.index(nom)
return key
modules.sort(key = _key)
|
setokinto/slack-shogi | app/kifu.py | Python | mit | 255 | 0.011765 |
class | Kifu:
def __init__(self):
self.kifu = []
def add(self, from_x, from_y, to_x, to_y, promote, koma):
self.kifu.append((from_x, from_y, to_x, to_y, promote, koma))
def pop(self):
return self.kifu.p | op()
|
RodericDay/MiniPNM | unit_tests/test_graphics.py | Python | mit | 974 | 0.016427 | import numpy as np
import minipnm as mini |
def test_scene(N=10):
try:
import vtk
except ImportEr | ror:
return
scene = mini.Scene()
network = mini.Cubic([10,10])
# draw a simple wired cubic going from red to white to blue
script = [network.diagonals.data[0]*i for i in range(N)]
wires = mini.graphics.Wires(network.points, network.pairs, script)
scene.add_actors([wires])
# draw some... |
PythonProgramming/Support-Vector-Machines---Basics-and-Fundamental-Investing-Project | p10.py | Python | mit | 4,949 | 0.018792 | import pandas as pd
import os
import time
from datetime import datetime
import re
from time import mktime
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import style
style.use("dark_background")
# path = "X:/Backups/intraQuarter" # for Windows with X files :)
# if git clone'ed then use relative path... | tio':value,
'Price':stock_price,
'stock_p_change':stock_p_change,
'SP500':sp500_value,
'sp500_p_change':sp500_p_change,
| ############################
'Difference':difference,
'Status':status},
ignore_index=True)
except Exception as e:
pass
#print(ticker,e,file, value)
#print(ticker_list)
#print(df)
for each_... |
miguelinux/vbox | src/VBox/ValidationKit/testmanager/webui/wuihlpgraph.py | Python | gpl-2.0 | 4,309 | 0.01787 | # -*- coding: utf-8 -*-
# $Id: wuihlpgraph.py $
"""
Test Manager Web-UI - Graph Helpers.
"""
__copyright__ = \
"""
Copyright (C) 2012-2015 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and... | as GraphImplementation;
else:
try:
import matplotlib; # pylint: disable=W0611,F0401,import-error,wrong-import-order
from testmanager.webui import wuihlpgraphmatplotlib as GraphImplementation;
except:
from testmanager.webui import wuihlpgraphsimple as | GraphImplementation;
# pylint: disable=C0103
WuiHlpBarGraph = GraphImplementation.WuiHlpBarGraph;
WuiHlpLineGraph = GraphImplementation.WuiHlpLineGraph;
WuiHlpLineGraphErrorbarY = GraphImplementation.WuiHlpLineGraphErrorbarY;
|
a-rank/cassandra-tools | tests/test_cli.py | Python | apache-2.0 | 720 | 0 | import | pytest
from click.testing import CliRunner
from cassandra_tools import cli
@pytest.fixture
def runner():
return CliRunner()
def test_cli(runner):
result = runner.invoke(cli.main)
assert result.exit_code == 0
assert not result.exception
assert result.output.strip() == 'Hello, world.'
def test_... | , world.'
def test_cli_with_arg(runner):
result = runner.invoke(cli.main, ['Allan'])
assert result.exit_code == 0
assert not result.exception
assert result.output.strip() == 'Hello, Allan.'
|
carolFrohlich/nipype | nipype/interfaces/dipy/simulate.py | Python | bsd-3-clause | 12,156 | 0.000082 | # -*- coding: utf-8 -*-
"""Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
>>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data'))
>>> os.chdir(datadir)
"""
from __future__ import print_function, divisi... | ndom.randn(nvox, 3)
w = np.linalg.norm(fd, axis=1)
fd[w < np.finfo(float).eps, ...] = np.array([1., 0., 0.])
w[w < np.finfo(float).eps] = 1.0
fd /= w[..., np.newaxis]
dirs = np.hstack((dirs, fd))
sf_eval | s = list(self.inputs.diff_sf)
ba_evals = list(self.inputs.diff_iso)
mevals = [sf_evals] * nsticks + \
[[ba_evals[d]] * 3 for d in range(nballs)]
b0 = b0_im.get_data()[msk > 0]
args = []
for i in range(nvox):
args.append(
{'fractions': fr |
erudit/zenon | eruditorg/core/editor/migrations/0006_auto_20161028_1032.py | Python | gpl-3.0 | 620 | 0.001613 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-10-28 15:32
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('editor', '0005_auto_2016092... | migrations.AlterField(
model_name='issuesubmission',
name='contact',
| field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='Personne-ressource'),
),
]
|
fxia22/ASM_xf | PythonD/bin/python/drv_xmlproc.py | Python | gpl-2.0 | 11,377 | 0.022062 | """
A SAX driver for xmlproc
$Id: drv_xmlproc.py,v 1.9 1999/10/15 07:55:33 larsga Exp $
"""
version="0.95"
from xml.sax import saxlib,saxutils,saxmisc
from xml.parsers.xmlproc import xmlproc
import os
pre_parse_properties={"http://xml.org/sax/properties/namespace-sep":1,
"http:/... | l.org/sax/features/external-parameter-entities" or \
featureId=="http://xml.org/sax/ | features/namespaces" or \
featureId=="http://xml.org/sax/features/normalize-text":
raise saxlib.SAXNotSupportedException("Feature %s not supported" %
featureId)
else:
raise saxlib.SAXNotRecognizedException("Feature %s not ... |
openego/data_processing | dataprocessing/python_scripts/ego_dp_loadarea_peakload.py | Python | agpl-3.0 | 10,383 | 0.003275 | """
Calculates peak load per load area
"""
__copyright__ = "Reiner Lemoine Institut, Flensburg University of Applied Sciences, Centre for Sustainable Energy Systems"
__license__ = "GNU Affero General Public License Version 3 (AGPL-3.0)"
__url__ = "https://github.com/openego/data_processing/blob/master/LICENSE"
__a... | ofile_factors=
{'week': {'day': 0.8, 'night': 0.6},
'weekend': {'day': 0.6, 'night': 0.6}})
# Resample 15-minute values to hourly values and sum across sectors
elec_demand = elec_demand.resample('H').mean().fillna(0).max().to_frame().T#.max(axis=0)#.to_frame().unstack()#.\
... | 'id', inplace=True)
# rename columns
elec_demand.rename(columns=names_dc2, inplace=True)
# Add data to orm object
peak_load = orm_peak_load(
id=it,
retail=float(elec_demand['retail']),
residential=float(elec_demand['residential']),
indust... |
Taka-Coma/graphEmbedding_impls | TransH/train.py | Python | gpl-3.0 | 1,186 | 0.043845 | # -*- coding: utf-8 -*-
from transH import TransH
import pickle
import numpy as np
import sys
def main():
if len(sys.argv) != 3:
print '[Usage] python train.py train_data validation_data'
exit(0)
train_data, valid_data = sys.argv[1:]
X, E, R = loadData(train_data)
V = loadData(valid_data, E=E, R=R, mode='va... | sH.fit(X, validationset=V)
w = open('transH.model', 'w')
pickle.dump((transH, E, R), w)
def loadData(file_path, E=None, R=None, mode='train'):
if mode == 'train':
E, R = {}, {}
e_ind, r_ind = 0, 0
X = []
f | = open(file_path, 'r')
for line in f:
h, r, t = line.strip().split('\t')
if not h in E:
E[h] = e_ind
e_ind += 1
if not t in E:
E[t] = e_ind
e_ind +=1
if not r in R:
R[r] = r_ind
r_ind += 1
X.append((E[h], R[r], E[t]))
f.close()
return np.array(X), E, R
elif mode == 'valid... |
respawner/peering-manager | peering/migrations/0020_auto_20181105_0850.py | Python | apache-2.0 | 619 | 0 | # Generated by Django 2.1.3 on 2018-11-05 07:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("peering", "0019_router_netbo | x_device_id")]
operations = [
migrations.AddField(
model_name="directpeeringsession | ",
name="last_established_state",
field=models.DateTimeField(blank=True, null=True),
),
migrations.AddField(
model_name="internetexchangepeeringsession",
name="last_established_state",
field=models.DateTimeField(blank=True, null=True),
... |
DedMemez/ODS-August-2017 | minigame/MazeBase.py | Python | apache-2.0 | 5,752 | 0.003825 | # Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.minigame.MazeBase
from panda3d.core import VBase3
from direct.showbase.RandomNumGen import RandomNumGen
class MazeBase:
def __init__(self, model, mazeData, cellWidth, parent = None):
if parent is None:
parent = render
... | ALL_OFFSET_X = WALL_OFFSET
if offsetX < 0:
WALL_OFFSET_X = -WALL_OFFSET_X
WALL_OFFSET_Y = WALL_OFFSET
if offsetY < 0:
WALL_OFFSET_Y = -WALL_OFFSET_Y
newX = curX + offsetX + WALL_OFFSET_X
| newY = curY
newTX, newTY = self.world2tile(newX, newY)
if newTX != curTX:
if self.collisionTable[newTY][newTX] == 1:
offset.setX(calcFlushCoord(curTX, newTX, self.originTX) - curX)
newX = curX
newY = curY + offsetY + WALL_OFFSET_Y
newTX,... |
LoaDy588/py_battleship_sim | examples.py | Python | mit | 1,044 | 0 | from core import display, field_utils, player
from core import hunt_ai, probabilistic_ai
import time
def game_example():
"""
Simple simulation of Probabilistic AI playing against a dummy.
Displays the game field of dummy.
"""
# create players
dummy = player.Player()
ai = probabilistic_ai.... | ainst a dummy.
Displays the g | ame field of dummy.
"""
# create dummy
dummy = player.Player()
# create cheat_list for Hunt AI, create AI
cheat_list = field_utils.generate_cheat_list(dummy.get_field(), 3)
ai = hunt_ai.Hunt_AI(cheat=True, cheat_input=cheat_list)
# game loop
while not dummy.has_lost():
ai.turn(... |
lxc/pylxd | pylxd/models/operation.py | Python | apache-2.0 | 3,440 | 0 | # Copyright (c) 2016 Canonical Ltd
#
# 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 ... | "metadata",
"resources",
"status",
"status_code",
"updated_at",
]
@classmethod
def wait_for_operation(cls, client, operation_id):
"""Get an operation and wait for it to complete."""
operation = cls.get(client, operation_id)
operation.wait()
... | ef get(cls, client, operation_id):
"""Get an operation."""
operation_id = cls.extract_operation_id(operation_id)
response = client.api.operations[operation_id].get()
return cls(_client=client, **response.json()["metadata"])
def __init__(self, **kwargs):
super().__init__()
... |
allmightyspiff/softlayer-python | SoftLayer/CLI/block/replication/disaster_recovery_failover.py | Python | mit | 1,954 | 0.005118 | """Failover an inaccessible block volume to its available replicant volume."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
from SoftLayer.CLI import formatting
@click.command(epilog="""Failover an inaccessible... | an inacc | essible block volume to its available replicant volume."""
"""If a volume (with replication) becomes inaccessible due to a disaster event,"""
"""this method can be used to immediately failover to an available replica in another location."""
"""This method does not allow f... |
terotic/digihel | digi/migrations/0008_auto_20160909_1909.py | Python | mit | 3,342 | 0.005087 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-09 16:09
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
('wagtaildocs', '0007_merge'),
... | name='ID')),
('sort_order', models.IntegerField(blank=True, editable=False, null=True)),
('link_external', models.URLField(blank=True, verbose_name='External link')),
(' | title', models.CharField(help_text='Link title', max_length=255)),
('link_document', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='wagtaildocs.Document')),
('link_page', models.ForeignKey(blank=True, null=True, on_delete=djang... |
CheckiO-Missions/checkio-task-fizz-buzz | verification/referee.py | Python | gpl-2.0 | 2,378 | 0.005046 | """
CheckiOReferee is a base referee for checking you code.
arguments:
tests -- the dict contains t | ests in the specific structure.
You can find an | example in tests.py.
cover_code -- is a wrapper for the user function and additional operations before give data
in the user function. You can use some predefined codes from checkio.referee.cover_codes
checker -- is replacement for the default checking of an user function result. If given, ... |
ScottWales/rose | lib/python/rose/suite_engine_procs/cylc.py | Python | gpl-3.0 | 54,627 | 0.000092 | # -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# (C) British Crown Copyright 2012-5 Met Office.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose is free software: you can redistribute it and/or modify
# it under the terms of the GNU G... | cle DESC, task_events.submit_num DESC",
"name_desc_cycle_desc":
"name DESC, cycle DESC, task_events.submit_num DESC"}
PGREP_CYLC_RUN = r"python.*cylc-(run|restart)( | .+ )%s( |$)"
REASON_KEY_PROC = "process"
REASON_KEY_F | ILE = "port-file"
REC_CYCLE_TIME = re.compile(
r"\A[\+\-]?\d+(?:W\d+)?(?:T\d+(?:Z|[+-]\d+)?)?\Z") # Good enough?
REC_SEQ_LOG = re.compile(r"\A(.*\.)(\d+)(\.html)?\Z")
REC_SIGNALLED = re.compile(r"Task\sjob\sscript\sreceived\ssignal\s(\S+)")
SCHEME = "cylc"
STATUSES = {"active": ["ready", "q... |
DayGitH/Python-Challenges | DailyProgrammer/DP20130510C.py | Python | mit | 7,377 | 0.007049 | """
[05/10/13] Challenge #123 [Hard] Robot Jousting
https://www.reddit.com/r/dailyprogrammer/comments/1ej32w/051013_challenge_123_hard_robot_jousting/
# [](#HardIcon) *(Hard)*: Robot Jousting
You are an expert in the new and exciting field of *Robot Jousting*! Yes, you read that right: robots that charge one
another ... | -8 3 8 -3 -1 -10 10 -9 -10 3 -1 1 -1 5
-7 -8 -5 -10 1 7 -3 -6 5 5 2 6 3 -8 9 1 -5 8 5 1 4 -8 7 1 3 -5 10 -9 -2 4 -5 -7 8 8 -8 -7 9 1 6 6 3 4 5 6 -3 -7 2 -2 7
-1 2 2 2 5 10 0 9 6 10 -4 9 7 -10 -9 -6 0 -1 9 -3 -9 -7 0 8 -5 -7 -10 10 4 4 7 3 -5 3 7 6 3 -1 9 -5 4 -9 -8 - | 2 7 10 -1
-10 -10 -3 4 -7 5 -5 -3 9 7 -3 10 -8 -9 3 9 3 10 -10 -8 6 0 0 8 1 -7 -8 -6 7 8 -1 -4 0 -1 1 -4 4 9 0 1 -6 -5 2 5 -1 2 7
-8 5 -7 7 -7 9 -8 -10 -4 10 6 -1 -4 -5 0 -2 -3 1 -1 -3 4 -4 -6 4 5 7 5 -6 -6 4 -10 -3 -4 -4 -2 6 0 1 2 1 -7
# Challenge Note
Like any challenge of this complexity class, you are somewhat con... |
girving/tensorflow | tensorflow/python/keras/optimizer_v2/adagrad.py | Python | apache-2.0 | 4,793 | 0.003547 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | dtype,
"accumulator")
def _apply_dense(self, grad, var, state):
acc = state.get_slot(var, "accumulator")
return training_ops.apply_adagrad(
var,
acc,
state.get_hyper("learning_rate", var.dtyp | e.base_dtype),
grad,
use_locking=self._use_locking)
def _resource_apply_dense(self, grad, var, state):
acc = state.get_slot(var, "accumulator")
return training_ops.resource_apply_adagrad(
var.handle,
acc.handle,
state.get_hyper("learning_rate", var.dtype.base_dtype),
... |
ucb-sejits/ctree | ctree/tools/runner.py | Python | bsd-2-clause | 5,410 | 0.002588 | """
create specializer projects
basically copies all files and directories from a template.
"""
from __future__ import print_function
import sys
import argparse
import collections
import shutil
import os
import ctree
from ctree.tools.generators.builder import Builder
if sys.version_info >= (3, 0, 0): # python 3
... | arser
__author__ = 'chick'
def main(*args):
"""run ctree utility stuff, currently only the project generator"""
if sys.argv:
args = sys.argv[1:]
parser = argparse.ArgumentParser(prog="ctree", description="ctree is a python SEJITS framework")
parser. | add_argument('-sp', '--startproject', help='generate a specializer project')
parser.add_argument(
'-wu', '--wattsupmeter', help="start interactive watts up meter shell", action="store_true"
)
parser.add_argument('-p', '--port', help="/dev name to use for wattsup meter port")
parser.add_argument(... |
agry/NGECore2 | scripts/loot/lootPools/talus/re_junk_aakuan_follower.py | Python | lgpl-3.0 | 92 | 0.086957 |
d | ef itemNames():
return ['motor','software_module']
def itemChances():
return [50,50 | ] |
linglung/ytdl | youtube_dl/extractor/kamcord.py | Python | unlicense | 2,262 | 0.001326 | from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
int_or_none,
qualities,
)
class KamcordIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?kamcord\.com/v/(?P<id>[^/?#&]+)'
_TEST = {
'url': 'https://www.kamcord.co... | il_url,
'id': thumbnail_id,
'preference': preference_key(thumbnail_id),
} for thumbnail_id, thumbnail_url in (video.get('thumbnail') or {}).items()
if isinstance(thumbnail_id, compat_str) and isinstance(thumbnail_url, compat_str)]
return {
'id': video_id,... | 'uploader': uploader,
'uploader_id': uploader_id,
'view_count': view_count,
'like_count': like_count,
'comment_count': comment_count,
'thumbnails': thumbnails,
'formats': formats,
}
|
AMLab-Amsterdam/lie_learn | lie_learn/representations/SO3/spherical_harmonics.py | Python | mit | 13,535 | 0.005098 |
import numpy as np
from scipy.special import sph_harm, lpmv
try:
from scipy.misc import factorial
except:
from scipy.special import factorial
def sh(l, m, theta, phi, field='real', normalization='quantum', condon_shortley=True):
if field == 'real':
return rsh(l, m, theta, phi, normalization, condo... | r; the degree of the CSH.
:param m: integer, -l <= m <= l; the order of the CSH.
:param theta: the colatitude / polar angle,
ranging from 0 (North Pole, (X,Y,Z)=(0,0,1)) to pi (South Pole, (X,Y,Z)=(0,0,-1)).
:param phi: the longitude / azimuthal angle, ranging from 0 to 2 pi.
:param normalization: h... | basis
from CSH to RSH is unitary, the orthogonality and normalization properties are unchanged.
:return: the value of the real spherical harmonic S^l_m(theta, phi)
"""
l, m, theta, phi = np.broadcast_arrays(l, m, theta, phi)
# Get the CSH for m and -m, using Condon-Shortley phase (regardless of whh... |
PyCQA/pylint | tests/functional/ext/typing/typing_consider_using_alias_without_future.py | Python | gpl-2.0 | 2,165 | 0.004157 | """Test pylint.extension.typing - consider-using-alias
'py-version' needs to be set to '3.7' or '3.8' and 'runtime-typing=no'.
"""
# pylint: disable=missing-docstring,invalid-name,unused-arg | ument,line-too-long,unsubscriptable-object
import collections
import collections.abc
import typing
from collections.abc import Awaitable
from dataclasses import dataclass
from typing import Dict, List, Set, Union, TypedDict, Callable, Tuple, Type
var1: typing.Dict[str, int] # [consider-using-alias]
var2: List[int] #... | sider-using-alias]
var3: collections.abc.Iterable[int]
var4: typing.OrderedDict[str, int] # [consider-using-alias]
var5: typing.Awaitable[None] # [consider-using-alias]
var6: typing.Iterable[int] # [consider-using-alias]
var7: typing.Hashable # [consider-using-alias]
var8: typing.ContextManager[str] # [consider-us... |
EMSTrack/WebServerAndClient | login/models.py | Python | bsd-3-clause | 17,047 | 0.002053 | import logging
from enum import Enum
from django.contrib.auth.models import Group
from django.contrib.auth.models import User
from django.contrib.gis.db import models
from django.core.exceptions import PermissionDenied
from django.core.validators import MinValueValidator
from django.template.defaulttags import registe... | ,
verbose_name=_('group'))
hospital = models.ForeignKey('hospital.Hospital',
on_delete=models.CASCADE,
verbose_name=_('hospital'))
class Meta:
un | ique_together = ('group', 'hospital')
def __str__(self):
return '{}/{}(id={}): read[{}] write[{}]'.format(self.group,
self.hospital.name,
self.hospital.id,
... |
heiths/allura | Allura/allura/tests/unit/test_mixins.py | Python | apache-2.0 | 3,087 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (t... | sers == [self.user1.username,
self.user2.username]
vote.vote_down(self.user1) # unvote user1
assert vote.votes_down == 1
assert vote.votes_down_users == [self.use | r2.username]
assert vote.votes_up == 0, 'vote_up must be 0 if we voted down only'
assert len(vote.votes_up_users) == 0
def test_change_vote(self):
vote = VotableArtifact()
vote.vote_up(self.user1)
vote.vote_down(self.user1)
assert vote.votes_down == 1
asse... |
zhangpf/vbox | src/VBox/ValidationKit/tests/installation/tdGuestOsInstTest1.py | Python | gpl-2.0 | 20,047 | 0.012471 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id$
"""
VirtualBox Validation Kit - Guest OS installation tests.
"""
__copyright__ = \
"""
Copyright (C) 2010-2014 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
yo... | for win2k VMs.
kasIdeIrqDelay = [ 'VBoxInternal/Devices/piix3ide/0/Config/IRQDelay:1', ];
## Install ISO path relative to the testrsrc root.
ksIsoPathBase = os.path.join('4.2', 'isos');
def __init__(self, oSet, sVmName, sKind, sInstallIso, sHdCtrlNm, cGbHdd, fFlags):
vboxtestvms.TestVm._... | self.ksIsoPathBase, sInstallIso);
self.cGbHdd = cGbHdd;
self.fInstVmFlags = fFlags;
if fFlags & self.kfReqPae:
self.fPae = True;
if fFlags & (self.kfReqIoApic | self.kfReqIoApicSmp):
self.fIoApic = True;
# Tweaks
self.iOptRamAdjust = 0... |
assafnativ/NativDebugging | src/Win32/MemReaderBaseWin.py | Python | gpl-3.0 | 16,875 | 0.006815 | #
# MemoryReaderBaseWin.py
#
# MemoryReader - Remote process memory inspection python module
# https://github.com/assafnativ/NativDebugging.git
# Nativ.Assaf@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 publi... | rst_section + (sections_iter * win32con.IMAGE_SIZEOF_SECTION_HEADER) + win32con.PE_SECTION_VOFFSET_OFFSET )
section_size = self.readUInt32( \
pe + first_section + (sections_iter * win32con.IMAGE_SIZEOF_SECTION_HEADER) + win32con.PE_SECTION_SIZE_OF_RAW_DATA_OFFSET )
result.... | ize))
return result
def findSection( self, module_base, target_section, isVerbose=False ):
target_section = target_section.lower()
for section in self.getAllSections( module_base, isVerbose ):
if section[0].lower() == target_section:
return section
... |
omkartest123/django-causecode | causecode/causecode/project/migrations/0003_remove_product_code.py | Python | gpl-3.0 | 392 | 0 | # -*- codin | g: utf-8 -*-
# Generated by Django 1.9.12 on 2017-08-14 10:52
from __future__ impor | t unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('project', '0002_auto_20170814_1039'),
]
operations = [
migrations.RemoveField(
model_name='product',
name='code',
),
]
|
sonali0901/zulip | zerver/migrations/0030_realm_org_type.py | Python | apache-2.0 | 409 | 0 | # - | *- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migrat | ion):
dependencies = [
('zerver', '0029_realm_subdomain'),
]
operations = [
migrations.AddField(
model_name='realm',
name='org_type',
field=models.PositiveSmallIntegerField(default=1),
),
]
|
channelcat/sanic | tests/test_worker.py | Python | mit | 5,289 | 0 | import asyncio
import json
import shlex
import subprocess
import time
import urllib.request
from unittest import mock
import pytest
from sanic_testing.testing import ASGI_PORT as PORT
from sanic.app import Sanic
from sanic.worker import GunicornWorker
@pytest.fixture(scope="module")
def gunicorn_worker():
com... | open(f"http: | //localhost:{PORT + 2}/") as _:
gunicorn_worker_with_env_var.kill()
assert not gunicorn_worker_with_env_var.stdout.read()
def test_gunicorn_worker_with_logs(gunicorn_worker_with_access_logs):
"""
default - show access logs
"""
with urllib.request.urlopen(f"http://localhost:{PORT + 1}/"... |
saymedia/python-danga-gearman | setup.py | Python | mit | 699 | 0.02289 | #!/usr/bin/env python
from distutils.core import setup
from dangagearman import __version__ as version
setup(
name = 'danga-gearman',
version = version,
description = 'Client for the Danga (Perl) Gearman implementation',
author = 'Samu | el Stauffer',
author_email = 'samuel@descolada.com',
url = 'http://github.com/saymedia/python-danga-gearman/tree/master',
packages = ['dangagearman'],
classifiers = [
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
' | Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
timdiels/0install | zeroinstall/cmd/whatchanged.py | Python | lgpl-2.1 | 2,814 | 0.033404 | """
The B{0install whatchanged} command-line interface.
"""
# Copyright (C) 2012, Thomas Leonard
# See the README file for details, or visit http://0install.net.
from __future__ import print_function
import os
from zeroinstall import _, SafeException
from zeroinstall.cmd import UsageError
syntax = "APP-NAME"
def ... | okup_app(name, missing_ok = False)
history = app.get_history()
if not history:
raise SafeException(_("Invalid application: no selections found! Try '0install destroy {name}'").format(name = name))
import time
last_checked = app.get_last_c | hecked()
if last_checked is not None:
print(_("Last checked : {date}").format(date = time.ctime(last_checked)))
last_attempt = app.get_last_check_attempt()
if last_attempt is not None:
print(_("Last attempted update: {date}").format(date = time.ctime(last_attempt)))
print(_("Last update : {date}").form... |
OKFNat/offenewahlen-nrw17 | src/offenewahlen_api/wsgi.py | Python | mit | 701 | 0.001427 | """
WSGI config for offenewahlen_nrw17 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https: | //docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
os.environ.setdefa | ult("DJANGO_SETTINGS_MODULE", "offenewahlen_api.settings")
application = get_wsgi_application()
application = DjangoWhiteNoise(application)
# Fix django closing connection to MemCachier after every request (#11331)
from django.core.cache.backends.memcached import BaseMemcachedCache
BaseMemcachedCache.close = lambda s... |
RGood/praw | tests/integration/models/test_comment_forest.py | Python | bsd-2-clause | 3,621 | 0 | """Test praw.models.comment_forest."""
from praw.models import Submission
from .. import IntegrationTest
class TestCommentForest(IntegrationTest):
def setup(self):
super(TestCommentForest, self).se | tup()
# Responses do not decode well on travis so manually renable gzip.
self.reddit._core._r | equestor._http.headers['Accept-Encoding'] = 'gzip'
def test_replace__all(self):
with self.recorder.use_cassette(
'TestCommentForest.test_replace__all',
match_requests_on=['uri', 'method', 'body']):
submission = Submission(self.reddit, '3hahrw')
before... |
LABETE/TestYourProject | config/urls.py | Python | bsd-3-clause | 1,501 | 0.000666 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.c | onf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
urlpatterns = [
url(r'^$', TemplateView.as_view(
template_name='pages/home.html'), name="home"),
url(r'^about/$',
TemplateView.as_view(template_... | ers.urls", namespace="users")),
url(r'^accounts/', include('allauth.urls')),
# Your stuff: custom urls includes go here
url(r'^api-auth/', include(
'rest_framework.urls', namespace='rest_framework')),
url(r'^api/', include('core.api', namespace='api')),
url(r'^rest-auth/', include('rest_aut... |
jiobert/python | Quintana_Jerrod/Assignments/f+sql_projects/full_friends/mysqlconnection.py | Python | mit | 2,239 | 0.005806 | """ import the necessary modules """
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import text
# Create a class that will give us an object that we can use to connect to a database
class MySQLConnection(object):
def __init__(self, app, db):
config = {
'host': 'localhost',
... | an insert, return the id of the
# commit changes
self.db.sess | ion.commit()
# row that was inserted
return result.lastrowid
else:
# if the query was an update or delete, return nothing and commit changes
self.db.session.commit()
# This is the module method to be called by the user in server.py. Make sure to provide the db nam... |
frasertweedale/drill | py/test_trie.py | Python | mit | 1,273 | 0 | import random
import unittest
from . import trie
class RWayTrieCase(unittest.TestCase):
def test_stores_values(self):
xs = range(4096)
random.shuffle(xs)
t = trie.RWayTrie()
for i in xs:
t.put(str(i), i)
for i in xs:
self.assertEqual(t.get(str(i)), ... | .get('16')
t = trie.RWayTrie()
t.put('asdf', 1)
with self.assertRaises(KeyError):
t.get('a')
class TernarySearchTrieCase(unittest.TestCase):
def test_stores_values(self):
xs = range(4096)
random.shuffle(xs)
t = trie.TernarySearchTrie()
| for x in xs:
t.put(str(x), x)
for x in xs:
self.assertEqual(t.get(str(x)), x)
def test_raises_KeyError_if_key_not_in_tree(self):
t = trie.TernarySearchTrie()
for i in range(15):
t.put(str(i), i)
with self.assertRaises(KeyError):
t.get... |
zygmuntz/kaggle-advertised-salaries | split.py | Python | mit | 825 | 0.069091 | '''
split a file into two randomly, line by line.
Usage: split.py <input file> <output file 1> <output file 2> [<probability of writing to the first file>]'
'''
import csv
import sys
import random
try:
P = float( sys.argv[4] )
except IndexError:
P = 0.9
print "P = %s" % ( P )
input_file = sys.argv[1]
output_fil... | der( i )
writer1 = csv.writer( o1 )
writer2 = csv.writer( o2 )
#headers = reader.next()
#writer1.writerow( headers )
#writer2.writerow( headers )
counter = 0
for line in reader:
r = random.random()
if r > P:
writer2.writerow( line )
else:
writer1.writerow( line )
counter += 1
if counter % 100000 | == 0:
print counter
|
ubiquitypress/rua | src/api/views.py | Python | gpl-2.0 | 1,221 | 0 | import json
from django.http import HttpResponse
from django.utils.encoding import smart_text
from rest_framework import viewsets, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import JSONRendere | r
from api import serializers
from core.models import Book
class JSONResponse(HttpResponse):
""" An HttpResponse that renders its content into JSON. """
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONRes... | ndex(request):
response_dict = {
'Message': 'Welcome to the API',
'Version': '1.0',
'API Endpoints':
[],
}
json_content = smart_text(json.dumps(response_dict))
return HttpResponse(json_content, content_type="application/json")
class JuraBookViewSet(viewsets.ModelVi... |
sergiooramas/tartarus | src/train.py | Python | mit | 27,751 | 0.008937 | from __future__ import print_function
import argparse
from collections import OrderedDict
import json
import os
import logging
from keras.callbacks import EarlyStopping
from sklearn.preprocessing import normalize
from sklearn.metrics import roc_curve, auc, roc_auc_score, precision_score, recall_score, f1_score, accurac... | y' % (metadata_source,dataset))
X_train = all_X
Y_train = all_Y
else:
N = all_Y.shape[0]
train_percent = 1 - val_percent - test_percent
N_train = int(train_percent * N)
N_val = int(val_percent * N)
logging.debug(" | Training data points: %d" % N_train)
logging.debug("Validation data points: %d" % N_val)
logging.debug("Test data points: %d" % (N - N_train - N_val))
if not only_metadata:
# Slice data
X_train = all_X[:N_train]
X_val = all_X[N_train:N_train + N_val]
... |
hamish2014/optTune | docs/conf.py | Python | gpl-3.0 | 7,028 | 0.006545 | # -*- coding: utf-8 -*-
#
# optTune documentation build configuration file, created by
# sphinx-quickstart on Wed Jan 11 12:14:27 2012.
#
# 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... | port sys, os
# If extensions (or modu | les to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration ------------------------------------... |
Stanford-Online/edx-platform | lms/djangoapps/certificates/queue.py | Python | agpl-3.0 | 22,442 | 0.001203 | """Interface for adding certificate generation tasks to the XQueue. """
import json
import logging
import random
from uuid import uuid4
import lxml.html
from django.conf import settings
from django.urls import reverse
from django.test.client import RequestFactory
from lxml.etree import ParserError, XMLSyntaxError
from... | is in the whitelist
table for the course a request will be made for a new cert.
If a student has allow_certificate set to False in the
userprofile table the status will change to 'restricted'
If a student does not have a passing grade the status
will change to status.notpassin... | (
u"Cannot create certificate generation task for user %s "
u"in the course '%s'; "
u"certificates are not allowed for CCX courses."
),
student.id,
unicode(course_id)
)
retu... |
PegasusWang/pyhome | crawler/morningstar/morningstar.py | Python | mit | 2,629 | 0.001193 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""晨星基金评级数据,用来买基金作为参考"""
import _env
import copy
import heapq
import requests
from operator import itemgetter
from tornado.escape import utf8
from six import print_
from bs4 import BeautifulSoup
from web_util import get
def parse_html(html):
html = utf8(html)
sou... | fund_array.sort(key=itemgetter(sort_index), reverse=True)
fund_array = fund_array[0:num]
num /= 2
fund_str_array = [' '.join([str(i) for i in | l]) for l in fund_array]
res = '\n'.join(fund_str_array)
with open('res', 'w') as f:
f.write(res)
if __name__ == '__main__':
choose('./log')
|
galeone/pgnet | inputs/pascifar.py | Python | mpl-2.0 | 3,128 | 0.003517 | #Copyright (C) 2016 Paolo Galeone <nessuno@nerdz.eu>
#
#This Source Code Form is subject to the terms of the Mozilla Public
#License, v. 2.0. If a copy of the MPL was not distributed with this
#file, you can obtain one at http://mozilla.org/MPL/2.0/.
#Exhibit B is not attached; this software is compatible with the
#lic... | UT_SIDE = 32
# Global constants describing the PASCIFAR data set.
NUM_CLASSES = 17
NUM_EXAMPLES = 42000
def read_pascifar(pascifar_path, queue):
""" Reads and parses files from the queue.
Args:
pascifar_path: a constant string tensor representing the path of the PASCIFAR dataset
queue: A queu... | image_path: a tf.string tensor. The absolute path of the image in the dataset
label: a int64 tensor with the label
"""
# Reader for text lines
reader = tf.TextLineReader(skip_header_lines=1)
# read a record from the queue
_, row = reader.read(queue)
# file,width,height,label
r... |
fifengine/fifengine-demos | pychan_demo/styling.py | Python | lgpl-2.1 | 3,586 | 0.044897 | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2013 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
#... | 'border_size': 0,
'background_color' : fifechan.Color(0,0,0,0),
},
'RadioButton' : {
'border_size': 0,
'background_color' : fifechan.Color(0,0,0,0),
},
'Label' : {
'border_size': 0,
'font' : 'samanata_small'
},
'ListBox' : {
'border_size': 0,
'font' : 'samanata_small'
},
'Window' : {
'border_ | size': 1,
'margins': (10,10),
'opaque' : False,
'titlebar_height' : 30,
'background_image' : 'gui/backgrounds/background.png',
'font' : 'samanata_large'
},
'TextBox' : {
'font' : 'samanata_small'
},
('Container','HBox','VBox') : {
'border_size': 0,
'background_image' : 'gui/backgrounds/background.pn... |
calvinchengx/O-Kay-Blog-wih-Kay-0.10.0 | kay/auth/backends/googleaccount.py | Python | bsd-3-clause | 2,423 | 0.011969 | # -*- coding: utf-8 -*-
"""
Kay authentication backend using google account.
:Copyright: (c) 2009 Accense Technology, Inc.
Takashi Matsuo <tmatsuo@candit.jp>,
All rights reserved.
:license: BSD, see LICENSE for more details.
"""
from google.appengine.ext import db
from goog... | ntity = auth_model_class.get_by_key_name(key_name)
if entity is None:
entity = auth_model_class(
key_name=key_name,
email=email,
is_admin=is_current_user_admin,
)
entity.put()
else:
update_user = Fal | se
if entity.is_admin != is_current_user_admin:
entity.is_admin = is_current_user_admin
update_user = True
if entity.email != email:
entity.email = email
update_user = True
if update_user:
entity.put()
return entity
... |
RaitoBezarius/mangaki | mangaki/mangaki/migrations/0014_auto_20150624_0003.py | Python | agpl-3.0 | 2,006 | 0.001496 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('mangaki', '0013_auto_20150616_0919'),
]
operations = [
migrations.AddField(
model_name='profile',
na... | em',
field=models.CharField(verbose_name='Partie concernée', max_length=8, choices=[('title', "Le titre n'est pas le bon"), ('poster', 'Le poster ne convient pas'), ( | 'synopsis', 'Le synopsis comporte des erreurs'), ('author', "L'auteur n'est pas le bon"), ('composer', "Le compositeur n'est pas le bon"), ('double', 'Ceci est un doublon'), ('nsfw', "L'oeuvre est NSFW"), ('n_nsfw', "L'oeuvre n'est pas NSFW")]),
preserve_default=True,
),
]
|
jolyonb/edx-platform | cms/djangoapps/contentstore/management/commands/delete_course.py | Python | agpl-3.0 | 3,575 | 0.004755 | from __future__ import print_function
from six import text_type
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from contentstore.utils import delete_course
from xmodule.contentstore.django import contentstore
from xm... | rse-v1:edX+DemoX+Demo_Course' --remove-assets --settings=devstack
Note:
The keep-instructors option is useful for resolving issues that arise when a course run's ID is duplicated
in a case-insensitive manner. MongoDB is case-sensitive, but MySQL is case-insensitive. This results in
course-v... | ently in MongoDB from course-v1:edX+DemoX+1T2017 (capital 'T').
If you need to remove a duplicate that has resulted from casing issues, use the --keep-instructors flag
to ensure that permissions for the remaining course run are not deleted.
Use the remove-assets option to ensure all assets are... |
utcoupe/coupe18 | ros_ws/src/processing_belt_interpreter/src/belt_interpreter_node.py | Python | gpl-3.0 | 9,252 | 0.002702 | #!/usr/bin/env python
import rospy
from belt_parser import BeltParser
import tf
import tf2_ros
import math
import copy
from memory_definitions.srv import GetDefinition
from processing_belt_interpreter.msg import *
from drivers_ard_others.msg import BeltRange
from geometry_msgs.msg import Pose2D, TransformStamped, Poi... | width = self.get_rect_width(data.range, params)
height = self.get_rect_height(data.range, params)
rect = RectangleStamped()
rect.header.frame_id = self.SENSOR_FRAME_ID.format(data.sensor_id)
rect.header.stamp = rospy.Time.now()
rect.x = self.... | , params)
rect.y = 0
rect.w = width
rect.h = height
rect.a = 0
self._current_rects.update({data.sensor_id: rect})
self._current_statuses.update({data.sensor_id: True})
def get_rect_width(self, r, params):
prec = r * params["precision... |
zeraien/odb_shared_django | http_shortcuts.py | Python | mit | 2,641 | 0.006437 | from past.builtins import basestring
import os.path
import simplejson as json
from django.shortcuts import render as django_render
from django.http import HttpResponseRedirect, HttpResponse, HttpResponsePermanentRedirect
from django.utils.decorators | import available_attrs
from functools import wraps
def render(request, template, context = {}, ignore_ajax = False, obj=None, content_type=None, status=None | , using=None):
if request.is_ajax() and not ignore_ajax:
basename = os.path.basename(template)
if not basename.startswith("_"):
dirname = os.path.dirname(template)
template = "%s/_%s"%(dirname,basename)
response = django_render(request=request, template_name=template,... |
3299/visioninabox | helpers/generateCalibration.py | Python | mit | 1,843 | 0.004883 | #!/usr/bin/env python
# Thank you | to https://goo.gl/NDyw63
# Imports
import os
import json
from glob import glob
import numpy as np
import cv2
class GenerateCalibration(object):
def __init__(self, directory, saveFilename):
self.directory = directory
self.saveFilename = saveFilename
def run(self):
img_names = glob(os.... | pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32)
pattern_points[:, :2] = np.indices(pattern_size).T.reshape(-1, 2)
pattern_points *= square_size
obj_points = []
img_points = []
h, w = 0, 0
img_names_undistort = []
for fn in img_names:
... |
CasherWest/django-post_office | post_office/migrations/0003_auto_20150608_1115.py | Python | mit | 699 | 0.002861 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('post_office', '0002_auto_20150204_1403'),
]
operations = [
migrations.AddField(
model_name='emailbackend',
... | eld(default='hosting@zweipunktnull.de', max_length=254),
preserve_default=False,
),
migrations.AlterField(
model_name='email',
name='backend',
field=models.ForeignKey(related_name='emails', blank=True, to='post_office.EmailBackend', null=True),
| ),
]
|
henrythasler/TileGenerator | py3_render.py | Python | gpl-2.0 | 18,299 | 0.014427 | #!/usr/bin/env python
"""
Python script to generate map tiles with mapnik using metatiles and multiprocessing/threading for improved performance
(c) Henry Thasler
based on other scripts from http://svn.openstreetmap.org/applications/rendering/mapnik/
"""
from math import pi, cos, sin, log, exp, atan, floor, ceil, sqr... | ap(TILE_SIZE, TILE_SIZE)
# Load style XML
mapnik.load_map(self.m, mapfile, True)
# Obtain | <Map> projection
self.prj = mapnik.Projection(self.m.srs)
# Projects between tile pixel co-ordinates and LatLong (EPSG:4326)
self.tileproj = GoogleProjection(maxZoom)
def render_tile(self, z, scale, p0, p1, metawidth, metaheight, debug):
# Calculate pixel positions of bottom-left &... |
maxwward/SCOPEBak | askbot/migrations/0017_add_group__moderators.py | Python | gpl-3.0 | 25,692 | 0.008446 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from django.contrib.auth.models import Group
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
moderators = Group(name = 'askbot_... | ngo.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'locked_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
| 'locked_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locked_problems'", 'null': 'True', 'to': "orm['auth.User']"}),
'offensive_flag_count': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'exercise': ('django.db.models.... |
santisiri/popego | envs/ALPHA-POPEGO/lib/python2.5/site-packages/SQLAlchemy-0.4.3-py2.5.egg/sqlalchemy/schema.py | Python | bsd-3-clause | 64,162 | 0.001901 | # schema.py
# Copyright (C) 2005, 2006, 2007, 2008 Michael Bayer mike_mp@zzzcomputing.com
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""The schema module provides the building blocks for database metadata.
Each element within this ... | owner
Defaults to None: optional owning user of this table.
useful for databases such as Oracle to aid in table
reflection.
quote
Defaults to False: indicates that the Table identifier
must be properly escaped and quoted before being sent to
... | r
must be properly escaped and quoted before being sent to
the database. This flag overrides all other quoting
behavior.
"""
super(Table, self).__init__(name)
self.metadata = metadata
self.schema = kwargs.pop('schema', None)
self.owner = kwarg... |
ajkannan/Classics-Research | Utilities/TermFrequencyInverseDocumentFrequency.py | Python | mit | 1,955 | 0.032225 | from Text import Text
from pprint import pprint
import numpy as np
class TermFrequencyInverseDocumentFrequency(object):
"""docstring for TermFrequencyInverseDocumentFrequency"""
def __init__(self):
super(TermFrequencyInverseDocumentFrequency, self).__init__()
self.corpus = []
self.corpus_frequencies = {}
... | rd] = text_freque | ncies.get(word, 0.0) + 1.0
if add_text:
self.corpus_frequencies[word] = self.corpus_frequencies.get(word, 0.0) + 1.0
for word in text_frequencies.keys():
text_frequencies[word] /= length
return text_frequencies
def calculate_similarity_scores(self, text):
query_text_frequencies = self.calculate_no... |
rdhyee/osf.io | admin_tests/meetings/test_forms.py | Python | apache-2.0 | 2,864 | 0 | from nose import tools as nt
from tests.base import AdminTestCase
from tests.factories import AuthUserFactory
from tests.test_conferences import ConferenceFactory
from admin.meetings.forms import MeetingForm, MultiEmailField
data = dict(
edit='False',
endpoint='short',
name='Much longer',
info_url='... | t(data)
mod_data.update({'admins': self.user.emails[0], 'edit': 'True'})
f | orm = MeetingForm(data=mod_data)
nt.assert_in('endpoint', form.errors)
nt.assert_equal('Meeting not found with this endpoint to update',
form.errors['endpoint'][0])
def test_clean_endpoint_raise_exists(self):
conf = ConferenceFactory()
mod_data = dict(data)
... |
RedhawkSDR/integration-gnuhawk | components/quadrature_demod_cf/tests/test_quadrature_demod_cf.py | Python | gpl-3.0 | 4,545 | 0.006601 | #!/usr/bin/env python
#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of GNUHAWK.
#
# GNUHAWK is free software: you can redistribute it and/or modify is under the
# terms of the GNU General Public License as published by ... | ved a copy of the GNU General Public License along with
# this program. If not, see http://www.gnu.org/licenses/.
#
import unittest
import ossie.utils.testing
import os
from omniORB import any
class ComponentTests(ossie.utils.testing.ScaComponentTestCase):
"""Test for all component implementations in quadratur... | ######################################
# Launch the component with the default execparams
execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
self.launch(execpara... |
BaiduPS/tera | src/sdk/python/TeraSdk.py | Python | bsd-3-clause | 39,743 | 0 | # -*- coding: utf-8 -*-
"""
Tera Python SDK. It needs a libtera_c.so
TODO(taocipian) __init__.py
"""
from ctypes import CFUNCTYPE, POINTER
from ctypes import byref, cdll, string_at
from ctypes import c_bool, c_char_p, c_void_p
from ctypes import c_uint32, c_int32, c_int64, c_ubyte, c_uint64
class Status(object):
... | )
def SetBufferSize(self, buffer_size):
"""
服务端将读取的数据攒到buffer里,最多积攒到达buffer_size以后返回一次 | ,
也有可能因为超时或者读取到达终点而buffer没有满就返回,默认值 64 * 1024
这个选项对scan性能有非常明显的影响,
我们的测试显示,1024*1024(1MB)在很多场景下都有比较好的表现,
建议根据自己的场景进行调优
Args:
buffer_size: scan操作buffer的size,单位Byte
"""
lib.tera_scan_descriptor_set_buffer_size(self.desc, buffer_size)
def SetPackIn... |
codemasteroy/py-viitenumero | setup.py | Python | gpl-3.0 | 547 | 0.014625 | #!/usr/bin/env python
from distutils.core import setup
setup(
name='py-viitenumero',
version='1.0',
description='Python module for generating Finnish national payment reference number',
author='Mohanjith Sudirikku Hannadige',
author_email='moha@codemaster.fi',
url='http... | ],
| keywords=[ 'payments', 'creditor reference', 'finland', 'suomi' ]
)
|
balanced/status.balancedpayments.com | situation/settings.py | Python | mit | 2,611 | 0 | # Notice:
# If you are running this in production environment, generate
# these for your app at https://dev.twitter.com/apps/new
TWITTER = {
'AUTH': {
'consumer_key': 'XXXX',
'consumer_secret': 'XXXX',
'token': 'XXXX',
'token_secret': 'XXXX',
}
}
# We're pulling data from grap... | 'XXXX',
'from_number': 'XXXX'
}
DEBUG = True
# Currently DASHBOARD do | es not send out notifications
NOTIFY_SERVICES = ['API', 'JS']
|
square/pants | tests/python/pants_test/tasks/test_ensime_integration.py | Python | apache-2.0 | 2,018 | 0.011893 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
import os
from pant... | + ['--ensime-project-dir={dir}'.format(dir=path), ])
self.assertEquals(pants_run.returncode, self.PANTS_SUCCESS_CODE,
"goal ensime expected success, got {0}\n"
"got stderr:\n{1}\n"
"got stdout:\n{2 | }\n".format(pants_run.returncode,
pants_run.stderr_data,
pants_run.stdout_data))
# TODO: Actually validate the contents of the project files, rather than just
# checking if they exist.
expected_file... |
marlengit/electrum198 | lib/__init__.py | Python | gpl-3.0 | 692 | 0.001445 | from version import ELECTRUM_VERSION
from util import format_satoshis, print_msg, print_json, print_error, set_verbosity
from wallet import WalletSynchronizer, WalletStorage
from wallet import Wallet
from verifier import TxVerifier
from network import Network, DEFAULT_SERVERS, DEFAULT_PORTS, pick_random_server
from int... | ic import mn_decode as mnemo | nic_decode
from commands import Commands, known_commands
from daemon import NetworkProxy, NetworkServer
|
danche354/Sequence-Labeling | ner_BIOES/evaluate-senna-hash-2-pos-chunk-128-64-rmsprop5.py | Python | mit | 3,163 | 0.008536 | '''
evaluate result
'''
from keras.models import load_model
from keras.utils import np_utils
import numpy as np
import os
import sys
# add path
sys.path.append('../')
sys.path.append('../tools')
from tools import conf
from tools import load_data
from tools import prepare
# input sentence dimensions
step_leng | th = conf.ner_step_length
pos_length = conf.ner_pos_length
chunk_length = conf.ner_chunk_length
# gazetteer_length = conf.gazetteer_length
IOB = conf.ner_BIOES_decode
data = sys.argv[1]
best_epoch = sys.argv[2]
if data=="dev": |
test_data = load_data.load_ner(dataset='eng.testa', form='BIOES')
elif data == "test":
test_data = load_data.load_ner(dataset='eng.testb', form='BIOES')
tokens = [len(x[0]) for x in test_data]
print(sum(tokens))
print('%s shape:'%data, len(test_data))
model_name = os.path.basename(__file__)[9:-3]
folder_path ... |
projectcalico/calico-neutron | neutron/db/l3_agentschedulers_db.py | Python | apache-2.0 | 22,584 | 0.000221 | # Copyright (c) 2013 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | emy.orm import exc
from sqlalchemy.orm import joinedload
from sqlalchemy import sql
from neutron.common import constants
from neutron.common import utils as n_utils
from neutron import context as n_ctx
from neutron.db import agents_db
from neutron.db import agentschedulers_db
from neutron.db import l3_attrs_db
from ne... |
from neutron import manager
from neutron.openstack.common import log as logging
from neutron.openstack.common import loopingcall
LOG = logging.getLogger(__name__)
L3_AGENTS_SCHEDULER_OPTS = [
cfg.StrOpt('router_scheduler_driver',
default='neutron.scheduler.l3_agent_scheduler.ChanceScheduler',
... |
happz/ducky | ducky/cpu/instructions.py | Python | mit | 78,868 | 0.019247 | import ctypes
import enum
import logging
import sys
from six import add_metaclass, iteritems, string_types
from six.moves import range
from functools import partial
from collections import OrderedDict
from .registers import Registers, REGISTER_NAMES
from ..mm import u32_t, i32_t, UINT16_FMT, UINT32_FMT
from ..util im... | coding.repr(sel | f, [('reg1', '%02d'), ('reg2', '%02d'), ('reg3', '%02d')])
class EncodingContext(LoggingCapable, object):
def __init__(self, logger):
super(EncodingContext, self).__init__(logger)
if hasattr(sys, 'pypy_version_info'):
self.u32_to_encoding = self._u32_to_encoding_pypy
else:
self.u32_to_encod... |
quanta413/Population-Evolution-Project-Source-Code | populationevolution/stenciledsum.py | Python | bsd-2-clause | 6,254 | 0.00048 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
def subarray_multislice(array_ndim, fixed_axes, indices):
'''
Return tuple of slices that if indexed into an array with given dimensions
will return subarray with the axes in axes fixed at given indices
... | # If steps is None, default to step size of 1
if steps is None:
for i in range(array.ndim):
multislice = multislice + (slice(starts[i], ends[i], 1),)
else:
for i in range(array.ndim):
multislice = multislice + (slice(starts[i], ends[i], steps[i]),)
return | array[multislice]
def check_axes_access(axes, array_ndim):
if np.max(axes) >= array_ndim or np.min(axes) < -array_ndim:
raise IndexError('too many indices for array')
# regular numpy scheme for which positive index a negative index corresponds to
def convert_axes_to_positive(axes, array_ndim):
f... |
xbmcmegapack/plugin.video.megapack.dev | resources/lib/favourites_manager.py | Python | gpl-3.0 | 2,043 | 0.000979 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine (xbmcmegapack@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 published by
the Free Software... | 3 of the Lic | ense, 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 Public License for more details.
You should have... |
optiflows/nyuki | nyuki/workflow/db/storage.py | Python | apache-2.0 | 8,557 | 0 | import logging
import os
from copy import deepcopy
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo.errors import ServerSelectionTimeoutError
from .triggers import TriggerCollection
from .data_processing import DataProcessingCollection
from .metadata import MetadataCollection
from .workflow_templates i... | ne(
tid,
draft=draft,
version=int(version) if version else None,
)
if not template:
return
metadata = await self._workflow_metadata.get_one(tid)
template.update(metadata)
template['tasks' | ] = await self._task_templates.get(
template['id'], template['version']
)
return template
async def delete_template(self, tid, draft=False):
"""
Delete a whole template or only its draft.
"""
await self._workflow_templates.delete(tid, draft)
if dr... |
mikekestemont/PyStyl | pystyl/clustering/distance.py | Python | bsd-3-clause | 1,971 | 0.006596 | # Hierarchical Agglomerative Cluster Analysis
#
# Copyright (C) 2013 Folgert Karsdorp
# Author: Folgert Karsdorp <fbkarsdorp@gmail.com>
# URL: <https://github.com/fbkarsdorp/HAC-python>
# For licence information, see LICENCE.TXT
import numpy
from numpy import dot, sqrt
def binarize_vector(u):
return u > 0
def co... | um(abs(u-v) / abs(u+v))
def correlation(u, v):
"""Return the correlation distance between two vectors."""
u_var = u - u.mean()
v_var = v - v.mean()
return 1.0 - dot(u_var, v_var) / (sqrt(dot(u_var, u_var)) *
sqrt(dot(v_var, v_var)))
def dice(u, v):
"""Return t... |
"""return jaccard distance"""
u = numpy.asarray(u)
v = numpy.asarray(v)
return (numpy.double(numpy.bitwise_and((u != v),
numpy.bitwise_or(u != 0, v != 0)).sum())
/ numpy.double(numpy.bitwise_or(u != 0, v != 0).sum()))
def jaccard(u, v):
"""Return the Jaccard coefficient be... |
dsqmoore/0install | zeroinstall/injector/trust.py | Python | lgpl-2.1 | 9,078 | 0.031725 | """
Records who we trust to sign feeds.
Trust is divided up into domains, so that it is possible to trust a key
in some cases and not others.
@var trust_db: Singleton trust database instance.
"""
# Copyright (C) 2009, Thomas Leonard
# See the README file for details, or visit http://0install.net.
from zeroinstall i... | config = config
self._current_confirm = None # (a lock to prevent asking the | user multiple questions at once)
@tasks.async
def confirm_keys(self, pending):
"""We don't trust any of the signatures yet. Collect information about them and add the keys to the
trusted list, possibly after confirming with the user (via config.handler).
Updates the L{trust} database, and then calls L{trust.Tr... |
ActiveState/code | recipes/Python/577283_Decorator_expose_local_variables_functiafter/recipe-577283.py | Python | mit | 3,276 | 0.004579 | import new
import byteplay as bp
import inspect
def persistent_locals(f):
"""Function decorator to expose local variables after execution.
Modify the function such that, at the exit of the function
(regular exit or exceptions), the local dictionary is copied to a
read-only function property 'locals'.
... | following:
def f(self, *args, **kwargs):
try:
... old code ...
finally:
self._locals = locals().copy()
del self._locals['self']
"""
# ### disassemble f
f_code = bp.Code.from_code(f.func_code)
# ### use bytecode injection to add try...finally st... | bel()
# try:
code_before = (bp.SETUP_FINALLY, finally_label)
# [original code here]
# finally:
code_after = [(finally_label, None),
# self._locals = locals().copy()
(bp.LOAD_GLOBAL, 'locals'),
(bp.CALL_FUNCTION, 0),
(bp.LOAD... |
viewworld/django-auth-iam | setup.py | Python | gpl-3.0 | 1,017 | 0.001967 | #!/usr/bin/env python
import os
from setuptools import setup |
fr | om distutils.cmd import Command
import django_auth_iam
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(
name='django-auth-iam',
version=django_auth_iam.__version__,
description='Django authentication backend using Amazon IAM',
long_description=read('... |
Karosuo/Linux_tools | xls_handlers/xls_sum_venv/lib/python3.6/site-packages/pip/_internal/exceptions.py | Python | gpl-3.0 | 9,145 | 0 | """Exceptions used throughout package"""
from __future__ import absolute_import
from itertools import chain, groupby | , repeat
from pip._vendor.six import iteritems
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from typing import Optional # noqa: F401
from pip._internal.req.req_install import InstallRequirement # noqa: F401
class PipError(Exception):
"""Base pip exception"""
clas... | class UninstallationError(PipError):
"""General exception during uninstallation"""
class DistributionNotFound(InstallationError):
"""Raised when a distribution cannot be found to satisfy a requirement"""
class RequirementsFileParseError(InstallationError):
"""Raised when a general error occurs parsing a... |
Shinoby1992/xstream | sites/hdfilme_tv.py | Python | gpl-3.0 | 13,459 | 0.006638 | # -*- coding: utf-8 -*-
from resources.lib.gui.gui import cGui
from resources.lib.gui.guiElement import cGuiElement
from resources.lib.handler.requestHandler import cRequestHandler
from resources.lib.parser import cParser
from resources.lib import logger
from resources.lib.handler.ParameterHandler import Paramete... | name
iYear = year
break
# prüfen ob der Eintrag ein Serie/Staffel ist
isTvshow = True if sEpisodeNrs else False
# Listen-Eintrag erzeugen
oGuiElement = cGuiEl | ement(sName, SITE_IDENTIFIER, 'showHosters')
# Bei Serien Title anpassen
res = re.search('(.*?)\s(?:staf+el|s)\s*(\d+)', sName,re.I)
if res:
oGuiElement.setTVShowTitle(res.group(1))
oGuiElement.setTitle('%s - Staffel %s' % (res.group(1),int(res.group(2))))
... |
PSU-OIT-ARC/django-arcutils | arcutils/tests/test_settings.py | Python | mit | 2,723 | 0.000367 | from django.test import override_settings, SimpleTestCase
from arcutils.settings import NO_DEFAULT, PrefixedSettings, get_setting
@override_settings(ARC={
'a': 'a',
'b': [0, 1],
'c': [{'c': 'c'}],
'd': 'd',
})
class TestGetSettings(SimpleTestCase):
def get_setting(self, key, default=NO_DEFAULT):... | dict(self):
self.assertEqual(self.get_setting('ARC.a'), 'a')
def test_can_traverse_into_dict_then_list(self):
| self.assertEqual(self.get_setting('ARC.b.0'), 0)
def test_can_traverse_into_list_then_dict(self):
self.assertEqual(self.get_setting('ARC.c.0.c'), 'c')
def test_returns_default_for_non_existent_root(self):
default = object()
self.assertIs(self.get_setting('NOPE', default), default)
... |
ktan2020/legacy-automation | win/Lib/test/test_dictviews.py | Python | mit | 6,667 | 0.00045 | import unittest
from test import test_support
class DictSetTest(unittest.TestCase):
def test_constructors_not_callable(self):
kt = type({}.viewkeys())
self.assertRaises(TypeError, kt, {})
self.assertRaises(TypeError, kt)
it = type({}.viewitems())
self.assertRaises... | ssertEqual(d1.viewitems() & set(d3.viewitems()), set())
self.assertEqual(d1.viewitems() | d1.vie | witems(),
{('a', 1), ('b', 2)})
self.assertEqual(d1.viewitems() | d2.viewitems(),
{('a', 1), ('a', 2), ('b', 2)})
self.assertEqual(d1.viewitems() | d3.viewitems(),
{('a', 1), ('b', 2), ('d', 4), ('e', 5)})
self.asse... |
prppedro/mercurium | plugins/multipurpose.py | Python | mit | 3,764 | 0.003208 | # Plugin mais feio do mundo, mas é só pra um chat específico.
# Aqui temos comandos que são pequenos demais pra terem seu próprio módulo.
# O stats fora inicialmente implementado aqui, depois fora transferido [Tadeu, 23/Ago]
# A maioria é um port bem rápido de https://github.com/lucasberti/telegrao/blob/master/p... | rch(text)
if match:
send_message(chat, "@berti @beaea @getulhao @rauzao @xisteaga @axasdas @Garzarella")
# TODO: fazer esta listagem de modo dinâmico e, talvez, por plugin
# calma
pattern = re.compile("^calma$")
match = pattern.search(text)
if match:
send_message(ch... |
# rau
pattern = re.compile("^rau$")
match = pattern.search(text)
if match:
send_message(chat, "meu pau no seu cu")
# Contribuição de Humberto
pattern = re.compile("^!+$")
match = pattern.search(text)
if match:
send_audio_id(chat, "CQADAQADFQAD4CAoRdcd4TJ... |
Azure/azure-sdk-for-python | sdk/communication/azure-communication-identity/tests/testcase.py | Python | mit | 2,935 | 0.006814 |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import os... |
super(CommunicationIdentityTestCase, self).setUp()
if self.is_playback():
self.connection_str = "endpoint=https://sanitized/;accesskey=fake==="
self.m365_app_id = "sanitized"
self.m365_aad_authority = "sanitized"
| self.m365_aad_tenant = "sanitized"
self.m365_scope = "sanitized"
self.msal_username = "sanitized"
self.msal_password = "sanitized"
self.expired_teams_token = "sanitized"
self.skip_get_token_for_teams_user_tests = "false"
else:
sel... |
e-gob/plataforma-kioscos-autoatencion | scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/windows/win_msg.py | Python | bsd-3-clause | 3,581 | 0.001955 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Jon Hawkesworth (@jhawkesworth) <figs@unity.demon.co.uk>
#
# This file is part of Ansible
#
# Ansible 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, eith... | her press 'ok' or for
the timeout to elapse before moving on to the next user.
type: bool
default: 'no'
msg:
description:
- The text of the message to be displayed.
- The message must be less than 256 characters.
default: Hello world!
author:
- Jon Hawkesworth (@jhawkesworth)
no | tes:
- This module must run on a windows host, so ensure your play targets windows
hosts, or delegates to a windows host.
- Messages are only sent to the local host where the module is run.
- The module does not support sending to users listed in a file.
- Setting wait to true can result in long run ti... |
plotly/plotly.py | packages/python/plotly/plotly/validators/contourcarpet/line/_smoothing.py | Python | mit | 505 | 0.00198 | import _plotly_utils.basevalidators
class SmoothingValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name= | "smoothing", parent_name="contourcarpet.line", **kwargs
):
super(SmoothingValidator, self).__init__(
pl | otly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
max=kwargs.pop("max", 1.3),
min=kwargs.pop("min", 0),
**kwargs
)
|
sserrot/champion_relationships | venv/Lib/site-packages/nbconvert/preprocessors/sanitize.py | Python | mit | 4,070 | 0 | """
NBConvert Preprocessor for sanitizing HTML rendering of notebooks.
"""
from bleach import (
ALLOWED_ATTRIBUTES,
ALLOWED_STYLES,
ALLOWED_TAGS,
clean,
)
from traitlets import (
Any,
Bool,
List,
Set,
Unicode,
)
from .base import Preprocessor
class SanitizeHTML(Preprocessor):
... | cell, resources
def sanitize_code_outputs(self, outputs):
"""
| Sanitize code cell outputs.
Removes 'text/javascript' fields from display_data outputs, and
runs `sanitize_html_tags` over 'text/html'.
"""
for output in outputs:
# These are always ascii, so nothing to escape.
if output['output_type'] in ('stream', 'error'):
... |
edwardsnj/rmidb2 | rmidb2/sosecpwhashprovider.py | Python | mit | 317 | 0.015773 | f | rom turbogears.identity.soprovider import *
from secpwhash import check_password
class SoSecPWHashIdentityProvider(SqlObjectIdentityProvider):
def validate_password(self, user, user_name, password):
# print >>sys.stderr, user, user.password, user_name, passw | ord
return check_password(user.password,password)
|
igormartire/esii | chess/ui/ui.py | Python | mit | 20,909 | 0 | import os
import time
import pygame
from pygame.locals import *
from chess.core.models import Coordinate, Color, Piece, Player
from chess.core.utils import WHITE_PIECES
from chess.core.query import (destinations,
is_check_for_player,
is_checkmate_for_player,... | ": self.load_png('white-rook.png'),
"BLACK_PAWN_IMAGE": self.load_png('black-pawn.png'),
"BLACK_BISHOP_IMAGE": self.load_png('black-bishop.png'),
"BLACK_KING_IMAGE": self.load_png('black-king.png'),
"BLACK_KNIGHT_IMAGE": self.load_png('black-knight.png'),
"BLA... | K_IMAGE": self.load_png('black-rook.png')
}
self.assets = {
'title': self.load_png('title.png'),
'logo_small': self.load_png('logo_small.png'),
'bg': self.load_png('bg.png'),
}
self.__displayed_text = self.font.render("", 1, (255, 255, 255))
... |
bgroveben/python3_machine_learning_projects | oreilly_GANs_for_beginners/oreilly_GANs_for_beginners/introduction_to_ml_with_python/mglearn/mglearn/plot_nn_graphs.py | Python | mit | 3,510 | 0.001709 |
def plot_logistic_regression_graph():
import graphviz
lr_graph = graphviz.Digraph(node_attr={'shape': 'circle', 'fixedsize': 'True'},
graph_attr={'rankdir': 'LR', 'splines': 'line'})
inputs = graphviz.Digraph(node_attr={'shape': 'circle'}, name="cluster_0")
output = gra... | .body.append('color = "white"')
lr_graph.subgraph(inputs)
output.body.append('label = "output"')
output.body.append('color = "white"')
output.node("y")
lr_graph.subgraph(output)
for i in range(4):
lr_graph.edge("x[%d] | " % i, "y", label="w[%d]" % i)
return lr_graph
def plot_single_hidden_layer_graph():
import graphviz
nn_graph = graphviz.Digraph(node_attr={'shape': 'circle', 'fixedsize': 'True'},
graph_attr={'rankdir': 'LR', 'splines': 'line'})
inputs = graphviz.Digraph(node_attr={'s... |
plamut/ggrc-core | src/ggrc/models/notification.py | Python | apache-2.0 | 1,986 | 0.012085 | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""GGRC notification SQLAlchemy layer data model extensions."""
from sqlalchemy.orm import backref
from ggrc import db
from ggrc.models.mixins import Base
from ggrc.models import utils
class Notification... | ]
VALID_TYPES = [
'Email_Now',
'Email_Digest',
'Calendar',
]
class NotificationType(Base, db.Model):
__tablename__ = 'notification_types'
name = db.Column(db.String, nullable=False)
description = db.Column(db.String, nullable=True)
advance_notice = db.Column(db.DateTime, nullable=True... | object_id = db.Column(db.Integer, nullable=False)
object_type = db.Column(db.String, nullable=False)
send_on = db.Column(db.DateTime, nullable=False)
sent_at = db.Column(db.DateTime, nullable=True)
custom_message = db.Column(db.Text, nullable=True)
force_notifications = db.Column(db.Boolean, default=False, n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.