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 |
|---|---|---|---|---|---|---|---|---|
choderalab/assaytools | examples/direct-fluorescence-assay/inputs_p38_singlet.py | Python | lgpl-2.1 | 1,067 | 0.045923 | import json
import numpy as np
from glob import glob
inputs = {
'xml_file_path' : "./data/single_wavelength_copy",
'file_set' : {'p38' : glob( "./data/single_wavelength_copy/*.xml")},
'section' : '280_480_TOP_120',
'ligand_order' : ['Bosutinib','Bosutinib Isomer','Erlotinib','Gefitinib'... | assay_volume' : 50e-6, # assay volume, L
'well_area' : 0.1369, # well area, cm^2 for 4ti-0203 [http://4ti.co.uk/files/3113/4217/2464/4ti-0201.pdf]
}
inputs['Lstated'] = inputs['Lstated'].tolist()
inputs['Pstated'] = inputs['Pstated'].tolist()
with open('inputs.jso | n', 'w') as fp:
json.dump(inputs, fp)
|
erickpeirson/mbl-browser | browser/migrations/0010_auto_20160804_1644.py | Python | gpl-3.0 | 13,851 | 0.001877 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('browser', '0009_splitevent'),
]
operations = [
migrations.AddField(
model_name='affiliation',
name='... | _name='historicalperson',
name='validated_on',
field=models.DateTimeField(null=True, blank=True),
),
migrations.AddField(
model_name='institution',
name='validated_on',
field=models.DateTimeField(null=True, blank=True),
),
migra... | blank=True),
),
migrations.AddField(
model_name='knowninstitution',
name='validated_on',
field=models.DateTimeField(null=True, blank=True),
),
migrations.AddField(
model_name='knownlocation',
name='validated_on',
fi... |
michaelgugino/web_keyer | sqlalchemy/events.py | Python | gpl-3.0 | 31,080 | 0.000611 | # sqlalchemy/events.py
# Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Core event interfaces."""
from . import event, exc
from .pool import Pool
fro... | ethods here define the name of an event as well
as the names of members that are passed to listener
functions.
See also:
:ref:`event_ | toplevel`
:class:`.DDLElement`
:class:`.DDL`
:ref:`schema_ddl_sequences`
"""
_target_class_doc = "SomeSchemaClassOrObject"
_dispatch_target = SchemaEventTarget
def before_create(self, target, connection, **kw):
"""Called before CREATE statments are emitted.
... |
ytsarev/rally | rally/osclients.py | Python | apache-2.0 | 7,886 | 0.000127 | # Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | service_type='compute',
http_log_debug=CONF.debug,
timeout=CONF.openstack_client_http_timeout,
insecure=CONF.https_insecure,
cacert=CONF.https_cacert)
return client
@me... | username=self.endpoint.username,
password=self.endpoint.password,
tenant_name=self.endpoint.tenant_name,
auth_url=self.endpoint.auth_url,
timeout=CONF.openstack_client_http_ti... |
alexmilesyounger/ds_basics | s3v2.py | Python | mit | 2,936 | 0.016349 | from s3v1 import *
def filter_col_by_string(data_sample, field, filter_condition):
filtered_rows = [] # create a new list
col = int(data_sample[0].index(field)) # create a variable (col) and asign it to an integer which is pulled from the header row of the data_sample and which is the index (probably also an integer... | v, "brandName", "falfkafj") # this a test of a non-existant thing to see if the lowercase "gucci" tie was a global error... like every request wil | l return a minimum of one record even if zero exist.
# print("Found {} silk ties".format(number_of_records(silk_ties)))
# print("Found {} wool ties".format(number_of_records(wool_ties)))
# print("Found {} cotton ties".format(number_of_records(cotton_ties)))
# print("Found {} Gucci ties".format(number_of_records(gucc... |
kurtraschke/pyRFC3339 | pyrfc3339/generator.py | Python | mit | 2,170 | 0 | import pytz
from pyrfc3339.utils import timezone, timedelta_seconds
def generate(dt, utc=True, accept_naive=False, microseconds=False):
'''
Generate an :RFC:`3339`-formatted timestamp from a
:class:`datetime.datetime`.
>>> from datetime import datetime
>>> generate(datetime(2009,1,1,12,59,59,0,p... | raise ValueError("cannot generate a local timestamp from " +
"a naive datetime")
| else:
raise ValueError("naive datetime and accept_naive is False")
if utc is True:
dt = dt.astimezone(pytz.utc)
timestamp = dt.strftime('%Y-%m-%dT%H:%M:%S')
if microseconds is True:
timestamp += dt.strftime('.%f')
if dt.tzinfo is pytz.utc:
timestamp += 'Z'
... |
gundalow/ansible-modules-extras | windows/win_uri.py | Python | gpl-3.0 | 4,484 | 0.000669 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Corwin Brown <corwin@corwinbrown.com>
#
# 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, either version 3 of the... | ion: The HTTP Status Code of the response.
returned: success
type: int
sample: 200
status_description:
description: A summery of the status.
returned: success
type: string
stample: "OK"
raw_content:
description: The raw content of the HTTP response.
returned: success
type: string
sample: 'HTTP/1.1... | gle.com:443"; ma=2592000; v="30,29,28,27,26,25",quic=":443"; ma=2...'
headers:
description: The Headers of the response.
returned: success
type: dict
sample: {"Content-Type": "application/json"}
raw_content_length:
description: The byte size of the response.
returned: success
type: int
sample: 54447
"""... |
anaran/olympia | sites/landfill/settings_base.py | Python | bsd-3-clause | 5,402 | 0.002962 | """private_base will be populated from puppet and placed in this directory"""
import logging
import os
import dj_database_url
from lib.settings_base import CACHE_PREFIX, ES_INDEXES, KNOWN_PROXIES, LOGGING
from .. import splitstrip
import private_base as private
ENGAGE_ROBOTS = False
EMAIL_BACKEND = 'django.core.m... | SPIDERMONKEY = '/usr/bin/tracemonkey'
# Remove DetectMobileMiddleware from middleware in production.
detect = 'mo | bility.middleware.DetectMobileMiddleware'
csp = 'csp.middleware.CSPMiddleware'
RESPONSYS_ID = private.RESPONSYS_ID
CRONJOB_LOCK_PREFIX = 'addons-landfill'
BUILDER_SECRET_KEY = private.BUILDER_SECRET_KEY
BUILDER_VERSIONS_URL = "https://builder-addons-dev.allizom.org/repackage/sdk-versions/"
ES_HOSTS = splitstrip(p... |
stefanseefeld/synopsis | Synopsis/ASG.py | Python | lgpl-2.1 | 19,516 | 0.015936 | #
# Copyright (C) 2000 Stefan Seefeld
# Copyright (C) 2000 Stephen Davies
# All rights reserved.
# Licensed to the public under the terms of the GNU LGPL (>= 2),
# see the file COPYING for details.
#
"""Abstract Syntax Tree classes.
This file contains classes which encapsulate nodes in the ASG. The base class
is the ... | ias
self.premod = premod
self.postmod = postmod
def accept(self, visitor): visitor.visit_modifier_type_id(self)
def __cmp__(self, other):
"Comparison operator"
return (ccmp(self,other)
or cmp(self.alias,other.alias)
or cmp(self.premod,other.premo... | ''.join(self.postmod))
class ArrayTypeId(TypeId):
"""A modifier that adds array dimensions to a type-id."""
def __init__(self, language, alias, sizes):
super(ArrayTypeId, self).__init__(language)
self.alias = alias
self.sizes = sizes
def accept(self, visi... |
yackj/GameAnalysis | gameanalysis/script/sgboot.py | Python | apache-2.0 | 3,682 | 0 | """calculate bootstrap bounds on a sample game"""
import argparse
import json
import sys
import numpy as np
from gameanalysis import bootstrap
from gameanalysis import gameio
from gameanalysis import regret
from gameanalysis import scriptutils
CHOICES = {
'regret': (bootstrap.mixture_regret, regret.mixture_regr... | es', metavar='<profile>', nargs='+', help="""File or string with
profiles from input game for which regrets should be calculated. This
file can be a list or a single profile""")
parser.add_argument(
'-t', '--type', default='regret', choices=CHOICES, help="""What to
return. regret - ... | lus of every profile. (default: %(default)s)""")
parser.add_argument(
'--processes', metavar='num-processes', type=int, help="""The number of
processes when constructing bootstrap samples. Default will use all the
cores available.""")
parser.add_argument(
'--percentiles', '-p', ... |
zakuro9715/luka | luka_maya.py | Python | gpl-3.0 | 2,318 | 0.006471 | import shutil
import os
import base64
from PySide.QtCore import *
from PySide.QtGui import *
from maya.app.general.mayaMixin import MayaQWidgetBaseMixin, MayaQWidgetDockableMixin
from maya import cmds
from luka import Luka
from luka.gui.qt import TakeSnapshotWidget, SnapshotListWidget
__all__ = ['LukaTakeSnapshotUI... |
ui.show()
def restore(self, s):
super(LukaUI, self).restore(s)
v = cmds.confirmDialog(
title='Restore snapshot',
message='All changes including SAV | ED will be lost. Are you sure?',
button=['OK','Cancel'], defaultButton='OK',
cancelButton='Cancel', dismissString='Cancel')
if v != 'OK':
return
cmds.file(cmds.file(q=True, sceneName=True), open=True, force=True)
def remove(self, s):
v = cmds.con... |
sambayless/monosat | src/monosat/api/python/tests/__init__.py | Python | mit | 102 | 0 | import u | nittest
import tests
import tests.test_logic
import tests.test_graph
impor | t tests.test_output
|
nerevu/riko | riko/modules/strreplace.py | Python | mit | 6,865 | 0.000146 | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
riko.modules.strreplace
~~~~~~~~~~~~~~~~~~~~~~~
Provides functions for string search-and-replace.
You provide the module with the text string to search for, and what to replace
it with. Multiple search-and-replace pairs can be added. You can specify to
replace all... | ): The keyword arguments passed to the wrapper
Kwargs:
conf (dict): The pipe configuration. Must contain the key 'rule'.
rule (dict): can be either a dict or list of dicts. Must contain
the keys 'find' and 'replace'. May contain the key 'param'.
find (str): The... | ,
'last', or 'every' (default: 'every').
assign (str): Attribute to assign parsed content (default: strreplace)
field (str): Item attribute to operate on (default: 'content')
Returns:
Deferred: twisted.internet.defer.Deferred item with replaced content
Examples:
... |
cbrafter/TRB18_GPSVA | codes/mainCode/ParallelSpecialMac.py | Python | mit | 5,186 | 0.005401 | # -*- coding: utf-8 -*-
import sys
import os
import shutil
import psutil
import subprocess
import time
import numpy as np
import itertools
# from matplotlib import pyplot
from routeGen import routeGen
from sumoConfigGen import sumoConfigGen
from stripXML import stripXML
import multiprocessing as mp
from glob import glo... | CAVratio, stepSize, run, simport)
# Connect to model
connector = sumoConnect.sumoConnect(configFile, gui=False, port=simport)
connector.launchSumoAndConnect()
# Get junction data
jd = readJunctionData.readJunctionData(model + modelName + ".jcn.xml")
junctionsList =... | trollerList = []
for junction in junctionsList:
controllerList.append(tlController(junction))
# Step simulation while there are vehicles
while traci.simulation.getMinExpectedNumber():
# connector.runSimulationForSeconds(1)
traci.simulationStep()
f... |
QuinDiesel/CommitSudoku-Project-Game | Euromast/menu.py | Python | mit | 6,569 | 0.003349 | import pygame
music_on = 0
# Set up a button class for later usage
class Button:
def __init__(self, x, y, w, h, img):
self.x = x
self.y = y
self.w = w
self.h = h
self.img = img
self.surface = w * h
def buttonHover(self):
mouse = pygame.mo... | 280, 220, 100, 50, startButtonGrayImg)
gameRulesButton = Button(280, 326, 250, 50, buttonGameRulesImg)
gameRulesButtonGray = Button(280, 326, 250, 50, buttonGameRulesGrayImg)
buttonInstruction = Button(280, 273, 250, 50, buttonInstructionImg)
buttonInstructionGray = Button(280, 273, 250, 50, buttonI... | ttonImg)
HighscoreButton = Button(280, 379, 250, 50, HighscoreButtonImg)
HighscoreButtonGray = Button(280, 379, 250, 50, HighscoreButtonGrayImg)
# Initialize game loop
phase = "menu"
loop = True
while loop:
# Check if user wants to quit
for event in pygame.event.get()... |
leonyeh/CoffeeScript-Hello-World | fabfile.py | Python | apache-2.0 | 1,250 | 0.0256 | from fabric.api import hosts, run, sudo, local
from fabric.contrib.console import confirm
from fabric.utils import puts,warn
DEV_PROVISIONING_UUID = "XXXXXXXX-XXXX-XXXX-XX | XX-XXXXXXXXXXXX"
DEV_SIGN = "Mobi Ten"
DEV_APP_NAME = "G | ym Mama"
DEV_APP_ID = 'com.mobiten.gym_mama'
TITANIUM_SDK_VERSION = '1.5.1'
IPHONE_SDK_VERSION = '4.2'
DEVICE_FAMILY = 'iphone'
BUILDER = "/Library/Application\ Support/Titanium/mobilesdk/osx/%s/iphone/builder.py" % (TITANIUM_SDK_VERSION)
def coffee():
local("coffee --watch -o Resources/js/ --compile App/*.coffee "... |
DavidPowell/OpenModes | openmodes/constants.py | Python | gpl-3.0 | 1,192 | 0.001678 | # -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# OpenModes - An eigenmode solver for open electromagnetic resonantors
# Copyright (C) 2013 David Powell
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Gen... | 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 received a copy of the GNU General Public License
# along with this program. If not, see ... | ww.gnu.org/licenses/>.
#-----------------------------------------------------------------------------
"""
Various useful constants for electromagnetism. Most of these are already
defined in scipy.constants, but are duplicated here for convenience.
"""
import numpy as np
pi = np.pi
c = 299792458.0
mu_0 = 4e-7*pi
epsil... |
waynechu/PythonProject | dns/wiredata.py | Python | mit | 3,751 | 0.000267 | # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
# Copyright (C) 2011,2017 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permis... | if start < 0 or stop < 0:
raise dns.exception.FormError
# If it's not an empty slice, access left and right bounds
# to make sure they're valid
if start != stop:
super(WireData, self).__getitem__(start... | else:
for index in (start, stop):
if index is None:
continue
elif abs(index) > len(self):
raise dns.exception.FormError
return WireData(super(WireData, self).__get... |
Treggats/DicewarePassphrase | docs/conf.py | Python | gpl-2.0 | 11,767 | 0.006289 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Diceware documentation build configuration file, created by
# sphinx-quickstart on Mon Oct 26 22:19:13 2015.
#
# 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
# a... | e to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) 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 ... | iles,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
... |
klim-iv/phantomjs-qt5 | src/webkit/Tools/Scripts/webkitpy/common/config/committers.py | Python | bsd-3-clause | 11,526 | 0.001822 | # Copyright (c) 2011, Apple Inc. All rights reserved.
# Copyright (c) 2009, 2011, 2012 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must ret... | me.lower():
return True
if self.irc_nicknames:
for nickname in self.irc_nicknames: |
if string in nickname.lower():
return True
for email in self.emails:
if string in email:
return True
return False
def matches_glob(self, glob_string):
if fnmatch.fnmatch(self.full_name, glob_string):
return True
... |
e-gob/plataforma-kioscos-autoatencion | scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/plugins/callback/default.py | Python | bsd-3-clause | 13,463 | 0.002823 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
callback: default
type:... | in_options.get('show_skipped_hosts', C.DISPLAY_SKIPPED_HOSTS): # fallba | ck on constants for inherited plugins missing docs
self._clean_results(result._result, result._task.action)
if self._play.strategy == 'free' and self._last_task_banner != result._task._uuid:
self._print_task_banner(result._task)
if result._task.loop and 'results' i... |
jt6562/XX-Net | python27/1.0/lib/SimpleHTTPServer.py | Python | bsd-2-clause | 7,826 | 0.001278 | """Simple HTTP Server.
This module builds on BaseHTTPServer by implementing the standard GET
and HEAD requests in a fairly straightforward manner.
"""
__version__ = "0.6"
__all__ = ["SimpleHTTPRequestHandler"]
import os
import posixpath
import BaseHTTPServer
import urllib
import cgi
import sys
i... | splaypat | h)
f.write("<hr>\n<ul>\n")
for name in list:
fullname = os.path.join(path, name)
displayname = linkname = name
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
displayname = name + "/"
l... |
Korkki/djangocms-text-tinymce | djangocms_text_tinymce/migrations/0001_initial.py | Python | bsd-3-clause | 703 | 0.001422 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
| ('cms', '0004_auto_20141112_1610'),
]
operations = [
migrations.CreateModel(
name='Text',
fields=[
('cmsplugin_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='cms.CMSPlugin')),
('body', tinymc... | )),
],
options={
'abstract': False,
},
bases=('cms.cmsplugin',),
),
]
|
stvstnfrd/edx-platform | cms/djangoapps/contentstore/tests/test_i18n.py | Python | agpl-3.0 | 10,854 | 0.002588 | # -*- coding: utf-8 -*-
"""
Tests for validate Internationalization and Module i18n service.
"""
import gettext
from unittest import skip
import mock
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.utils import translation
from django.utils.translation impo... | -called
self.translations = translations
def ugettext(self, msgid):
"""
Mock override for ugettext translation operation
"""
return self.translations.get(msgid, msgid)
gettext = u | gettext
@staticmethod
def translator(locales_map): # pylint: disable=method-hidden
"""Build mock translator for the given locales.
Returns a mock gettext.translation function that uses
individual TestTranslations to translate in the given locales.
:param locales_map: A map from... |
vincentping/pythis | setup.py | Python | mit | 1,142 | 0.016637 | #! /usr/bin/env python
# -*- coding=utf-8 -*-
from distutils.core import setup
setup(
name='pythis',
version='1.4',
description='zen of python in Simplified Chinese',
url='https://github.com/vincentping/pythis',
author='Vincent Ping',
author_email='vincentping@gmail.com',
licen... | 5 - Production/Stable
'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Software Development',
# Specify the Python versions you support here. In particular, ensure
# th | at you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :... |
arunchaganty/aeschines | django/twit/management/commands/annotate_features.py | Python | mit | 1,154 | 0.006066 | from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
import sys
import json
from twit.models import User, Tweet, Mention, UserMention
from javanlp.models import Sentence, Sentiment
from javanlp.util import AnnotationException, annotate_document_with_sentiment
class Com... | json tweet on each line.")
def handle(self, *args, **options):
for tweet in Tweet.objects.all():
if Sentence.objects.filter(doc_id = tweet.id).exists(): continue
try:
with transaction.atomic():
for sentence, sentime | nt in annotate_document_with_sentiment(tweet.id, tweet.text):
sentence.save()
sentiment.sentence = sentence
sentiment.save()
except AnnotationException:
pass # Couldn't annotate this sentence...
|
rrafiringa/is210-week-04-warmup | task_01.py | Python | mpl-2.0 | 759 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This module provides a function that knows what you mean"""
def know_what_i_mean(wink, numwink=2):
""" Prints "Know what I mean?" with a variable number of winks.
Args:
wink (mixed): Represents a wink.
numwink (int): Wink multiplier. Defaults to... | 'Know what I mean? winkwink, nudge nudge'
>>> know_what_i_mean('wink', 3)
'Know what I mean? winkwinkwink, nudge nudge nudge'
"""
winks = (wink * numwink) | .strip()
nudges = ('nudge ' * numwink).strip()
retstr = 'Know what I mean? {}, {}'.format(winks, nudges)
return retstr
|
sushi-irc/tekka | signal_handler.py | Python | bsd-2-clause | 38,295 | 0.032208 | # coding:UTF-8
"""
Copyright (c) 2009-2010 Marian Tietz
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions... | i):
global init
if init == False:
# Message-Signals
connect_signal("message", userMessage_cb)
connect_signal("notice", userNotice_cb)
connect_signal("action", userAction_c | b)
connect_signal("away_message", userAwayMessage_cb)
connect_signal("ctcp", userCTCP_cb)
connect_signal("error", userError_cb)
# action signals
connect_signal("part", userPart_cb)
connect_signal("join", userJoin_cb)
connect_signal("names", userNames_cb)
connect_signal("quit", userQuit_cb)
connect_si... |
eusoubrasileiro/fatiando_seismic | cookbook/gravmag_magdir_dipolemagdir.py | Python | bsd-3-clause | 2,519 | 0 | """
GravMag: Use the DipoleMagDir class to estimate the magnetization direction
of dipoles with known centers
"""
import numpy
from fatiando import mesher, gridder
from fatiando.utils import ang2vec, vec2ang, contaminate
from fatiando.gravmag import sphere
from fatiando.vis import mpl
from fatiando.gravmag.magdir impo... | , shadow=True, prop={'size': 13})
mpl.xlabel('East y (m)', fontsize= | 14)
mpl.ylabel('North x (m)', fontsize=14)
mpl.subplot(1, 2, 2)
residuals_mean = numpy.mean(solver.residuals())
residuals_std = numpy.std(solver.residuals())
# Each residual is subtracted from the mean and the resulting
# difference is divided by the standard deviation
s = (solver.residuals() - residuals_mean) / residu... |
shmish/core-assess | core/urls.py | Python | mpl-2.0 | 549 | 0.014572 | from django.conf.urls import url
from . import views
from core.views import list_evidence_view, create_evidence_view, list_ | submissions_view
app_name = 'core'
urlpatterns = [
# ex: /core/
url(r'^$', views.index, name='index'),
url(r'^(?P<corecomp_id>[0-9]+)/$', views.detail, name='detail'),
url(r'^submitted', views.submitted, name='submitted'),
url(r'^evide | nce_form/$', create_evidence_view, name='evidence'),
url(r'^CES/$', list_evidence_view, name='CES'),
url(r'^submissions/$', list_submissions_view, name='submissions')
] |
ekiro/chaps | tests/test_instance_scope.py | Python | mit | 436 | 0 | from haps.scopes.instance import InstanceScope
def test_get_object(some_class):
some_instanc | e = InstanceScope().get_object(some_class)
assert isinstance(some_instance, some_class)
def test_get_multiple_objects(some_class):
scope = InstanceScope()
objects = {scope.get_object(some_class) for _ in range(100)}
assert all(isinstance(o, some_class) for o in objects)
| assert len({id(o) for o in objects}) == 100
|
arsgeografica/kinderstadt-registry | setup.py | Python | gpl-3.0 | 1,548 | 0.000646 | #!/usr/bin/env python
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import versioneer
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initializ... | est.main(self.pytest_args + ' test')
sys.exit(errno)
cmd_classes = versioneer.get_cmdclass()
cmd_classes['test'] = PyTest
setup(
name="kinderstadt-registry",
version=versioneer.get_version(),
cmdclass=cmd_classes,
packages=find_packages(),
install_requires=[
'alembic==0.7.6',
... | =0.5.2',
'Flask-Migrate==1.4.0',
'Flask-SQLAlchemy==2.0',
'Flask-WTF==0.11',
'Flask==0.10.1',
'path.py==7.3',
'pgcli==0.17.0',
'python-stdnum==1.1',
'SQLAlchemy-Searchable==0.9.3',
'SQLAlchemy-Utils==0.30.12',
],
extras_require={
'd... |
dedichan/ChemDB | principal.py | Python | gpl-3.0 | 18,412 | 0.01423 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/victorgarric/Documents/INVENTAIRE/principal.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QWidget
from PyQt5.Qt... | self.button_manual.clicked.connect(self.manu)
self.button_repop.clicked.connect(self.repop)
def invent(self) :
prog=QProgressDialog("Compiling inventory...","Cancel",0,100,self)
prog.open()
allconn=cursor.connection()
curs | =allconn[0]
data=allconn[1]
curs.execute("""SELECT * FROM "main"."chem" WHERE "id" > 0 """)
store=curs.fetchall()
a=excel.makeinvent(store)
a.begin()
internal=0
if prog.wasCanceled() :
return None
while internal != 100 :
try :
... |
datapythonista/pandas | pandas/core/ops/mask_ops.py | Python | bsd-3-clause | 5,124 | 0.000195 | """
Ops for masked arrays.
"""
from typing import (
Optional,
Union,
)
import numpy as np
from pandas._libs import (
lib,
missing as libmissing,
)
def kleene_or(
left: Union[bool, np.ndarray],
right: Union[bool, np.ndarray],
left_mask: Optional[np.ndarray],
right_mask: Optional[np.nd... | """
Boolean ``o | r`` using Kleene logic.
Values are NA where we have ``NA | NA`` or ``NA | False``.
``NA | True`` is considered True.
Parameters
----------
left, right : ndarray, NA, or bool
The values of the array.
left_mask, right_mask : ndarray, optional
The masks. Only one of these may be N... |
andrewsmedina/django | django/db/models/sql/aggregates.py | Python | bsd-3-clause | 4,116 | 0.001944 | """
Classes to represent the default SQL aggregate functions
"""
import copy
from django.db.models.fields import IntegerField, FloatField
# Fake fields used to identify aggregate types in data-conversion operations.
ordinal_aggregate_field = IntegerField()
computed_aggregate_field = FloatField()
class Aggregate(obje... | ection)
elif isinstance(self.col, (list, tuple)):
field_name = '.'.join([qn(c) for c in self.col])
else:
field_name = self | .col
substitutions = {
'function': self.sql_function,
'field': field_name
}
substitutions.update(self.extra)
return self.sql_template % substitutions, params
class Avg(Aggregate):
is_computed = True
sql_function = 'AVG'
class Count(Aggregate):
is_... |
froyobin/ironic | ironic/drivers/modules/drac/common.py | Python | apache-2.0 | 4,782 | 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... | st one. Defaults to False.
:returns: if find_all is False the element object will be returned
if found, None if not found. If find_all is True a list of
element objects will be returned or an empty list if no
elements were found.
"""
query = ('.//{%(namespace)s}%(i... | ce,
'item': item})
if find_all:
return doc.findall(query)
return doc.find(query)
|
jinzekid/codehub | python/lyutil/ly_proxy_test.py | Python | gpl-3.0 | 3,046 | 0.009321 | # Author: Jason Lu
import urllib.request
from bs4 import BeautifulSoup
import time
req_header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#'Accept-Language': 'en-U... | tds = tr.find_all('td')
ip = tds[1].text.strip()
port = tds[2].text.strip()
protocol = tds[5].text.strip()
if protocol == 'HTTP' or protocol == 'HTTPS':
#of.write('%s=%s:%s\n' % (protocol, ip, port))
print('%s=%s:%s' % (protoc | ol, ip, port))
grasp_num +=1
proxyHandler = urllib.request.ProxyHandler({"http": r'http://%s:%s' % (ip, port)})
opener = urllib.request.build_opener(cookies, proxyHandler)
opener.addheaders = [('User-Agent',
'Mozilla/5.0 (Windows NT 6.1;... |
bcsaller/layercake | tests/utils.py | Python | apache-2.0 | 671 | 0.00149 | from contextlib import contextmanager
import pkg_resources
import os
def local_stream(name):
return pkg_resources.resource_stream(__name__, name)
def local_file(name):
return pkg_resources.resource_filename(__name__ | , name)
@contextmanager
def Environ(**kwargs):
orig = | os.environ.copy()
replace = set(kwargs.keys()) & set(orig.keys())
removes = set(kwargs.keys()) - set(orig.keys())
try:
os.environ.update(kwargs)
yield
finally:
for r in removes:
os.environ.pop(r)
for r in replace:
os.environ[r] = orig[r]
class O(... |
adusca/treeherder | treeherder/model/fields.py | Python | mpl-2.0 | 1,086 | 0 | from django.db import models
# Django doesn't support big auto fields out of the box, see
# https://code.djangoproject.com/ticket/14286.
# This is a stripped down version of the BoundedBigAutoField from Sentry.
class BigAutoField(models.AutoField):
description = "Big Integer"
def db_type(self, connection):
... | FlexibleForeignKey(models.ForeignKey):
def db_type(self, connection):
# This is required to support BigAutoField
rel_field = self.related_fi | eld
if hasattr(rel_field, 'get_related_db_type'):
return rel_field.get_related_db_type(connection)
return super(FlexibleForeignKey, self).db_type(connection)
|
bronycub/sugarcub | users/validators.py | Python | gpl-3.0 | 1,069 | 0.008419 | from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _
from django.core import validators
@deconstructible
class SkypeValidator:
message = _('Enter a valid URL.')
code = 'invalid'
... | with('skype:'):
raise ValidationError(self.message, code=self.code)
@deconstructible
class UrlValidator:
message = _('Enter a valid URL.')
code = 'invalid'
validators = [validators.URLValidator(), validators.EmailValidator(), SkypeValidator()]
def __call__(self, value):
def apply_... | validator(value)
except ValidationError as e:
skype_failed = True
return _apply_validator
if any(map(apply_validator(value), self.validators)):
raise ValidationError(self.message, code=self.code)
|
PythonScientists/Shape | main/module/about/views.py | Python | apache-2.0 | 173 | 0.017341 | # | -*-coding:utf-8-*-
from . import about_blueprint
from flask import render_template
@about_blueprint.r | oute("/")
def about_index():
return render_template("about.html") |
heracek/django-nonrel | django/core/cache/__init__.py | Python | bsd-3-clause | 6,144 | 0.001302 | """
Caching framework.
This package defines set of cache backends that all conform to a simple API.
In a nutshell, a cache is a set of values -- which can be any object that
may be pickled -- identified by string keys. For the complete API, see
the abstract BaseCache class in django.core.cache.backends.base.
Client ... | nf.copy()
backend = args.pop('BACKEND')
location = args.pop('LOCATION', '')
return backend, location, args
else:
# Trying to import the given backend, in case it's a dotted path
mod_path, cls_name = bac | kend.rsplit('.', 1)
try:
mod = importlib.import_module(mod_path)
backend_cls = getattr(mod, cls_name)
except (AttributeError, ImportError):
raise InvalidCacheBackendError("Could not find backend '%s'" % backend)
location = kwargs.pop('LOCATION', '')
re... |
Oscarbralo/TopBlogCoder | SRMs/SRM180PY/250/250.py | Python | mit | 326 | 0.003067 | class DinkyFish:
def monthsUnti | lCrowded(self, tankVolume, maleNum, femaleNum):
months = 0
while maleNum + femaleNum <= (tankVolume * 2):
minFishes = min(maleNum, femaleNum)
maleNum += minFishes
femaleNum += minFi | shes
months += 1
return months |
gnss-lab/gnss-tec | tests/conftest.py | Python | mit | 21,163 | 0.002755 | import datetime
from io import StringIO
from pytest import fixture
from gnss_tec import ObsFileV2, ObsFileV3
RNX_V2 = """\
2.11 OBSERVATION DATA M (MIXED) RINEX VERSION / TYPE
teqc 2016Nov7 NOAA/NOS/NGS/CORS 20170707 04:06:33UTCPGM / RUN BY / DATE
ASPA ... | INTERVAL
18 LEAP SECONDS
2017 7 6 0 0 0.0000000 GPS TIME OF FIRST OBS
END OF HEADER
4 5
ASPA (COGO code) | COMMENT
0.000 (antenna height) COMMENT
-14.32609534 (latitude) COMMENT
-170.72243361 (longitude) COMMENT
0053.667 (elevation) COMMENT
17 7 6 0 0 0.0000000... |
red-hood/calendarserver | txweb2/test/test_http_headers.py | Python | apache-2.0 | 32,998 | 0.004273 | # Copyright (c) 2008 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{txweb2.http_headers}.
"""
from twisted.trial import unittest
import random
import time
from txweb2 import http_headers
from txweb2.http_headers import Cookie, HeaderHandler, quoteString, generateKeyValues
from twisted.python... | ow in table:
if len(row) == 2:
rawHeaderInput, parsedHeaderData = row
requiredGeneratedElements = []
elif len(row) == 3:
rawHeaderInput, parsedHeaderDat | a, requiredGeneratedElements = row
assert isinstance(requiredGeneratedElements, list)
# parser
parsed = parseHeader(headername, [rawHeaderInput, ])
self.assertEquals(parsed, parsedHeaderData)
regeneratedHeaderValue = generateHeader(headername, parsed)
... |
lsbardel/flow | flow/conf/__init__.py | Python | bsd-3-clause | 1,191 | 0.012594 | import os
from jflow.utils.importlib import import_module
from jflow.conf import global_settings
#If django is installed used the django setting object
try:
from django.conf import settings as django_settings
except:
django_settings = None
ENVIRONMENT_VARIABLE = "JF | LOW_SETTINGS_MODULE"
class Settings(object):
pass
def fill(self, settings_module):
# update this dict from global settings (but only for ALL_CAPS settings)
for setting in dir(global_settings):
if setting == setting.upper():
if not hasattr(self,setting | ):
setattr(self, setting, getattr(global_settings, setting))
return self
def get_settings():
settings_module = os.environ.get(ENVIRONMENT_VARIABLE,None)
if settings_module:
try:
mod = import_module(settings_module)
except ImportErr... |
UltronAI/Deep-Learning | Pattern-Recognition/hw2-Feature-Selection/skfeature/utility/entropy_estimators.py | Python | mit | 7,335 | 0.00259 | # Written by Greg Ver Steeg (http://www.isi.edu/~gregv/npeet.html)
import scipy.spatial as ss
from scipy.special import digamma
from math import log
import numpy.random as nr
import numpy as np
import random
# continuous estimators
def entropy(x, k=3, base=2):
"""
The classic K-L k-nearest nei... | q(x); x, xp should be a list of vectors, e.g. x = [[1.3],[3.7],[5.1],[2.4]]
if x is a one-dimensional scalar and we have four samples
"""
assert k <= len(x) - 1, "Set k smaller than num. samples - 1"
assert k <= len(xp) - 1, "Set k smaller than num. samples - | 1"
assert len(x[0]) == len(xp[0]), "Two distributions must have same dim."
d = len(x[0])
n = len(x)
m = len(xp)
const = log(m) - log(n-1)
tree = ss.cKDTree(x)
treep = ss.cKDTree(xp)
nn = [tree.query(point, k+1, p=float('inf'))[0][k] for point in x]
nnp = [treep.query(point, ... |
KlubJagiellonski/pola-backend | pola/product/migrations/0017_remove_product_companies.py | Python | bsd-3-clause | 329 | 0 | # Generated by | Django 3.1.7 on 2021-09-27 16:10
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('product', '0016_product_company'),
]
| operations = [
migrations.RemoveField(
model_name='product',
name='companies',
),
]
|
openqt/algorithms | projecteuler/ac/old/pe029_distinct_powers.py | Python | gpl-3.0 | 823 | 0 | #!/usr/bin/env python
# coding=utf-8
"""
Distinct powers
Problem 29
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical... | h any repeats removed, we get
th | e following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and
2 ≤ b ≤ 100?
"""
from __future__ import print_function
def power_combinations(a, b):
for i in range(2, a):
for j in r... |
sgerhart/ansible | lib/ansible/modules/cloud/pubnub/pubnub_blocks.py | Python | mit | 23,797 | 0.00021 | #!/usr/bin/python
#
# PubNub Real-time Cloud-Hosted Push API and Push Notification Client
# Frameworks
# Copyright (C) 2016 PubNub Inc.
# http://www.pubnub.com/
# http://www.pubnub.com/terms
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_i... | t'
pubnub_blocks:
email: '{{ email }}'
password: '{{ password }}'
application: '{{ app_name }}'
keyset: '{{ keyset_name }}'
name: '{{ block_name }}'
event_handlers:
-
name: '{{ handler_name }}'
event: 'js-after-publish'
# Stop block and event handlers.
- name: Sto | pping block
pubnub_blocks:
email: '{{ email }}'
password: '{{ password }}'
application: '{{ app_name }}'
keyset: '{{ keyset_name }}'
name: '{{ block_name }}'
state: stop
# Multiple module calls with cached result passing
- name: Create '{{ block_name }}' block
register: module_cache
pubnu... |
CMLL/taiga-back | taiga/projects/userstories/migrations/0010_remove_userstory_watchers.py | Python | agpl-3.0 | 1,220 | 0.004098 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import connecti | on
from django.db import models, migrations
from django.contrib.contenttypes.models import | ContentType
from django.contrib.contenttypes.management import update_all_contenttypes
def create_notifications(apps, schema_editor):
update_all_contenttypes(verbosity=0)
sql="""
INSERT INTO notifications_watched (object_id, created_date, content_type_id, user_id, project_id)
SELECT userstory_id AS object_id,... |
bunjiboys/security_monkey | security_monkey/common/sts_connect.py | Python | apache-2.0 | 3,363 | 0.000892 | # Copyright 2014 Netflix, 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... | le.connect_to_region(
region,
aws_access_key_id=role.credentials.access_key,
aws_secret_access_key=role.credentials.secret_key,
| security_token=role.credentials.session_token
)
|
alexryndin/ambari | ambari-server/src/main/resources/stacks/BigInsights/4.2/services/HBASE/package/scripts/hbase_decommission.py | Python | apache-2.0 | 2,306 | 0.009974 | #!/usr/bin/env python
"""
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 (the
"License");... | n_drainer} remove {host}")
Execute(regiondrainer_cmd,
user=params.hbase_user,
logoutput=True
)
pass
pass
else:
for host in hosts:
if host:
regiondrainer_cmd = format(
"{kinit_cmd_decommission} {hbase_cmd} --config {hbase_conf_dir... | mat(
"{kinit_cmd_decommission} {hbase_cmd} --config {hbase_conf_dir} org.jruby.Main {region_mover} unload {host}")
Execute(regiondrainer_cmd,
user=params.hbase_user,
logoutput=True
)
Execute(regionmover_cmd,
user=params.hbase_user,
... |
sylverspace/craft_game | app.py | Python | mit | 10,026 | 0.033513 | from flask import Flask, render_template, redirect, url_for, request, session, flash, jsonify, g
import sqlite3 as sql
import os
import random
import json
from flask_sqlalchemy import SQLAlchemy
import ast #To change string list to a python list
import collections #To conte duplicate in iventory list using Count... | _repr__(self):
# return '{}'.format(self.id)
class Recipe(db.Model):
num_of_rec = 0
__tablen | ame__ = "recipes"
id = db.Column('id', db.Integer, primary_key=True)
name = db.Column("name", db.String(20))
type = db.Column("type", db.String(20))
result = db.Column("result", db.String(20))
prereq = db.Column("prereq", db.String(20))
ing_1 = db.Column("ing_1", db.String(20))
ing_qty_1 = db.Column("ing_... |
CKPalk/SeattleCrime_DM | DataMining/Stats/coord_bounds.py | Python | mit | 801 | 0.087391 | ''' Work of Cameron P | alk '''
import sys
import pandas as pd
def main( argv ):
try:
csv_filepath = argv[ 0 ]
output_filepath = argv[ 1 ]
except IndexError:
print( "Error, usage: \"python3 coord_bounds.py <CSV> <output_file>\"" )
return
trainin | g_data = pd.read_csv( csv_filepath )
training_data[ 'clean_Latitude' ] = training_data[ training_data.Latitude > 47 ].Latitude
training_data[ 'clean_Longitude' ] = training_data[ training_data.Longitude < -122 ].Longitude
training_data.dropna()
print( training_data[ 'clean_Latitude' ] )
for axis in [ 'clea... |
mrocklin/streams | streamz/sources.py | Python | bsd-3-clause | 25,985 | 0.001347 | from glob import glob
import os
import time
import tornado.ioloop
from tornado import gen
from .core import Stream, convert_interval, RefCounter
def PeriodicCallback(callback, callback_time, asynchronous=False, **kwargs):
source = Stream(asynchronous=asynchronous)
def _():
result = callback()
... | when the source
is started, and closed upon ``stop()``
delimit | er : bytes
The incoming data will be split on this value. The resulting events
will still have the delimiter at the end.
start : bool
Whether to immediately initiate the source. You probably want to
set up downstream nodes first.
server_kwargs : dict or None
If given, add... |
psycofdj/xtd | xtd/network/server/application.py | Python | gpl-3.0 | 5,010 | 0.020958 | # -*- coding: utf-8
#------------------------------------------------------------------#
__author__ = "Xavier MARCELET <xavier@marcelet.com>"
#------------------------------------------------------------------#
import json
import sys
import cherrypy
from xtd.core import logger, config
from xtd.co... | _logPage, "/admin/log", {
"/write" : {
'tools.auth_basic.on': True,
'tools.auth_basic.realm': 'localhost',
'tools.auth_basic.checkpassword': l_logPage.check_password
}
}, __name__)
ServerManager.subscribe("exit", super().stop, 100)
@cherrypy.expose
@cherrypy.tools.j... | "method" : cherrypy.request.method,
"path" : cherrypy.request.path_info,
"params" : cherrypy.request.params,
"headers" : cherrypy.request.headers
}
logger.error(self.m_name, "unhandled request : %s", json.dumps(l_reqinfo))
cherrypy.response.status = 500
return {
"error" :... |
murffer/DetectorSim | MCNPXRPMModels/WrappedCylinders/CylinderMCNPX.py | Python | apache-2.0 | 23,537 | 0.016145 | #!/usr/bin/env python
"""
MCNPX Model for Cylindrical RPM8
"""
import sys
sys.path.append('../MCNPTools/')
sys.path.append('../')
from MCNPMaterial import Materials
import subprocess
import math
import mctal
import numpy as np
import itertools
import os
class CylinderRPM(object):
# Material Dictionaries
cell... | l['Detector'] = {'name':'Detector','mt': 3, 'rho': 1.1,'matString':None} # detector
self.material['LightGuide'] = {'name': 'PMMA','mt':10, 'rho':0.93} # PMMA
self.material['Moderator'] = {'name':'HDPE','mt':456, 'rho': 0.93} # HPDE
# Cell and Surface Inital Numbering
... | self.SurfaceStartNum = 600
self.ZeroSurfaceNum = 500
self.UniverseNum = 200
self.surfGeo = None
self.inp = inp
self.name = 'OUT_'+self.inp.strip('.mcnp')+'.'
self.setMaterial(0.1,'PS')
def __str__(self):
s = '\tMCNPX Model of Wrapped Cylinder\n'
... |
dansackett/Todooo | todooo/validators.py | Python | mit | 1,462 | 0.001368 | import errors
def validate_num_arguments_eq(num_args):
"""Validate that the number of supplied args is equal to some number"""
def decorator(func):
def wrapped_func(*args, **kwargs):
if len(args[1]) != num_args:
raise errors.InvalidArgumentError
else:
... | r"""
def decorator(func):
def wrapped_func(*args, **kwargs):
if len(args[1]) < num_args:
raise errors.InvalidArgumentE | rror
else:
func(*args, **kwargs)
return wrapped_func
return decorator
def parse_index(lst, id):
"""Validate an index to the list is within range and a digit and return it"""
if not id.isdigit():
raise errors.ExpectedItemError
idx = int(id) - 1
if idx >... |
xypron/mini-dinstall | minidinstall/ChangeFile.py | Python | gpl-2.0 | 4,579 | 0.005241 | # ChangeFile
# A class which represents a Debian change file.
# Copyright 20 | 02 Colin Walters <walters@gnu.org>
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as p | ublished by
# the Free Software Foundation; either version 2 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
#... |
uclouvain/osis | reference/admin.py | Python | agpl-3.0 | 2,104 | 0.000476 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | e http:// | www.gnu.org/licenses/.
#
##############################################################################
from django.contrib import admin
from reference.models import *
admin.site.register(continent.Continent,
continent.ContinentAdmin)
admin.site.register(currency.Currency,
cur... |
Affirm/moto | moto/dynamodb2/comparisons.py | Python | apache-2.0 | 15,123 | 0.00238 | from __future__ import unicode_literals
import re
import six
# TODO add tests for all of these
EQ_FUNCTION = lambda item_value, test_value: item_value == test_value # flake8: noqa
NE_FUNCTION = lambda item_value, test_value: item_value != test_value # flake8: noqa
LE_FUNCTION = lambda item_value, test_value: item_va... | ue:
values_map[key] = value['S']
elif 'NS' in value:
values_map[key] = tuple(value['NS'])
elif 'SS' in value:
values_map[key] = tuple(value['SS'])
elif 'L' in value:
values_map[key] = tuple(value['L'])
else:
raise NotImple | mentedError()
# Remove all spaces, tbf we could just skip them in the next step.
# The number of known options is really small so we can do a fair bit of cheating
expr = list(expr.strip())
# DodgyTokenisation stage 1
def is_value(val):
return val not in ('<', '>', '=', '(', ')')
def c... |
kfieldho/SMQTK | python/smqtk/representation/code_index/memory.py | Python | bsd-3-clause | 5,235 | 0.000764 | import cPickle
import os.path as osp
from smqtk.representation.code_index import CodeIndex
from smqtk.utils import SimpleTimer
__author__ = "paul.tunison@kitware.com"
class MemoryCodeIndex (CodeIndex):
"""
Local RAM memory based index with an optional file cache
"""
@classmethod
def is_usable(... | mqtk.representation.DescriptorElement)]
"""
for c, d in code_descriptor_pairs:
self.add_descriptor(c, d, True)
self.cache_table()
def get_descriptors(self, code_or_codes):
"""
Get iterable of descriptors associated to this code or iterable of
codes. This... | r or iterable of integer bit-codes.
:type code_or_codes: collections.Iterable[int] | int
:return: Iterable of descriptors
:rtype: collections.Iterable[smqtk.representation.DescriptorElement]
"""
if hasattr(code_or_codes, '__iter__'):
# noinspection PyTypeChecker
... |
projectweekend/Links-API | links/issues/mixins.py | Python | mit | 849 | 0 | from issues.models import ReportedLink, ReportedUser
from issues.serializers import ReportedLinkSerializer, ReportedUserSerializer
class ReportedLinkAPI(object):
serializer_class = ReportedLinkSerializer
def get_queryset(self):
return ReportedLink.objects.all()
class ReportedLinkSelfAPI(object):
... | def pre_save(self, obj):
obj.reporter = self.request.user
class ReportedUserAPI(object):
serializer_class = ReportedUserSerializer
def get_queryset(self):
| return ReportedUser.objects.all()
class ReportedUserSelfAPI(object):
def get_queryset(self):
return ReportedUser.objects.filter(reporter=self.request.user)
def pre_save(self, obj):
obj.reporter = self.request.user
|
LaoZhongGu/kbengine | kbe/src/lib/python/PCbuild/build_ssl.py | Python | lgpl-3.0 | 9,198 | 0.002827 | # Script for building the _ssl and _hashlib modules for Windows.
# Uses Perl to setup the OpenSSL environment correctly
# and build OpenSSL, then invokes a simple nmake session
# for the actual _ssl.pyd and _hashlib.pyd DLLs.
# THEORETICALLY, you can:
# * Unpack the latest SSL release one level above your main Python ... | = makefile
dirsuffix = "32"
elif sys.argv[2] == "x64":
arch="amd64"
configure = "VC-WIN64A"
do_script = "ms\\do_win64a"
makefile = "ms\\nt64.mak"
m32 = makefile.replace('64', '')
dirsuffix = "64"
#os | .environ["VSEXTCOMP_USECL"] = "MS_OPTERON"
else:
raise ValueError(str(sys.argv))
make_flags = ""
if build_all:
make_flags = "-a"
# perl should be on the path, but we also look in "\perl" and "c:\\perl"
# as "well known" locations
perls = find_all_on_path("perl.exe", ["\\perl\\bi... |
wichert/rest_toolkit | tests/test_resource.py | Python | bsd-2-clause | 3,615 | 0 | import pytest
from webtest import TestApp
from pyramid.config import Configurator
from pyramid.testing import DummyRequest
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.authentication import AuthTktAuthenticationPolicy
def make_app(config):
return TestApp(config.make_wsgi_app())
@pytest.... | = Configura | tor()
config.scan('controller')
app = make_app(config)
r = app.get('/engage')
assert r.json == {'message': 'Warp engine offline'}
@pytest.mark.parametrize('method', ['delete', 'get', 'patch', 'put'])
def test_controller_invalid_method(method):
config = Configurator()
config.scan('controller')
... |
PearsonIOKI/compose-forum | askbot/utils/twitter.py | Python | gpl-3.0 | 479 | 0.002088 | import urllib
from askbot.deps.django_authopenid.util import OAuthConnection
class Twitter(OAuthCon | nection):
def __init__(self):
super(Twitter, self).__init__('twitter')
self.tweet_url = 'https://api.twitter.com/1.1/statuses/update.json'
def tweet(self, text, access_token=None):
client = self.get_client(access_token)
body = urllib.url | encode({'status': text})
return self.send_request(client, self.tweet_url, 'POST', body=body)
|
bruderstein/PythonScript | PythonLib/min/argparse.py | Python | gpl-2.0 | 97,984 | 0.000235 | # Author: Steven J. Bethard <steven.bethard@gmail.com>.
# New maintainer as of 29 August 2019: Raymond Hettinger <raymond.hettinger@gmail.com>
"""Command-line parsing library
This module is an optparse-inspired command-line parsing library that:
- handles both optional and positional arguments
- produces hi... | and RawTextHelpFormatter tell the parser
not to change the formatting for help text, and
ArgumentDefaultsHelpFormatter adds information about argument defaults
to the help.
All other classes in this module are considered implementation details.
(Also note that HelpFormatter and RawDescriptionH... | red an implementation detail.)
"""
__version__ = '1.1'
__all__ = [
'ArgumentParser',
'ArgumentError',
'ArgumentTypeError',
'BooleanOptionalAction',
'FileType',
'HelpFormatter',
'ArgumentDefaultsHelpFormatter',
'RawDescriptionHelpFormatter',
'RawTextHelpFormatter',
'MetavarTypeHe... |
devs4v/devs4v-information-retrieval15 | project/lucene/pylucene-4.9.0-0/jcc/helpers/linux.py | Python | mit | 7,260 | 0.003306 | # 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
# distribu... | eargs=None, extra_postargs=None, build_temp=None, target_lang=None):
assert output_dir is None # distutils build_ext doesn't pass this
output_dir, filename = os.path.split(output_libname)
basename, ext = os.path.splitext(filename)
if self.library_filename("x").startswith('lib'):
# strip 'lib' ... | ame, output_dir, debug, target_lang)
def check_packages(dist, attr, value):
for pkgname in value:
if not re.match(r'\w+(\.\w+)*', pkgname):
distutils.log.warn(
"WARNING: %r not a valid package name; please use only"
".-separated package names in setup.py", pkgnam... |
LeunamBk/translatorPy | globalHotkeys.py | Python | gpl-3.0 | 950 | 0.009474 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
try:
from PyQt4.QtGui import QApplication, QKeySequence
except ImportError:
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QKeySequence
from pygs import QxtGlobalShortcut
def hotkeyBinding():
| SHORTCUT_SHOW = "Ctrl+Alt+S" # Ctrl maps to Command on Mac OS X
SHORTCUT_EXIT = "Ctrl+Alt+F" # again, Ctrl maps to Command on Mac OS X
def show_activated():
print("Shortcut Activated!")
app = QApplication([])
shortcut_show = QxtGlobalShortcut()
shortcut_show.setSho | rtcut(QKeySequence(SHORTCUT_SHOW))
shortcut_show.activated.connect(show_activated)
shortcut_exit = QxtGlobalShortcut()
shortcut_exit.setShortcut(QKeySequence(SHORTCUT_EXIT))
shortcut_exit.activated.connect(app.exit)
return_code = app.exec_()
del shortcut_show
del shortcut_exit... |
mmilkin/cchaser | chaser/tests/test_controller.py | Python | mit | 4,019 | 0.000498 | import unittest
from mock import patch, call
from chaser.controller import MotorController, LEFT_KEY, RIGHT_KEY, UP_KEY, DOWN_KEY, MotorInputError
class ControllerTestCase(unittest.TestCase):
@patch('chaser.controller.gpio')
def test_init(self, io):
io.OUT = True
calls = [call(4, True), call(... | False), call(17, False), call(24, False), call(25, False)]
io.output.assert_has_calls(calls)
@patch('chaser.controller.gpio')
def test_left(self, io):
controller = MotorController()
controller.left()
calls = [call(24, True), call(25, False)]
io.output.assert_has_calls(c... | haser.controller.gpio')
def test_left_stop(self, io):
controller = MotorController()
controller.turn_keys.add(LEFT_KEY)
controller.left()
calls = [call(24, False), call(25, False)]
io.output.assert_has_calls(calls)
self.assertEqual(controller.state, 'stopped')
@p... |
google/pikov | python/pikov/properties.py | Python | apache-2.0 | 2,766 | 0 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
raise NotImplementedError()
def __get__(self, obj, type=None):
return self.from_node(obj, obj[self._label])
def __set__(self, obj, value):
obj[self._label] = self.to_node(value)
class UnspecifiedProperty(AbstractSemanticGraphProperty):
def from_node(self, obj, value):
| obj._graph.get_value(obj, self._label)
def to_node(self, value):
# Value should already by a Node.
return value
class GuidProperty(AbstractSemanticGraphProperty):
def __init__(self, label, cls):
super().__init__(label)
self._cls = cls
def from_node(self, obj, value):
... |
DiegoQueiroz/scriptLattes | scriptLattes/producoesBibliograficas/outroTipoDeProducaoBibliografica.py | Python | gpl-2.0 | 3,771 | 0.032388 | #!/usr/bin/python
# encoding: utf-8
# filename: outroTipoDeProducaoBibliografica.py
#
# scriptLattes V8
# Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr.
# http://scriptlattes.sourceforge.net/
#
#
# Este programa é um software livre; você pode redistribui-lo e/ou
# modifica-lo dentro dos termos d... | bruto
idMembro = None
relevante = None
autores = None
titulo = None
ano = None
natureza = None # tipo de producao
chave = None
def __init__(self, idMembro, partesDoItem='', relevante=''):
self.idMembro = set([])
self.idMembro.add(idMembro)
if not partesDoI | tem=='':
# partesDoItem[0]: Numero (NAO USADO)
# partesDoItem[1]: Descricao do livro (DADO BRUTO)
self.relevante = relevante
self.item = partesDoItem[1]
# Dividir o item na suas partes constituintes
partes = self.item.partition(" . ")
self.autores = partes[0].strip()
partes = partes[2]
aux... |
ElliotTheRobot/LILACS-mycroft-core | mycroft/skills/LILACS_knowledge/services/wikidata/__init__.py | Python | gpl-3.0 | 2,400 | 0.002917 | from os.path import abspath
import wptools
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_knowledge.services import KnowledgeBackend
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(abspath(__file__).split('/')[-2])
class WikidataService(KnowledgeBackend):... |
self.emitter.on('WikidataKnowledgeAdquire', self._adquire)
def _adquire(self, message=None):
logger.info('WikidataKnowledge_Adquire')
subject = message.data["subject"]
if subject is None:
| logger.error("No subject to adquire knowledge about")
return
else:
dict = {}
node_data = {}
# get knowledge about
# TODO exception handling for erros
try:
page = wptools.page(subject, silent=True, verbose=False).get_wik... |
bollwyvl/jademagic | jademagic.py | Python | bsd-3-clause | 1,775 | 0 | # -*- coding: utf-8 -*-
from __future__ import print_function
from IPython import get_ipython
from IPython.display import (
display,
Javascript,
HTML,
)
from IPython.core import magic_arguments
from IPython.core.magic import (
Magics,
magics_class,
cell_magic,
)
import pyjade
__version_info_... | s JadeMagics(Magics):
"""
Write and load HTML with Jade in the IPython Notebook.
Example:
%%jade
ul
li: some text!
"""
def __init__(self, shell):
super(JadeMagics, self).__init__(shell)
@cell_magic
@magic_arguments.magic_arguments()
@magic_argument... | ent(
"var_name",
default=None,
nargs="?",
help="""Name of local variable to set to parsed value"""
)
def jade(self, line, cell):
line = line.strip()
args = magic_arguments.parse_argstring(self.jade, line)
display(Javascript(
"""
re... |
vmanoria/bluemix-hue-filebrowser | hue-3.8.1-bluemix/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/test/test_sf.py | Python | gpl-2.0 | 460 | 0.041304 |
# This is to see that the total memory usage | doesn't increase with time
# i.e. no leakage / link between consecutive usages of hsp.
# This will run for ever, to be monitored by the printout and some external monitor.
def t():
from guppy import hsp
while 1:
import guppy.heapy.UniSet
import gc
reload( guppy.heapy.UniSet )
hp = hsp()
x = None
x = hp.h... | t x[0]
print x[1]
print x[2]
gc.collect()
print x&dict
|
ThisLife/aws-management-suite | amslib/network/route53.py | Python | mit | 46,031 | 0.004627 | import boto
from amslib.core.manager import BaseManager
from amslib.instance.instance import InstanceManager
import argparse
from errors import *
import pprint
import time
pp = pprint.PrettyPrinter(indent=4)
# Custom HealthCheck object to add support for failure threshold...seems to have been missed in boto
class He... | """<EvaluateTargetHealth>%s</EvaluateTargetHealth>"""
valid_failover_roles = ['PRIMARY', 'SECONDARY']
def __init__(self, name=None, type=None, ttl=600, resource_records=None,
alias_hosted_zone_id=None, alias_dns_name=None, identifier=None,
weight=None, region=None, alias_evaluate_targ... | = type
self.ttl = ttl
if resource_records is None:
resource_records = []
self.resource_records = resource_records
self.alias_hosted_zone_id = alias_hosted_zone_id
self.alias_dns_name = alias_dns_name
self.identifier = identifier
self.weight = weight
... |
mancoast/CPythonPyc_test | cpython/266_test_zipimport_support.py | Python | gpl-3.0 | 10,482 | 0.000859 | # This test module covers support in various parts of the standard library
# for working with modules located inside zipfiles
# The tests are centralised in this fashion to make it easy to drop them
# if a platform doesn't support zipimport
import unittest
import test.test_support
import os
import os | .path
import sys
import textwrap
import zipfile
import zipimport
import doctest
import inspect
import linecache
import pdb
import warnings
verbose = test.test_support.verbose
# Library modules covered by this test set
# pdb (Issue 4201)
# inspect (Issue 4223)
# doctest (Issue 4197)
# Other test modules with zipim... | sts
# test_zipimport (of course!)
# test_cmd_line_script (covers the zipimport support in runpy)
# Retrieve some helpers from other test cases
from test import test_doctest, sample_doctest
from test.test_importhooks import ImportHooksBaseTestCase
from test.test_cmd_line_script import temp_dir, _run_python, \
... |
ldemattos/openComtradeViewer | src/pyComtrade.py | Python | gpl-3.0 | 15,076 | 0.022221 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Copyright (c) 2013 Miguel Moreto <http://sites.google.com/site/miguelmoreto/>
#This file is part of pyComtrade.
#
# pyComtrade is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fre... | lf.lf = int(float(self.filehandler.readline()))
| # Read sampling rates:
self.nrates = int(self.filehandler.readline()) # nrates.
for i in range(self.nrates): #@UnusedVariable
line = self.filehandler.readline()
templist = line.split(',')
self.samp.append(int(float(templist[0])))
self.endsamp.app... |
eternalfame/django-russian_fields | russian_fields/__init__.py | Python | mit | 56 | 0.035714 | __version__ = "0 | .1.3"
get_version = lambda: __ | version__ |
Ebag333/Pyfa | eos/effects/highspeedmanuveringcapacitorneedmultiplierpostpercentcapacitorneedlocationshipmodulesrequiringhighspeedmanuvering.py | Python | gpl-3.0 | 568 | 0.003521 | # highSpeedManuveringCapacitorNeedMultiplierPostPercentCapacitorNeedLocationShipModulesRequiringHighSpeedManuvering
#
# Used by:
# Implants named like: Eifyr and Co. 'Rogue' High Speed Maneuvering HS (6 of 6)
# Skill: High Speed Maneuvering
type = "passive"
def handler(fit, container, context):
l | evel = container.level if "skill" in context else 1
fit.modules.filteredItemBoost(lambda mod: mod.item.requiresSkill("High Speed Maneuvering"),
"capacitorNeed", container.getModifiedItemAtt | r("capacitorNeedMultiplier") * level)
|
dmitry-sobolev/ansible | lib/ansible/module_utils/vyos.py | Python | gpl-3.0 | 4,383 | 0.004335 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | t(fallbac | k=(env_fallback, ['ANSIBLE_NET_PASSWORD']), no_log=True),
'ssh_keyfile': dict(fallback=(env_fallback, ['ANSIBLE_NET_SSH_KEYFILE']), type='path'),
'timeout': dict(type='int'),
'provider': dict(type='dict'),
}
def check_args(module, warnings):
provider = module.params['provider'] or {}
for key in vy... |
shsingh/ansible | lib/ansible/cli/__init__.py | Python | gpl-3.0 | 20,952 | 0.002816 | # Copyright: (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright: (c) 2016, Toshio Kuratomi <tkuratomi@ansible.com>
# Copyright: (c) 2018, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import ... | le.parsing.dataloader import DataLoader
from ansible.parsing.vault import PromptVaultSecret, get_file_vault_secret
from ansible.plugins.loader import add_all_plugin_dirs
from ansible.release import __version__
from ansible.ut | ils.collection_loader import AnsibleCollectionLoader, get_collection_name_from_path, set_collection_playbook_paths
from ansible.utils.display import Display
from ansible.utils.path import unfrackpath
from ansible.utils.unsafe_proxy import to_unsafe_text
from ansible.vars.manager import VariableManager
try:
import ... |
davidam/python-examples | nlp/nltk/howtos/generate.py | Python | gpl-3.0 | 537 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from nltk.parse.generate import generate, demo_grammar
from nltk import CFG
grammar = CFG.fromstring(demo_grammar)
print(grammar)
for sentence in generate(grammar, n=10):
print(' '.join(sentence))
for sentence | in generate(grammar, depth=4):
print(' '.join(sentence))
print(len(list(generate(grammar, depth=3))))
print(len(list(generate(grammar, depth=4))))
print(len(list(generate(grammar, depth=5))))
print(len(list(generate(grammar, depth=6))))
print(len(list(generate(grammar)) | ))
|
katakumpo/pipetools | pipetools/debug.py | Python | mit | 672 | 0 | from itertools import imap, chain
def set_name(name, f):
try:
f.__pipetools__name__ = name
except (AttributeError, UnicodeEncodeError):
pass
return f
def get_name(f):
from pipetools.main import Pipe
pipetools_name = getattr(f, '__pipetools__name__', None)
if pipetools_name:
... | me() if callable(pipetools_name) else pipetools_name
if isinstance(f, Pipe):
return repr(f)
return f.__name__ if hasattr(f, '__name__') else repr(f)
def repr_args(*args, **kwargs):
return ', '.join(chain(
imap('{0!r}'.format, args),
imap('{0[0]}={0[1]!r}'.format, kwargs.iteritems... | ))))
|
paulbellamy/Rhythmbox-iPod-Plugin | plugins/jamendo/jamendo/__init__.py | Python | gpl-2.0 | 4,882 | 0.020893 | # -*- coding: utf-8 -*-
# __init__.py
#
# Copyright (C) 2007 - Guillaume Desmottes
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#... | activate(self, shell):
self.db = shell.get_property("db")
self.entry_type = self.db.entry_register_type("JamendoEntryType")
# allow changes which don't do anything
self.entry_t | ype.can_sync_metadata = True
self.entry_type.sync_metadata = None
group = rb.rb_source_group_get_by_name ("stores")
if not group:
group = rb.rb_source_group_register ("stores",
_("Stores"),
rb.SOURCE_GROUP_CATEGORY_FIXED)
theme = gtk.icon_theme_get_default()
rb.append_plugin_s... |
ilpianista/ansible | lib/ansible/playbook/task.py | Python | gpl-3.0 | 20,951 | 0.002148 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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, either version 3 of the License, or
# (at your option) an... | 'loop' keyword instead", version="2.10")
def preprocess_data(self, ds):
'''
tasks are especially complex arguments so need pre-processing.
keep it short.
'''
if not isinstance(ds, dict):
raise AnsibleAssertionError('ds (%s) should be a dict but was a %s' % (ds | , type(ds)))
# the new, cleaned datastructure, which will have legacy
# items reduced to a standard structure suitable for the
# attributes of the task class
new_ds = AnsibleMapping()
if isinstance(ds, AnsibleBaseYAMLObject):
new_ds.ansible_pos = ds.ansible_pos
... |
pythonprobr/pythonpro-website | pythonpro/analytics/context_processors.py | Python | agpl-3.0 | 197 | 0 | from | django.conf import settings
def posthog_configurations(request):
return {
'POSTHOG_API_KEY': settings.POSTHOG_API_KEY,
'POSTHOG_API_URL': settings.POSTHOG_API_URL,
} | |
tectronics/nyctos | src/data.res/scripts/npcs/retiredminer.py | Python | gpl-2.0 | 1,428 | 0.008403 | import parole
from parole.colornames import colors
from parole.display import interpolateRGB
import pygame, random
import sim_creatures, main, rando | m
from util import *
description = \
"""
This guy should really look into another line of work.
"""
nagLines = [
'*sigh*',
"It's not been the same 'round 'ere.",
"Ain't been no work since the mines... changed.",
"We been in | for some rough times.",
"I pray they don't get to the wells.",
]
class NPCClass(sim_creatures.NPC):
def __init__(self):
sim_creatures.NPC.__init__(
self,
'retired miner', # name
parole.map.AsciiTile('@', colors['Gray']), # symbol, color
11, # str
... |
ProgDan/maratona | SPOJ/UJ.py | Python | gpl-3.0 | 129 | 0.124031 | while 1:
arr=input().split(' ')
k=arr[0]
n=arr[1]
if k==' | 0' and n=='0':
break
ans=int(int(k)**int(n | ))
print (int(ans))
|
nirmeshk/oh-mainline | vendor/packages/oauthlib/tests/oauth2/rfc6749/endpoints/test_credentials_preservation.py | Python | agpl-3.0 | 4,860 | 0.003086 | """Ensure credentials are preserved through the authorization.
The Authorization Code Grant will need to preserve state as well as redirect
uri and the Implicit Grant will need to preserve state.
"""
from __future__ import absolute_import, unicode_literals
import json
import mock
from .test_utils import get_query_cre... | .web.create_authorization_response(
auth_uri + 'code', scopes=['random'])
self.assertEqual(s, 302)
self.assertIn('Location', h)
code = get_query_credentials(h['Location'])['code'][0]
self.validator.validate_code.side_effect = self.set_state('xyz')
_, body, _ = sel... | token_response(token_uri,
body='grant_type=authorization_code&code=%s' % code)
self.assertEqual(json.loads(body)['state'], 'xyz')
# implicit grant
h, _, s = self.mobile.create_authorization_response(
auth_uri + 'token', scopes=['random'])
self.assertEqual... |
Bulochkin/tensorflow_pack | tensorflow/python/kernel_tests/fft_ops_test.py | Python | apache-2.0 | 18,811 | 0.010207 | # 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... | nk in VALID_FFT_RANKS:
for dims in xrange(rank, rank + 3):
x = np.zeros((0,) * dims).astype(np.complex64)
self.assertEqual(x.shape, self._tfFFT(x, rank).shape)
self.assertEqual(x.shape, self._tfIFFT(x, rank).shape)
def t | estBasic(self):
with self._fft_kernel_label_map():
for rank in VALID_FFT_RANKS:
for dims in xrange(rank, rank + 3):
self._Compare(
np.mod(np.arange(np.power(4, dims)), 10).reshape(
(4,) * dims).astype(np.complex64), rank)
def testBasicPlaceholder(self):
... |
Flyingfox646/flyingfox | src/chunks/migrations/0004_faq_fairplay.py | Python | mit | 5,970 | 0.004275 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
faq_en = '''
<p>
<b>Why statistics on the site does not coincide with the statistics in the game?</b>
</p>
<p>
Algorithms collection statistics IL2 stats differs from statistics in-game. As a consequence of these... | ок зарабатывает очков за одну жизнь - очки / (смерти + плен) = ОС<br>
2) вычисляем сколько игрок зарабатывает очков за один час налета - очки / налет часов = ОЧ<br>
3) вычисляем рейтинг по формуле: (ОС * ОЧ * очки) / 1000
</p>
<br>
<p>
<b>Почему мой профиль не отображается в общей таблице игроков?</b>
</p>
<p>
В стати... | 7 дней - не участвуют в рейтинге.
</p>
<br>
<p>
<b>Я приземлился на аэродром, но в статусе вылета указана посадка в поле. Почему?</b>
</p>
<p>
Посадка засчитывается только на активный аэродром. Как правило активный аэродром это тот на котором вы можете начать вылет.
</p>
<br>
<p>
<b>Что такое "Индекс честной игры"?</... |
ofer43211/unisubs | apps/teams/migrations/0057_auto__chg_field_project_slug__chg_field_task_assignee.py | Python | agpl-3.0 | 23,628 | 0.008507 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Project.slug'
db.alter_column('teams_project', 'slug', self.gf('django.db.models.fie... | ignee_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['teams.TeamMember'], null=True, blank=True))
models = {
'auth.customuser': {
| 'Meta': {'object_name': 'CustomUser', '_ormbases': ['auth.User']},
'autoplay_preferences': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'award_points': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'biography': ('django.db.models.fields.Text... |
Alex-Ian-Hamilton/solarbextrapolation | solarbextrapolation/preprocessors/base.py | Python | mit | 2,867 | 0.006278 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 19:18:58 2015
@author: alex_
"""
# General Imports
import matplotlib as mpl
mpl.use('TkAgg') # Force mpl backend not to use qt. Else we have a conflict.
import numpy as np
import pickle
import time
from datetime import datetime
from collections import namedtuple
impor... | self.map_input = map_data
self.routine = kwargs.get('preprocessor_routine', type(self))
self.meta = self.map_input.meta
self.meta['preprocessor_notes'] = kwargs.get('notes', '')
self.meta['preprocessor_routine'] = self.routine
self.filepath = kwargs.get('filepath', None)
... | ility this should add entries into the metadata that
include any parameters used for the given run.
"""
map_output = sunpy.map.Map(self.map_input.data, self.meta)
return map_output
def preprocess(self, **kwargs):
"""
Method to be called to run the preprocessor.
... |
fizz-ml/pytorch-aux-reward-rl | model_generator.py | Python | mit | 671 | 0.011923 | import os
import sys
import getopt
import json
def main(argv):
"""Specify input to generator with:
-s : save | path
-f : model_def folder
"""
opts, args = getopt.getopt(argv,"s:f:")
save_location = "models/ddpg_models/"
model_def_folder = ""
print(opts)
for opt, arg in opts:
if opt == "-s":
save_location = arg
elif opt == "-f":
model_def_folder = arg
... | json.loads(json_data)
print(config_dict)
exec('')
os.system("script2.py 1")
if __name__ == "__main__":
main(sys.argv[1:])
|
ieuan1630-cmis/ieuan1630-cmis-cs2 | cs2quiz1.py | Python | cc0-1.0 | 2,934 | 0.02454 | #40/40
#Part 1: Terminology (15 points) --> 15/15
#1 1pt) What is the symbol "=" used for?
#to assign and store values to and in variables
# 1pt
#
#2 3pts) Write a technical definition for 'function'
#a named sequence of calculations which takes input and returns output
# 3pts
#
#3 1pt) What does the keyword "return" d... | g main
main()
#1pt explanatory comments
#1pt code format
| |
g2p/xtraceback | xtraceback/lexer.py | Python | mit | 2,860 | 0.006643 | try:
from pygments.lexer import bygroups, include, using
from pygments.lexers.agile import PythonLexer, PythonTracebackLexer
from pygments.token import Text, Name, Number, Generic, String, Operator
except ImportError: # pragma: no cover
# this is for nose coverage which does a recursive import on the p... | ef = "(<ref offset)(=)(\-\d+)( ?)((?:name)?)(=?)((?:%s)?)(>?)" % BASE_NAME
tokens["root"].insert(0, (ref, bygroups(Name.Builtin, Name.Operator,
Number, Text, Name.Builtin,
Name.Operator, Name.Variable,
... | "root": [
include("entry"),
include("exception"),
(r"^.*\n", Generic.Error),
],
"entry": [
(r"^Traceback \(most recent call last\):\n",
Generic.Error,
"frame"),
# file - path i... |
alex/flanker | flanker/mime/message/headers/encodedword.py | Python | apache-2.0 | 3,690 | 0.000815 | # coding:utf-8
import logging
import regex as re
import email.quoprimime
import email.base64mime
from base64 import b64encode
from flanker.mime.message import charsets, errors
log = logging.getLogger(__name__)
#deal with unfolding
foldingWhiteSpace = re.compile(r"(\n\r?|\r\n?)(\s*)")
def unfold(value):
"""
... | _unicode("=?UTF-8?B?UmVbMl06INCX0LXQvNC70Y/QutC4?=")
u"Земляки"
>>> header_to_unicode("hello")
u"Hello"
"""
try:
header = unfold(header)
decoded = [] # decoded parts
while header:
match = encodedWord.search(header)
if match:
s... | t])
if value.strip():
decoded.append(value)
# decode a header =?...?= of encoding
charset, value = decode_part(
match.group('charset').lower(),
match.group('encoding').lower(),
match.g... |
congminghaoxue/learn_python | change_pic_size_by_cut.py | Python | apache-2.0 | 1,474 | 0.003634 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# function: 剪切更改图片尺寸大小
import os
import os.path
import sys
import argparse
from PIL import Image
def CutImage(filein, fileout, width, height, type):
'''
# 从左上角开始 剪切 width*height的图片
filein: 输入图片
fileout: 输出图片
width: 输出图片宽度
height:输出图片高度
type:输... | = "__main__":
argc = len(sys.argv)
cmdargs = str(sys.argv)
parser = argparse.ArgumentParser(description="Tool for change the picture to custom size")
parser.add_argument('-f', '--file', required=True, help='the file path of the input file')
parser.add_argument('-H', '--height', | type=int, required=True, help='height of the output file')
parser.add_argument('-W', '--width', type=int, required=True, help='width of the output file')
parser.add_argument('-T', '--type', required=False, help='the type of the output file: jpeg, git, png ,etc')
args = parser.parse_args()
filein = args... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.