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 |
|---|---|---|---|---|---|---|---|---|
ArcherSys/ArcherSys | skulpt/src/lib/markupbase.py | Python | mit | 73 | 0 | r | aise NotImplementedError("markupbase is not | yet implemented in Skulpt")
|
ysrodrigues/Fund-Prog | AD1-Exerc2.py | Python | gpl-3.0 | 1,948 | 0.019608 | def verificaPalindrome(frase):
removeWhiteSpaces = [] ### Array util para remover os espaços em brancos
removeHypen = [] ### Array util para remover os hifen
palindromo = str( | frase).lower().strip() ### Remove os espaços em brancos no inicio e final e coloca toda a palavra em letra minuscula
if (len(palindromo) == 1): ### Se o tamanho da palavra for 1, entao ele deve retornar verdadeiro
return True
### BEGIN - Remover os | espaços em branco no meio da frase - BEGIN ###
removeWhiteSpaces = palindromo.split(' ')
palindromo = str()
for word in removeWhiteSpaces:
palindromo = palindromo + word
### END - Remover os espaços em branco no meio da frase - END ###
### BEGIN - Remover hypen no meio da frase - BEGIN ###... |
wdq007/supreme-garbanzo | fkkenv/fukoku/env/admin.py | Python | gpl-3.0 | 461 | 0.02603 | fr | om django.contrib import admin
# Register your models here.
from .models import Environment,EnvironmentAdmin,Component,ComponentAdmin,Environment_property,Environment_propertyAdmin,Component_attribute,Component_attributeAdmin
admin.site.register(Environment,EnvironmentAdmin)
admin.site.register(Component,ComponentAd... | (Component_attribute,Component_attributeAdmin)
|
davelab6/pyfontaine | fontaine/charsets/noto_chars/notosanshebrew_regular.py | Python | gpl-3.0 | 9,355 | 0.015927 | # -*- coding: utf-8 -*-
class Charset(object):
common_name = 'NotoSansHebrew-Regular'
native_name = ''
def glyphs(self):
chars = []
chars.append(0x0000) #null ????
chars.append(0x200C) #uni200C ZERO WIDTH NON-JOINER
chars.append(0x000D) #nonmarkingreturn ????
ch... | WITH MAPIQ
chars.append(0xFB35) #vavdagesh HEBREW LETTER VAV WITH DAGESH
chars.append(0xFB36) #zayindagesh HEBREW LETTER ZAYIN WITH DAGESH
chars.append(0xFB38) #tetdagesh HEBREW LETTER TET WITH DAGESH
chars.append(0xFB39) #yoddagesh HEBREW LETTER YOD WITH DAGESH
chars.append... | HEBREW LETTER LAMED WITH DAGESH
chars.append(0xFB3E) #memdagesh HEBREW LETTER MEM WITH DAGESH
chars.append(0xFB40) #nundagesh HEBREW LETTER NUN WITH DAGESH
chars.append(0xFB41) #samekhdagesh HEBREW LETTER SAMEKH WITH DAGESH
chars.append(0xFB43) #finalpedagesh HEBREW LETTER FINAL PE ... |
mschwager/dhcpwn | dhcpwn.py | Python | gpl-3.0 | 2,829 | 0 | #!/usr/bin/env python3
import argparse
import logging
import string
# Quiet scapy
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy import volatile # noqa: E402
from scapy import sendrecv # noqa: E402
from scapy import config # noqa: E402
from scapy.layers import l2 # noqa: E402
from scapy.la... | '--count',
action='store',
default=10,
type=int,
help='number of addresses to consume'
)
subparsers.add_parser('sniff')
args = p.parse_args()
return args
def main():
args = parse_args()
dispatch = {
"flood": dhcp_flood,
"sniff": dhcp_sniff,
... | **vars(args))
if __name__ == "__main__":
main()
|
repology/repology | repology/parsers/parsers/cpan.py | Python | gpl-3.0 | 4,152 | 0.002168 | # Copyright (C) 2016-2019 Dmitry Marakasov <amdmi3@amdmi3.ru>
#
# This file is part of repology
#
# repology 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 optio... | g('unable to parse package name', Logger.ERROR)
continue
package_name, package_version = package_name.rsplit('-', 1)
if package_version.st | artswith('v') or package_version.startswith('V'):
package_version = package_version[1:]
if not package_version[0].isdecimal():
pkg.log('skipping bad version {}'.format(package_version), Logger.ERROR)
continue
if module.replace... |
googleinterns/via-content-understanding | VideoClassification/SegmentLevelClassifier/writer.py | Python | apache-2.0 | 13,749 | 0.014183 | """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 agreed to in writing, software
distr... | "audio": tf.train.FeatureList(feature=[audio]), "rg | b": tf.train.FeatureList(feature=[rgb])}
features = tf.train.FeatureLists(feature_list=features)
return features
def serialize_class_features(features):
"""Serialize features.
Args:
features: features of the video
"""
audio = features["audio"].tostring()
rgb = features["rgb"].tostring()
class_feat... |
rockychen-dpaw/oim-cms | core/views.py | Python | apache-2.0 | 11,814 | 0.001608 | from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden
from django.contrib.auth import login, logout
from django.core.cache import cache
from django.shortcuts import render
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from ipware.ip import get_ip
impor... | st.user.is_authenticated():
return auth(request)
# else return an empty response
response = HttpResponse('{}', content_type='application/json')
return response
@csrf_exempt
@never_cache
def auth_ip(request):
# Get the IP of the current user, try and match it up to a session.
current_ip = ... | s a basic auth header, perform a check.
basic_auth = request.META.get("HTTP_AUTHORIZATION")
if basic_auth:
# Check basic auth against Azure AD as an alternative to SSO.
username, password = base64.b64decode(
basic_auth.split(" ", 1)[1].strip()).decode('utf-8').split(":", 1)
u... |
ActiveState/code | recipes/Python/298336_http__Exploring_Headers_Cookies/recipe-298336.py | Python | mit | 9,871 | 0.005471 | #!/usr/bin/python -u
# 18-08-04
# v1.1.1
# http.py
# A simple CGI script, to explore http headers, cookies etc.
# Copyright Michael Foord
# Free to use, modify and relicense.
# No warranty express or implied for the accuracy, fitness to purpose or otherwise for this code....
# Use at your own risk !!!
# E-mail or mi... | ues = map(lambda x: x.value, theform[field]) # allows for list type values
data[field] = values
return data
errormess = "<H1>An Error Has Occurred</H1><BR><B><PRE>"
theformhead = """<HTML><HEAD><TITLE>http.py - Playing With Headers and Cookies</TITLE></HEAD>
<BODY><CENTER | >
<H1>Welcome to http.py - <BR>a Python CGI</H1>
<B><I>By Fuzzyman</B></I><BR>
"""+fontline +"Version : " + versionstring + """, Running on : """ + strftime('%I:%M %p, %A %d %B, %Y')+'''.</CENTER>
<BR>'''
HR = '<BR><BR><HR><BR><BR>'
theform = """This CGI script allows you to specify a URL using the form below.<BR>
It... |
thombashi/sqlitebiter | test/test_version_subcommand.py | Python | mit | 373 | 0 | from click.testing import | CliRunner
from sqlitebiter.__main__ import cmd
from sqlitebiter._const import ExitCode
from .common import print_traceback
class Test_version_subcommand:
def test_smoke(self):
runner = CliRunner()
result = runner.invoke(cmd, ["version"])
print_traceback(result)
assert result.exi... | SS
|
F483/trainlessmagazine.com | article/migrations/0020_remove_article_issue.py | Python | mit | 366 | 0 | # -*- co | ding: utf-8 -*-
from __future__ import unicode_literals
f | rom django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('article', '0019_remove_article_ordering_featured'),
]
operations = [
migrations.RemoveField(
model_name='article',
name='issue',
),
]
|
Prashant-Surya/addons-server | src/olympia/conf/stage/settings.py | Python | bsd-3-clause | 8,094 | 0 | import logging
import os
import environ
import datetime
from olympia.lib.settings_base import * # noqa
environ.Env.read_env(env_file='/etc/olympia/settings.env')
env = environ.Env()
CDN_HOST = 'https://addons-stage-cdn.allizom.org'
CSP_FONT_SRC += (CDN_HOST,)
CSP_FRAME_SRC += ('https://www.sandbox.paypal.com',)
CSP... | n the slave DB.
DATABASES['slave']['ATOMIC_REQUESTS'] = False
DATABASES['slave']['ENGINE'] = 'django.db.backends.mysql'
# Pool our database connections up for 300 s | econds
DATABASES['slave']['CONN_MAX_AGE'] = 300
SERVICES_DATABASE = env.db('SERVICES_DATABASE_URL')
SLAVE_DATABASES = ['slave']
CACHE_PREFIX = 'olympia.%s' % ENV
KEY_PREFIX = CACHE_PREFIX
CACHE_MIDDLEWARE_KEY_PREFIX = CACHE_PREFIX
CACHES = {}
CACHES['default'] = env.cache('CACHES_DEFAULT')
CACHES['default']['TIMEOU... |
gstiebler/odemis | src/odemis/acq/align/test/find_overlay_test.py | Python | gpl-2.0 | 3,688 | 0.003526 | # -*- coding: utf-8 -*-
'''
Created on 19 Dec 2013
@author: Kimon Tsitsikas
Copyright © 2012-2013 Kimon Tsitsikas, Delmic
This file is part of Odemis.
Odemis is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License version 2 as published by the Free Software
Fou... | Test FindOverlay failure due to low maximum allowed difference
"""
f = align.FindOverlay((6, 6), 1e-6, 1e-08, self.ebeam, self.ccd, self.sed, skew=True)
with self.assertRaises(ValueError):
f.result()
# @unittest.skip("skip")
def test_find_overlay_cancelled(self):
... |
f = align.FindOverlay((6, 6), 10e-06, 1e-07, self.ebeam, self.ccd, self.sed, skew=True)
time.sleep(0.04) # Cancel almost after the half grid is scanned
f.cancel()
self.assertTrue(f.cancelled())
self.assertTrue(f.done())
with self.assertRaises(futures.CancelledError):
... |
rspavel/spack | var/spack/repos/builtin/packages/py-colorpy/package.py | Python | lgpl-2.1 | 902 | 0.002217 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyColorpy(PythonPackage):
"""ColorPy is a Python package to convert physical descriptions ... | er screen. It provides a nice set of attractive plots
that you can make of such spectra, and some other color related
functions as well.
"""
homepage = "http://markkness.net/colorpy/ColorPy.html"
url = "https://pypi.io/packages/source/c/colorpy/colorpy-0.1.1.tar.gz"
version('0.1.1', sha25... | plotlib', type='run')
|
j0gurt/ggrc-core | src/ggrc/models/clause.py | Python | apache-2.0 | 1,804 | 0.006652 | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Module for Clause model."""
from ggrc import db
from ggrc.models.mixins import CustomAttributable
from ggrc.models.deferred import deferred |
from ggrc.models.mixins import Described
from ggrc.models.mixins import Hierarchical
from ggrc.models.mixins import Hyperlinked
from ggrc.models.m | ixins import Noted
from ggrc.models.mixins import Slugged
from ggrc.models.mixins import Stateful
from ggrc.models.mixins import Timeboxed
from ggrc.models.mixins import Titled
from ggrc.models.mixins import WithContact
from ggrc.models.object_owner import Ownable
from ggrc.models.object_person import Personable
from g... |
paurosello/frappe | frappe/modules/utils.py | Python | mit | 7,994 | 0.026395 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals, print_function
"""
Utilities for using modules
"""
import frappe, os, json
import frappe.utils
from frappe import _
def export_module_json(doc, is_standard, module):
"""Make a... | w: row.get(doctype_fieldname), data[key])))
# sync single doctype exculding the | child doctype
def sync_single_doctype(doc_type):
frappe.db.sql('delete from `tab{0}` where `{1}` =%s'.format(
custom_doctype, doctype_fieldname), doc_type)
for d in data[key]:
if d.get(doctype_fieldname) == doc_type:
d['doctype'] = custom_doctype
doc = frappe.get_doc(d)
doc.db_insert()
... |
devendermishrajio/nova_test_latest | nova/tests/unit/objects/test_block_device.py | Python | apache-2.0 | 16,751 | 0.00006 | # Copyright 2013 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | 'connection_info': "{'fake': 'connection_info'}",
'snapshot_id': 'fake-snapshot-id-1',
'boot_index': -1
})
if instance:
fake_bdm['ins | tance'] = instance
return fake_bdm
def _test_save(self, cell_type=None):
if cell_type:
self.flags(enable=True, cell_type=cell_type, group='cells')
else:
self.flags(enable=False, group='cells')
fake_bdm = self.fake_bdm()
with test.nested(
... |
gregpuzzles1/Sandbox | Example Programs/Ch_11_Student_Files/Case Study/algorithms.py | Python | gpl-3.0 | 1,983 | 0.004539 | """
File: algorithms.py
Algorithms configured for profiling.
"""
from profiler import Profiler
def selectionSort(lyst, profiler):
i = 0
while i < len(lyst) - 1: # Do n - 1 searches
minIndex = i # for the largest
j = i + 1
while j < len(lyst)... | profiler.comparison()
if itemToInsert < lyst[j]:
lyst[j + 1] = lyst[j]
profiler.exchange()
j -= 1
else:
break
lyst[j + 1] = itemToInsert
profiler.exchange()
| i += 1
def swap(lyst, i, j, profiler):
"""Exchanges the elements at positions i and j."""
profiler.exchange()
temp = lyst[i]
lyst[i] = lyst[j]
lyst[j] = temp
|
byn9826/Thousand-Day | handlers/token.py | Python | bsd-3-clause | 1,530 | 0.007843 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import mysql.connector
#from token find userId
#return 0 for error
def find | User(userToken, cnx):
userQuery = 'SELECT user_id FROM user_token WHERE user_token = %s'
try:
userCursor = cnx.cursor()
userCursor.execute(userQuery, (userToken, ))
return userCursor.fetchone()
#return 0 for db error
except mysql.connector.Error a | s err:
print('Something went wrong: {}'.format(err))
return '0'
finally:
userCursor.close()
#create new token
#return 1 for success
#return 0 for error
def addToken(userId, userToken, cnx):
addQuery = 'INSERT INTO user_token (user_id, user_token) VALUES (%s, %s) ON DUPLICATE KEY UPDATE... |
unreal666/outwiker | plugins/export2html/export2html/branchexporter.py | Python | gpl-3.0 | 7,572 | 0.008429 | # -*- coding: UTF-8 -*-
import os.path
import re
from outwiker.core.tree import WikiDocument
from outwiker.utilites.textfile import readTextFile, writeTextFile
from .exporterfactory import ExporterFactory
from .indexgenerator import IndexGenerator
class BranchExporter (object):
def __init__ (self, startpage, n... | /
slashPos = uid.fin | d ("/")
uid_clean = uid[: slashPos] if slashPos != -1 else uid
page = self.__application.pageUidDepot[uid_clean]
anchor = self.__getAnchor (uid)
return (page, anchor)
def __getAnchor (self, href):
"""
Попытаться найти якорь, если используется ссылка вида page://...... |
thp44/delphin_6_automation | data_process/wp6_v2/not_in_sample.py | Python | mit | 3,478 | 0.003163 | __author__ = "Christian Kongsgaard"
__license__ = 'MIT'
# -------------------------------------------------------------------------------------------------------------------- #
# IMPORTS
# Modules
# RiBuild Modules
from delphin_6_automation.database_interactions.db_templates import delphin_entry
from delphin_6_autom... | e in enumerate(samples):
if j == 0:
pass
else:
print(f'Deleting: {sample.id}')
#sample.delete()
if __name__ == '__main__':
server = mongo_setup.global_init(auth_dict)
#modify_sample()
#correct_sample()
#correct_... |
mongo_setup.global_end_ssh(server)
|
a25kk/apm | docs/conf.py | Python | mit | 5,991 | 0.006343 | # -*- coding: utf-8 -*-
# Build configuration file.
# This file is execfile()d with the current directory set to its
# containing dir.
# Note that not all possible configuration values are present in this
# autogenerated file.
# All configuration values have a default; values that are commented out
# serve to show the ... | r_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual])
latex_documents = [
('index',
'buildout.tex',
u'apm.buildout Documentation',
u'... | ),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents... |
255BITS/HyperGAN | hypergan/train_hooks/negative_momentum_train_hook.py | Python | mit | 887 | 0.021421 | import torch
from hypergan.train_hooks.base_train_hook import BaseTrainHook
class NegativeMomentumTrainHook(BaseTrainHook):
def __init__(self, gan=None, config=None, trainer=None):
super().__init__(config=config, gan=gan, trainer=trainer)
self.d_grads = None
self.g_grads = None
def gradients(sel... | ew_d_grads = [g.clone() for g in d_grads]
new_g_grads = [g.clone() for g in g_grads]
d_grads = [_g - self.config.gamma * _g2 for _g, _g2 in zip(d_grads, self.d_grads)]
g_grads = [_g - self.c | onfig.gamma * _g2 for _g, _g2 in zip(g_grads, self.g_grads)]
self.d_grads = new_d_grads
self.g_grads = new_g_grads
return [d_grads, g_grads]
|
probonopd/video2smarttv | yt2chromecast.py/usr/bin/video2chromecast.py | Python | mit | 240 | 0.008333 | #!/usr/bin/python
import time, sys
if(len(sys.argv) > 0):
video = sys. | argv[1]
e | lse:
video = "REjj1ruFQww"
try:
import pychromecast
pychromecast.play_youtube_video(video, pychromecast.PyChromecast().host)
except:
pass
|
novoid/Memacs | memacs/kodi.py | Python | gpl-3.0 | 6,858 | 0.00175 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import json
import logging
import sys
import time
from itertools import tee, islice, chain
from orgformat import OrgFormat
from memacs.lib.orgproperty import OrgProperties
from memacs.lib.reader import UnicodeDictReader
from .csv import Csv
# stolen fro... | ader)
self.read_log(reader)
except TypeError as e:
logging.error("not enough fieldnames or wrong delimiter given")
logging.debug("Error: %s" % e)
sys.exit(1)
except UnicodeDecodeError as e:
logging.error(
... | )
sys.exit(1)
|
fengbeihong/tempest_automate_ironic | tempest/api/volume/test_volume_transfers.py | Python | apache-2.0 | 4,317 | 0 | # Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | transfer in body:
if volume['id'] == transfer['volume_id']:
break
else:
self.fail('Transfer not fo | und for volume %s' % volume['id'])
# Delete a volume transfer
self.client.delete_volume_transfer(transfer_id)
self.client.wait_for_volume_status(volume['id'], 'available')
class VolumesV1TransfersTest(VolumesV2TransfersTest):
_api_version = 1
|
holli-holzer/python-docx | docx/engines/DjangoEngine.py | Python | mit | 1,123 | 0.010686 | import os
import django
from django.conf import settings; settings.configure()
from docx.engines.base import Engine as base
from | django.template import Template
from django.template import Template, Context
"""
Engine for Django
"""
class Engine(base):
def __init__(self):
| self.tag_re = "(\{[^\}]+?\}\}?)"
"""
Fix the template and feed it to the engine
"""
def render(self, template, context):
django.setup()
self._register_filters()
xml = self.fix_tag_gaps(template)
xml = self.fix_block_tags(xml)
self.template = Template(xm... |
Rob-Rau/EbbCFD | ms_refinement/plot_conv.py | Python | mit | 2,727 | 0.005501 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
from math import sqrt
from math import log
dx = [1/sqrt(16), 1/sqrt(64), 1/sqrt(256), 1/sqrt(1024)]
dx_tri = [1/sqrt(32), 1/sqrt(128), 1/sqrt(512), 1/sqrt(2048)]
dx_pert = [0.0270466, 0.0134827, 0.00680914, 0.00367054]
dx_fp = [0.122799, 0.081584, 0.0445639, 0.022... | = [0.00242227, 0.000586065, 0.000140727]
rl2_euler_limited = [0.00187271, 0.000435096, 0.000120633, 2.90233e-05]
rl2_euler_lp_limited = [0.00180033, 0.000422567, 0.000120477, 2.90644e-05]
rl2_ns = [0.000576472, 0.000132735, 7.0506e-05, 6.67272e-05]
rl2_ns_fp = [abs(fp_actual - 0.008118), abs(fp_actual - 0.015667), abs... | l2: "+str(log(rl2_euler[2]/rl2_euler[3])/log(dx[2]/dx[3])))
print("rho euler tri l2: "+str(log(rl2_euler_tri[2]/rl2_euler_tri[3])/log(dx_tri[2]/dx_tri[3])))
print("rho euler tri perturbed l2: "+str(log(rl2_euler_tri_pert[1]/rl2_euler_tri_pert[2])/log(dx_pert[1]/dx_pert[2])))
print("rho euler tri lim... |
Aloomaio/googleads-python-lib | examples/ad_manager/v201811/proposal_service/submit_proposals_for_approval.py | Python | apache-2.0 | 2,333 | 0.00943 | #!/usr/bin/env python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of th | e 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 spe | cific language governing permissions and
# limitations under the License.
"""This code example approves a single proposal.
To determine which proposals exist, run get_all_proposals.py.
"""
# Import appropriate modules from the client library.
from googleads import ad_manager
PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'... |
openannotation/annotateit | console.py | Python | agpl-3.0 | 306 | 0.009804 | from IPython import embed
import annotateit
from annotateit import model, | db, es
from fl | ask import g
def main():
app = annotateit.create_app()
with app.test_request_context():
g.user = model.User.fetch('admin')
embed(display_banner=False)
if __name__ == '__main__':
main()
|
happy5214/competitions-scheduler | competitions/scheduler/roundrobin.py | Python | lgpl-3.0 | 9,367 | 0.000641 | # -*- coding: utf-8 -*-
"""Round-robin scheduling."""
# Copyright (C) 2015 Alexander Jones
#
# This program 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 3 of | the License, or
# (at your option) any later version.
#
# This pro | gram 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 Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# al... |
ChrisLR/Python-Roguelike-Template | bodies/blood/base.py | Python | mit | 178 | 0.005618 | class Blood(object):
uid = "blood"
name = "Blood"
"""
Most characters will have ordinary bloo | d but some could have acidic blood or with other | properties.
"""
|
mcueto/djangorestframework-auth0 | rest_framework_auth0/authentication.py | Python | mit | 6,383 | 0.000783 | import logging
from django.contrib.auth.backends import (
RemoteUserBackend,
get_user_model,
)
from django.contrib.auth.models import (
Group,
)
from django.utils.translation import ugettext as _
from rest_framework import exceptions
from rest_framework_auth0.settings import (
auth0_api_settings,
)
fro... | _EXTENSION is enabled, defaults to False
If AUTHORIZATION_EXTENSION is enabled, created and associated groups
with th | e current user (the user of the token).
"""
if auth0_api_settings.AUTHORIZATION_EXTENSION:
logger.debug(
"Using Auth0 Authorization Extension"
)
logger.debug(
"Clearing groups for user: {username}".format(
username=... |
rubennj/pvlib-python | pvlib/test/test_atmosphere.py | Python | bsd-3-clause | 1,611 | 0.017381 | import logging
pvl_logger = logging.getLogger('pvlib')
import datetime
import numpy as np
import pandas as pd
from nose.tools import raises
from nose.tools import assert_almost_equals
from pvlib.location import Location
from pvlib import solarposition
from pvlib import atmosphere
# setup times and location to be ... | end=datetime.datetime(2014,6,26), freq='1Min')
tus = Location(32.2, -111, 'US/Arizona', 700)
times_localized = times.tz_localize(tus.tz)
ephem_data = solarposition.get_solarposition(times, tus)
# need to add physical tests instead of just functional tests
def test_pres2alt():
atmosphere.pr... | ate unique unit tests for each model
def test_airmasses():
models = ['simple', 'kasten1966', 'youngirvine1967', 'kastenyoung1989',
'gueymard1993', 'young1994', 'pickering2002', 'invalid']
for model in models:
yield run_airmass, ephem_data['zenith'], model
def run_airmass(zenith, model... |
deniscostadsc/regex-tutorial | 17-exercises/01-ponto/regex.py | Python | mit | 282 | 0 | '''
Nesse exer você deve casar linha que tem 'tio', mas que tenham 1 caractere
antes | .
Para fixação, usar o '.' (ponto).
'''
import re
import sys
REGEX = r''
lines = sy | s.stdin.readlines()
for line in lines:
if re.search(REGEX, line):
print(line.replace('\n', ''))
|
natabbotts/math-prog-club | prime.py | Python | mit | 1,686 | 0.007711 | import heapq, itertools
def factorisation(number):
"""Returns a list of the prime factors of a number in ascending order."""
factors = []
while number > 1:
for factor in range(2, number + 1):
if number % factor == 0:
factors.append(factor)
# floor divisi... | ]
x[0] += x[1]
heapq.heapreplace(nonprimes, x)
else: # prime
# insert a 2-element list into the priority queue:
# [current multiple, prime]
# the first element allows sorting by value of current multiple
# we | start with i^2
heapq.heappush(nonprimes, [i*i, i])
yield i
i += 1
|
oktayuyar/Velespi | profiles/urls.py | Python | gpl-3.0 | 328 | 0.006098 | from django.conf.urls import url
from profiles import views
urlpatterns = [
url(r"users$", views.UserList.as_view(),
name="api-user-list"),
url(r"user/(?P<pk>[0-9]+)$", views.UserSingle.as_view( | ),
| name="api-review-list"),
url(r"userlogin$", views.UserLogin.as_view(),
name="api-login"),
] |
camptocamp/QGIS | python/plugins/GdalTools/tools/widgetBatchBase.py | Python | gpl-2.0 | 5,310 | 0.030697 | # -*- coding: utf-8 -*-
"""
***************************************************************************
widgetBatchBase.py
---------------------
Date : June 2010
Copyright : (C) 2010 by Giuseppe Sucameli
Email : brush dot tyler at gmail dot com
************... | .batchIndex, self.batchTotal )
def batchFinished( self ):
self.base.stop()
if len(self.errors) > 0:
msg = u"Processing of the following files ended with error: <br><br>" + "<br><br>".join( self.errors )
QErrorMessag | e( self ).showMessage( msg )
inDir = self.getInputFileName()
outDir = self.getOutputFileName()
if outDir == None or inDir == outDir:
self.outFiles = self.inFiles
# load layers managing the render flag to avoid waste of time
canvas = self.iface.mapCanvas()
previousRenderFlag... |
steven-cutting/latinpigsay | test.py | Python | mit | 636 | 0 | # -*- coding: utf-8 -*-
__title__ = 'latinpig | say'
__license__ = 'MIT'
__author__ = 'Steven Cutting'
__author_email__ = 'steven.c.projects@gmail.com'
__created_on__ = '12/7/2014'
if __name__ == "__main__":
from tests import testscript as ts
from tests import contstests
from latinpigsay.tmp.experiments import exp
from data.text import samples as sa... | gging.basicConfig(filename='tests.log')
testtorun = sys.argv[1]
if testtorun == 'contspara':
contstests.contsparatest()
|
quantumlib/OpenFermion-FQE | src/fqe/fqe_ops/fqe_ops_utils.py | Python | apache-2.0 | 2,752 | 0 | # Copyright 2020 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | ring expression to be computed.
Returns
(str): Either 'element' or 'tensor'.
"""
qftops = ops.split()
nops = len(qftops)
assert (nops | % 2) == 0
if any(char.isdigit() for char in ops):
creation = re.compile(r"^[0-9]+\^$")
annihilation = re.compile(r"^[0-9]+$")
ncre = 0
nani = 0
for opr in qftops:
if creation.match(opr):
ncre += 1
elif annihilation.match(opr):
... |
maartenq/pcrunner | tests/test_configuration.py | Python | isc | 1,602 | 0 | # tests/test_configuration.py
# vim: ai et ts=4 sw=4 sts=4 ft=python fileencoding=utf-8
from io import StringIO
from pcrunner.configuration import (
read_check_commands,
read_check_commands_txt,
read_check_commands_yaml,
)
def test_read_check_commmands_txt_with_extra_lines():
fd = StringIO(
... | 'name': u'CHEC | K_01',
'result_type': 'PROCESS_SERVICE_CHECK_RESULT',
},
{
'command': u'check_dummy.py 1 WARNING -s 10',
'name': u'CHECK_02',
'result_type': 'PROCESS_SERVICE_CHECK_RESULT',
},
]
def test_read_check_commmands_yaml():
fd = StringIO(
... |
wangyum/tensorflow | tensorflow/python/debug/lib/stepper_test.py | Python | apache-2.0 | 45,190 | 0.012304 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | self.sess.run(variables.global_variables_initializer())
def tearDown(self):
ops.reset_default_graph()
def testContToFetchNotInTr | ansitiveClosureShouldError(self):
with NodeStepper(self.sess, "e:0") as stepper:
sorted_nodes = stepper.sorted_nodes()
self.assertEqual(7, len(sorted_nodes))
self.assertLess(sorted_nodes.index("a"), sorted_nodes.index("a/read"))
self.assertLess(sorted_nodes.index("b"), sorted_nodes.index("b/... |
ychab/privagal | privagal/core/management/commands/genfactories.py | Python | bsd-3-clause | 1,893 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import random
from django.conf import settings
from django.core.management.base import BaseCommand
from wagtail.wagtailcore.models import Page
from wagtail.wagtailimages.models import get_image_model
from privagal.gallery.factories import Gal... | mage.objects.all().delete()
images = []
for image in IMAGES:
images.append(
ImageFa | ctory(file__from_path=os.path.join(ASSETS_PATH, image)))
timeline = Timeline.objects.last()
for i in range(0, options['limit']):
random.shuffle(images)
gallery = GalleryFactory(images__images=images)
timeline.add_child(instance=gallery)
self.stdout.write(
... |
amoshyc/tthl-code | train_resnet.py | Python | apache-2.0 | 1,324 | 0.005287 | import json
from datetime import datetime
import numpy as np
import pandas as pd
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
set_session(tf.Session(config=config))
from keras.models import Sequential, Model
from ker... | kpoint, CSVLogger
from myutils import get_callbacks
inp = Input(shape=(224, 224, 3))
x = Batc | hNormalization()(inp)
x = ResNet50(weights='imagenet', include_top=False, pooling='max')(x)
x = Dense(16, activation='relu')(x)
x = Dropout(0.5)(x)
x = Dense(1, activation='sigmoid')(x)
model = Model(inputs=inp, outputs=x)
model_arg = {
'loss': 'binary_crossentropy',
'optimizer': 'sgd',
'metrics': ['binary... |
mitsuhiko/sentry | tests/sentry/api/endpoints/test_shared_group_details.py | Python | bsd-3-clause | 1,141 | 0.000876 | from __future__ import absolute_import, print_function
from sentry.testutils import APITestCase
class SharedGroupDetailsTest(APITestCase):
def test_simple(self):
self.login_as(user=self.user)
group = self.create_group()
event = self.create_event(group=group)
url = '/api/0/shared... | assert response.data['project']['slug'] == group.project.slug
assert response.data['project']['organization']['slug'] == group.organization.slug
def test_feature_disabled(self):
self.login_as(user=self.user)
group = self.create_group()
org = group.organization
org.f... | red_issues = True
org.save()
url = '/api/0/shared/issues/{}/'.format(group.get_share_id())
response = self.client.get(url, format='json')
assert response.status_code == 404
|
manz/python-mapnik | test/python_tests/cairo_test.py | Python | lgpl-2.1 | 8,571 | 0.015634 | #!/usr/bin/env python
from __future__ import print_function
import os
import shutil
import mapnik
from nose.tools import eq_
from .utilities import execution_path, run_all
def setup():
# All of the paths used are relative, if we run the tests
# from another directory we need to chdir()
os.chdir(execution... | Draw a Map Title near the top of a page."""
middle = m.width/2.0
ctx.set_source_rgba(*cairo_co | lor(color))
ctx.select_font_face("DejaVu Sans Book", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
ctx.set_font_size(size)
x_bearing, y_bearing, width, height = ctx.text_extents(text)[:4]
ctx.move_to(middle - width / 2 - x_bearing, 20.0 - height / 2 - y_bearing)
ctx.show_text(text)
def draw_ne... |
Zymo-Research/mirror-seq | setup.py | Python | apache-2.0 | 939 | 0.017039 | from setuptools import setup
exec(open('mirror_seq/v | ersion.py').read())
LONG_DESCRIPTION = '''
Please visit the GitHub repo (https://github.com/Zymo-Research/mirror-seq) for detail information.
'''
INSTALL_REQUIRES = [
'pandas>=0.18.0',
'pysam>=0.9.0',
'cutadapt==1.9.1',
]
setup(name='mirror_seq',
version=__version__,
description='The bioinformati... | 'Hunter Chung',
author_email='b89603112@gmail.com',
licence='Apache License 2.0',
scripts=['bin/mirror-seq', 'bin/mirror-trim', 'bin/mirror-call'],
packages=['mirror_seq'],
test_suite='nose.collector',
tests_require=['nose'],
install_requires=INSTALL_REQUIRES,
classifiers=['Programming L... |
CalvinHsu1223/LinuxCNC-EtherCAT-HAL-Driver | configs/sim/remap/manual-toolchange-with-tool-length-switch/python/gladevcp-handler.py | Python | gpl-2.0 | 801 | 0.014981 | #!/usr/bin/env python
import hal
class HandlerClass:
def on_led_change(self,hal_led,data=None):
'''
the gladevcp.change led had a transition
'''
if hal_led.hal_pin.get():
if self.halcomp["number"] > 0.0:
self.change_text.set_label("Insert too number %d"... | umber", hal.HAL_FLOAT, hal.HAL_IN)
def get | _handlers(halcomp,builder,useropts):
return [HandlerClass(halcomp,builder,useropts)]
|
googleapis/python-dialogflow-cx | samples/generated_samples/dialogflow_v3_generated_flows_validate_flow_sync.py | Python | apache-2.0 | 1,436 | 0.000696 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache | License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Lic | ense 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for ValidateFlow
# NOTE: This snippet has been automatic... |
trosa/forca | scripts/cleanhtml.py | Python | gpl-2.0 | 2,334 | 0.065981 | import sys
import re
def cleancss(text):
text=re.compile('\s+').sub(' ', text)
text=re.compile('\s*(?P<a>,|:)\s*').sub('\g<a> ', text)
text=re.compile('\s*;\s*').sub(';\n ', text)
text=re.compile('\s*\{\s*').sub(' {\n ', text)
text=re.compile('\s*\}\s*').sub('\n}\n\n', text)
return text
... | s+\<br(?P<a>.*?)\/\>').sub('<br\g<a>/>',text)
text=re.compile('\>(?P<a>\s+)(?P<b>[\.\,\:\;])').sub('>\g<b>\g<a>',text)
text=re.compile('\n\s* | \n').sub('\n',text)
for script in scripts:
text=text.replace('<script />', script, 1)
for style in styles:
text=text.replace('<style />', cleancss(style), 1)
return text
def read_file(filename):
f = open(filename, 'r')
try:
return f.read()
finally:
f.close()
fil... |
idl3r/Ropper | ropperapp/loaders/pe_intern/__init__.py | Python | gpl-2.0 | 729 | 0 | #!/usr/bin/env python2
# coding=utf-8
#
# Copyright 2014 Sascha Schirra
#
# This file is part of Ropper.
#
# Ropper is free software: you can redistribute it and/or modify
# it under the t | erms 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.
#
# Ropper is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR... | have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
yuxiang-zhou/menpo | menpo/model/vectorizable.py | Python | bsd-3-clause | 6,200 | 0.000484 |
class VectorizableBackedModel(object):
r"""
Mixin for models constructed from a set of :map:`Vectorizable` objects.
Supports models for which visualizing the meaning of a set of components
is trivial.
Requires that the following methods are implemented:
1. `component_vector(index)`
2. `in... | ameters
----------
instance : :map:`Vectorizable`
A novel instance.
Returns
-------
projected : ``(n_components,)`` `ndarray`
A vector of optimal linear weightings.
"""
retur | n self.project_vector(instance.as_vector())
def reconstruct_vector(self, instance_vector):
"""
Projects an `instance_vector` onto the linear space and rebuilds from the
weights found.
Syntactic sugar for: ::
instance_vector(project_vector(instance_vector))
but... |
erwindl0/python-rpc | org.eclipse.triquetrum.python.service/scripts/scisoftpy/python/pycomparisons.py | Python | epl-1.0 | 1,127 | 0.008873 | ###
# Copyright 2011 Diamond Light Source Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | t = _np.logical_not
logical_and = _np.logical_and
logical_or = _np.logical_or
logical_xor = _np.logical_xor
allclose = _np.allc | lose
nonzero = _np.nonzero
where = _np.where
iscomplex = _np.iscomplex
isreal = _np.isreal
|
enen92/script.matchcenter | resources/lib/tweets.py | Python | gpl-2.0 | 4,506 | 0.025522 | # -*- coding: utf-8 -*-
'''
script.matchcenter - Football information for Kodi
A program addon that can be mapped to a key on your remote to display football information.
Livescores, Event details, Line-ups, League tables, next and previous matches by team. Follow what
others are saying about the match ... | bmc.executebuiltin("SetProperty(loading-script-matchcenter-twitter,1,home)")
self.getTweets()
xbmc.executebuiltin("ClearProperty(loading-script-matchcenter-twitter,Home)")
i=0
while self.isRunning:
if (float(i*200)/(twitter_update_time*60*1000)).is_integer() and ((i*200)/(3*60*1000)) != 0:
self.getTweets... | tControl(32500).setLabel("#"+self.hash)
self.getControl(32503).setImage(os.path.join(addon_path,"resources","img","twitter_sm.png"))
tweetitems = []
tweets = tweet.get_hashtag_tweets(self.hash)
if tweets:
for _tweet in tweets:
td = ssutils.get_timedelta_string(datetime.datetime.utcnow() - _tweet["date"])... |
izapolsk/integration_tests | cfme/tests/cloud_infra_common/test_events.py | Python | gpl-2.0 | 3,523 | 0.001419 | """This module tests events that are invoked by Cloud/Infra VMs."""
import fauxfactory
i | mport pytest
from cfme import test_requirements
from cfme.cloud.provider import CloudProvider
from cfme.cloud.provider.gce import GCEProvider
from cfme.control.explorer.policies import VMControlPolicy
from cfme.infrastructure.provider import InfraProvider
from cfme.infrastructure.provider.kubevirt import KubeVirtProvi... | t wait_for
all_prov = ProviderFilter(classes=[InfraProvider, CloudProvider],
required_fields=['provisioning', 'events'])
excluded = ProviderFilter(classes=[KubeVirtProvider], inverted=True)
pytestmark = [
pytest.mark.usefixtures('uses_infra_providers', 'uses_cloud_providers'),
pytest... |
oturing/pyun | pyun_tests.py | Python | mit | 373 | 0 | # coding: | utf-8
"""
>>> from pyun import *
>>> yun = YunBridge('192.168.2.9')
>>> yun.pinMode(13, INPUT)
'input'
>>> yun.digitalRead(13)
0
>>> yun.digitalWrite(13, 1)
1
>>> yun.digitalWrite(13, 0)
0
>>> 0 <= yun.analogRead(5) < 1024
True
"""
import doctest
doctest.testmod(opti... | |
sevein/archivematica | src/dashboard/src/components/ingest/views_NormalizationReport.py | Python | agpl-3.0 | 4,152 | 0.007225 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica 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 F... | normalization_attempted,
case when a.fileID is not null and c.exitcode = 1 then 1 else 0 en | d as access_normalization_failed,
case when b.exitCode < 2 and a.fileID is not null then 1 else 0 end as preservation_normalization_attempted,
case when a.fileID is not null and b.exitcode = 1 then 1 else 0 end as preservation_normalization_failed,
c.taskUUID as access_normalization_task_uuid,
... |
antoinecarme/pyaf | tests/model_control/detailed/transf_Integration/model_control_one_enabled_Integration_PolyTrend_Seasonal_Minute_NoAR.py | Python | bsd-3-clause | 161 | 0.049689 | import tests.model_control.test_ozone_custom_models_enabled as te | stmod
testmod.build_model( ['Integration'] , ['PolyTrend'] , ['Seasonal_Minute'] | , ['NoAR'] ); |
Angoreher/xcero | magic/migrations/0007_auto_20170928_2258.py | Python | mit | 2,691 | 0.004088 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-29 01:58
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('magic', '0006_auto_20170928_2238'),
]
o... | s',
field=django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True),
),
migrations.AlterField(
| model_name='card',
name='cmc',
field=models.IntegerField(blank=True, null=True, verbose_name='converted mana cost'),
),
migrations.AlterField(
model_name='card',
name='color_identity',
field=django.contrib.postgres.fields.jsonb.JSONFi... |
jteehan/cfme_tests | cfme/intelligence/chargeback/rates.py | Python | gpl-2.0 | 9,761 | 0.001332 | # -*- coding: utf-8 -*-
# Page model for Intel->Chargeback->Rates.
from . import ChargebackView
from cached_property import cached_property
from navmazing import NavigateToSibling, NavigateToAttribute
from utils.appliance import Navigatable
from utils.appliance.implementations.ui import navigator, navigate_to, CFMENav... | escription))
class ComputeRate(Updateable, Pretty, Navigatable):
"""This class represents a Compute Chargeback rate.
Example:
.. code-block:: python
>>> import cfme.intelligence.chargeback.rates as rates
>>> rate = rates.ComputeRate(description=desc,
fields={'... |
'Used Disk I/O':
{'per_time': 'Hourly', 'variable_rate': '2'},
'Used Memory':
{'per_time': 'Hourly', 'variable_rate': '2'}})
>>> rate.create()
>>> rate.delete()
Args:
descrip... |
jaejun1679-cmis/jaejun1679-cmis-cs2 | cs2quiz2.py | Python | cc0-1.0 | 2,209 | 0.024898 | #PART 1: Terminology
#1) Give 3 examples of boolean expressions.
#a) "apple" == "apple"
#b) 1 != 1
#c) 5 >= 6
#2) What does 'return' do?
#'Return' returns a value. It can be used after an calculation is
#executed. When the python interpreter solves a math problem, you can
#"return" the value back into the interpreter... | elongs in a certain function.
#b) And the correct indentation levels tells python when a specific function ends.
#PART 2: Reading
#Type the values for 9 of the 12 of the variables below.
#
#problem1_a) 36
#problem1_b) square root of 3
#problem1_c) square root of 0 = 0
#problem1_d) -5
#
#problem2 | _a) True
#problem2_b) False
#problem2_c) False
#problem2_d) False x
#
#problem3_a) 0.3
#problem3_b) 0.5
#problem3_c) 0.5
#problem3_d) 0.5
#
#problem4_a) 7
#problem4_b) 5
#problem4_c) 0.125
#problem4_d) 4.5
#
#PART 3: Programming
#Write a script that asks the user to type in 3 different numbers.
#If the user types 3 dif... |
gavioto/fiware-orion | test/acceptance/lettuce/integration/steps_lib/ngsi_request.py | Python | agpl-3.0 | 5,069 | 0.004933 | # -*- coding: utf-8 -*-
"""
# Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U
#
| # This file is part of Orion Context Broker.
#
# Orion Context Broker is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Orion ... | 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 Affero
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Orion Context B... |
JoseGuzman/stimfit | src/stimfit/py/spells.py | Python | gpl-2.0 | 18,106 | 0.011046 | """
spells.py
Python recipes to solve frequently requested tasks with Stimfit.
You can find a complete description of these functions in the
Stimfit online documentation (http://www.stimfit.org/doc/sphinx/index.html)
Check "The Stimfit Book of Spells" for details.
Authors: Jose Guzman, Alois Schloegl and Christoph S... | ing mean of a single trace
Arguments:
binwidth -- size of the bin in sampling points (pt).
Obviously, it should be smaller than the length of the trace.
trace: -- ZERO-BASED index of the trace within the channel.
Note that this is one less than what is shown in the drop-down box.
The defa... | ctive or not. The default value of -1
returns the currently active channel.
Returns:
A smoothed traced in a new stf window.
"""
# loads the current trace of the channel in a 1D Numpy Array
sweep = stf.get_trace(trace, channel)
# creates a destination python list to append the data
ds... |
spirali/qit | src/qit/domains/product.py | Python | gpl-3.0 | 3,854 | 0.002076 |
from qit.base.bool import Bool
from qit.base.struct import Struct
from qit.domains.domain import Domain
from qit.domains.iterator import Iterator
from qit.base.function import Function
from qit.functions.int import multiplication_n
class Product(Domai | n):
""" Cartesian product of domains """
def __init__(self, *args):
domains = []
struct_args = []
for arg in args:
if isinstance(arg, tuple) and len(arg) == 2:
domain | = arg[0]
domains.append(domain)
struct_args.append((domain.type, arg[1]))
else:
domains.append(arg)
struct_args.append(arg.type)
type = Struct(*struct_args)
super().__init__(
type,
self._make_ite... |
lonnen/socorro | webapp-django/crashstats/authentication/management/commands/auditgroups.py | Python | mpl-2.0 | 4,373 | 0.000686 | # 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/.
"""
Audit groups and removes inactive users.
"""
import datetime
from django.contrib.auth.models import Group, User
fr... | LogEntry.objects.log_action(
user_id=auditgrou | ps_user.id,
content_type_id=ContentType.objects.get_for_model(User).pk,
object_id=user.pk,
object_repr=user.email,
action_flag=CHANGE,
change_message="Removed %s from hackers--%s."
% (user.email, reas... |
justasabc/python_tutorials | project/chat/chatserver.py | Python | gpl-3.0 | 1,221 | 0.039312 | # Note: run this server by using python2.7 instead of python3.2
from asyncore import dispatcher
from asynchat import async_chat
import | socket, asyncore
IP = ''
PORT = 5555
SEP = '\n'
class ChatSession(async_chat):
"""
A simple chat session corresponding to a client
"""
def __init__(self,sock):
async_chat.__init__(self,sock)
self.set_terminator(SEP)
self.data = []
def collect_incoming_data(self, data):
print("---------------collect_inc... | rminator(self):
print("---------------found_terminator")
line = ''.join(self.data)
self.data = []
print(line)
class ChatServer(dispatcher):
"""
a simple chat server.
a server has n clients and n sessions.
"""
def __init__(self, ip,port):
dispatcher.__init__(self)
self.create_socket(socket.AF_INET, soc... |
bearbear12345/school_SDD_prelimYear | Assessments/AS4 - NCSS Python Programming Challenge/NCSS Challenge (Advanced) 2016/1.2.3 - Box in a Box.py | Python | gpl-3.0 | 736 | 0.046196 | def genbox(i):
i = int(i)
def draw(size, yc, xc):
y = yc
for _ in range(0,size):
if _ == 0 or _ == size-1:
x = xc
i = 0
while i < size:
if not g[_+y][x]=="x": g[_+y][x] = "x"
x += 2
i+=1
| else:
if not g[_+y][xc]=="x": g[_+y][xc] = "x"
if not g[_+y][(len(g[0])-xc-1)]=="x": g[_+y][(len(g[0])-xc-1)] = "x"
pass
g = []
for _ in range(1,i+1):
h = []
for _ in range(1,2*i):
h.append(" ")
g.append(h)
c = i
a = 0
| b = 0
while c > 0:
draw(c,a,b)
c -= 4
a += 2
b += 4
output = ""
for row in g:
output += "".join(row) + "\n"
return output.strip()
print(genbox(input("Enter size: "))) |
hanamvu/C4E11 | SS1/tur_a_circle.py | Python | gpl-3.0 | 313 | 0.025559 | from turtle import *
from rand | om import *
speed(0)
colormode(255)
for side_n in range(15,2,-1):
color((randint(1, 255),randint(1, 255),randint(1, 255)),(randint(1, 255),randint(1, 255),randint(1, 255)))
begin_fill()
for i in range(side_n):
forward( | 100)
left(360/side_n)
end_fill()
|
rackerlabs/django-DefectDojo | dojo/db_migrations/0022_google_sheet_sync_additions.py | Python | bsd-3-clause | 963 | 0 | # Generated by Django 2.2.1 on 2019-09-19 11:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dojo', '0021_cve_index'),
]
operations = [
migrations.AddField(
model_name='system_settings',
name='credentials',
... | Field(
model_name='system_settings',
name='column_widths',
field=models.CharField(max_length=1500, blank=True),
),
migrations.AddF | ield(
model_name='system_settings',
name='drive_folder_ID',
field=models.CharField(max_length=100, blank=True),
),
migrations.AddField(
model_name='system_settings',
name='enable_google_sheets',
field=models.BooleanField(null=True, ... |
ctiller/grpc | tools/run_tests/xds_k8s_test_driver/framework/rpc/grpc.py | Python | apache-2.0 | 3,227 | 0 | # Copyright 2020 gRPC authors.
#
# 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... | g_level: Optional[int] = logging.DEBUG) -> Message:
if deadline_sec is None:
deadline_sec = self.DEFAULT_RPC_DEADLINE_SEC
call_kwargs = dict(wait_for_ready=True, timeout=deadline_sec)
self._log_rpc_request(rpc, req, call_kwargs, log_ | level)
# Call RPC, e.g. RpcStub(channel).RpcMethod(req, ...options)
rpc_callable: grpc.UnaryUnaryMultiCallable = getattr(self.stub, rpc)
return rpc_callable(req, **call_kwargs)
def _log_rpc_request(self, rpc, req, call_kwargs, log_level=logging.DEBUG):
logger.log(logging.DEBUG if l... |
commandline/flashbake | src/flashbake/console.py | Python | gpl-3.0 | 11,505 | 0.005389 | #!/usr/bin/env python
''' flashbake - wrapper script that will get installed by setup.py into the execution path '''
# copyright 2009 Thomas Gideon
#
# This file is part of flashbake.
#
# flashbake is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Lice... | False
def print_usage(self, file=None):
if not self.suppress_exit:
OptionPars | er.print_usage(self, file)
def exit(self, status=0, msg=None):
if self.suppress_exit:
raise ParserError(status, msg)
else:
OptionParser.exit(self, status, msg)
def _build_main_parser():
usage = "usage: %prog [options] <project_dir> [quiet_min]"
parser = FlashbakeO... |
atopuzov/pyzebos | setup.py | Python | mit | 2,544 | 0.00118 | # -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2014 Aleksandar Topuzović <aleksandar.topuzovic@gmail.com>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documenta | tion files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following condition... | ll 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 COPY... |
agusmakmun/Some-Examples-of-Simple-Python-Script | Stegano-Extract-and-Read-File-From-Image/script.py | Python | agpl-3.0 | 2,974 | 0.025891 | """
Name : Stegano Extract and Read File From Image
Created By : Agus Makmun (Summon Agus)
Blog : bloggersmart.net - python.web.id
License : GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
Documentation : https://github.com/agusmakmun/Some-Examples-of-Simple-Python-Script/
"... | e."
print " 2. Extract files from image."
print " 3. Stegano read file from image.\n"
mome = scureImage()
choice = raw_input("[+] >>> ")
if choice == "1":
print os.listdir(".")
img = raw_input("[+] Type Image file that will save ... | +] >>> ")
zip = raw_input("[+] Type your Zip file: ")
new_img = raw_input("[+] Type New Image that will save your zip: ")
mome._secure(img, zip, new_img)
print os.listdir(".")
elif choice == "2":
print os.listdir(".")
... |
AlpacaDB/chainer | chainer/functions/loss/negative_sampling.py | Python | mit | 6,667 | 0 | import numpy
import six
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class NegativeSamplingFunction(function.Function):
def __init__(self, sampler, sample_size):
self.sampler = sampler
self.sample_size = sample_size
def _make_samples(self, t):
... | } else {
loss = f + __logf(1 + __expf(-f));
}
y = l | oss;
''',
'negative_sampling_forward'
)(self.wx, n_in, self.sample_size + 1)
# TODO(okuta): merge elementwise
loss = cuda.cupy.sum(y)
return loss,
def backward_cpu(self, inputs, grads):
x, t, W = inputs
gloss, = grads
gx = numpy.zeros... |
Yarrick13/hwasp | tests/asp/gringo/modelchecker.046.test.py | Python | apache-2.0 | 186,113 | 0.00029 | input = """
p24|p8|not_p15:-p7,p2,not p25.
p11|not_p20|p8|not_p15:-p24,p2.
p3|p20|p18|p3:-p1,not p22.
not_p5|not_p5|not_p19|p22.
p1|p12|p2|not_p16:-not p23,not p3.
p3|not_p20|p18:-p13,not p22,not p14.
p17|p12|p8|not_p8.
p15|not_p22|p24|not_p12.
not_p21|p20|p18:-p1,not p22.
p24|p9|p24|not_p22:-p12,p23.
not_p2|... | , not_p4, p21, p16, not_p3}
{p25, p18, p1, not_p5, p17, p15, not_p4, p21, p16, not_p25}
{p25, p20, p1, not_p5, p17, p15, not_p4, p21, p16, not_p25}
{p2, p25, not_p5, p17, p15, not_p4, p21, p16, not_p25}
{p7, p20, p1, not_p5, p17, p15, p9, not_p4, p21, p16}
{p11, p20, p1, not_p5, p17, p15, p9, not_p4, p21, p16, p6}
{p25... | not_p5, p17, p15, p9, not_p4, p21, p16}
{not_p20, not_p5, p12, p17, p15, not_p4, p16, not_p3}
{not_p20, p18, p1, not_p5, p17, p15, not_p4, p16, not_p3}
{not_p20, p20, p1, not_p5, p17, p15, not_p4, p16, not_p3}
{p2, not_p20, not_p5, p17, p15, not_p4, p16, not_p3}
{not_p20, not_p5, p12, p17, p15, not_p4, p16, not_p25}
{n... |
rs2/pandas | pandas/tests/indexing/test_iloc.py | Python | bsd-3-clause | 46,354 | 0.001079 | """ test positional based indexing with iloc """
from datetime import datetime
import re
from warnings import (
catch_warnings,
simplefilter,
)
import numpy as np
import pytest
import pandas.util._test_decorators as td
from pandas import (
NA,
Categorical,
CategoricalDtype,
DataFrame,
In... | wn)
| expected = df.iloc[:, :0]
tm.assert_frame_equal(result, expected)
result = df.iloc[:, 10:11] # 0 < len < start < stop
expected = df.iloc[:, :0]
tm.assert_frame_equal(result, expected)
# slice bounds exceeding is ok
result = s.iloc[18:30]
expected = s.iloc[18:]
... |
ranok/sledgehammer | klee-unit/klee-unit.py | Python | mit | 4,806 | 0.007491 | #!/usr/bin/env python
#########################################################################################
# KLEE-Unit
# Author: Jacob Torrey
# Date: 3/15/2016
#
# Script to auto-generate test harness and execute symbolically with KLEE for a passed C
# file
########################################################... | print "Unable to parse pattern: " + pattern
sys.exit(-1)
return (node.ext[-1].name, _explain_type(node.ext[-1]))
def _explain_type(decl):
'''Recursively explains a type decl node'''
typ = type(decl)
if typ == c_ast.TypeDecl:
quals = ' '.join(decl.quals) + ' ' if decl.qua... | ype(decl.type)
elif typ == c_ast.IdentifierType:
return ' '.join(decl.names)
elif typ == c_ast.PtrDecl:
quals = ' '.join(decl.quals) + ' ' if decl.quals else ''
return quals + _explain_type(decl.type) + "*"
elif typ == c_ast.ArrayDecl:
arr = 'array'
if decl.dim: arr +... |
lluxury/pcc_exercise | 07/pastrami.py | Python | mit | 265 | 0.030189 | sandwich_orders = ['Bacon | ','Bacon, egg and cheese','Bagel toast','pastrami','pastrami','pastrami']
print ('pastrami sandwich was sold out')
finished_sandwiches = []
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print(sandwich_o | rders) |
JMoravec/unkRadnet | zunzunCode/pythonequations/Examples/SimpleExamples/NonLinearFit2D.py | Python | bsd-3-clause | 1,888 | 0.009534 | #! /usr/bin/python
# Version info: $Id: NonLinearFit2D.p | y 230 2010-06-30 20:20:14Z zunzun.com $
# the pythonequations base is located up one directory from the top-level examples
# directory, go up one directory in the path from there for the import to work properly
import sys, os
if os.path.join(sys.path[0][:sys.p | ath[0].rfind(os.sep)], '../..') not in sys.path:
sys.path.append(os.path.join(sys.path[0][:sys.path[0].rfind(os.sep)], '../..'))
import pythonequations
equation = pythonequations.Equations2D.Exponential.Exponential2D() # Simple non-linear function
equation.fittingTarget = 'SSQABS' # see the Equation base class f... |
ankanch/tieba-zhuaqu | user-application/KCrawlerControal/Debug/plugins/trash/singleword.py | Python | gpl-3.0 | 978 | 0.032663 | import lib.result_functions_file as RFF
import lib.maglib as MSG
import os
# | 这个库是统计各个词语的出现次数,并显示
#这是tieba-zhuaqu项目的用户端基本插件
def satisticWord(word,datalist):
os.system('cls')
print('>>>>>开始统计【',word,'】出现次数.. | ..')
sum=1
mlist=[]
for item in datalist:
if item.find(word) != -1:
sum+=1
mlist.append(item)
print('>',end='')
print('>>>>>统计完成!\n\n')
MSG.printline2x35(2)
print('\r\n>>>>>统计结果>----->共【',sum-1,'/',len(datalist),'】条匹配数据,结果如下','\r\n')
MSG.printline2x35(... |
SpaceGroupUCL/qgisSpaceSyntaxToolkit | esstoolkit/external/networkx/algorithms/assortativity/tests/test_mixing.py | Python | gpl-3.0 | 5,415 | 0.000923 | import pytest
np = pytest.importorskip("numpy")
npt = pytest.importorskip("numpy.testing")
import networkx as nx
from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
class TestDegreeMixingDict(BaseTestDegreeMixing):
def test_degree_mixing_dict_undirected(self):
d = nx.degree_mixing_dict... | o": 1, "red": 2, "blue": 3}
a_result = np.array([[4, 0, 0, 0], [0, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
a = nx.attribute_mixing_matrix(
self.M, "fish", mapping=mapping, normalized=False
)
npt.assert_equal(a, a_result) |
a = nx.attribute_mixing_matrix(self.M, "fish", mapping=mapping)
npt.assert_equal(a, a_result / float(a_result.sum()))
|
zofuthan/airmozilla | airmozilla/manage/views/users.py | Python | bsd-3-clause | 3,960 | 0 | import collections
from django.conf import settings
from django.contrib.auth.models import User, Group
from django.core.cache import cache
from django.contrib import messages
from django.shortcuts import render, redirect
from django.db import transaction
from django.db.models import Q
from funfactory.urlresolvers imp... | 'POST':
form = forms.UserEditForm(request.POST, instance=user)
if form.is_valid():
form.save()
messages.info(request, 'User %s saved.' % user.email)
| return redirect('manage:users')
else:
form = forms.UserEditForm(instance=user)
return render(request, 'manage/user_edit.html',
{'form': form, 'user': user})
|
arsenovic/clifford | clifford/test/test_tools.py | Python | bsd-3-clause | 8,422 | 0.0019 |
import pytest
import numpy as np
from numpy import testing
from clifford import Cl
from clifford.tools import orthoFrames2Versor as of2v
from clifford._numba_utils import DISABLE_JIT
from clifford import tools
from . import rng # noqa: F401
too_slow_without_jit = pytest.mark.skipif(
DISABLE_JIT, reason="test ... | aScene()
# gs.add_objects(point_list, static=True, color=int('00000000', 16))
# gs.add_objects(flats, color=int('00FF0000', 16))
# draw(gs, scale=0.05)
def test_convex_hull_facets(self, rng): # noqa: F811
from clifford.too | ls.g3c import random_conformal_point
from clifford.tools.point_processing import GAConvexHull
point_list = [random_conformal_point(rng=rng) for i in range(100)]
hull = GAConvexHull(point_list, hull_dims=3)
facets = hull.conformal_facets()
# from pyganja import GanjaScene, draw
... |
ramineni/my_congress | congress/tests/dse2/test_datasource.py | Python | apache-2.0 | 8,631 | 0 | # Copyright (c) 2014 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 ... | nfig']['password'] = "<hidden>"
del(result['id'])
self.assertEqual(result, req)
def test_create_datasource_duplicate_name(self):
req = self._get_datasource_request()
self.ds_manager.add_datasource(req)
self.assertRaises(congressException.DatasourceNameInUse,
... | t_delete_datasource(self):
req = self._get_datasource_request()
result = self.ds_manager.add_datasource(req)
self.ds_manager.delete_datasource(result)
# check that service is actually deleted
services = self.dseNode.get_services()
self.assertEqual(len(services), 0)
... |
leezu/mxnet | python/mxnet/gluon/contrib/estimator/event_handler.py | Python | apache-2.0 | 33,227 | 0.002889 | # 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"); you may not u... | def batch_end(self, estimator, *args, **kwargs):
self.current_batch += 1
if self.current_batch == self.max_batch:
self.stop_training = True
| return self.stop_training
def epoch_end(self, estimator, *args, **kwargs):
self.current_epoch += 1
if self.current_epoch == self.max_epoch:
self.stop_training = True
return self.stop_training
class MetricHandler(EpochBegin, BatchEnd):
"""Metric Handler that update metri... |
mrrodd/Samples | DLR-IronPython/IronPython.UI/Scripts/SampleScript02.py | Python | lgpl-3.0 | 1,026 | 0.024366 | import clr
clr.AddReference("mscorlib")
clr.AddReference("PresentationFramework")
from System.Windows import Application
from System.IO import StreamReader
from System.Threading import Thread
from System.Windows.Markup import XamlReader
from System.Reflection import Assembly
from System import Action
class ViewModel:... | ataContext = vm
window.FindName("CloseButton").Click += lambda s, e: window.Close()
window.Show()
Application.Current.Dispatcher.BeginInvoke(Action(lambda: getNumberOfSpeakers()))
for i in range(0, 10):
print str(i+1)
| Thread.Sleep(500)
print "Done!" |
adlermedrado/abbr | setup.py | Python | apache-2.0 | 1,346 | 0 | # Copyright 2016 Adler Brediks Medrado
#
# 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... | ermissions and
# limitations under the License.
from setuptools import setup, find_packages
with open("requirements.txt") as reqs:
install_requires = reqs.readlines()
setup(
name="abbr",
version="0.0.1" | ,
url="https://github.com/adlermedrado/abbr",
author="Adler Brediks Medrado",
author_email="abbr@adlermedrado.com.br",
license="Apache-2.0",
description="A client library to abbreviate string contents",
long_description=open('README.rst').read(),
packages=find_packages(),
install_req... |
rishita/mxnet | example/rcnn/rcnn/pycocotools/cocoeval.py | Python | apache-2.0 | 19,780 | 0.009757 | __author__ = 'tsungyi'
from __future__ import print_function
import numpy as np
import datetim | e
import time
from collections import defaultdict
import mask
import copy
class COCOe | val:
# Interface for evaluating detection on the Microsoft COCO dataset.
#
# The usage for CocoEval is as follows:
# cocoGt=..., cocoDt=... # load dataset and results
# E = CocoEval(cocoGt,cocoDt); # initialize CocoEval object
# E.params.recThrs = ...; # set parameters as desired
... |
hiaselhans/OpenGlider | tests/visual_test_flatten_glider.py | Python | gpl-3.0 | 4,457 | 0.004487 | #! /usr/bin/python2
# -*- coding: utf-8; -*-
#
# (c) 2013 booya (http://booya.at)
#
# This file is part of the OpenGlider project.
#
# OpenGlider is free software; you can | redistribute it and/or mo | dify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# OpenGlider is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCH... |
Benxxen/pythonwetter | pythonwetter/serializers.py | Python | mit | 385 | 0.007792 | __author__ = 'McDaemon'
from models import Weather
from rest_framework import serializers
cla | ss WeatherSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Weather
fields = ('datum', 'stadt', 'anbieter', 'anbieter', 'wetter', 'tagestemperatur', 'einheit', 'kondition',
| 'windgeschwindigkeit', 'windrichtung', 'url') |
klen/muffin-example | example/manage.py | Python | mit | 817 | 0.001224 | """Setup the application's CLI commands."""
from example import app, db
@app.manage
def hello(name, upper=False):
"""Write command help text here.
:param name: W | rite your name
:param upper: Use uppercase
"""
greetings = f"Hello {name}!"
if upper:
greetings = greetings.upper()
print(greetings)
@app.manage
async def example_users():
"""Create users for the example."""
from example.models import User
async with | db.connection():
await User.get_or_create(email='user@muffin.io', defaults={
'username': 'user', 'password': User.generate_password('pass'),
})
await User.get_or_create(email='admin@muffin.io', defaults={
'username': 'admin', 'password': User.generate_password('pass'), '... |
Onirik79/aaritmud | src/socials/social_eyebrow.py | Python | gpl-2.0 | 98 | 0.010204 | # -*- | coding: utf-8 | -*-
def social_eyebrow(entity, argument):
return True
#- Fine Funzione -
|
RNAcentral/rnacentral-import-pipeline | rnacentral_pipeline/cli/cpat.py | Python | apache-2.0 | 1,587 | 0 | # -*- coding: utf-8 -*-
"""
Copyright [2009-2021] EMBL-European Bioinformatics Institute
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... | S OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from pathlib import Path
import pickle
import click
from rnacentral_pipeline.cpat import parser
| from rnacentral_pipeline.cpat.data import CpatWriter
from rnacentral_pipeline.writers import build
@click.group("cpat")
def cli():
"""
Commands with processing the Rfam metadata.
"""
pass
@cli.command("parse")
@click.argument("cutoffs", type=click.File("rb"))
@click.argument("model_name")
@click.arg... |
diogocs1/comps | web/addons/account/wizard/account_report_common_partner.py | Python | apache-2.0 | 1,999 | 0.004502 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | ('customer_supplier','Receivable and Payable Accounts')],
"Partner's", required=True),
}
_defaults = {
'result_selection | ': 'customer',
}
def pre_print_report(self, cr, uid, ids, data, context=None):
if context is None:
context = {}
data['form'].update(self.read(cr, uid, ids, ['result_selection'], context=context)[0])
return data
#vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=... |
hglattergotz/sfdeploy | bin/config.py | Python | mit | 2,796 | 0.002146 | """
Configuration tasks
This module provides tools to load yaml configuration files.
"""
import os
from fabric.api import *
from fabric.contrib.console import confirm
from fabric.colors import red, green
try:
import yaml
except ImportError:
print(red('pyYaml module not installed. Run the following commands t... | ile.
Calling the function with 'prod' as the value for env will return the key/
value pairs from the 'all' section with the values from the 'prod' section
overriding any that might have been loaded from the all | section.
"""
config = load_yaml(path)
if config:
if 'all' in config:
all = config['all']
else:
return {}
if env != '':
if env in config:
all.update(config[env])
return all
else:
return {}... |
asteca/ASteCA | packages/update_progress.py | Python | gpl-3.0 | 553 | 0 |
import sys
def updt(total, progress, extra=""):
"""
Displays or updates a console progress bar.
Original source: https://stackoverflow.com/a/15860757/1391441
"""
barLength, status = 20, ""
progress = float( | progress) / float(total)
if progress >= 1.:
progress, status = 1, "\r\n"
block = int(round(barLength * progr | ess))
text = "\r[{}] {:.0f}% {}{}".format(
"#" * block + "-" * (barLength - block),
round(progress * 100, 0), extra, status)
sys.stdout.write(text)
sys.stdout.flush()
|
repotvsupertuga/tvsupertuga.repository | script.module.openscrapers/lib/openscrapers/sources_openscrapers/en/coolmoviezone.py | Python | gpl-2.0 | 2,749 | 0.001091 | # -*- coding: utf-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.... | return url
except:
return
def sources(self, url, hostDict | , hostprDict):
try:
sources = []
r = self.scraper.get(url).content
match = re.compile('<td align="center"><strong><a href="(.+?)"').findall(r)
for url in match:
host = url.split('//')[1].replace('www.', '')
host = host.split('/')[0]... |
gdebure/cream | projects/migrations/0004_project_status.py | Python | gpl-3.0 | 466 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration | (migrations.Migration):
dependencies = [
('projects', '0003_auto_20150618_1121'),
]
operations = [
migrations.AddField(
model_name='project',
| name='status',
field=models.ForeignKey(default='a', to='projects.ProjectStatus'),
preserve_default=False,
),
]
|
clinton-hall/nzbToMedia | libs/common/babelfish/__init__.py | Python | gpl-3.0 | 761 | 0.003942 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2013 the BabelFish authors. All rights reserved.
# Use of this source c | ode is governed by the 3-clause BSD license
# that can be found in the LICENSE file.
#
import sys
if sys.version_info[0] >= 3:
basestr = str
else:
basestr = basestring
from .converters import (LanguageConverter, LanguageReverseConverter, LanguageEquivalenceConverter, CountryConverter,
CountryReverseConver... | tions import Error, LanguageConvertError, LanguageReverseError, CountryConvertError, CountryReverseError
from .language import language_converters, LANGUAGES, LANGUAGE_MATRIX, Language
from .script import SCRIPTS, SCRIPT_MATRIX, Script
|
edwar/repositio.com | ProyectoDeGrado/forms.py | Python | mit | 2,750 | 0.016364 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
from django import forms
from django.core.mail import send_mail
from django.template import Context
from ProyectoDeGrado.settings import MEDIA_ROOT
from apps.administrador.models import *
from django.contrib.auth.models import User
class PerfilForm(forms.M... | ,'title':'Seleccione sus carreras'})
}
def __init__(self, *args, **kwargs):
super(PerfilForm, self).__init__(*args, **kwargs)
self.fields['sede'].empty_label = "Seleccione la su sede"
def enviar(self, data):
link = "http://www.repositio.com/activate/"+data['username']+"/"+ data... | send_mail(data['email_subject'], message, 'Repositio <repositio@gmail.com>', [data['username']+data['dominio']],fail_silently=False)
def save(self, data):
perfil = Perfil()
usuario = User.objects.get(username = data['username'])
perfil.usuario = usuario
perfil.activation_key=da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.