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 |
|---|---|---|---|---|---|---|---|---|
awyrough/xsoccer | xsoccer/eventstatistics/migrations/0005_auto_20170112_2009.py | Python | mit | 461 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-12 20:09
from __future__ import unicode_literals
from django.db im | port migrations
class Migration(migrations.Migration):
dependencies = [
('eventstatistics', '0004_auto_20170112_2007'),
]
operations = [
migrations.RenameField(
model_name='eventstatistic',
old_name='relative_time',
new_name='relative_seconds',
| ),
]
|
Crypto-Expert/Electrum-obsolete | lib/util.py | Python | gpl-3.0 | 5,928 | 0.009447 | import os, sys, re, json
import platform
import shutil
from datetime import datetime
is_verbose = True
class MyEncoder(json.JSONEncoder):
def default(self, obj):
from transaction import Transaction
if isinstance(obj, Transaction):
return obj.as_dict()
return super(MyEncoder, s... | d hours ago" % (round(distance_in_minutes / 60.0))
elif distance_in_minutes < 2880:
return "1 day ago"
elif distance_in_minutes < 43220:
return "%d days ago" % (round(distance_in_minutes / 1440))
elif distance_in_minutes < 86400:
return "about 1 month ago"
elif distance_in_minute... | (round(distance_in_minutes / 43200))
elif distance_in_minutes < 1051200:
return "about 1 year ago"
else:
return "over %d years ago" % (round(distance_in_minutes / 525600))
# URL decode
_ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
urldecode = lambda x: _ud.sub(lambda m: chr(int(m.grou... |
etingof/pysmi | pysmi/searcher/base.py | Python | bsd-2-clause | 405 | 0 | #
# This file is part of pysmi software.
#
# Copyright (c) 2015-2020, Ilya Etingof <[email protected]> |
# License: http://snmplabs.com/pysmi/license.html
#
class AbstractSearcher(object):
def setOptions(self, **kwargs):
for k in kwargs: |
setattr(self, k, kwargs[k])
return self
def fileExists(self, mibname, mtime, rebuild=False):
raise NotImplementedError()
|
egustafson/sandbox | Python/py-setup/ex_pkg1/__init__.py | Python | apache-2.0 | 110 | 0.036364 | #!/usr/bin/env python
print("Example package 1 in ex_pkg1/*")
## | Local Variables:
## mode: python
## End: | |
caspervg/pylex | src/pylex/lot.py | Python | mit | 4,510 | 0.001996 | from base64 import b64encode
import os
import requests
from .route import Route
class LotRoute(Route):
"""
Contains endpoints related to LEX lots
"""
def lot(self, id, user=True, dependencies=True, comments=True, votes=True, no_strip=False):
"""
Retrieve the lot with given identifier... |
args['dependencies'] = 'true'
if comments:
args['comments'] = 'true'
if votes:
args['votes'] = 'true'
if no_strip:
args['nostrip'] = 'true'
return self._get_json('lot/{0}', id, | **args)
def all(self):
"""
Retrieve a concise list of all available lots
:return: List of all lots
:rtype: list
"""
return self._get_json('lot/all')
def download(self, id, directory):
"""
Download the file with given identifier to the given dir... |
jessedsmith/Arcte | modules/containers.py | Python | gpl-3.0 | 23,623 | 0.021297 | # -*- coding: utf-8 -*-
import os
import numpy as n
from collections import OrderedDict
from vtk import *
from qt4 import *
class Structure:
'''
Base class for all crystal baseStructs
'''
def __init__(self):
self.natoms = 0
self.composition = ''
self.system = ""
self.bra... | 'i':self.ary([[0,1],[1,0]]),
'j':self.ary([[1,0],[0,1],[1,1]]),
'k':self.ary([[0,0],[2,0]]),
'l':self.ary([[0,0],[1,0],[2,0]]),
'm':self.ary([[0,0],[0,1],[2,0]]),
'n':self.ary([[0,0],[0,1],[1,1],[2,0]]),
... | 'p':self.ary([[0,0],[0,1],[1,0],[2,0]]),
'q':self.ary([[0,0],[0,1],[1,0],[1,1],[2,0]]),
'r':self.ary([[0,0],[1,0],[1,1],[2,0]]),
's':self.ary([[0,1],[1,0],[2,0]]),
't':self.ary([[0,1],[1,0],[1,1],[2,0]]),
... |
shadowmint/nwidget | lib/cocos2d-0.5.5/samples/demo_flag3d.py | Python | apache-2.0 | 7,097 | 0.014231 | #
# cocos2d:
# http://cocos2d.org
#
# An example of how to generate a 3D scene manually
# Of course, the easiest way is to execute an Waves3D action,
# but this example is provided to show the
# 'internals' of generating a 3D effect.
#
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__... | dexed( (self.grid_size.x+1) * (self.grid_size.y+1),
idx_pts, "t2f", "v3f/stream","c4B")
self.vertex_list.vertices = ver_pts_idx # vertex points
self.vertex_list.tex_coords = tex_pts_idx # texels
self.vertex_list.colors = (255,255,255,255) * (self.grid_size.... | er is active
self.schedule(self.step)
def on_enter(self):
super(Flag3D,self).on_enter()
# hook on resize to override the default projection with a custom one.
# cocos2d's default projetion is also a 3d projection, but since this
# is a demo, we show how to customi... |
jakbob/guitarlegend | songbuilder.py | Python | gpl-3.0 | 1,430 | 0.01958 | import getopt
import sys
import midi
#constants
keycodes = {1 : 64, #midi keycodes
2 : 59,
3 : 55,
4 : 50,
5 : 45,
6 : 40,
-1 : -1,} #flag for deletition
def rearange(infile, outfile):
#read infile
mid = midi.MidiFile()
mid.open(infile)
mid.read()
mid.close()
#rearange note... | ack.events.remove(event)
#write new file
mid.open(outfile, "wb")
mid.write()
mid.close()
if __name__ == "__main__":
infile = outfile = None
optlist, args = getopt.getopt(sys.argv[1:], "i:o:")
for flag, value in optlist:
if flag == "-i":
infile = v | alue
elif flag == "-o":
outfile = value
if not (infile and outfile):
raise "Must specifile infile (-i) and outfile (-o)"
rearange(infile, outfile) |
mardix/pylot | pylot/app_templates/default/__init__.py | Python | mit | 8 | 0.125 |
# Pylo | t | |
mbrossard/yum-s3-iam | s3iam.py | Python | apache-2.0 | 9,027 | 0.000111 | #!/usr/bin/env python
# Copyright 2012, Julius Seporaitis
#
# 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 ... | the file to the local filesystem."""
request = self._request(url)
if filename is None:
| filename = request.get_selector()
if filename.startswith('/'):
filename = filename[1:]
response = None
try:
out = open(filename, 'w+')
response = urllib2.urlopen(request)
buff = response.read(8192)
while buff:
... |
code4bones/androguard | demos/crackme_dexlabs_patch.py | Python | apache-2.0 | 1,566 | 0.028736 | #!/usr/bin/env python
import sys
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)
from androguard.core.bytecodes import dvm
from androguard.core.bytecodes import apk
from androguard.core.analysis import analysis
from androguard.core import androconf
class Nop(dvm.Instruction10x):
def __init__(self):
se... | x(None, "\x00\x00") )
method.set_instructions( instructions )
FILENAME_INPUT = "apks/crash/crackme-obfuscator.apk"
FILENAME_OUTPUT = "./toto.dex"
androconf.set_debug()
a = apk.APK( FILENAME_INPUT )
vm = dvm.DalvikVMFormat( a.get_dex() )
vmx = analysis.VMAnalysis( vm )
patch_dex( vm )
new_dex = vm.save()
wit | h open(FILENAME_OUTPUT, "w") as fd:
fd.write( new_dex )
|
sunfounder/SunFounder_Dragit | Dragit/Dragit/libs/modules/i2c_lcd.py | Python | gpl-2.0 | 2,054 | 0.055015 | #!/usr/bin/env python
import time
import smbus
BUS = smbus.SMBus(1)
def write_word(addr, data):
global BLEN
temp = data
if BLEN == 1:
temp |= 0x08
else:
temp &= 0xF7
BUS.write_byte(addr ,temp)
def send_command(comm):
# Send bit7-4 firstly
buf = comm & 0xF0
buf |= 0x04 # RS = 0, RW = 0, EN ... | ):
if x < 0:
x = 0
if x > 15:
x = 15
if y <0:
y = 0
if y > 1:
y = 1
# Move cursor
addr = 0x80 + 0x40 * y + x
send_command(addr)
for chr in str:
send_data(ord(chr))
if | __name__ == '__main__':
init(0x27, 1)
write(4, 0, 'Hello')
write(7, 1, 'world!')
|
bwall/bamfdetect | BAMF_Detect/modules/herpes.py | Python | mit | 1,507 | 0.001991 | from common import Modules, data_strings, load_yara_rules, PEParseModule, ModuleMetadata, is_ip_or_domain
from re import match
class herpes(PEParseModule):
def __init__(self):
md = ModuleMetadata(
module_name="herpes",
bot_name="Herpes Net",
description="Botnet that rea... | server = s
if mat | ch(r'^\d\.\d\.\d$', s) is not None:
results["version"] = s
if server is not None and gate is not None:
results["c2_uri"] = "%s%s" % (server, gate)
return results
Modules.list.append(herpes()) |
cydrobolt/lucem | lucem/urls.py | Python | apache-2.0 | 732 | 0.002732 | from django.conf.urls import url, include
from django.contrib.auth import views as auth_views
from django.contrib import admin
from app import views
from app import api_views
api_urlpatterns = [
url(r'^get_friends_light_states', api_views.json_friends_light_states, name='api_v1_get_friends_light_states'),
| url(r'^ping_friend_lights', api_views.ping_light, name='api_v1_ping_friend_lights'),
]
urlpatterns = [
# Views
url(r'^$', views.index, name='home'),
url(r'^logo | ut/$', views.logout, name='logout'),
# Admin and authentication
url('', include('social_django.urls', namespace='social')),
url(r'^admin/', admin.site.urls),
# API endpoints
url(r'^api/v1/', include(api_urlpatterns)),
]
|
vijayanandau/KnowledgeShare | makahiki/apps/widgets/AskedQuestions/urls.py | Python | mit | 216 | 0.009259 | "" | "Ask Admin URL."""
from django.conf.urls.defaults import url, patterns
urlpatterns = patterns('',
url(r'^my_question/$',
'apps.widgets.AskedQuestions.views.send_question', name="ask_que_question"),
| )
|
asterix135/whoshouldivotefor | explorer/migrations/0007_auto_20170626_0543.py | Python | mit | 1,175 | 0.000851 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-26 09:43
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('explorer', '0006_auto_20170626_0345'),
]
operation... | old_name=' | politician',
new_name='candidate',
),
migrations.AlterField(
model_name='electioncandidate',
name='election',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='candidate_details', to='explorer.Election'),
),
... |
dmlc/tvm | python/tvm/topi/hexagon/conv2d.py | Python | apache-2.0 | 973 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# dis | tributed with this work for additional information
# regarding copyright own | ership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
SebastianoF/LabelsManager | nilabels/agents/header_controller.py | Python | mit | 6,482 | 0.004937 | import nibabel as nib
import numpy as np
from nilabels.tools.aux_methods.utils_rotations import get_small_orthogonal_rotation
from nilabels.tools.aux_methods.utils_path import get_pfi_in_pfi_out, connect_path_tail_head
from nilabels.tools.aux_methods.utils_nib import modify_image_data_type, \
modify_affine_transfo... | fo_in = input_data_folder
self.pfo_out = output_data_folder
def modify_image_type(self, filename_in, filename_out, new_dtype, update_description=None, verbose=1):
"""
Change data type and optionally update the nifti field descriptor.
:param filename_in: path to filename input
... | ng with the new 'descrip' nifti header value.
:param verbose:
:return: image with new dtype and descriptor updated.
"""
pfi_in, pfi_out = get_pfi_in_pfi_out(filename_in, filename_out, self.pfo_in, self.pfo_out)
im = nib.load(pfi_in)
new_im = modify_image_data_type(im, n... |
aliceinit/todogen | todogen_utils/todo_generator.py | Python | gpl-3.0 | 690 | 0.005797 | __author__ = 'aliceinit'
import heapq
from todogen_utils.todogen_task import TodoTask
class TodoGenerator(object):
# todo add required place for tasks, set (optionally) places for free time period | s
# todo add weather requirements for tasks (optionally) - connect to weather APIs
def __init__(self, task_manager, schedule_manager):
self.task_manager = task_manager
self.schedule_manager = schedule_manager
self.task_heap = []
def prioritize(self):
self.task_heap = []
... | todo_task)
|
citrix-openstack-build/python-openstackclient | openstackclient/tests/common/test_clientmanager.py | Python | apache-2.0 | 1,180 | 0 | # Copyright 2012-2013 OpenStack, 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 ... | one time and always returns the same value after that.
c = Container()
self.assertEqu | al(c.attr, c.attr)
|
brolewis/oracle_of_kirk | oracle.py | Python | bsd-3-clause | 12,551 | 0.000159 | #!/usr/bin/env python2.7
# Standard Library
import argparse
import collections
import os
import re
import xml.etree.cElementTree
# Third Party
import imdb
import imdb.helpers
import mediawiki
import sqlalchemy
import sqlalchemy.ext.declarative
import sqlalchemy.ext.hybrid
import sqlalchemy.orm
CANON = {'"Star Trek" (... | kref='appearance')
def __repr__(self):
return self.title
class Article(BASE):
__tablename__ = 'article' |
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
title = sqlalchemy.Column(sqlalchemy.String)
text = sqlalchemy.Column(sqlalchemy.String)
character_id = sqlalchemy.Column(sqlalchemy.Integer,
sqlalchemy.ForeignKey('character.id'))
appearance_id = sqla... |
kichkasch/ioids | g4ds/protocols/protocolinterface.py | Python | gpl-3.0 | 1,822 | 0.008233 | """
Provides the interface, each protocol implementation must implement to work with G4DS.
| Grid for Digital Security (G4DS)
@author: Michael Pilgermann
@contact: mailto:[email protected]
@license: GPL (General Public License)
"""
class ProtocolInterface:
"""
Provides a common interface for all implementations for protocols.
@ivar _name: Name of the Implementation
| @type _name: C{String}
"""
def __init__(self, name):
"""
Just ot set up the name of the implementation.
"""
self._name = name
def getName(self):
"""
GETTER
"""
return self._name
def listen(self, callback):
"""
... |
jjas0nn/solvem | tensorflow/lib/python2.7/site-packages/numpy/lib/tests/test_packbits.py | Python | mit | 3,214 | 0 | from __future__ import division, absolute_import, print_function
import numpy as np
from numpy.testing import assert_array_equal, assert_equal, assert_raises
def test_packbits():
# Copied from the docstring.
a = [[[1, 0, 1], [0, 1, 0]],
[[1, 1, 0], [0, 0, 1]]]
for dt in '?bBhHiIlLqQ':
ar... | (0, 0, 0), (0, 0, 0)], (0, 0, 0)),
]
for in_shapes, out_shap | e in shapes:
for ax, in_shape in enumerate(in_shapes):
a = np.empty(in_shape, dtype=np.uint8)
b = np.unpackbits(a, axis=ax)
assert_equal(b.dtype, np.uint8)
assert_equal(b.shape, out_shape)
|
QuantCrimAtLeeds/PredictCode | tests/gui/predictors/sepp2_test.py | Python | artistic-2.0 | 2,313 | 0.017294 | from .helper import *
import open_cp.gui.predictors.sepp2 as sepp2
import open_cp.gui.predictors.predictor
#import datetime
@pytest.fixture
def analysis_model2(analysis_mod | el):
analysis_model.time_range = (datetime.datetime(2017,5,21,12,30),
datetime.datetime(2017,5,21,13,30), None, None)
return analysis_model
@mock.patch("open_cp.seppexp")
def test_SEPP(seppmock, model, project_task, analysis_model2, grid_task):
provider = sepp2.SEPP(model)
... | ing is None
standard_calls(provider, project_task, analysis_model2, grid_task)
def test_serialise(model, project_task, analysis_model2, grid_task):
serialise( sepp2.SEPP(model) )
def test_no_data(model, project_task, analysis_model, grid_task):
analysis_model.time_range = (datetime.datetime(2017,5,20,12,3... |
ndawe/rootpy | rootpy/tests/test_decorators.py | Python | bsd-3-clause | 2,286 | 0.001312 | from rootpy import ROOT
from rootpy.base import Object
from rootpy.decorators import (method_file_check, method_file_cd,
snake_case_methods)
from rootpy.io import TemporaryFile
import rootpy
from nose.tools import assert_equal, assert_true, raises
def test_snake_case_methods():
cla... | the types
# are the same between B and snakeB.
for member in dir(snakeB):
if member.startswith("_"): continue
assert_equal(type(getattr(B, member)), type(getattr(snakeB, member)))
class Foo(Object, ROOT.R.TH1D):
@method_file_check
def something(self, foo):
self.file = ROOT.gD... | ectory
return foo
@method_file_cd
def write(self):
assert_true(self.GetDirectory() == ROOT.gDirectory)
def test_method_file_check_good():
foo = Foo()
with TemporaryFile():
foo.something(42)
#@raises(RuntimeError)
#def test_method_file_check_bad():
# foo = Foo()
# foo.s... |
Eliel-Lopes/Python-URI | 1003.py | Python | mit | 75 | 0.026667 | A = int(in | put())
B = int(input())
SOMA = (A + B)
print("SOMA = % | d" %SOMA)
|
mattrobenolt/warehouse | tasks/__init__.py | Python | apache-2.0 | 673 | 0 | # Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the | License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distr | ibuted 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.
import invoke
from . import release
from . import static
ns = invoke.Collection(release, static)
|
lecly/pymongo-driver | tests/data/for_purifier.py | Python | mit | 2,478 | 0.000404 | #!/usr/bin/env python
# vim: set fileencoding=utf-8 :
_str_field = 789
_int_field = '123'
_float_field = '123.45'
_bool_field = 'x'
_int_field_default_none = None
_tuple_int_field = ('12', '23')
_list_str_field = [78, 89]
def data_input():
source = {
'str_field': _str_field,
'int_field': _int_fie... | str_field,
}
return _data_build(source)
def data_output():
source = {
'str_field': str(_str_field),
'int_field': int(_int_field),
'float_field': float(_float_field),
'bool_field': bool(_bool_field),
'int_field_default_none': None if _int_field_default_none is None e... | r i in _tuple_int_field),
'list_str_field': list(str(s) for s in _list_str_field),
}
return _data_build(source)
def _data_build(source):
str_field = source.get('str_field')
int_field = source.get('int_field')
float_field = source.get('float_field')
bool_field = source.get('bool_field')... |
brianrodri/oppia | core/controllers/practice_sessions.py | Python | apache-2.0 | 3,351 | 0.000298 | # Copyright 2018 The Oppia 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 applicable ... | 'topic_name': topic.name,
'skill_ids_to_descriptions_map': skill_ids_to_descriptions_map
})
self.render_json(self.values)
| |
warner/magic-wormhole-transit-relay | misc/migrate_usage_db.py | Python | mit | 1,883 | 0 | """Migrate the usage data from the old bundled Transit Relay database.
The magic-wormhole package used to include both servers (Rendezvous and
Transit). "wormhole server" started both of these, and used the
"relay.sqlite" database to store both immediate server state and long-term
usage data.
These were split out to ... | sage.sqlite"
database in the current directory.
It will refuse to touch an existing "usage.sqlite" file.
The resuting "usage.sqlite" should be passed into --usage-db=, e.g. "twist
transitrelay --usage=.../PATH/TO/usage.sqlite".
"""
from __future__ import unicode_l | iterals, print_function
import sys
from wormhole_transit_relay.database import open_existing_db, create_db
source_fn = sys.argv[1]
source_db = open_existing_db(source_fn)
target_db = create_db("usage.sqlite")
num_rows = 0
for row in source_db.execute("SELECT * FROM `transit_usage`"
" ORDE... |
maxime-beck/compassion-modules | partner_communication_revision/wizards/submit_revision_wizard.py | Python | agpl-3.0 | 2,059 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <[email protected]>
#
# The licence is in the file __manifest__.py... | elf._context['active_id'])
@api.multi
def submit | (self):
self.ensure_one()
revision = self.revision_id
if self.state == 'pending':
subject_base = u'[{}] Revision text submitted'
body_base = u'A new text for was submitted for approval. {}'
revision.write({
'proposition_correction':
... |
elifesciences/elife-tools | tests/fixtures/test_refs/content_07_expected.py | Python | mit | 1,260 | 0.003175 | from collections import OrderedDict
expected = [
{
"uri_text": "http://www.ncbi.nlm.nih.gov/nuccore/120407038",
"comment": "http://www.ncbi.nlm.nih.gov/nuccore/120407038",
"data-title": "Mus musculus T-box 2 (Tbx2), mRNA",
"article_doi": "10.5334/cstp.77",
"authors": | [
{"surname": "Bollag", "given-names": "RJ", "group-type": "author"},
{"surname": "Siegfried", "given-names": "Z", "group-type": "author"},
{"surname": "Cebra-Thomas", "gi | ven-names": "J", "group-type": "author"},
{"surname": "Garvey", "given-names": "N", "group-type": "author"},
{"surname": "Davison", "given-names": "EM", "group-type": "author"},
{"surname": "Silver", "given-names": "LM", "group-type": "author"},
],
"accession": "NM_00... |
bioinform/somaticseq | somaticseq/combine_callers.py | Python | bsd-2-clause | 22,749 | 0.018243 | #!/usr/bin/env python3
import os, re, subprocess
import somaticseq.vcfModifier.copy_TextFile as copy_TextFile
import somaticseq.vcfModifier.splitVcf as splitV | cf
import somaticseq.vcfModifier.getUniqueVcfPositions as getUniqueVcfPositions
from somaticseq.vcfModifier.vcfIntersector import *
# Combine individual VCF output into a simple combined VCF file, for single-sample callers
def comb | ineSingle(outdir, ref, bam, inclusion=None, exclusion=None,
mutect=None, mutect2=None, varscan=None, vardict=None, lofreq=None, scalpel=None, strelka=None,
arb_snvs=None, arb_indels=None, keep_intermediates=False):
if arb_snvs is None: arb_snvs = []
if arb_indels is No... |
mtreinish/stestr | stestr/tests/test_selection.py | Python | apache-2.0 | 7,058 | 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 at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | elf):
test_list = ['a', 'b', 'c']
result = selection.filter_tests(None, test_list)
self.assertEqual(test_list, result)
def test_filter_tests(self):
test_list = ['a', 'b', 'c']
result = selection.filter_tests(['a'], test_list)
self.assertEqual(['a'], result)
def ... | ction.filter_tests,
['fake_regex_with_bad_part[The-BAD-part]'],
test_list)
mock_exit.assert_called_once_with(5)
class TestExclusionReader(base.TestCase):
def test_exclusion_reader(self):
exclude_list = io.StringIO()
for i in ... |
ml31415/numpy-groupies | numpy_groupies/tests/__init__.py | Python | bsd-2-clause | 2,023 | 0.00346 | import pytest
from .. import aggregate_purepy, aggregate_numpy_ufunc, aggregate_numpy
try:
from .. import aggregate_numba
except ImportError:
aggregate_numba = None
try:
from .. import aggregate_weave
except ImportError:
aggregate_weave = None
try:
from .. import aggregate_pandas
except ImportError... | y_impl_name.get | (func, None)
if wrap_funcs is None or func in wrap_funcs:
pytest.xfail("Functionality not implemented")
else:
raise e
if name:
_try_xfail.__name__ = name
else:
_try_xfail.__name__ = impl.__name__
return _try_xfail
func_list = ('sum', ... |
ceibal-tatu/sugar-toolkit | tests/graphics/toolbarpalettes.py | Python | lgpl-2.1 | 1,649 | 0 | # Copyright (C) 2007, Red Hat, Inc.
# |
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the | Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General P... |
deerwalk/voltdb | lib/python/voltcli/checkstats.py | Python | agpl-3.0 | 18,888 | 0.006777 | # This file is part of VoltDB.
# Copyright (C) 2008-2017 VoltDB Inc.
#
# 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 ver... | notifyInterva | l = 10
if last_table_stat_time > 1 and export_tables_with_data:
print_export_pending(runner, export_tables_with_data)
lastUpdatedTime = monitorStatisticsProgress(last_export_tables_with_data, export_tables_with_data, lastUpdatedTime, runner, 'Exporter')
last_export_ta... |
BlackVikingPro/D.A.B. | dab.py | Python | gpl-3.0 | 14,157 | 0.043205 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
""" Python DAB ~ DoS Tool ~ By Wįłłý Fœx : @BlackVikingPro """
""" Current Version: v2.0 """
"""
Python D.A.B. [ |)3|\|`/ 411 |31T(|-|3z ] ~ DoS Tool ~ By Wįłłý Fœx : @BlackVikingPro
Use at your own risk. I do/will not condone any illegal activity
I'm not responsible f... | sys.argv:
s_option_pos = sys.argv.index('-s')
target = sys.argv[(s_option_pos + 1)]
elif '--server' in sys.argv:
s_option_pos = sys.argv.index('--server')
target = sys.argv[(s_option_pos + 1)]
else:
error("Error: Server not defined.")
usage()
sys.exit()
pass
if '-p' in sys.argv:
p_option_pos = sy... | f '--port' in sys.argv:
p_option_pos = sys.argv.index('--port')
port = sys.argv[(p_option_pos + 1)]
elif '--port-threading' in sys.argv:
port = 1
else:
error("Error: Port not defined.")
usage()
sys.exit()
pass
if '-t' in sys.argv:
t_option_pos = sys.argv.index('-t')
_type = sys.argv[(t_option_pos... |
videntity/tweatwell | apps/tips/models.py | Python | gpl-2.0 | 440 | 0.022727 | from django | .db import models
class Tip | (models.Model):
text = models.TextField(max_length=1000)
date = models.DateField(auto_now_add=True)
class Meta:
ordering = ['-date']
def __unicode__(self):
return '%s ' % (self.text)
class CurrentTip(models.Model):
index = models.IntegerField(max_length... |
2Checkout/2checkout-python | twocheckout/sale.py | Python | mit | 3,388 | 0.003542 | from api_request import Api
from util import Util
from twocheckout import Twocheckout
class Sale(Twocheckout):
def __init__(self, dict_):
super(self.__class__, self).__init__(dict_)
@classmethod
def find(cls, params=None):
if params is None:
params = dict()
response = ... | is None:
params = dict | ()
if hasattr(self, 'lineitem_id'):
params['lineitem_id'] = self.lineitem_id
url = 'sales/refund_lineitem'
elif hasattr(self, 'invoice_id'):
params['invoice_id'] = self.invoice_id
url = 'sales/refund_invoice'
else:
params['sale_id'] = s... |
SnakeHunt2012/word2vec | post-process/exclusion.py | Python | apache-2.0 | 24,401 | 0.005128 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from re import compile
from copy import copy, deepcopy
from codecs import open
from argparse import ArgumentParser
from itertools import product
DEBUG_FLAG = False
def duration(start, end):
second = (end - start) % 60
minute = (end - start) % 3600 / 60
hour ... | ix_list = []
for natitionality in nationality_list:
location_suffix_list.append(natitionality)
if len(natitionality.decode("utf-8")) > 2:
lo | cation_suffix_list.append(natitionality[:-len("族")])
location_suffix_list = product(location_suffix_list, ["自治区", "自治州", "自治县"])
location_suffix_list = ["".join([a, b]) for a, b in location_suffix_list]
location_suffix_list.extend(["土家族苗族自治县", "依族苗族自治县", "苗族瑶族傣族自治县", "布依族苗族自治州", "回族彝族自治县", "哈尼族彝族傣族自治县", "壮族... |
neuroneuro15/aspp-test | counter.py | Python | gpl-2.0 | 18 | 0.055556 | print(range | (10)) | |
philrosenfield/ResolvedStellarPops | utils/mpfit/mpfit.py | Python | bsd-3-clause | 93,267 | 0.000729 | """
Perform Levenberg-Marquardt least-squares minimization, based on MINPACK-1.
AUTHORS
The original version of this software, called LMFIT, was written in FORTRAN
as part of the MINPACK-1 package by XXX.
Craig Markwardt converted the FORTRAN code to IDL. The information for ... | d.
MPFIT does not perfor | m more general optimization tasks. See TNMIN
instead. MPFIT is customized, based on MINPACK-1, to the
least-squares minimization problem.
USER FUNCTION
The user must define a function which returns the appropriate
values as specified above. The function should return the weighte... |
openstack/taskflow | taskflow/examples/resume_vm_boot.py | Python | apache-2.0 | 9,636 | 0.000934 | # -*- coding: utf-8 -*-
# Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... | tarting vm creation.", no_slow=True),
lf.Flow('vm-maker').add(
# First create a specification for the final vm to-be.
DefineVMSpec("define_spec"),
# This does all the | image stuff.
gf.Flow("img-maker").add(
LocateImages("locate_images"),
DownloadImages("download_images"),
),
# This does all the network stuff.
gf.Flow("net-maker").add(
AllocateIP("get_my_ips"),
CreateNetwor... |
firi/appengine-btree | btree/btree_test.py | Python | mit | 26,756 | 0.001644 | """
Tests for the BTrees.
"""
import logging
import unittest
from google.appengine.ext import ndb
from google.appengine.ext import testbed
from google.appengine.datastore import datastore_stub_util
from . import BTree, MultiBTree, MultiBTree2
import internal
class BTreeTestBase(unittest.TestCase):
def setUp(sel... | tree
itself and the root node. No indices, no other nodes.
"""
first = tree.key
last = | ndb.Key(first.kind(), first.id() + u"\ufffd")
q = ndb.Query(ancestor=first)
q = q.filter(tree.__class__.key < last)
keys = list(q.iter(keys_only=True))
self.assertEqual(keys, [first, tree._make_node_key("root")])
def test_create(self):
tree = BTree.create("tree", 2)
... |
deka108/meas_deka | apiv2/utils/text_util.py | Python | apache-2.0 | 2,391 | 0.000418 | import re
from nltk.corpus import stopwords
from nltk.corpus import words
from nltk.stem.snowball import SnowballStemmer
from apiv2.models import QuestionText, Question
from apiv2.search.fsearch import formula_extractor as fe
cachedStopWords = stopwords.words("english")
english_vocab = set(w.lower() for w in words.wo... | emmer.stem(word) for word in text.split()])
def preprocess(text, **kwargs):
preprocessed_text = text
# Recognise and remove LaTeX (detect formula function)
preprocessed_text = clean_latex(preprocessed_text)
# Remove non alphabetical characters
preprocessed_text = remove_non_alphabet(preprocessed... | er words
if kwargs.get("english", True):
preprocessed_text = english_only(preprocessed_text)
if kwargs.get("stem", True):
preprocessed_text = stem_text(preprocessed_text)
return preprocessed_text
def preprocess_unique(text, **kwargs):
results = preprocess(text, **kwargs).split()
... |
tbs1980/cosmo-codes | peebles/larura_pcl.py | Python | mpl-2.0 | 5,243 | 0.040244 | from subprocess import call
import matplotlib.pyplot as plt
import numpy as np
import healpy as hp
import sys
import time
map_to_alm='Map2Alm'
alm_to_cl='Alm2Cl'
spice_data='spice_data.fits'
spice_data_alm='spice_data_alm.fits'
spice_noise='spice_noise.fits'
spice_noise_alm='spice_noise_alm.fits'
spice_mask='spice_ma... | B_l_in = np.loadtxt(beam_file,delimiter=",")
np.savetxt(spice_bl,np.asarray([B_l_in[:,0],B_l_in[:,1]]).T,fmt='%d %0.2f')
B_l = B_l_in[:,1]
#compute the powe spectrum of the data
call([map_to_alm,'-I',spice_data,'-O',spice_data_alm,'-L',str(2*nside),'-m',spice_mask])
call([alm_to_cl,'-I',spice_d... | dl,'-P','-m',spice_mask,'-G','-C',spice_ilm_jlm,'-M',spice_data,'-N',str(nside),'-L',str(2*nside+1)])
call(['rm',spice_data_alm])
call(['rm',spice_data])
#read the power spectrum
D_l = np.loadtxt(spice_dl,skiprows=2)[:,1]
#apply beam to the cls
D_l /= B_l**2
#compute the noise power spec... |
yucefsourani/Cnchi | cnchi/download/download_requests.py | Python | gpl-3.0 | 7,157 | 0.001956 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# download_requests.py
#
# Copyright © 2013-2015 Antergos
#
# This file is part of Cnchi.
#
# Cnchi 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 ... | break
else:
download_error = True
msg = _("Can't download {0}, Cnchi will try another mirror.").format(url)
# completed_length = 0
logging.warning(msg)
if download_error:
... | msg = _("Can't download {0}, even after trying all available mirrors")
msg = msg.format(element['filename'])
all_successful = False
logging.error(msg)
downloads_percent = round(float(downloaded / total_downloads), 2)
self.que... |
dimddev/NetCatKS | NetCatKS/Components/api/interfaces/factories/__init__.py | Python | bsd-2-clause | 65 | 0 | """
A good p | lace for fatories interfaces
"""
__author_ | _ = 'dimd'
|
hesam-setareh/nest-simulator | pynest/nest/tests/test_siegert_neuron.py | Python | gpl-2.0 | 4,811 | 0 | # -*- coding: utf-8 -*-
#
# test_siegert_neuron.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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 Lic... | diffusion_connection'}
nest.Connect(
self.siegert_drive, self.siegert_neuron, syn_spec=syn_dict)
self.multimeter = nest.Create(
"multimeter", params={'record_from': ['rate'],
| 'interval': self.dt})
nest.Connect(
self.multimeter, self.siegert_neuron)
def test_RatePrediction(self):
"""Check the rate prediction of the siegert neuron"""
# simulate
nest.Simulate(self.simtime)
# get rate prediction from siegert neuron
... |
rafa400/telepi | script.telepi-master/addon.py | Python | gpl-2.0 | 669 | 0.031484 | import xbmcaddon
import xbmcgui
import subprocess,os
def EstoEsUnaFun( str ):
xbmcgui.Dialog().ok("ESO ES" | ,"AHHHH",str)
return
addon = xbmcaddon.Addon()
addonname = addon.getAddonInfo('name')
line1 = "Hello World!"
line2 = "We can write anything we want here"
line3 = "Using Python"
my_s | etting = addon.getSetting('my_setting') # returns the string 'true' or 'false'
addon.setSetting('my_setting', 'false')
os.system("echo caca>>/home/rafa400/caca.txt")
dia=xbmcgui.Dialog();
dia.addControl(xbmcgui.ControlLabel(x=190, y=25, width=500, height=25, label="Hoooolaa"))
dia.ok(addonname, line1, line2, line3 + ... |
pcamp/google-appengine-wx-launcher | launcher/taskcontroller.py | Python | apache-2.0 | 12,617 | 0.005627 | #!/usr/bin/env python
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | t with Stop/Run for easier testing)
"""
[t.stop() for t in self._threads] # t.stop() is async.
def _FindThreadForProject(self, project):
"""Find and return the launcher.TaskThread for project, or None.
Args:
pr | oject: the project whose thread we are looking for
"""
for thread in self._threads:
if thread.project == project:
return thread
return None
def Logs(self, event):
"""Display the Console window for the project(s) selected in the main frame.
Called directly from UI.
"""
for p... |
jepegit/cellpy | dev_utils/helpers/performance.py | Python | mit | 2,592 | 0.002315 | import os
import sys
import time
print(f"running {sys.argv[0]}")
import cellpy
from cellpy import cellreader, log
from cellpy.parameters import prms
# -------- defining overall path-names etc ----------
current_file_path = os.path.dirname(os.path.realpath(__file__))
relative_test_data_dir = "../testdata"
test_data_d... | ----------------finished------------------")
report_time(t1, t2)
def missing_stats_file():
d = cellreader.CellpyData()
raw_file_loader = d.l | oader
test = raw_file_loader(new_arbin_file)
d.cells.append(test[0])
d.set_mass(new_arbin_mass)
d.make_summary(use_cellpy_stat_file=False)
if __name__ == "__main__":
missing_stats_file()
|
aarongarrett/inspyred | inspyred/swarm/topologies.py | Python | mit | 4,282 | 0.008174 | """
=====================================
:mod:`topologies` -- Swarm topologies
=====================================
This module defines various topologies for swarm intelligence algorithms.
Particle swarms make use of topologies, which determine the logical
relationships among partic... | this permission notice shall be included in
all copies or substantial portions of the Software.
.. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO | THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH TH... |
ArcherSys/ArcherSys | Lib/lib2to3/fixes/fix_exec.py | Python | mit | 3,143 | 0.007636 | <<<<<<< HEAD
<<<<<<< HEAD
# Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Fixer for exec.
This converts usages of the exec statement into calls to a built-in
exec() function.
exec code in ns1, ns2 -> exec(code, ns1, ns2)
"""
# Local imports
from .. import pytre... | (' [any] ')'>) a=any >
"""
def transform(self, node, results):
assert results
syms = self.syms
a = results["a"]
b = results.get("b")
c = results.get("c")
args = [a.clone()]
args[0].prefix = ""
if b is | not None:
args.extend([Comma(), b.clone()])
if c is not None:
args.extend([Comma(), c.clone()])
return Call(Name("exec"), args, prefix=node.prefix)
=======
# Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Fixer for exec.
Th... |
rowinggolfer/openmolar2 | configure.py | Python | gpl-3.0 | 6,157 | 0.012993 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
## ##
## Copyright 2011-2012, Neil Wallace <[email protected]> ##
## ... | r the namespace"
)
option = self.add_option("-a", "--admin",
dest = "admin",
action="store_true", default=False,
help = "pa | ckage or install sources for the admin application"
)
option = self.add_option("-c", "--client",
dest = "client",
action="store_true", default=False,
help = "package or install sources for the client application"
... |
mawenbao/pelican-blog-content | plugins/summary/summary.py | Python | bsd-3-clause | 1,503 | 0.002001 | # -*- encoding: UTF-8 -*-
from __future__ import unicode_literals
from HTMLParser import HTMLParser
from pelican import signals, contents
_MAX_SUMMARY_POS = 45
class FirstParagraphParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.paragraphTag = 'p'
self.data = ''
... | content = instance._content
firstP = FirstParagraphParser()
firstP.feed(content)
endCharA = '。'
endCharB = '.'
endPosA = firstP.data.find(endCharA)
endPosB = firstP.data.find(endCharB)
endPos = min(max(endPosA, endPosB), _MAX_SUMMARY_POS)
instance._su... | ontent_object_init)
|
NikolausDemmel/catkin_tools | docs/conf.py | Python | apache-2.0 | 8,535 | 0.005272 | # -*- coding: utf-8 -*-
#
# catkin_tools documentation build configuration file, created by
# sphinx-quickstart on Mon Feb 24 18:03:21 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.
... | phinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
... | th) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "d... |
hacktyler/hacktyler_crime | sirens/urls.py | Python | mit | 250 | 0.008 | #!/usr/bin/en | v python
from django.conf.urls.defaults import patterns, url
from sirens import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^pusher/auth$', views.pusher_user_auth, name='pusher_user_auth') |
)
|
Microvellum/Fluid-Designer | win64-vc/2.78/scripts/addons/cycles/__init__.py | Python | gpl-3.0 | 3,600 | 0.001667 | #
# Copyright 2011-2013 Blender Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache | .org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, 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.
#
# <pep8 compliant>
bl_info = {
"name": "Cycles Render Engine",
"author": "",
"blen... |
jmluy/xpython | exercises/practice/custom-set/.meta/example.py | Python | mit | 1,184 | 0 | class CustomSet:
def __init__(self, elements=None):
self.elements = list(elements) if elements is not None else list([])
def isempty(self):
return no | t self.elements
def __iter__(self):
return iter(self.elements)
def __contains__(self, element):
return element in self.elements
def issubset(self, other):
return all(idx in other for idx in self)
def isdisjoint(self, other):
return all(idx not in other | for idx in self)
def __eq__(self, other):
return self.issubset(other) and other.issubset(self)
def add(self, element):
if element not in self:
self.elements.append(element)
def intersection(self, other):
result = CustomSet()
for idx in self:
if idx ... |
openego/dingo | ding0/core/network/cable_distributors.py | Python | agpl-3.0 | 2,143 | 0.007933 | """This file is part of DING0, the DIstribution Network GeneratOr.
DING0 is a tool to generate synthetic medium and low voltage power
distribution grids based on open data.
It is developed in the project open_eGo: https://openegoproject.wordpress.com
DING0 lives at github: https://github.com/openego/ding0/
The docume... | '_'.join(['MV', str(self.grid.id_db),
'cld', str(self.id_db)])
def __repr__(self):
return 'mv_cable_dist_' + repr(self.grid) + '_' + str(self.id_db)
class LVCableDistributorDing0(CableDistributorDing0):
""" LV Cable distributor (connection point)
Attributes... | Description #TODO
in_building :
Description #TODO
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.string_id = kwargs.get('string_id', None)
self.branch_no = kwargs.get('branch_no', None)
self.load_no = kwargs.get('load_no', None)
... |
michaelchu/kaleidoscope | kaleidoscope/options/iterator/option_chain.py | Python | mit | 849 | 0 | from kaleidoscope.event import DataEvent
from kaleidoscope.options.option_query import OptionQuery
class O | ptionChainIterator(object):
def __init__(self, data):
self.data = data
# get all quote dates that can be iterated
self.dates = sorted(data['quote_date'].unique())
# turn list of dates into an iterable
self.dates = iter(self.dates)
def __iter__(self):
return self... | option_chains = df.loc[df['quote_date'] == quote_date]
# create the data event and return it
return DataEvent(quote_date, OptionQuery(option_chains))
except StopIteration:
raise
|
flav-io/flavio | flavio/functions.py | Python | mit | 13,966 | 0.00222 | """Main functions for user interaction. All of these are imported into the
top-level namespace."""
import | flavio
import numpy as np
from collections import defaultdict
from multiprocessing import Pool
from functools import partial
import warnings
def np_prediction(obs_name, wc_obj, *args, **kwargs):
"""Get the central value of the new physics prediction of an observable.
Parameters
----------
- `obs_nam... | `: name of the observable as a string
- `wc_obj`: an instance of `flavio.WilsonCoefficients`
Additional arguments are passed to the observable and are necessary,
depending on the observable (e.g. $q^2$-dependent observables).
"""
obs = flavio.classes.Observable[obs_name]
return obs.prediction_c... |
looker-open-source/sdk-codegen | examples/python/lookersdk-flask/app/auth.py | Python | mit | 2,667 | 0.001125 | import functools
import os
import flask
import werkzeug.security
from .db import get_db
from .looker import get_my_user
bp = flask.Blueprint("auth", __name__, url_prefix="/auth")
@bp.route("/register", methods=("GET", "POST"))
def register():
if flask.request.method == "POST":
username = flask.request.f... | def login():
if flask.request.method == "POST":
username = flask.request.form["usern | ame"]
password = flask.request.form["password"]
db = get_db()
error = None
user = db.execute(
"SELECT * FROM user WHERE username = ?", (username,)
).fetchone()
if user is None:
error = "Incorrect username."
elif not werkzeug.security.check... |
anshulthakur/ClusterManager | src/docGen.py | Python | gpl-2.0 | 8,148 | 0.026141 | """
A script to extract description from my Code into MD format, for documentational purpose
Source format:
/**STRUCT+********************************************************************/
/* Structure: HM_NOTIFICATION_CB */
/* */
/* N... | ^/\*\s?(?P<line>.*)\*/')
struct_comment_boundary = re.compile(r'^/\*(\*)+\*/')
struct_start = re.compile(r'^\s?(?P<line>typedef\s+struct\s+\w+.*)')
struct_var_declaration = re.compile(r'^\s*(?P<type>\w)\s+(?P<var_name>\w)\s?;.*')
struct_end = re.compile(r'^\s?(}\s+(?P<name>\w)\s?;)')
struct_end_re = re.compile(r'\*ST... | t sys.argv[1].endswith('.h'):
raise Error("Specified file is not a header file.")
fd = open(sys.argv[1], 'r')
md_target = open('conv.md', 'w')
line_num = 0
#We have the file opened. Now read it line by line and look for beginning of structures:
looking_for_struct_start = True
finding_purpose = False
finding_info = F... |
garvenshen/zeda-swift | swift/common/manager.py | Python | apache-2.0 | 21,270 | 0.000047 | # Copyright (c) 2010-2012 OpenStack, 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 agreed to ... | that
aren't responding to signals.
:param server_pids: a dict, lists of pids [int,...] keyed on
Server objects
"""
statu | s = {}
start = time.time()
end = start + interval
server_pids = dict(server_pids) # make a copy
while True:
for server, pids in server_pids.items():
for pid in pids:
try:
# let pid stop if it wants to
os.waitpid(pid, os.WNOHANG... |
SixTrack/SixTrack | test/chebythin6d/cheby_plot_map.py | Python | lgpl-2.1 | 3,183 | 0.051838 | '''
color code of points:
- black: outside R2 or inside R1 (check);
- colored: inside R2 and outside R1 (check);
- magenta: outside R2 or inside R1 (check) but wronlgy labelled as inside;
- white: inside R2 and outside R1 (check) but wronlgy labelled as outside;
'''
import matplotlib.pyplot as plt
import numpy as np
... | np.loadtxt('cheby%s_pot.dat'%(jj+1))
ids_in=np.where(mapIn[:,5]!=0)[0] # flagged as in by 6T
ids_out=np.where(mapIn[:,5]==0)[0] # flagged as out by 6T
xx=mapIn[:,0]-offx[jj]
yy=mapIn[:,1]-offy[jj]
angles=np.arctan2(yy,xx)-cAngles[jj]
rr=np.sqrt(xx**2+yy**2)
xx=rr*np.cos(angles)
yy=rr*np.sin(angles)
... | ]*gteps) )) [0]
idc_in =np.where(np.logical_not( np.logical_or( np.logical_and(xx<R1[jj]*lteps,yy<R1[jj]*lteps), np.logical_or(xx>R2[jj]*gteps,yy>R2[jj]*gteps) )))[0]
for ii in range(len(coords)):
plt.subplot(nRows,nCols*len(coords),ii+jj*len(coords)+1)
# points outside domain (black)
plt.scatter(mapIn... |
openstack/sahara | sahara/tests/unit/service/edp/data_sources/base_test.py | Python | apache-2.0 | 2,415 | 0.00207 | # Copyright (c) 2017 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | es.base import DataSourceType
import testtools
class DataSourceBaseTestCase(testtools.TestCase):
def setUp(self):
super(DataSourceBaseTestCase, self).setUp()
self.ds_base = DataSourceType()
def test_construct_url_no_placeholders(self):
base_url = "swift://container/in | put"
job_exec_id = uuidutils.generate_uuid()
url = self.ds_base.construct_url(base_url, job_exec_id)
self.assertEqual(base_url, url)
def test_construct_url_job_exec_id_placeholder(self):
base_url = "swift://container/input.%JOB_EXEC_ID%.out"
job_exec_id = uuidutils.generat... |
akhavr/OpenBazaar | tests/test_db_store.py | Python | mit | 5,980 | 0.000502 | import os
import tempfile
import unittest
from node import db_store, setup_db
class TestDbOperations(unittest.TestCase):
"""Test DB operations in an unencrypted DB."""
disable_sqlite_crypt = True
@classmethod
def setup_path(cls):
cls.db_dir = tempfile.mkdtemp()
cls.db_path = os.path... | re.Obdb(
self.db_path,
disable_sqlite_crypt=self.disable_sqlite_crypt
)
def test_insert_select_operations(self):
# Cre | ate a dictionary of a random review
review_to_store = {"pubKey": "123",
"subject": "A review",
"signature": "a signature",
"text": "Very happy to be a customer.",
"rating": 10}
# Use the insert o... |
rigetticomputing/pyquil | pyquil/latex/tests/test_latex.py | Python | apache-2.0 | 4,016 | 0.001245 | import pytest
from pyquil.quil import Program, Pragma
from pyquil.quilbase import Declare, Measurement, JumpTarget, Jump
from pyquil.quilatom import MemoryReference, Label
from pyquil.gates import H, X, Y, RX, CZ, SWAP, MEASURE, CNOT, WAIT, MOVE
from pyquil.latex import to_latex, DiagramSettings
from pyquil.latex._dia... | [2.0]))
with pytest.raises(ValueError):
_ = to_latex(p)
def test_gate_group_pragma():
"Check that to_lat | ex does not fail on LATEX_GATE_GROUP pragma."
p = Program()
p.inst(Pragma("LATEX_GATE_GROUP", [], "foo"), X(0), X(0), Pragma("END_LATEX_GATE_GROUP"), X(1))
_ = to_latex(p)
def test_fail_on_bad_pragmas():
"Check that to_latex raises an error when pragmas are imbalanced."
# missing END_LATEX_GATE_GR... |
mitschabaude/nanopores | scripts/pughpore/new_sobol_points.py | Python | mit | 6,272 | 0.064413 | import sys
from math import sqrt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
#from numpy.random import random
import matplotlib.pyplot as plt
from folders import fields
import nanopores.geometries.pughpore as pughpore
import nanopores
from sobol.sobol_seq import i4_sobol_generate as sobol
up = nanopores... | pore,-.5*l1,size,5,5)
surfx(0.,.5*l2,.5*hpore-h2,.5*hpore-h1,-.5*l2,size,5,5)
surfx(0.,.5*l3,-.5*hpore,.5*hpore-h2,-.5*l3,size,5,5)
surfx(0.,.5*l0,-.5*hpore+hmem,.5*hpore,-.5*l0,size,5,5)
ax.scatter(X,Y,Z)
ax.sc | atter(X,-Y,Z)
ax.scatter(-X,Y,Z)
ax.scatter(-X,-Y,Z)
ax.scatter(Y,X,Z)
ax.scatter(Y,-X,Z)
ax.scatter(-Y,X,Z)
ax.scatter(-Y,-X,Z)
plt.tight_layout()
plt.show()
plt.scatter(X_points,Y_points)
plt.plot([0.,1.,1.,0.,0.,1.],[0.,0.,1.,1.,0.,1.],color='blue')
ax=plt.gca()
ax.s... |
xbmcmegapack/plugin.video.megapack.dev | resources/lib/menus/home_countries_saint_pierre_and_miquelon.py | Python | gpl-3.0 | 1,147 | 0.00262 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine ([email protected])
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
| the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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 Gen... | l Public License for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.html
"""
class Countries_Saint_pierre_and_miquelon():
'''Class that manages this specific menu context.'''
def open(self, plu... |
riseml/config-parser | config_parser/sections/deploy.py | Python | mit | 198 | 0.005051 | from .job | s import JobSection
class DeploySection(JobSection):
schema_file = 'deploy.json'
def __init__(self, image, run, **kwargs):
super | (DeploySection, self).__init__(image, run) |
playingaround2017/test123 | gamera/backport/textwrap.py | Python | gpl-2.0 | 13,844 | 0.000939 | """Text wrapping and filling.
"""
# Copyright (C) 1999-2001 Gregory P. Ward.
# Copyright (C) 2002, 2003 Python Software Foundation.
# Written by Greg Ward <[email protected]>
__revision__ = "$Id$"
import string, re
# Do the right thing with boolean values for all known Python versions
# (so this module can be copied... | [strin | g])
Correct for sentence endings buried in 'chunks'. Eg. when the
original text contains "... foo.\nBar ...", munge_whitespace()
and split() will convert that to [..., "foo.", " ", "Bar", ...]
which has one too few spaces; this method simply changes the one
space to two.
... |
uw-it-aca/myuw | myuw/test/dao/test_quicklinks.py | Python | apache-2.0 | 8,048 | 0 | # Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.test import TransactionTestCase
from myuw.models import VisitedLinkNew, CustomLink, PopularLink, User
from myuw.test import get_request_with_user
from myuw.dao.user import get_user_model
from myuw.dao.affiliation import ... | stom_link(req, link1.pk, url2, label2)
self.assertIsNotNone(link2)
self.assertEquals(link2.label, label2)
def test_get_quicklink_data(self):
dat | a = {
"affiliation": "student",
"url": "http://iss1.washington.edu/",
"label": "ISS1",
"campus": "seattle",
"pce": False,
"affiliation": "{intl_stud: True}",
}
plink = PopularLink.objects.create(**data)
username = "jint... |
escapewindow/signingscript | src/signingscript/vendored/mozbuild/mozbuild/test/configure/test_configure.py | Python | mpl-2.0 | 54,289 | 0.000368 | # 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/.
from __future__ import absolute_import, print_function, unicode_literals
from StringIO import StringIO
import os
import... | eOptionValue(),
'WITH_ENV': NegativeOptionValue(),
}, config)
def test_help(self):
help, config = self.get_config(['--help'], prog='configure')
self.assertEquals({}, config)
self.maxDiff = None
self.assertEquals(
'Usage: configure [options]\n'
... | print this message\n'
' --enable-simple Enable simple\n'
' --enable-with-env Enable with env\n'
' --enable-values Enable values\n'
' --without-thing Build without thing\n'
' --with-stuff Bui... |
gregvonkuster/icqsol | tests/testQuadratureCpp.py | Python | mit | 1,770 | 0.007345 | from __future__ import print_function
from ctypes import cdll, POINTER, byref, c_void_p, c_double
import numpy
import pkg_resources
from icqsol.bem.icqQuadrature import triangleQuadrature
import glob
import sys
PY_MAJOR_VERSION = sys.version_info[0]
# On some distributions the fuly qualified shared library name
# inc... | Tests
def func(p):
pNorm = numpy.linalg.norm(p)
return 1.0/(-4*numpy.pi*pNorm)
maxOrder = lib.icqQuadratureGetMaxOrder(byref(handle))
pa = numpy.array([0., 0., 0.])
pb = numpy.array([1., 0., 0.])
pc = numpy.array([0., 1., 0.])
paPtr = pa.ctypes.data_as(POINTER(c_double))
pbPtr = pb.ctypes.data_as(POINTER(c_... | l = lib.icqQuadratureEvaluate(byref(handle), order, paPtr, pbPtr, pcPtr)
integral2 = triangleQuadrature(order=order, pa=pa, pb=pb, pc=pc, func=func)
print('order = ', order, ' integral = ', integral, ' integral2 = ', integral2)
assert(abs(integral - integral2) < 1.e-10)
# Destructor
lib.icqQuadratureDel(by... |
clement-masson/IN104_simulateur | IN104_simulateur/boardState.py | Python | mit | 39 | 0 | f | rom .cpp.boardState import BoardState | |
benjyw/pants | src/python/pants/util/osutil.py | Python | apache-2.0 | 2,336 | 0.001712 | # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, V | ersion 2.0 (see LICENSE).
import errno
import logging
import os
import posix
from functools import reduce
from typing import Optional, Set
logger = logging.getLogger(__name__)
OS_ALIASES = {
"darwin": {"macos", "darwin", "macosx", "mac os x", "mac"},
"linux": {"linux", "linux2"},
}
Pid = int
def get_os_n... | _result = os.uname()
return uname_result[0].lower()
def normalize_os_name(os_name: str) -> str:
"""
:API: public
"""
if os_name not in OS_ALIASES:
for proper_name, aliases in OS_ALIASES.items():
if os_name in aliases:
return proper_name
logger.warning(
... |
heldergg/dre | lib/bs4/__init__.py | Python | gpl-3.0 | 12,881 | 0.001009 | """Beautiful Soup
Elixir and Tonic
"The Screen-Scraper's Friend"
http://www.crummy.com/software/BeautifulSoup/
Beautiful Soup uses a pluggable XML or HTML parser to parse a
(possibly invalid) document into a tree representation. Beautiful Soup
provides provides methods and Pythonic idioms that make it easy to
navigate... | ueError(
"Couldn't find a tree builder with the features you "
"requested: %s. Do you need to install a parser library?"
% ",".join(features))
builder = builder_class()
self.builder = builder
self.is_xml = builder.is_xml
sel... | self.parse_only = parse_only
self.reset()
if hasattr(markup, 'read'): # It's a file-type object.
markup = markup.read()
(self.markup, self.original_encoding, self.declared_html_encoding,
self.contains_replacement_characters) = (
self.builder.prepar... |
google/objax | objax/optimizer/lars.py | Python | apache-2.0 | 2,914 | 0.002745 | # 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag | reed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# lim | itations under the License.
__all__ = ['LARS']
from typing import List
import jax.numpy as jn
from objax.module import Module, ModuleList
from objax.typing import JaxArray
from objax.util import class_name
from objax.variable import TrainRef, StateVar, TrainVar, VarCollection
class LARS(Module):
"""Layerwise ... |
JulienMcJay/eclock | windows/Python27/Lib/site-packages/pywin32-218-py2.7-win32.egg/scripts/killProcName.py | Python | gpl-2.0 | 1,766 | 0.026048 | # Kills a process by process name
#
# Uses the Performance Data Helper to locate the PID, then kills it.
# Will only kill the process if there is only one process of that name
# (eg, attempting to kill "Python.exe" will only work if there is only
# one Python.exe running. (Note that the current process does not
# coun... | of information about a running process and many
# other aspects of your system.
import win32api, win32pdhutil, win32con, sys
def killProcName(procname):
# Change suggested by Dan Knierim, who found that this performed a
# "refresh", allowing us to kill processes created since this was run
# for the first time.
tr... | win32pdhutil.FindPerformanceAttributesByName(procname)
# If _my_ pid in there, remove it!
try:
pids.remove(win32api.GetCurrentProcessId())
except ValueError:
pass
if len(pids)==0:
result = "Can't find %s" % procname
elif len(pids)>1:
result = "Found too many %s's - pids=`%s`" % (procname,pids)
else:
h... |
ilcn/NumericalAnalysis | a3.py | Python | gpl-2.0 | 659 | 0.069803 | def p5a():
xs = [-.75, -0.5,-0.25,0]
fxs = [-.0718125, -.02475, .3349375, 1.101]
getdd123(xs,fxs,3)
def getdd123(xs,fxs,n):
#derivatives
l1stdd = []
l2nddd = []
l3rddd = []
for i in range | (0,n):
l1stdd.append((fxs[i+1]-fxs[i])/(xs[i+1]-xs[i]))
for i in range(0,n-1):
l2nddd.append((l1stdd[i+1]-l1stdd[i])/(xs[i+2]-xs[i]))
for i in range(0,n-2):
l3rddd.append((l2nddd[i+1]-l2nddd[i])/(xs[i+3]-xs[i]))
#print [l1stdd,l2nddd,l3rddd]
return [l1stdd,l2nddd,l3rddd]
def p7a():
xs = [-.1, 0... | 3)
|
alex/djangobench | djangobench/benchmarks/query_latest/benchmark.py | Python | bsd-3-clause | 241 | 0.016598 | from djangobench.utils import run_benchmark
from query_latest.models import Book
def benchmark():
Book.objects.latest()
run_benchmark(
benchmark,
meta = | {
'description': 'A si | mple Model.objects.latest() call.',
}
)
|
MTgeophysics/mtpy | legacy/csvutm.py | Python | gpl-3.0 | 3,718 | 0.000807 | #!/usr/bin/env python
'''Convert and add columns for different coordinate systems to a CSV file.
This script requires pyproj installed. If you have a CSV file with two columns
containing x and y coordinates in some coordinate system (the "from" system),
this script will add another two columns with the coordinates tra... | fieldnames
if tx not in fnames:
fnames += [tx]
if ty not in fnames:
fnames += [ty]
w = csv.DictWriter(out_file, fieldnames=fnames, delimiter=delimiter)
w.writeheader()
for i, row in enumerate(r):
row[tx] = txs[i]
row[ty] = tys[i]
w.writerow(row)
def get_pars... | oc__.split('\n')[0],
epilog=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--fx',
default='lon',
help='column header for x coord of 1st (from) coord system')
parser.add_argument(
'--fy',
default=... |
exic/spade2 | examples/unittests/dadTestCase.py | Python | lgpl-2.1 | 14,968 | 0.012427 | import os
import sys
import time
import unittest
sys.path.append('../..')
import spade
import xmpp
import xml.dom.minidom
def CreateSD(s=""):
sd = spade.DF.ServiceDescription()
sd.setName("servicename1"+s)
sd.setType("type1"+s)
sd.addProtocol("sdprotocol1"+s)
sd.addOntologies("sdontology1"+s)
... | rvice(sd2)
self.assertEqual(dad1.match(dad2),True)
def testXML(self):
xml1='<name><name>aidname1</name></name><lease- | time>1000</l |
rajathkumarmp/robocomp | tools/rcmonitor/examples/laserViewer.py | Python | gpl-3.0 | 3,144 | 0.024491 | # -*- coding: utf-8 -*-
# Copyright (C) 2010 by RoboLab - University of Extremadura
#
# This file is part of RoboComp
#
# RoboComp 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)
for wm in range(10):
w = 1000. * (1.+wm) * self.spinBox.value()
painter.drawEllipse(QRectF(0.5*self.width()-w/2., 0.5*self.height()-w/2., w, w))
for wm in range(5):
w = 200. * (1.+wm) * self.spinBox.value()
painter.drawEllipse(QRectF(0.5*self.width()-w/2., 0.5*self.height()-w/2., w, w))
#painter.... | ine(QPoint(0.5*self.width(), 0.5*self.height()), QPoint(0.5*self.width(), 0.5*self.height()+20))
#painter.drawLine(QPoint(0.5*self.width(), 0.5*self.height()), QPoint(0.5*self.width()+5, 0.5*self.height()+20))
#painter.drawLine(QPoint(0.5*self.width(), 0.5*self.height()), QPoint(0.5*self.width()-5, 0.5*self.height(... |
unpingco/csvkit | csvkit/utilities/csvstat.py | Python | mit | 8,673 | 0.007149 | #!/usr/bin/env python
import datetime
from heapq import nlargest
from operator import itemgetter
import math
import six
from csvkit import CSVKitReader, table
from csvkit.cli import CSVKitUtility
NoneType = type(None)
MAX_UNIQUE = 5
MAX_FREQ = 5
OPERATIONS =('min', 'max', 'sum', 'mean', 'median', 'stdev', 'nulls',... | pe(stat))
else:
sel | f.output_file.write('%3i. %s: %s\n' % (c.order + 1, c.name, stat))
# Output all stats
else:
for op in OPERATIONS:
stats[op] = getattr(self, 'get_%s' % op)(c, values, stats)
self.output_file.write(('%3i. %s\n' % (c.order + 1, c.name)))
... |
catapult-project/catapult | third_party/requests_toolbelt/requests_toolbelt/adapters/socket_options.py | Python | bsd-3-clause | 4,789 | 0 | # -*- coding: utf-8 -*-
"""The implementation of the SocketOptionsAdapter."""
import socket
import warnings
import sys
import requests
from requests import adapters
from .._compat import connection
from .._compat import poolmanager
from .. import exceptions as exc
class SocketOptionsAdapter(adapters.HTTPAdapter):
... | 'count', 5)
socket_options = socket_options + [
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
]
# NOTE(Ian): OSX does not have these constants defined, so we
| # set them conditionally.
if getattr(socket, 'TCP_KEEPINTVL', None) is not None:
socket_options += [(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL,
interval)]
elif sys.platform == 'darwin':
# On OSX, TCP_KEEPALIVE from netinet/tcp.h is not exported
... |
eduNEXT/edx-platform | openedx/core/djangoapps/api_admin/api/v1/views.py | Python | agpl-3.0 | 2,304 | 0.003038 | """
API Views.
"""
from django_filters.rest_framework import DjangoFilterBackend
from edx_rest_framework_extensions.auth.jwt.authentication import JwtAuthentication
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics impor... | cted | ": true
}
],
"next": null,
"start": 0,
"previous": null
}
"""
authentication_classes = (JwtAuthentication, BearerAuthentication, SessionAuthentication,)
permission_classes = (IsAuthenticated, )
serializer_class = api_access_serializ... |
WW-Digital/django-activity-stream | example_project/testapp/streams.py | Python | bsd-3-clause | 444 | 0.004505 | from datetime import datetime
from django.contrib.contenttypes.models import ContentType
from actstream.manager | s import ActionManager, stream
class MyActionManager(ActionManager):
@stream
def testfoo(self, object, time=None):
if time is None:
time = datetime.now()
return object.actor_actions.filter(timestamp__lte = time)
@stream
def testbar | (self, verb):
return self.filter(verb=verb)
|
deis/django-fsm | django_fsm/__init__.py | Python | mit | 9,452 | 0.001375 | # -*- coding: utf-8 -*-
"""
State tracking functionality for django models
"""
import inspect
from collections import namedtuple
from functools import wraps
from django.db import models
from django.db.models.signals import class_prepared
from django.utils.functional import curry
from django_fsm.signals import pre_tran... | e in [curr_state, '*']:
if state in meta.transitions:
target, conditions = meta.transitions[state]
if all(map(lambda condition: condition(instance), conditions)):
yield Transition(
name=name,
source=state,
... | et=target,
conditions=conditions,
method=transition)
def get_all_FIELD_transitions(instance, field):
return field.get_all_transitions(instance.__class__)
class FSMMeta(object):
"""
Models methods transitions meta information
"""
def __init__(self, ... |
edx-solutions/edx-platform | openedx/core/djangoapps/user_authn/cookies.py | Python | agpl-3.0 | 12,065 | 0.002404 | """
Utility functions for setting "logged in" cookies used by subdomains.
"""
import json
import logging
import time
import six
from django.conf import settings
from django.contrib.auth.models import User
from django.dispatch import Signal
from django.urls import NoReverseMatch, reverse
from django.utils.http import... | ed by external sites
# to customize content based on user information. Currently,
# we include information that's used to customize the "account"
# links in the header of subdomain sites (such as the marketing site).
header_urls = {'logout': reverse('logout')}
| # Unfortunately, this app is currently used by both the LMS and Studio login pages.
# If we're in Studio, we won't be able to reverse the account/profile URLs.
# To handle this, we don't add the URLs if we can't reverse them.
# External sites will need to have fallback mechanisms to handle this case
#... |
erasche/galactic-radio-telescope | web/context_processors.py | Python | agpl-3.0 | 246 | 0.004065 | from django.conf import settings
cached_data = {
'URL_PREFIX': settings.URL_PREFIX,
'APP_VERSION': settings.GRT_VERSION,
'GIT_REVISION': settings.RAVEN_CONFIG.get( | 'release', None),
}
def url_prefix(requ | est):
return cached_data
|
MuckRock/muckrock | muckrock/crowdsource/tests/test_views.py | Python | agpl-3.0 | 9,147 | 0.00164 | """Tests for crowdsource views"""
# pylint: disable=invalid-name
# Django
from django.contrib.auth.models import AnonymousUser
from django.test import RequestFactory, TestCase
from django.urls import reverse
# Third Party
from nose.tools import assert_false, assert_true, eq_
# MuckRock
from muckrock.core.factories ... | e = self.view(request, slug=crowdsource.slug, idx=crowdsource.pk)
eq_(response.status_code, 302)
def test_owner_can_view(self):
"""Owner can view a crowdsource's details"""
crowdsource = CrowdsourceFactory()
url = reve | rse(
"crowdsource-detail",
kwargs={"slug": crowdsource.slug, "idx": crowdsource.pk},
)
request = self.request_factory.get(url)
request = mock_middleware(request)
request.user = crowdsource.user
response = self.view(request, slug=crowdsource.slug, idx=crowd... |
SUSE/azure-sdk-for-python | azure-keyvault/azure/keyvault/models/issuer_parameters.py | Python | mit | 1,158 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Mi | crosoft (R) AutoRest Code Generator.
# Ch | anges may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class IssuerParameters(Model):
"""Parameters for the issuer of the X509 component of a certificate.
:param nam... |
gallantlab/pycortex | examples/webgl/static.py | Python | bsd-2-clause | 675 | 0 | """
======================
Create a static viewer
======================
A static viewer is a brain viewer that exists permanently on a filesystem
The viewer is stored in a directory that stores html, javascript, data, etc
The viewer directory must be hosted by a server such as nginx
"""
import cortex
import numpy... | e = cortex.Volume.random(subject='S1', xfmname='fullhead')
# select path for static viewer | on disk
viewer_path = '/path/to/store/viewer'
# create viewer
cortex.webgl.make_static(outpath=viewer_path, data=volume, recache=True)
# a webserver such as nginx can then be used to host the static viewer
|
calico/basenji | basenji/dataset.py | Python | apache-2.0 | 29,864 | 0.014633 | # Copyright 2017 Calico 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, sof... |
else:
assert(self.num_targets == targets1.shape[-1])
targets_nonzero = np.logical_or(targets_nonzero, (targets1 != 0).sum(axis=0) > 0)
# count sequences
self.num_seqs += 1
# warn user about nonzero targets
if self.num_seqs > 0:
self.num_targets_nonzero = (targets_nonze... | d sequences with %d/%d targets' % (self.tfr_path, self.num_seqs, self.num_targets_nonzero, self.num_targets), flush=True)
else:
self.num_targets_nonzero = None
print('%s has %d sequences with 0 targets' % (self.tfr_path, self.num_seqs), flush=True)
def numpy(self, return_inputs=True, return_outputs=... |
ryanmdavis/BioTechTopics | BTT_functions.py | Python | mit | 997 | 0.018054 | import string,nltk
from nltk.corpus import stopwords
from nltk.stem.porter impo | rt *
def tokenizeAndStemStrings(text):
# turn text to tokens
tokens = nltk.word_tokenize(text)
# remove stop words
tokens_no_sw = [word for word in tokens if not word in stopwords.words('english')]
# stem words
stem | med = []
stemmer = PorterStemmer()
for item in tokens_no_sw:
# this line converts strings to unicode, so here I do it explicitly
#try:
stemmed.append(stemmer.stem(item))
#except:
# stemmed.append(unicode(item)) # for example, stemmer can't stem aed because it expects a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.