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 |
|---|---|---|---|---|---|---|---|---|
sesuncedu/bitcurator | tools/py3fpdf/attic/font/calligra.py | Python | gpl-3.0 | 2,763 | 0.199421 |
type='TrueType'
name='Calligrapher-Regular'
desc={'Ascent':899,'Descent':-234,'CapHeight':731,'Flags':32,'FontBBox':'[-50 -234 1328 899]','ItalicAngle':0,'StemV':70,'MissingWidth':800}
up=-200
ut=20
cw={
'\x00':800,'\x01':800,'\x02':800,'\x03':800,'\x04':800,'\x05':800,'\x06':800,'\x07':800,'\x08':800,'\t':800,'\n':8... | 5':603,'\xa6':0,'\xa7':519,'\xa8':254,'\xa9':800,'\xaa':349,'\xab':0,'\xac':0,'\xad':432,'\xae':800,'\xaf':278,
'\xb0':0,'\xb1':0,'\xb2' | :0,'\xb3':0,'\xb4':278,'\xb5':614,'\xb6':0,'\xb7':254,'\xb8':278,'\xb9':0,'\xba':305,'\xbb':0,'\xbc':0,'\xbd':0,'\xbe':0,'\xbf':501,'\xc0':743,'\xc1':743,'\xc2':743,'\xc3':743,'\xc4':743,'\xc5':743,
'\xc6':1060,'\xc7':598,'\xc8':608,'\xc9':608,'\xca':608,'\xcb':608,'\xcc':308,'\xcd':308,'\xce':308,'\xcf':308,'\xd0':0,... |
davidmarin/pbg | python/pbg/common/microdata.py | Python | apache-2.0 | 1,121 | 0.000892 | """Thin wrapper around the microdata library."""
from __future__ import absolute_import
import microdata
class Item(microdata.Item):
"""Add an "extra" field to microdata Items, so people won't feel the need
to make up ad-hoc properties.
Also add __eq__() and __repr__().
"""
def __init__(self, *a... | and
self.itemtype == other.itemtype and
self.props == other.props and
self.extra == getattr(other, 'extra', {}))
def __repr__(self):
return '%s(%r, %r, props=%r, extra=%r)' % (
self.__class__.__name__,
' '.join(uri.string for uri in sel... | mtype),
self.itemid,
self.props,
self.extra)
|
olhoneles/olhoneles | montanha/util.py | Python | agpl-3.0 | 3,167 | 0.000316 | # -*- coding: utf-8 -*-
#
# Copyright (©) 2013 Marcelo Jorge Vieira <metal@alucinados.com>
# Copyright (©) 2013 Gustavo Noronha Silva <gustavo@noronha.eti.br>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the F... | cense
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from datetime import date
from montanha.models import Institution, Legislature
def filter_for_institution(data, institution):
if not institutio | n:
return data
if not isinstance(institution, Institution):
institution = Institution.objects.get(siglum=institution)
data = data.filter(mandate__legislature__institution=institution)
return data
def get_date_ranges_from_data(institution, data, consolidated_data=False, include_date_objec... |
guorendong/iridium-browser-ubuntu | tools/telemetry/telemetry/results/page_test_results_unittest.py | Python | bsd-3-clause | 12,842 | 0.002803 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import unittest
from telemetry import page as page_module
from telemetry.page import page_set
from telemetry.results import base_test_results_unit... | ts.all_page_runs))
self.assertTrue(results.all_page_runs[0].failed)
self.assertTrue(results.all_page_runs[1].ok)
def testSkip | s(self):
results = page_test_results.PageTestResults()
results.WillRunPage(self.pages[0])
results.AddValue(skip.SkipValue(self.pages[0], 'testing reason'))
results.DidRunPage(self.pages[0])
results.WillRunPage(self.pages[1])
results.DidRunPage(self.pages[1])
self.assertTrue(results.all_pag... |
openatv/enigma2 | lib/python/Plugins/Extensions/QuadPip/plugin.py | Python | gpl-2.0 | 682 | 0.030792 | from __future__ import absolute_import
from Plugins.Plugin import PluginDescriptor
from Components.PluginComponent import plugins
from enigma import eDBoxLCD
from .qpip import QuadPipScreen, setDecoderMode
def main(session, **kwargs):
session.open(QuadPipScreen)
def autoStart(reason, **kwargs):
if reason == 0:
... | nDescriptor(name=_("Enable Quad PIP"),
description="Quad Picture in | Picture",
where=[PluginDescriptor.WHERE_EXTENSIONSMENU],
fnc=main))
list.append(
PluginDescriptor(
where=[PluginDescriptor.WHERE_AUTOSTART],
fnc=autoStart))
return list
|
edx/configuration | util/create_data_czar/create_org_data_czar_policy.py | Python | agpl-3.0 | 2,563 | 0.001951 | """
create_org_data_czar_policy.py
Creates an IAM group for an edX org and applies an S3 policy to that group
that allows for read-only access to the group.
"""
import argparse
import boto3
from botocore.exceptions import ClientError
from string import Template
import sys
template = Template("""{
"Version":"2012-1... | g_group(org, iam_connection)
else:
parser.print_usage()
sys.exit(1)
| sys.exit(0)
|
devton/pagarme-py | pagarme/transaction.py | Python | mit | 1,490 | 0.000671 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from .exceptions import TransactionValidationError
AVAIABLE_PAYMENT_METHOD = ['credit_card', 'boleto']
def validate_transaction(attrs):
if len(attrs) <= 0:
raise TransactionValidationError('Need a vali... | unt'] <= 0:
errors.append('Need to define an amount')
if 'payment_method' not in attrs:
errors.append('Need to define an valid payment_method')
if 'payment_method' in attrs:
if not attrs['payment_method'] in AVAIABLE_PAYMENT_METHOD:
errors.append(
"invalid p... | class Transaction():
def __init__(self, requester):
self.requester = requester
self.attributes = {}
def get_transactions(self, page=1):
return self.requester.commit('/transactions', {'page': page}, 'GET')
def build_transaction(self, transaction_attributes):
if not isinstanc... |
51reboot/actual_09_homework | 07/xq/app.py | Python | mit | 10,060 | 0.018564 | #encoding: utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8') #设置命令行为utf-8,让代码里面的中文正常显示
from flask import Flask #从flask包导入Flask类
from flask import render_template #从flask包导入render_template函数
from flask import request ... | = request.form.get('username', '') #接收用户提交的数据
password = request.form.get('password', '')
print "username is %s" %username
_users,_error = user.get_info(username=username)
if _users:
_id = _users[0]['id']
else:
_id = ''
#希望把ID加进去作为session绑定,后面根据id修改对应用户的密码!
#需要验证用户名密码是否正... | ord): #判断用户登录是否合法
session['user'] = {'username':username} #设置session,绑定用户身份信息,和用户名绑定,类似办银行卡
session['id'] = {'id':_id}
flash("登陆成功!") #flask的消息闪现,一次生成一个, 通过函数get_flashed_messages()获取
print session #打印session信息,用于查看,理解session
... |
rtucker-mozilla/inventory | vendor-local/src/django-extensions/django_extensions/management/commands/create_command.py | Python | bsd-3-clause | 3,608 | 0.003326 | import os
from django.core.management.base import CommandError, AppCommand
from django_extensions.management.utils import _make_writeable
from optparse import make_option
class Command(AppCommand):
option_list = AppCommand.option_list + (
make_option('--name', '-n', action='store', dest='command_name', de... | ept OSError, e:
raise CommandError(e)
copy_template('command_template', project_dir, options.get('command_name'), '%sCommand' % options.get('base_command'))
def copy_template(template_name, copy_to, com | mand_name, base_command):
"""copies the specified template directory to the copy_to location"""
import django_extensions
import re
import shutil
template_dir = os.path.join(django_extensions.__path__[0], 'conf', template_name)
handle_method = "handle(self, *args, **options)"
if base_comman... |
auag92/n2dm | Asap-3.8.4/Debug/UnBalance.py | Python | mit | 1,763 | 0.01418 | #PBS -N UnBalance
#PBS -m ae
#PBS -q long
#PBS -l nodes=1:opteron:ppn=2
"""Test handling of extreme load-unbalancing."""
from asap3 import *
from asap3.md import MDLogger
from ase.lattice.cubic import FaceCenteredCubic
import numpy as np
from asap3.mpi import world
#DebugOutput("UnBalance.%d.out")
#set_verbose(1)
pr... | MakeParallelAtoms(atoms, cpulayout)
print len(atoms), atoms.get_number_of_atoms()
atoms.set_calculator(EMT())
traj = PickleTrajectory("UnBalance.traj", "w", atoms)
if fast:
atoms.get_forces()
traj.write()
for i in range(50):
| print "\n\n\n\n*** STEP %i ***\n\n\n\n\n" % (i,)
r = atoms.get_positions()
r += atoms.get_tags().reshape((-1,1)) * np.array([[0, 0, 20.0],])
atoms.set_positions(r)
atoms.get_forces()
traj.write()
else:
dyn = VelocityVerlet(atoms, 5*units.fs)
logger = MDLogger(dyn, a... |
lerker/cupydle | cupydle/dnn/capas.py | Python | apache-2.0 | 8,329 | 0.005043 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Ponzoni, Nelson"
__copyright__ = "Copyright 2015"
__credits__ = ["Ponzoni Nelson"]
__maintainer__ = "Ponzoni Nelson"
__contact__ = "npcuadra@gmail.com"
__email__ = "npcuadra@gmail.com"
__license__ = "GPL"
__version__ = "1.0.0"
_... | if funcionActivacion == 'sigmoidea':
funcionActivacion_tmp = sigmoideaTheano()
elif funcionActivacion == 'linealRectificada':
funcionActivacion_tmp = linealRectificadaTheano()
else:
funcionActivacion_tmp = None
self.funcionActivacion = funcionActivacion_tmp
... | s = numpy.asarray(
rng.uniform(
low=-numpy.sqrt(6. / (unidadesEntrada + unidadesSalida)),
high=numpy.sqrt(6. / (unidadesEntrada + unidadesSalida)),
size=(unidadesEntrada, unidadesSalida)
),
dtype=theano.config.fl... |
ah-anssi/SecuML | SecuML/core/DimensionReduction/Configuration/Projection/SdmlConfiguration.py | Python | gpl-2.0 | 1,670 | 0.001198 | # SecuML
# Copyright (C) 2016 ANSSI
#
# SecuML is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# SecuML is distributed in the hope t... | u should have received a copy of the GNU General Public License along
# with SecuML. If not, see <http://www.gnu.org/licenses/>.
from SecuML.core.DimensionReduction.Algorithms.Projection.Sdml import Sdml
from SecuML.core.DimensionReduct | ion.Configuration import DimensionReductionConfFactory
from .SemiSupervisedProjectionConfiguration import SemiSupervisedProjectionConfiguration
class SdmlConfiguration(SemiSupervisedProjectionConfiguration):
def __init__(self, families_supervision=None):
SemiSupervisedProjectionConfiguration.__init__(
... |
MartinHjelmare/home-assistant | homeassistant/components/emoncms_history/__init__.py | Python | apache-2.0 | 2,839 | 0 | """Support for sending data to Emoncms."""
import logging
from datetime import timedelta
import requests
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_API_KEY, CONF_WHITELIST, CONF_URL, STATE_UNKNOWN, STATE_UNAVAILABLE,
CONF_SCAN_INTERVAL)... | st.json'.format(url)
data = {"apikey": apikey, "data": payload}
parameters = {"node": node}
req = requests.post(
fullurl, params=parameters, data=data, allow_redirects=True,
timeout=5)
except requests.exceptions.RequestException:
_... | oad, fullurl)
else:
if req.status_code != 200:
_LOGGER.error(
"Error saving data %s to %s (http status code = %d)",
payload, fullurl, req.status_code)
def update_emoncms(time):
"""Send whitelisted entities states regularly to Emon... |
gchq/gaffer-tools | python-shell/src/example.py | Python | apache-2.0 | 26,676 | 0.000487 | #
# Copyright 2016-2019 Crown Copyright
#
# 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 i... | ter_functions(gc)
get_class_filter_functions(gc)
get_element_generators(gc)
get_object_generators(gc)
get_operations(gc)
get_serialised_fields(gc)
get_store_traits(gc)
is_operation_supported(gc)
add_elements(gc)
get_elements(gc)
get_adj_seeds(gc)
get_all_elements(gc)
ge... | rate_domain_objects_chain(gc)
get_element_group_counts(gc)
get_sub_graph(gc)
export_to_gaffer_result_cache(gc)
get_job_details(gc)
get_all_job_details(gc)
add_named_operation(gc)
get_all_named_operations(gc)
named_operation(gc)
delete_named_operation(gc)
add_named_view_summaris... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/samba/dcerpc/drsblobs/DsCompressedChunk.py | Python | gpl-2.0 | 1,282 | 0.00702 | # encoding: utf-8
# module samba.dcerpc.drsblobs
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/drsblobs.so
# by generator 1.135
""" drsblobs DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class DsCompressedChunk(__talloc.Object):
# no | doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
def __ndr_pack__(self, *args, **kwargs): # real signature unknown
"""
S.ndr_pack(object) -> blob
NDR pack
"""
pass
def __ndr_print__(self, *args, **kwargs): # real signature unknown
... | """
S.ndr_unpack(class, blob, allow_remaining=False) -> None
NDR unpack
"""
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
... |
mo/project-euler | python/problem15.py | Python | mit | 8,409 | 0.015816 | #
# In this file, there are code present for solving this pr | oblem using
# several different approaches. The first ones were two slow to be
# valid solution (Project EULER says that it should be possible to
# find an algorithm that solves the problem in less than 60 secs).
#
#
# In the end, method number five ended up solving this problem in
# 0.024 secs which is really nic... | sequence (the number of unique paths through an NxN grid)
# in Sloane's integer sequence dictionary:
#
# http://www.research.att.com/~njas/sequences/?q=2%2C6%2C20%2C70%2C252%2C924%2C3432%2C12870%2C48620&language=english&go=Search
import time
def number_of_bits_set(n):
bits_set = 0
while (n):
bits_set ... |
jchodera/bhmm | bhmm/init/__init__.py | Python | lgpl-3.0 | 859 | 0.001164 |
# This file is part of BHMM (Bayesian Hidden Markov Models).
#
# Copyright (c) 2016 Frank Noe (Freie Universitaet Berlin)
# and John D. Chodera (Memorial Sloan-Kettering Cancer Center, New York)
#
# BHMM is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public Licen... | TNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Les | ser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__author__ = 'noe'
|
feigaochn/leetcode | p686_repeated_string_match.py | Python | mit | 1,105 | 0.001817 | #!/usr/bin/env python
# coding: utf-8
"""
Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.
For example, with A = "abcd" and B = "cdabcdab".
Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substrin... | class Solution:
def repeatedStringMatch(self, A, B):
"""
:type A: str
:type B: str
:rtype: int
"""
| from math import ceil
repeats = int(ceil(len(B) / len(A)))
container = ""
for _ in range(repeats):
container += A
if container.find(B) != -1:
return repeats
container += A
if container.find(B) != -1:
return repeats + 1
re... |
jeroanan/Nes2 | Tests/OpCodeTests/TestRtiOpCode.py | Python | bsd-3-clause | 313 | 0.003195 | from Chip import OpCodeDefinitions
from Tests.OpCodeTests.OpCodeTestBase import OpCodeTestBase
class TestRt | iOpCode(OpCodeTestBase):
def test_execute_rti_implied_command_calls_and_method(self):
self.assert_opcode_execution(OpCodeDefinitions.rti_implied_command, self.target.get_rti_com | mand_executed)
|
muccg/rdrf | rdrf/rdrf/admin.py | Python | agpl-3.0 | 19,470 | 0.001079 | from django.utils.html import format_html
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.urls import reverse
from rdrf.models.definition.models import Registry
from rdrf.models.definition.models import RegistryForm
from rdrf.models.definition.models import QuestionnaireR... | IP_DEFLATED)
for registry in registrys:
yaml_data = export_registry(registry, request)
if yaml_data is None:
return | HttpResponseRedirect("")
zf.writestr(registry.code + '.yaml', yaml_data)
zf.close()
zippedfile.flush()
zippedfile.seek(0)
response = HttpResponse(FileWrapper(zippedfile), content_type='application/zip')
name = "export_" + export_time + "_" + \
reduce(la... |
durandj/codeeval | python/3_prime_palindrome.py | Python | gpl-3.0 | 521 | 0.009597 | import math
def is_palindro | me(n):
s = str(n)
return s == s[::-1]
def is_prime(n):
if n <= 1:
return False
if n % 2 == 0 and n != 2:
return False
if n == 2:
return True
root = math.sqrt(n)
i = 3
while i <= root:
if n % i == 0:
return False
i += 2
ret... | break
|
kennedyshead/home-assistant | homeassistant/components/plex/config_flow.py | Python | apache-2.0 | 16,121 | 0.000806 | """Config flow for Plex."""
import copy
import logging
from aiohttp import web_response
import plexapi.exceptions
from plexapi.gdm import GDM
from plexauth import PlexAuth
import requests.exceptions
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components import http
from homeas... | _LOGGER.error("Plex server could not be reached: %s", server_identifier)
errors[CONF_HOST] = "not_found"
except ServerNotSpecified as available_servers:
self.available_servers = available_servers.args[0]
return await self.async_step_select_server()
except Exc... | )
return self.async_abort(reason="unknown")
if errors:
if self._manual:
return await self.async_step_manual_setup(
user_input=server_config, errors=errors
)
return await self.async_step_user(errors=errors)
server_i... |
etz69/irhelper | vol_plugins/hollowfind.py | Python | gpl-3.0 | 18,182 | 0.00935 | # Author: Monnappa K A
# Email : monnappa22@gmail.com
# Twitter: @monnappa22
# Description: Volatility plugin to detect different types of Process Hollowing
import os
import volatility.obj as obj
import volatility.utils as utils
from volatility.plugins.taskmods import PSList
import volatility.plugins.vadinfo as vadin... | if vad_found == False:
self.proc_vad_info[pid].extend(["NA", Address(0), Hex(0), "NA", "NA"])
else:
self.proc_vad_info[pid].extend(["No VAD", Address(0), Hex(0), "No VAD", "No VAD"])
def get_proc_peb_info(self):
return self.pro... | returns dictionary with pid as the key and type of process hollowing as value"""
proc_peb_info = self.get_proc_peb_info()
proc_vad_info = self.get_proc_vad_info()
hol_type = None
self.hollowed_procs = {}
for pid in proc_peb_info:
(proc, pid, proc_name, ppid, create_t... |
RossBrunton/BMAT | tags/context_processors.py | Python | mit | 338 | 0.008876 | """C | ontext processors, these get called and add things to template contexts"""
from .models import Tag
def pinned_tags(request):
""" Adds the list of tags this user has pinned """
out = {}
if request.user.is_authenticated():
out["pinned_tags"] = Tag.by_user(request.user).filter(pinned=True)
... | eturn out
|
openjck/distribution-viewer | viewer/api/views.py | Python | mpl-2.0 | 4,165 | 0 | import datetime
from django.conf import settings
from django.contrib.auth import get_user_mod | el, login
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse
from djang | o.views.decorators.csrf import csrf_exempt
from oauth2client import client, crypt
from rest_framework.decorators import (api_view, authentication_classes,
permission_classes,
renderer_classes)
from rest_framework.exceptions import (Authentic... |
Azure/azure-sdk-for-python | sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_permissions_operations.py | Python | mit | 10,365 | 0.004824 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | _name, 'str', max_length=90, min_length=1),
'subscriptio | nId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
... |
guillochon/FriendlyFit | mosfit/modules/engines/rprocess.py | Python | mit | 3,010 | 0.001329 | """Definitions for the `RProcess` class."""
from math import isnan
import numpy as np
from astrocats.catalog.source import SOURCE
from mosfit.constants import C_CGS, DAY_CGS, IPI, KM_CGS, M_SUN_CGS
from mosfit.modules.engines.engine import Engine
from scipy.interpolate import RegularGridInterpolator
# Important: Onl... | sities = [
self._lscale * (0.5 - IPI * np.arctan(
(t * DAY_CGS - 1.3) / 0.11)) ** 1.3 *
(np.exp(-self._a * t) + np.log1p(
self._bx2 * t ** self._d) / (self._bx2 * t ** self._d))
for t in ts
]
luminosities = [0.0 if isnan(x) | else x for x in luminosities]
return {self.dense_key('luminosities'): luminosities} |
GrotheFAF/client | src/model/player.py | Python | gpl-3.0 | 4,660 | 0 | from PyQt5.QtCore import QObject, pyqtSignal
class Player(QObject):
updated = pyqtSignal(object, object)
newCurrentGame = pyqtSignal(object, object, object)
"""
Represents a player the client knows about.
"""
def __init__(self,
id_,
login,
gl... | ormat(
self.id,
self.login,
self.global_rating,
self.ladder_rating
)
@property
def currentGame(self):
return self._currentGame
@currentGame.setter
def currentGame(self, game):
self.set_current_game_defer_signal(game)()
def se... | ._currentGame
self._currentGame = game
return lambda: self._emit_game_change(game, old)
def _emit_game_change(self, game, old):
self.newCurrentGame.emit(self, game, old)
if old is not None:
old.ingamePlayerRemoved.emit(old, self)
if game is not None:
... |
eamonnmag/hepdata3 | hepdata/modules/records/api.py | Python | gpl-2.0 | 24,761 | 0.003029 | # -*- coding: utf-8 -*-
#
# This file is part of HEPData.
# Copyright (C) 2016 CERN.
#
# HEPData is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later... | e for the current version if present.
: | param ctx:
:param recid:
"""
try:
commit_message_query = RecordVersionCommitMessage.query \
.filter_by(version=ctx["version"], recid=recid)
if commit_message_query.count() > 0:
commit_message = commit_message_query.one()
ctx["revision_message"] = {
... |
kubeflow/pipelines | sdk/python/kfp/deprecated/dsl/artifact_utils.py | Python | apache-2.0 | 3,439 | 0 | # Copyright 2021 The Kubeflow 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... | property_def['type'])
except ValueError:
raise ValueError('Unsupported type:{} specified for field: {} \
in schema'.format(property_def['type'], property_name))
return title, properties
def verify_schema_instance(schema: str, instance: Dict[str, Any]):
"""Verifies inst... | for verification.
instance: Object represented as Dict to be verified.
Raises:
RuntimeError if schema is not well-formed or instance is invalid against
the schema.
"""
if len(instance) == 0:
return
try:
jsonschema.validate(instance=instance, schema=yaml.full_load(sc... |
OneBitSoftware/jwtSample | src/Spa/env1/Lib/site-packages/gunicorn/util.py | Python | mit | 12,319 | 0.001786 | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
try:
import ctypes
except MemoryError:
# selinux execmem denial
# https://bugzilla.redhat.com/show_bug.cgi?id=488396
ctypes = None
except ImportError:
# Python on Solaris ... | dot = package.rindex('.', 0, dot)
except ValueError:
raise ValueError("attempted relative import beyond top-level "
"package")
return "%s.% | s" % (package[:dot], name)
def import_module(name, package=None):
"""Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
"""
if name.startswith('... |
saruberoz/leetcode-oj | leetcode-solutions/python/add_two_numbers.py | Python | mit | 1,303 | 0 | # https://oj.leetcode.com/problems/add-two-numbers/
# 1555 / 1555 test cases passed.
# You are given two linked lists representing two non-negative numbers.
# The digits are stored in reverse order and each of their nodes contain
# a single digit. Add the two numbers and return it as a linked list.
#
# Input: (2 -> 4 -... | efinition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @return a ListNod | e
def addTwoNumbers(self, l1, l2):
carry = 0
head = ListNode(0)
curr = head
while l1 and l2:
sum = l1.val + l2.val + carry
carry = sum / 10
curr.next = ListNode(sum % 10)
l1 = l1.next
l2 = l2.next
curr = curr.ne... |
SSCPS/bip-gam-v1 | bip.py | Python | gpl-3.0 | 1,835 | 0.005995 | #! /usr/bin/env python
#################################################################################################
#
# Script Name: bip.py
# Script Usage: This script is the menu system and runs everything else. Do not use other
# files unless you are comfortable with the code.
#
# ... | ing run.ps1.
#
# Script Updates:
# 201709191243 - rdegennaro@sscps.org - copied boilerplate.
#
#################################################################################################
import os # os.system for clearing screen and simple gam calls
import subprocess # subprocess.Popen is to capture ... | relevant tables
import csv # CSV is used to read output of drive commands that supply data in CSV form
import bip_config # declare installation specific variables
# setup for MySQLdb connection
varMySQLHost = bip_config.mysqlconfig['host']
varMySQLUser = bip_config.mysqlconfig['user']
varMySQLPassword = bip_con... |
ActiveState/code | recipes/Python/511434_Paint_10/recipe-511434.py | Python | mit | 3,174 | 0.008507 | HOST = '127.0.0.1'
PORT = 8080
from Tkinter import *
import tkColorChooser
import socket
import thread
import spots
################################################################################
def main():
global hold, fill, draw, look
hold = []
fill = '#000000'
connect()
root = Tk()
root... | r Canvas')
draw = Canvas(upper, bg='#f | fffff', width=400, height=300, highlightthickness=0)
look = Canvas(lower, bg='#ffffff', width=400, height=300, highlightthickness=0)
cursor = Button(upper, text='Cursor Color', command=change_cursor)
canvas = Button(upper, text='Canvas Color', command=change_canvas)
draw.bind('<Motion>', motion)
dra... |
google/ml-metadata | ml_metadata/tools/documentation/build_docs.py | Python | apache-2.0 | 4,411 | 0.005214 | # 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 writing, ... | ("tf","keras","layers","Dense")
parent: The parent object.
children: A list of (name, value) pairs. The attributes of the patent.
Returns:
A filtered list of children `(name, value)` p | airs. With all proto methods
removed.
"""
del path
new_children = []
if not isinstance(parent, GeneratedProtocolMessageType):
return children
new_children = []
for (name, obj) in children:
if 'function' in str(obj.__class__):
continue
new_children.append((name, obj))
return new_child... |
cswank/mongodoc | mongodoc/collection_doc.py | Python | mit | 3,438 | 0.003781 | import difflib, re
from pymongo.objectid import ObjectId
class CollectionDoc(object):
def __init__(self, db, docs, find_links=True):
self._db = db
self._collection_names = db.collection_names()
self._docs = docs
self._find_links = find_links
@property
def text(self):
... | ields(doc.doc)
level = self._make_links(doc.collection, fields, text, level)
def _make_links(self, doc_collection_name, fields, text, level):
for key, value in fields.iteritems():
collection_name = self._find_collection(key, value)
if col | lection_name is not None:
self._make_link(doc_collection_name, collection_name, key, value, text, level)
level += 1
return level
def _make_link(self, doc_collection_name, collection_name, key, value, text, level):
for collection_start, row in enumerate(te... |
lnybrave/zzbook | data/sync.py | Python | apache-2.0 | 2,231 | 0.00137 | # !/usr/bin/python
# -*- coding=utf-8 -*-
import json
import urllib2
from books.models import Book
domain = "http://smartebook.zmapp.com:9026"
# 同步图书详情
def sync_book(bid, cm):
# 完结了的图书不更新信息
if Book.objects.filter(id=bid, status=1).count() == 0:
page = urllib2.urlopen("http://wap.cmread.com/r/p/view... | result['chapterSize']
book.score = result['score']
book.word_size = result['wordSize']
book.click_amount = result['clickValue']
book.kw = result['kw']
book.price = int(float(result['price']) * 100)
book.charge_mode = result['chargeMode']
... | _url_small', 'status', 'first_cid', 'last_cid',
'chapter_size', 'score', 'word_size', 'click_amount', 'kw', 'price', 'charge_mode'))
else:
book.save(force_insert=True)
return True
except Exception, e:
print e.message
return False
... |
IfcOpenShell/IfcOpenShell | src/ifcblender/io_import_scene_ifc/__init__.py | Python | lgpl-3.0 | 13,611 | 0.002057 | # IfcBlender - Blender IFC Importer
# Copyright (C) 2019 Thomas Krijnen <thomas@aecgeeks.com>
#
# This file is part of IfcBlender.
#
# IfcBlender 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 v... | faces = me.polygons if hasattr(me, "polygons") else me.faces
if len(faces) == len(matids):
for face, matid in zip(faces, matids):
face.material_index = matid + (1 if needs_default else 0)
# OBJECT CREATION
bob = bpy.data.objects.new(nm, me)
mat ... | |
jbloom/epitopefinder | scripts/epitopefinder_plotdistributioncomparison.py | Python | gpl-3.0 | 3,447 | 0.004642 | #!python
"""Script for plotting distributions of epitopes per site for two sets of sites.
Uses matplotlib. Designed to analyze output of epitopefinder_getepitopes.py.
Written by Jesse Bloom."""
import os
import sys
import random
import epitopefinder.io
import epitopefinder.plot
def main():
"""Main body of sc... | e in open(epitopesfile).readlines()[1 : ]:
if not (line.isspace() or line[0] == '#'):
(site, n) = line.split(',')
(site, n) = (int(site), int(n))
xlist.append(n)
if not xlist:
raise ValueError("%s failed to specify information for any sites... | o.ParseStringValue(d, 'title').strip()
if title.upper() in ['NONE', 'FALSE']:
title = None
pvalue = epitopefinder.io.ParseStringValue(d, 'pvalue')
if pvalue.upper() in ['NONE', 'FALSE']:
pvalue = None
pvaluewithreplacement = None
else:
pvalue = int(pvalue)
pvaluew... |
asolntsev/selenium | py/test/runner/run_pytest.py | Python | apache-2.0 | 1,047 | 0 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | r the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
with open("pytest.ini", "w") as ini_file:
ini_file.write("[pytest]\n"... | python_files = test_*.py *_tests.py\n")
raise SystemExit(pytest.main())
|
CMaiku/inhibit-screensaver | inhibit-screensaver.py | Python | gpl-2.0 | 851 | 0.007051 | #!/usr/bin/env python
import subprocess
import sys
from gi.repository import GLib, Gio
def main():
bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
pro | xy = Gio.DBusProxy.new_sync(bus, Gio.DBusProxyFlags.NONE, None,
'org.freedesktop.ScreenSaver', '/ScreenSaver',
'org.freedesktop.ScreenSaver', None)
cookie = proxy.Inhibit('(ss)', sys.argv[1],
"Wrapping this command in a sc | reensaver inhibitor")
print('Inhibited the screensaver')
try:
subprocess.call(sys.argv[1:])
finally:
proxy.UnInhibit('(u)', cookie)
print('UnInhibited the screensaver')
if __name__ == '__main__':
if len(sys.argv) >= 2:
main()
else:
import os.path
pr... |
bvernoux/micropython | tests/float/inf_nan_arith.py | Python | mit | 587 | 0.001704 | # Test behaviour of inf and nan in basic float operations
inf = float("inf")
nan = float("nan")
values = (-2, -1, 0, 1, 2, inf, nan)
for x in values:
for y in values:
print(x, y)
print(" + - *", x + y, x - y, x * y)
try:
| print(" /", x / y)
except ZeroDivisionError:
print(" / ZeroDivisionError")
try:
print(" ** pow", x ** y, pow(x, y))
except ZeroDivisionError:
| print(" ** pow ZeroDivisionError")
print(" == != < <= > >=", x == y, x != y, x < y, x <= y, x > y, x >= y)
|
scaramallion/pynetdicom3 | pynetdicom/pdu.py | Python | mit | 68,107 | 0.000675 | """DICOM Upper Layer Protocol Data Units (PDUs).
There are seven different PDUs:
- A_ASSOCIATE_RQ
- A_ASSOCIATE_AC
- A_ASSOCIATE_RJ
- P_DATA_TF
- A_RELEASE_RQ
- A_RELEASE_RP
- A_ABORT_RQ
::
from_primitive encode
+----------------+ ------> +------------+ -----> +-------------+
... | ive | | PDU | | Peer AE |
+----------------+ <------ +------------+ <----- +-------------+
to_primitive decode
"""
import codecs
import logging
from struct import Struct
from pynetdicom.pdu_items import (
ApplicationContextItem,
Presentati... | ,
PresentationDataValueItem,
PDU_ITEM_TYPES
)
from pynetdicom.utils import validate_ae_title
LOGGER = logging.getLogger('pynetdicom.pdu')
# Predefine some structs to make decoding and encoding faster
UCHAR = Struct('B')
UINT2 = Struct('>H')
UINT4 = Struct('>I')
UNPACK_UCHAR = UCHAR.unpack
UNPACK_UINT2 = UIN... |
primecloud-controller-org/pcc-cli | src/pcc/api/instance/edit_instance_vmware.py | Python | apache-2.0 | 1,746 | 0.004009 | # -*- coding: utf-8 -*-
def command():
return "edit-instance-vmware"
def init_argument(parser):
parser.add_argument("--instance-no", required=True)
parser.add_argument("--instance-type", required=True)
parser.add_argument("--key-name", required=True)
parser.add_argument("--compute-resource", requi... | _static_ip
if (ip_address != None):
parameters["IpAddress"] = ip_address
if (subnet_mask != None):
parameters["SubnetMask"] = subnet_mask
if (default_gateway != None):
parameters["DefaultGateway"] = default_gateway
if (comment != None):
parameters["Comment"] = comment... | itInstanceVmware", parameters)
|
HomeRad/TorCleaner | wc/dns/opcode.py | Python | gpl-2.0 | 2,630 | 0.003802 | # -*- coding: iso-8859-1 -*-
# Copyright (C) 2001-2007, 2009, 2010 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 permission notice
# appear in all copies.
... | code to a value suitable for ORing into DNS message
flags.
@rtype: int
"""
return (value << 11) & | 0x7800
def to_text(value):
"""Convert an opcode to text.
@param value: the opcdoe
@type value: int
@raises UnknownOpcode: the opcode is unknown
@rtype: string
"""
text = _by_value.get(value)
if text is None:
text = str(value)
return text
def is_update(flags):
"""True... |
keleshev/schema | setup.py | Python | mit | 1,562 | 0 | import codecs
import sys
from setuptools import setup
version_file = "schema.py"
with open(version_file) as f:
for line in f.read().split("\n"):
if line.startswith("__version__ ="):
version = eval(line.split("=", 1)[1])
break
else:
print("No __version__ attribute found ... | ogramming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Pyth... | .8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: Implementation :: PyPy",
"License :: OSI Approved :: MIT License",
],
)
|
pierrejean-coudert/winlibre_pm | package_manager/smart/commands/install.py | Python | gpl-2.0 | 6,529 | 0.002144 | #
# Copyright (c) 2004 Conectiva, Inc.
#
# Written by Gustavo Niemeyer <niemeyer@conectiva.com>
#
# This file is part of Smart Package Manager.
#
# Smart Package Manager 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 Fou... | ))
parser.add_opti | on("--explain", action="store_true",
help=_("include additional information about changes,"
"when possible"))
parser.add_option("-y", "--yes", action="store_true",
help=_("do not ask for confirmation"))
parser.add_option("--dump", action="... |
kako-nawao/django-group-by | django_group_by/mixin.py | Python | mit | 2,630 | 0.00038 | """
This module contains the final mixin implementation, for whatever version
of Django is present.
"""
from django.db.models import ForeignKey, ManyToManyField
try:
# Django 1.9+
from .iterable import GroupByIterableMixinBase as GroupByMixinBase
except ImportError:
# Django 1.8-
from .queryset import... | ted.items():
# Get field
fk = model._meta.get_field(fk_field_name)
# Get all fields for that related model
related_fields = cls._expand_group_by_fields(fk.related_model,
field_names)
# Append them with... | fields)
# Return all fields
return res
|
Orochimarufan/youtube-dl | youtube_dl/extractor/soundcloud.py | Python | unlicense | 29,898 | 0.001138 | # coding: utf-8
from __future__ import unicode_literals
import itertools
import re
from .common import (
InfoExtractor,
SearchInfoExtractor
)
from ..compat import (
compat_HTTPError,
compat_kwargs,
compat_str,
compat_urlparse,
)
from ..utils import (
error_to_compat_str,
ExtractorError... | loat_or_none,
HEADRequest,
int_or_none,
KNOWN_EXTENSIONS,
mimetype2ext,
str_or_none,
try_get,
unified_timestamp,
update_url_query,
url_or_none,
urlhandle_detect_ext,
)
class SoundcloudEmbedIE(InfoExtractor):
_VALID_URL = r'https?://(?:w|player|p)\.soundcloud\.com/player/?.*... | n-station-to-station-to-station-julkaisua-juhlitaan-tanaan-g-livelabissa/
'url': 'https://w.soundcloud.com/player/?visual=true&url=https%3A%2F%2Fapi.soundcloud.com%2Fplaylists%2F922213810&show_artwork=true&maxwidth=640&maxheight=960&dnt=1&secret_token=s-ziYey',
'only_matching': True,
}
@staticm... |
ignaeche/barf-project | barf/examples/arm/translate_smt.py | Python | bsd-2-clause | 1,055 | 0.000948 | #! /usr/bin/env python
import os
import sys
from barf.barf import BARF
if __name__ == "__main__":
#
# Open file
#
try:
filename = os.path.abspath("../../samples/toy/arm/branch4")
barf = BARF(filename)
except Exception as err:
print err
print "[-] Error opening fil... | for smt_expr in smt_exprs:
print("{0:16}{1}".format("", s | mt_expr))
except:
pass
|
rodo/django-perf | foo/hotel/urls.py | Python | gpl-3.0 | 544 | 0.003676 | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.views.generic import ListView
from django.views.generic.detail import DetailView
from foo.hotel.models import Hotel
from foo.hotel.views import HotelLimitListView
from foo.hotel.v | iews import HotelLimitNoOrderListView
urlpatterns = patterns( | '',
url(r'^$', HotelLimitListView.as_view(model=Hotel), name='hotel'),
url(r'^noorder$', HotelLimitNoOrderListView.as_view(model=Hotel), name='hotelnoorder'))
|
mikalstill/nova | nova/objects/migration_context.py | Python | apache-2.0 | 3,456 | 0.000289 | # Copyright 2015 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... | anguage governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
from oslo_utils import versionutils
from nova.db import api as db
from nova import exception
from nova.objects import base
from nova.objects import fields
@base.NovaObjectRegistry.register
class MigrationC... | ect):
"""Data representing additional resources related to a migration.
Some resources cannot be calculated from knowing the flavor alone for the
purpose of resources tracking, but need to be persisted at the time the
claim was made, for subsequent resource tracking runs to be consistent.
Migration... |
donkirkby/djsquash | fruit/migrations/0100_prepare_squash.py | Python | mit | 274 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
class Migration(migration | s.Migration):
dependencies | = [
('fruit', '0003_apple_size'),
('fruit', '0002_cranberry_bacon'),
]
operations = [
]
|
ScreamingUdder/mantid | scripts/AbinsModules/GeneralAbInitioProgram.py | Python | gpl-3.0 | 10,789 | 0.00482 | from __future__ import (absolute_import, division, print_function)
from mantid.kernel import logger
import AbinsModules
import six
from mantid.kernel import Atom
class GeneralAbInitioProgramName(type):
def __str__(self):
return self.__name__
# noinspection PyMethodMayBeStatic
@six.add_metaclass(GeneralA... | """
def __init__(self, input_ab_initio_filename=None):
self._num_k = None
self._num_atoms = None
| self._sample_form = None
self._ab_initio_program = None
self._clerk = AbinsModules.IOmodule(input_filename=input_ab_initio_filename,
group_name=AbinsModules.AbinsParameters.ab_initio_group)
def read_vibrational_or_phonon_data(self):
"""
... |
coati-00/nepi | nepi/main/tests/test_models.py | Python | gpl-2.0 | 11,699 | 0 | from datetime import date
import datetime
from django.contrib.auth.models import User
from django.test import TestCase
from pagetree.models import Hierarchy, Section, UserPageVisit
from pagetree.tests.factories import HierarchyFactory, ModuleFactory
from factories import SchoolGroupFactory
from nepi.main.models impor... | rofile.is_student())
self.assertFalse(self.school_admin.profile.is_student())
self.assertFalse(self.country_admin.profile.is_student())
self.assertFalse(self.icap.profile.is_student())
self.assertFalse(self.student.profile.is | _teacher())
self.assertTrue(self.teacher.profile.is_teacher())
self.assertFalse(self.school_admin.profile.is_teacher())
self.assertFalse(self.country_admin.profile.is_teacher())
self.assertFalse(self.icap.profile.is_teacher())
self.assertFalse(self.student.profile.is_institution... |
joferkington/oost_paper_code | invert_slip_fixed_azimuth.py | Python | mit | 966 | 0.003106 | """
Restores the | uplifted horizons while restricting slip along the fault to the
specified azimuth.
"""
import numpy as np |
import matplotlib.pyplot as plt
from fault_kinematics.homogeneous_simple_shear import invert_slip
import data
import basic
def main():
azimuth = data.fault_strike + 90
# azimuth = 304 # Plate motion from Loveless & Meade
def func(*args, **kwargs):
return forced_direction_inversion(azimuth, *args, ... |
Ensembles/ert | python/python/ert/ecl/fortio.py | Python | gpl-3.0 | 7,299 | 0.004384 | # Copyright (C) 2011 Statoil ASA, Norway.
#
# The file 'fortio.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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,... | ile "%s".' % file_name)
if mode == FortIO.READ_MODE:
c_pointer = self._open_reader(file_name, fmt_file, endian_flip_header)
elif mode == FortIO.WRITE_MODE:
c_pointer = self._open_writer(file_name, fmt_file, endian_flip_header)
elif mode == FortIO.READ_AND_WRITE_MODE:
... | pen_append(file_name, fmt_file, endian_flip_header)
else:
raise UserWarning("Unknown mode: %d" % mode)
self.__mode = mode
if not c_pointer:
raise IOError('Failed to open FortIO file "%s".' % file_name)
super(FortIO, self).__init__(c_pointer)
def close(self... |
krzotr/kismon | kismon/windows/channel.py | Python | bsd-3-clause | 3,856 | 0.038641 | from gi.repository import Gtk
class ChannelWindow:
def __init__(self, sources, client_thread):
self.sources = sources
self.client_thread = client_thread
self.changes = {}
self.widgets = {}
self.gtkwin = Gtk.Window()
self.gtkwin.set_position(Gtk.WindowPosition.CENTER)
self.gtkwin.set_default_size(320,... | _scroll.set_po | licy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
vbox.pack_start(sources_list_scroll, True, True, 0)
for uuid in self.sources:
self.widgets[uuid] = {}
source = self.sources[uuid]
frame = Gtk.Frame()
frame.set_label(source["username"])
self.sources_list.pack_start(frame, False, False, 0)
... |
zinnschlag/high-pygtk | highgtk/present/default/inquiry.py | Python | lgpl-3.0 | 2,487 | 0.018898 |
import gtk
import highgtk.entity
import highgtk.present.default.layout
def add (inquiry):
window = getattr (inquiry, "present_window", None)
if window is None:
inquiry.present_window = gtk.Dialog()
title = getattr (inquiry, "title", None)
if title is None:
root = highgtk.e... | ame = getattr (inquiry, "cancel_method", None)
if method_name is not None:
method = getattr (inquiry.parent, method_name)
method (inquiry)
inquiry.remove (inquiry)
def okay (inquiry) | :
method_name = getattr (inquiry, "ok_method", "inquiry_okay")
error = inquiry.present_layout.get_error()
if error is not None:
inquiry.error_report.primary = error
inquiry.add (inquiry.error_report)
else:
method = getattr (inquiry.parent, method_name)
method (inquiry, in... |
Taiwanese-Corpus/kaxabu-muwalak-misa-a-ahan-bizu | 後端/kaxabu/urls.py | Python | mit | 819 | 0 | """kaxabu URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... | ome
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, | include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^', include('族語辭典.網址')),
url(r'^admin/', admin.site.urls),
]
|
flavour/eden | modules/templates/BRCMS/RLP/anonymize.py | Python | mit | 7,359 | 0.001223 | # -*- coding: utf-8 -*-
from uuid import uuid4
from gluon import current
def rlpcm_person_anonymize():
""" Rules to anonymize a case file """
auth = current.auth
s3db = current.s3db
ANONYMOUS = "-"
# Standard anonymizers
from s3db.pr import pr_address_anonymise as anonymous_address, \
... | "key": "pe_id" | ,
"match": "pe_id",
"fields": {"image": "remove",
"url": "remove",
"description": "remove",
},
"delete": True,
}),
... |
MahjongRepository/mahjong | mahjong/hand_calculating/yaku_list/honroto.py | Python | mit | 679 | 0 | from functools import reduce
from mahjong.constants import HONOR_INDICES, TERMINAL_INDICES
from mahjong.hand_calculating.yaku import Yaku
class Honroto(Yaku):
"""
All tiles are terminals or honours
"""
def __init__(self, yaku_id=None):
super(Honroto, self).__init__(yaku_id)
| def set_attributes(self):
self.tenhou_id = 31
self.name = "Honroutou"
self.han_open = 2
self.han_closed = 2
self.is_yakuman = False
def is_condition_met(self, hand, *args):
indices = reduce(lambda z, y: z + y, hand)
result = HONOR_INDICES + TERMINAL_IN... | return all(x in result for x in indices)
|
jbking/python-stdnet | stdnet/apps/columnts/npts.py | Python | bsd-3-clause | 1,723 | 0 | '''Experimental!
This is an experimental module for converting ColumnTS into
dynts.timeseries. It requires dynts_.
.. _dynts: https://github.com/quantmind/dynts
'''
from collections import Mapping
from . import models as columnts
import numpy as ny
from dynts import timeseries, tsname
class ColumnT... | fields):
| '''Return the front pair of the structure'''
ts = self.irange(0, 0, fields=fields)
if ts:
return ts.start(), ts[0]
def back(self, *fields):
'''Return the back pair of the structure'''
ts = self.irange(-1, -1, fields=fields)
if ts:
return ts... |
Microsoft/ApplicationInsights-Python | tests/applicationinsights_tests/channel_tests/contracts_tests/TestData.py | Python | mit | 1,545 | 0.006472 | import unittest
import datetime
import uuid
import sys
import json
import sys, os, os.path
root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..')
if root_directory not in sys.path:
sys.path.append(root_directory)
from applicationinsights.channel.contracts import *
from ... | s TestData(unittest.TestCase):
def test_construct(self):
item = Data()
self.assertNotEqual(item, None)
def test_base_type_property_works_as_expected(self):
expected = 'Test string'
item = Data()
item.base_type = expected
actual = item.base_type
self.a... | l(expected, actual)
def test_base_data_property_works_as_expected(self):
expected = object()
item = Data()
item.base_data = expected
actual = item.base_data
self.assertEqual(expected, actual)
expected = object()
item.base_data = expected
actual = ... |
0x0AF/lamure | pypro/tests/context.py | Python | bsd-3-clause | 143 | 0.013986 | # -*- coding: utf-8 -*-
imp | ort sys
import os
sys.path.in | sert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import pypro
|
efectivo/network_sim | grid1_basic.py | Python | mit | 755 | 0.006623 | from units import runner
import numpy as np
def job_gen():
for N | in range(4, 21, 2):
for rate_power in [1, 3/2.]:
rate = np.power(N, rate_power)
test = {
'test': {},
'net': {'topology': 'grid', 'N': N},
'pattern': {'type': 'random_one_bent', 'rate': rate, 'power': rate_power},
'cycles': ... | {'type': 'goed', 'dh_type':'ogh', 'p': .1, 'scheduler': 'LIS'},
{'type': 'goed', 'dh_type': 'ogh', 'p': .5, 'scheduler': 'LIS'}
]
}
yield test
runner.run_parallel(15, job_gen, 'grid1')
|
prasannav7/ggrc-core | src/ggrc/migrations/versions/20151112145524_35e5344803b4_add_missing_constraints_for_vendors.py | Python | apache-2.0 | 783 | 0.003831 | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
"""Add missing constraints for vendo | rs
Revision ID: 35e5344803b4
Revises: 27684e5f313a
Create Date: 2015-11-12 14:55:24.420680
"""
from alembic import op
from ggrc.migrations.utils import resolve_duplicates
from ggrc.models | import Vendor
# revision identifiers, used by Alembic.
revision = '35e5344803b4'
down_revision = '27684e5f313a'
def upgrade():
resolve_duplicates(Vendor, "slug")
op.create_unique_constraint('uq_slug_vendors', 'vendors', ['slug'])
def downgrade():
op.drop_constraint('uq_slug_vendors', 'vendors', 'unique')
|
jejimenez/django | tests/csrf_tests/tests.py | Python | bsd-3-clause | 19,350 | 0.000413 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.middleware.csrf import (
CSRF_KEY_LENGTH, CsrfViewMiddleware, get_token,
)
from django.template import RequestContext, Template
from django.... | Middleware().process_response(req, resp)
csrf_cooki | e = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False)
self.assertEqual(csrf_cookie, False)
# Check the request processing
def test_process_request_no_csrf_cookie(self):
"""
Check that if no CSRF cookies is present, the middleware rejects the
incoming request. This will stop l... |
HashirZahir/FIFA-Player-Ratings | FIFAscrape/spiders/fifa_spider.py | Python | mit | 3,458 | 0.014748 | from scrapy.spiders import Spider
from scrapy.selector import Selector
from scrapy.http import Html | Response
from FIFAscrape.items import PlayerItem
from urlparse import urlparse, urljoin
from scrapy.http.request import Request
from scrapy.conf import settings
import random
import time
class fifaSpider(Spider):
name = "fifa"
| allowed_domains = ["futhead.com"]
start_urls = [
"http://www.futhead.com/16/players/?level=all_nif&bin_platform=ps"
]
def parse(self, response):
#obtains links from page to page and passes links to parse_playerURL
sel = Selector(response) #define selector based on re... |
bsmithers/CLIgraphs | histogram.py | Python | agpl-3.0 | 8,515 | 0.003641 | #!/usr/bin/env python2
from __future__ import division
import itertools
import math
import sys
import numpy
import scipy.stats
import cligraph
import utils
"""
TODO:
- Auto-detect number of bins
- Fixed width or variable width bins
- Stacked bins, overlapped bins or bins next to each other
- Change which side of bi... | t bin should be smallest multiple of bin_size that is >= max_val
bins = []
i = math.floor(min_val / cli_args.bin_size) * cli_args.bin_size
# By default, bits are offset by half their width from the lowest value rather
# than by their full width
if not cli_args.disable_bin_offse... | else:
i -= cli_args.bin_size
while i <= max_val:
bins.append(i)
i += cli_args.bin_size
bins.append(i) # Add final bin
# Combine offscreen bins for faster renders
if cli_args.min_x and cli_args.min_x > min_val:
first_onscreen = max([index... |
chitr/neutron | neutron/agent/linux/keepalived.py | Python | apache-2.0 | 15,590 | 0 | # Copyright (C) 2014 eNovance SAS <licensing@enovance.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | netaddr.IPSet(excluded_ranges)
for cidr in free_cidrs.iter_cidrs():
if cidr.prefixlen <= size:
| return '%s/%s' % (cidr.network, size)
raise ValueError(_('Network of size %(size)s, from IP range '
'%(parent_range)s excluding IP ranges '
'%(excluded_ranges)s was not found.') %
{'size': size,
'parent_range': pare... |
ketan-analytics/learnpython | IntermediatePython/Lynda_Bill_PYEssential/SQL.py | Python | gpl-2.0 | 1,160 | 0.002586 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
import sqlite3
def main():
print('connect')
db = sqlite3.connect('db-api.db')
cur = db.cursor()
print('create')
cur.execute("DROP TABLE IF EXISTS test")
cur.execute("""
CREATE TABLE test (
id INTEG... | test (string, number) VALUES ('one', 1)
""")
print('insert row')
cur.execute("""
INSERT INTO test (string, number) VALUES ('two', 2)
""")
print('insert row')
cur.execute("""
INSERT INTO test (string, number) VALUES ('three', 3)
| """)
print('commit')
db.commit()
print('count')
cur.execute("SELECT COUNT(*) FROM test")
count = cur.fetchone()[0]
print(f'there are {count} rows in the table.')
print('read')
for row in cur.execute("SELECT * FROM test"):
print(row)
print('drop')
cur.execut... |
vpelletier/neoppod | neo/tests/zodb/testRecovery.py | Python | gpl-2.0 | 1,770 | 0.00226 | #
# Copyright (C) 2009-2016 Nexedi SA
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed... | ts.RecoveryStorage import RecoveryStorage
from ZODB.tests.StorageTestBase import StorageTestBase
from ..functional import NEOCluster
from | . import ZODBTestCase
class RecoveryTests(ZODBTestCase, StorageTestBase, RecoveryStorage):
def setUp(self):
super(RecoveryTests, self).setUp()
dst_temp_dir = self.getTempDirectory() + '-dst'
if not os.path.exists(dst_temp_dir):
os.makedirs(dst_temp_dir)
self.neo_dst = ... |
SalesforceFoundation/CumulusCI | cumulusci/tasks/bulkdata/generate_and_load_data.py | Python | bsd-3-clause | 8,766 | 0.00308 | import os
from tempfile import TemporaryDirectory
from pathlib import Path
from sqlalchemy import MetaData, create_engine
from cumulusci.tasks.salesforce import BaseSalesforceApiTask
from cumulusci.tasks.bulkdata import LoadData
from cumulusci.tasks.bulkdata.utils import generate_batches
from cumulusci.core.config im... | t.
https://sfdc.co/ | bwKxDD
"""
task_options = {
"num_records": {
"description": "How many records to generate. Precise calcuation depends on the generator.",
"required": True,
},
"num_records_tablename": {
"description": "Which table to count records in.",
"r... |
denisenkom/django | tests/signals/tests.py | Python | bsd-3-clause | 5,273 | 0.000759 | from __future__ import unicode_literals
from django.db.models import signals
from django.dispatch import receiver
from django.test import TestCase
from django.utils import six
from .models import Person, Car
# #8285: signals can be any callable
class PostDeleteHandler(object):
def __init__(self, data):
... | gnals = (
len(signals.pre_save.receivers),
len(signals.post_save.receivers),
len(signals.pre_delete.receivers),
len(signals.post_delete.receivers),
)
self.assertEqual(pre_signals, post_signals)
def test_disconnect_in_dispatch(self):
"""
... | ching.
"""
a, b = MyReceiver(1), MyReceiver(2)
signals.post_save.connect(sender=Person, receiver=a)
signals.post_save.connect(sender=Person, receiver=b)
p = Person.objects.create(first_name='John', last_name='Smith')
self.assertTrue(a._run)
self.assertTrue(b._run... |
DigitalSlideArchive/large_image | .circleci/make_index.py | Python | apache-2.0 | 855 | 0 | #!/usr/bin/env python
import os
import sys
import time
path = 'gh-pages' if len(sys.argv) == 1 else sys.argv[1]
indexName = 'index.html'
template = """<html>
<head><title>large_image_wheels</ | title></head>
<body>
<h1>large_image_wheels</h1>
<pre>
%LINKS%
</pre>
</body>
"""
link = '<a href="%s" download="%s">%s</a>%s%s%11d'
wheels = [(name, name) for name in os.listdir(path) if name.endswith('whl')]
wheels = sorted(wheels)
maxnamelen = max(len(name) for name, url in wheels)
index = template.replace('%LINKS... | %Y-%m-%d %H:%M:%S', time.gmtime(os.path.getmtime(
os.path.join(path, name)))),
os.path.getsize(os.path.join(path, name)),
) for name, url in wheels]))
open(os.path.join(path, indexName), 'w').write(index)
|
polarise/BioClasses | FrameshiftSequence.py | Python | gpl-2.0 | 4,907 | 0.057469 | # -*- encoding: utf-8 -*-
from __future__ import division
import math
from FrameshiftSite import *
class FrameshiftSequence( object ):
def __init__( self, sequence, path ):
self.path = path
self.path_str = ",".join( map( str, [ a for a,b in path ]))
self.frameshifted_sequence, self.fragments, self.fragment_posi... | CAI: %s
Log-likelihood: %s"""\
% ( ",".join( map( str, self.path )), \
"...".join([ self.frameshifted_sequence[:20], \
self.frameshifted_sequence[-20:] ]), ", ".join( self.fragments ),\
",".join( self.signals ), self.length, self.frameshift_count, self.CAI, self.likelihood )
#*****... | self, sep="\t" ):
return sep.join([ "...".join([ self.frameshifted_sequence[:20],
self.frameshifted_sequence[-20:] ]), str( self.length ), \
str( self.frameshift_count ), str( self.CAI ), \
str( self.CAI/math.sqrt( self.frameshift_count + 1 )), ",".join( map( str, self.path )), \
",".join( self... |
ajkannan/Classics-Research | tf_idf_one_class_svm.py | Python | mit | 2,185 | 0.044394 | from os import listdir
from os.path import isfile, join
from Utilities.Text import Text
from Utilities.TermFrequencyInverseDocumentFrequency import TermFrequencyInverseDocumentFrequency as TFIDF
from sklearn import svm
from pprint import pprint
import numpy as np
from sklearn.decomposition import PCA
def main():
p... | = gamma)
clf.fit(x["train"])
y = {
"trai | n" : clf.predict(x["train"]),
"test" : clf.predict(x["test"])
}
if all(y["train"] == 1.0) and all(y["test"] == -1.0):
pprint({"nu" : nu, "gamma" : gamma, "y" : y, "kernel" : kernel})
# The following settings using term-frequency inverse-document frequency
# gives a perfect classificati... |
yephper/django | tests/prefetch_related/test_prefetch_related_objects.py | Python | bsd-3-clause | 4,853 | 0.001648 | from django.db.models import Prefetch, prefetch_related_objects
from django.test import TestCase
from .models import Author, Book, Reader
class PrefetchRelatedObjectsTests(TestCase):
"""
Since prefetch_related_objects() is just the inner part of
prefetch_related(), only do basic tests to ensure ... | , 'first_time_authors')
with self.assertNumQueries(0):
[list(book.first_time_authors.all()) for book in books]
def test_m2m_then_m2m(self):
"""
We can follow a m2m and another m2m.
"""
authors = list(Author.objects.all())
with self.ass | ertNumQueries(2):
prefetch_related_objects(authors, 'books__read_by')
with self.assertNumQueries(0):
self.assertEqual(
[
[[str(r) for r in b.read_by.all()] for b in a.books.all()]
for a in authors
],
... |
Qwaz/solved-hacking-problem | GoogleCTF/2018 Quals/dm_collision/not_des.py | Python | gpl-2.0 | 6,722 | 0.012348 | #!/usr/bin/env python3
import functools
import struct
KEY_SIZE = 8
BLOCK_SIZE = 8
# yapf: disable
# Note the 1-based indexing in all the following tables.
IP = [
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17... | plaintext = [plaintext[IP[i] - 1] for i in range(64)]
L, R = plaintext[:32], plaintext[32:]
# Feistel network.
for ki in KeyScheduler(key):
L, R = R, Xor(L, CipherFunction(ki, R))
# Final permutation.
ciphertext = Concat(R, L)
ciphertext = [ciphertext[IP_INV[i] - 1] for i in range(64)]
return Bits | 2Str(ciphertext)
def DESDecrypt(ciphertext, key):
if isinstance(key, bytes):
key = Str2Bits(key)
assert (len(key) == 64)
if isinstance(ciphertext, bytes):
ciphertext = Str2Bits(ciphertext)
# Initial permutation.
ciphertext = [ciphertext[IP[i] - 1] for i in range(64)]
L, R = ciphertext[:32], cip... |
joachimmetz/plaso | tests/parsers/chrome_cache.py | Python | apache-2.0 | 1,283 | 0.002338 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Chrome Ca | che files parser."""
import unittest
from plaso.parsers import chrome_cache
from tests.parsers import test_lib
class ChromeCacheParserTest(test_lib.ParserTestCase):
"""Tests for the Chrome Cache files parser.""" |
def testParse(self):
"""Tests the Parse function."""
parser = chrome_cache.ChromeCacheParser()
storage_writer = self._ParseFile(['chrome_cache', 'index'], parser)
number_of_events = storage_writer.GetNumberOfAttributeContainers('event')
self.assertEqual(number_of_events, 217)
number_of_war... |
itakouna/lymph | lymph/serializers/base.py | Python | apache-2.0 | 3,844 | 0.00026 | import abc
import datetime
import decimal
import functools
import json
import uuid
import pytz
import msgpack
import six
from lymph.utils import Undefined
@six.add_metaclass(abc.ABCMeta)
class ExtensionTypeSerializer(object):
@abc.abstractmethod
def serialize(self, obj):
raise NotImplementedError
... | tzinfo, obj = obj
except ValueError:
tzinfo = None
result = datetime.datetime.strptime(obj, self.format)
if not tzinfo:
return result
return pytz.timezone(tzinfo).localize(result)
class DateSerializer(ExtensionTypeSerializer):
format = '%Y-%m-%d'
de... | e.strptime(obj, self.format).date()
class TimeSerializer(ExtensionTypeSerializer):
format = '%H:%M:%SZ'
def serialize(self, obj):
return obj.strftime(self.format)
def deserialize(self, obj):
return datetime.datetime.strptime(obj, self.format).time()
class StrSerializer(ExtensionTypeSer... |
anbasile/donderskritikos | app/__init__.py | Python | apache-2.0 | 183 | 0.016393 | from flask import Flask
# from flask.ext.sqlalchemy import SQLAlchemy
app | = Flask(__name__)
app.config.from_o | bject('config')
# db = SQLAlchemy(app)
from app import views #, models
|
ChucklesZeClown/learn-python | Exercises-learn-python-the-hard-way/ex2-comments-and-pound-characters.py | Python | apache-2.0 | 301 | 0 | # A comment, this is so you | can read your program later.
# Anything af | ter the # is ignored by python.
print "I could have code like this." # and the comment after is ignored
# You can also use a comment to "disable" or comment out a piece of code:
# print "This won't run."
print "This will run."
|
dhzhd1/road_obj_detect | rfcn/core/loader.py | Python | apache-2.0 | 19,594 | 0.001735 | # --------------------------------------------------------
# Deformable Convolutional Networks
# Copyright (c) 2016 by Contributors
# Copyright (c) 2017 Microsoft
# Licensed under The Apache-2.0 License [see LICENSE for details]
# Modified by Yuwen Xiong
# --------------------------------------------------------
impor... | ta=self.provide_data, provide_label=self.provide_label)
else:
raise StopIteration
def getindex(self):
return self.cur / self.batch_size
def getpad(self):
if self.cur + self.batch_size > self.size:
return self.cur + self.batch_size - | self.size
else:
return 0
def get_batch(self):
cur_from = self.cur
cur_to = min(cur_from + self.batch_size, self.size)
roidb = [self.roidb[self.index[i]] for i in range(cur_from, cur_to)]
if self.has_rpn:
data, label, im_info = get_rpn_testbatch(roidb,... |
rec/BiblioPixel | test/bibliopixel/colors/closest_colors_test.py | Python | mit | 1,015 | 0.000985 | import collections, unittest
from bibliopixel.colors import closest_colors
closest = closest_colors.closest_colors
class ClosestColorsTest(unittest.TestCase):
def exhaustive(self, metric, start=32, skip=64, report=4):
for color in closest_colors.all_colors(start, skip=skip):
cl = closest(col... | 0)), ['red', 'red 1'])
def test_far(self):
c = closest((0, 0, 64), metric=closest_colors.taxicab)
self.assertEqual(c, ['black', 'navy', 'none', 'off'])
c = closest((64, 0, 0), metric=closest_colors.taxicab)
self.assertEqual(c, ['black', | 'maroon', 'none', 'off'])
def test_euclidean(self):
ex = list(self.exhaustive(closest_colors.euclidean))
self.assertEqual(ex, [])
def test_taxicab(self):
ex = list(self.exhaustive(closest_colors.taxicab))
self.assertEqual(ex, [])
|
hajicj/FEL-NLP-IR_2016 | npfl103/io/vectorization.py | Python | apache-2.0 | 3,709 | 0.00027 | # -*- coding: utf-8 -*-
"""This module implements a class that..."""
from __future__ import print_function, unicode_literals
import collections
import pprint
from npfl103.io.document import Document
__version__ = "0.0.1"
__author__ = "Jan Hajic jr."
class DocumentVectorizer:
"""The DocumentVectorizer class tra... | """We suggest using this class in experiments, so that it's obvious
what kind of vectors is coming out of it."""
pass
class TermFrequencyVectorizer(DocumentVectorizer):
"""The vectorizer for obtaining straightforward term frequencies."""
def transform(self, document):
output = collections.Orde... | **self.vtext_to_stream_kwargs):
if term not in output:
output[term] = 0
output[term] += 1
return output
|
bzamecnik/chord-labels | chord_labels/parser/ChordLabelListener.py | Python | mit | 3,465 | 0.012987 | # Generated from ChordLabel.g4 by ANTLR 4.7
from antlr4 import *
if __name__ is not None and "." in __name__:
from .ChordLabelParser import ChordLabelParser
else:
from ChordLabelParser import ChordLabelParser
# This class defines a complete listener for a parse tree produced by ChordLabelParser.
class ChordLab... | erDegree(self, ctx:ChordLabelParser.DegreeContext):
pass
# Exit a parse tree produced by ChordLabelParser#degree.
def exitDegree(self, ctx:ChordLabelParser.DegreeContext):
pass
# Enter a parse tree produced by ChordLabelParser#interval.
def enterInterval(self, ctx:ChordLabelParser.Int... | s
# Exit a parse tree produced by ChordLabelParser#interval.
def exitInterval(self, ctx:ChordLabelParser.IntervalContext):
pass
# Enter a parse tree produced by ChordLabelParser#bass.
def enterBass(self, ctx:ChordLabelParser.BassContext):
pass
# Exit a parse tree produced by Chor... |
popazerty/beyonwiz-4.1 | tools/host_tools/FormatConverter/input.py | Python | gpl-2.0 | 432 | 0.060185 | import sys
def inputText():
input = sys.stdin.readline()
return input.strip()
def inputChoices(list, backcmd = "b", backtext = "back"):
repeat = True
while repeat:
repeat = False
count = 0
for item in list:
print count, "-", item
count += 1
print backcmd, "- | ", backtext
input = inputText()
if input == backcmd:
return None
action = int(input)
if action >= len(list):
repeat = True
ret | urn action |
popuguy/mit-cs-6-034 | lab1/tests.py | Python | unlicense | 15,045 | 0.023862 | from production import IF, AND, OR, NOT, THEN, run_conditions
import production as lab
from tester import make_test, get_tests, type_encode, type_decode
from zookeeper import ZOOKEEPER_RULES
import random
random.seed()
try:
set()
except NameError:
from sets import Set as set, ImmutableSet as frozenset
### TES... | expected_val = "no",
name = test_s | hort_answer_2_getargs
)
### TEST 3 ###
test_short_answer_3_getargs = "ANSWER_3"
def test_short_answer_3_testanswer(val, original_val = None):
return str(val) == '2'
# The answer is 2 because, as it says in the lab description, "A
# NOT clause should not introduce new variables - the matcher
# won't k... |
XcomConvent/xcom40k-shades | xcom40k/app/migrations/0026_auto_20120106_2212.py | Python | apache-2.0 | 1,819 | 0.001649 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('app', '0025_auto_20150923_0843'),
]
operations = [
migrations.CreateMo... | name='BlogEntry',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=100)),
('text', models.CharField(max_length=10000)),
('pub_date', models.DateF... | ('author', models.ForeignKey(to='app.Account')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='BlogEntryTag',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, aut... |
suut/psychic-happiness | async_core.py | Python | unlicense | 2,381 | 0.00126 | #!/usr/local/bin/python3.4
# -*- coding: utf-8 -*-
import threading
import time
import sys
import trace
from inspect import isgeneratorfunction
import format
class KillableThread(threading.Thread):
"""A subclass of threading.Thread, with a kill() method provided by courtsey of Connelly Barnes."""
def __init_... | self.__run_backup = self.run
self.run = self.__run # Force the Thread to install our trace.
threading.Thread.start(self)
def __run(self):
"""Hacked run function, which installs the trace."""
sys.settrace(self.globaltrace)
self.__run_backup()
self.run = s... | ocaltrace
else:
return None
def localtrace(self, frame, why, arg):
if self.killed:
if why == 'line':
raise SystemExit()
return self.localtrace
def kill(self):
self.killed = True
class FunctionExecutor(KillableThread):
def __init__(s... |
leviroth/praw | praw/models/reddit/wikipage.py | Python | bsd-2-clause | 8,763 | 0 | """Provide the WikiPage class."""
from ...const import API_PATH
from ...util.cache import cachedproperty
from ..listing.generator import ListingGenerator
from .base import RedditBase
from .redditor import Redditor
class WikiPage(RedditBase):
"""An individual WikiPage object.
**Typical Attributes**
This ... | n ListingGenerator(
subreddit._reddit, url, **generator_kwargs
):
if revision["author"] is not None:
revision["author"] = Redditor(
subreddit._reddit, _data=revision["author"]["data"]
)
revision["page"] = WikiPage(
... | id"]
)
yield revision
@cachedproperty
def mod(self):
"""Provide an instance of :class:`.WikiPageModeration`."""
return WikiPageModeration(self)
def __eq__(self, other):
"""Return whether the other instance equals the current."""
return (
... |
jmeppley/py-metagenomics | assign_paths.py | Python | mit | 10,699 | 0 | #! /usr/bin/env python
"""
Takes a single hit table file and generates a table (or tables) of
pathway/gene family assignments for the query sequences (aka 'reads').
Assignments can be for gene families, gene classes, or pathways. Multiple
pathway or classification levels can be given. If they are, an assignment
will be... | ts.levels)
except Exception as e:
par | ser.error(str(e))
# map reads to hits
if arguments.mapFile is not None:
if arguments.mapStyle == 'auto':
with open(arguments.mapFile) as f:
firstLine = next(f)
while len(firstLine) == 0 or firstLine[0] == '#':
firstLine = next(f)
... |
mudzi42/pynet_class | class2/my_snmp.py | Python | apache-2.0 | 747 | 0.004016 | #!/usr/bin/env python
"""
4c. Create a script that connects to both routers (pynet-rtr1 and pynet-rtr2)
and prints out both the MIB2 sysName and sysDescr.
"""
from snmp_helper import snmp_get_oid, snmp_extract
COMMUNITY_STRING = 'galileo'
SYS_DESCR = '1.3.6.1.2.1.1.1.0'
SYS_NAME = '1.3.6.1.2.1.1.5.0'
|
def main():
pynet_rtr1 = ('184.105.247.70', COMMUNITY_STRING, 161)
pynet_rtr2 = ('184.105.247.71 | ', COMMUNITY_STRING, 161)
for a_device in (pynet_rtr1, pynet_rtr2):
print "\n"
for the_oid in (SYS_NAME, SYS_DESCR):
snmp_data = snmp_get_oid(a_device, oid=the_oid)
output = snmp_extract(snmp_data)
print output
print "\n"
if __name__ == "__main__":
... |
zuck/prometeo-erp | core/menus/signals.py | Python | lgpl-3.0 | 1,904 | 0.004202 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This file is part of the prometeo project.
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... | instance, *args, **kwargs):
"""Creates a new bookmarks list for the given object.
"""
if hasattr(instance, "bookmarks") and not instance.bookmarks:
bookmarks, is_new = Menu.objects.get_or_create(slug="%s_%d_bookmarks" % (sender.__name__.l | ower(), instance.pk), description=_("Bookmarks"))
if not is_new:
for l in bookmarks.links.all():
l.delete()
instance.bookmarks = bookmarks
instance.save()
def delete_bookmarks(sender, instance, *args, **kwargs):
"""Deletes the bookmarks list of the given object.
... |
ee64/data-and-algorithms | upload.py | Python | mit | 3,932 | 0.003913 | import requests
import os
print('\n***数据与算法 GitHub自动上传脚本***\n')
username = input('输入你在GitHub上的用户名,如 Robert Ying:')
email = input('输入你注册GitHub用的Email:')
print('\n开始配置Git...')
os.system('git config --global user.name "' + username + '"')
os.system('git config --global user.email ' + email)
print('\n你输入的信息如下:')
os.syst... | 码:')}
print()
response = requests.post(
'http://lambda.ee.tsinghua.edu.cn/api/auth/login/', data=payload)
answer = requests.get('http://lambda.ee.tsinghua.edu.cn/api/my/submits/', headers={
'Authorization': 'TOKEN ' + response.json()['auth_token']}, params={'page': 1, 'page_size': 1})
co | unt = answer.json()['count']
answer = requests.get('http://lambda.ee.tsinghua.edu.cn/api/my/submits/', headers={
'Authorization': 'TOKEN ' + response.json()['auth_token']}, params={'page': 1, 'page_size': count})
results = answer.json()['results']
if not os.path.exists('data-and-algorithms'):
... |
carlisson/legend | legend.py | Python | gpl-3.0 | 2,150 | 0.001395 | #!/usr/bin/env python2
import wx
import time
TRAY_TOOLTIP = 'Personal Legend'
TRAY_ICONS = {
'main': 'icon-main.png',
'c1': 'icon-1card.png',
'c2': 'icon-2cards.png',
'c3': 'icon-3cards.png',
'timer': 'icon-zero.png'
}
TRAY_TIMER = 30 * 60
def create_menu_item(menu, label, func):
item = wx.Me... | menu, 'Timer', self.stop_watch)
menu.Appen | dSeparator()
create_menu_item(menu, 'Exit', self.on_exit)
return menu
def set_icon(self, path):
icon = wx.IconFromBitmap(wx.Bitmap(path))
self.SetIcon(icon, TRAY_TOOLTIP)
def set_status(self, st):
self.set_icon(TRAY_ICONS[st])
self.status = st
def on_left_d... |
nkgilley/home-assistant | tests/components/auth/test_login_flow.py | Python | apache-2.0 | 3,442 | 0.000291 | """Tests for the login flow."""
from . import async_setup_auth
from tests.async_mock import patch
from tests.common import CLIENT_ID, CLIENT_REDIRECT_URI
async def test_fetch_auth_providers(hass, aiohttp_client):
"""Test fetching auth providers."""
client = await async_setup_auth(hass, aiohttp_client)
re... | [])
resp = await client.get("/auth/login_flow")
assert resp.status == 405
async def test_invalid_username_password(hass, aiohttp_client):
"""Test we cannot get flows in progress."""
client = await async_setup_auth(hass, aiohttp_client) |
resp = await client.post(
"/auth/login_flow",
json={
"client_id": CLIENT_ID,
"handler": ["insecure_example", None],
"redirect_uri": CLIENT_REDIRECT_URI,
},
)
assert resp.status == 200
step = await resp.json()
# Incorrect username
resp... |
erickpeirson/jhb-explorer | explorer/management/commands/loadauthorresources.py | Python | gpl-2.0 | 1,837 | 0.002722 | from django.core.management.base import BaseCommand
from explorer.models import Author, AuthorExternalResource, ExternalResource
import os
import csv
class Command(BaseCommand):
help = """Load data about external authority records for authors."""
def add_arguments(self, parser):
parser.add_argument... | fidence = 1.0
AuthorExternalResource(
author_id=pk,
resource=resource,
| confidence=confidence
).save()
self.stdout.write(self.style.SUCCESS(' | '.join[pk, name, identifier, source, confidence]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.