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 |
|---|---|---|---|---|---|---|---|---|
piyanatk/sim | opstats/utils/settings.py | Python | mit | 1,196 | 0.000838 | import numpy as np
from astropy.coordinates i | mport EarthLocation, SkyCoord
__all__ = ['MWA_LOC', 'MWA_FIELD_EOR0', 'MWA_FIELD_EOR1', 'MWA_FIELD_EOR2',
'MWA_FREQ_EOR_ALL_40KHZ', 'MWA_FREQ_EOR_ALL_80KHZ',
'MWA_FREQ_EOR_HI_40KHZ', 'MWA_FREQ_EOR_HI_80KHZ',
'MWA_FREQ_EOR_LOW_40KHZ', 'MWA_FREQ_EOR | _LOW_80KHZ',
'HERA_ANT_DICT', 'F21']
F21 = 1420.405751786e6
MWA_LOC = EarthLocation(lat='−26d42m11.94986s', lon='116d40m14.93485s',
height=377.827)
MWA_FIELD_EOR0 = SkyCoord(ra='0.0h', dec='-30.0d')
MWA_FIELD_EOR1 = SkyCoord(ra='4.0h', dec='-30.0d')
MWA_FIELD_EOR2 = SkyCoord(ra='1... |
alex/warehouse | tests/unit/i18n/test_init.py | Python | apache-2.0 | 1,717 | 0 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | etend.stub(
parse=pretend.call_recorder(lambda l: locale_obj),
)
monkeypatch.setattr(i18n, | "Locale", locale_cls)
request = pretend.stub(locale_name=pretend.stub())
assert i18n._locale(request) is locale_obj
assert locale_cls.parse.calls == [pretend.call(request.locale_name)]
def test_includeme():
config_settings = {}
config = pretend.stub(
add_request_method=pretend.call_recor... |
splice/splice-server | src/splice/common/rhic_serve_client.py | Python | gpl-2.0 | 3,508 | 0.005703 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or impli... | the implied warranties of MERCHANTABILITY,
# NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should
# have received a copy of GPLv2 along with this software; if not, see
# | http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
# Responsible for making a remote call to rhic_serve to fetch data for RHIC to Product mapping
#
import gzip
import httplib
import json
import logging
import time
import urllib
import StringIO
from django.conf import settings
from splice.common import config
fr... |
xkmato/tracpro | tracpro/charts/filters.py | Python | bsd-3-clause | 5,748 | 0.000696 | from __future__ import unicode_literals
import copy
from dateutil.relativedelta import relativedelta
import six
from dash.utils import get_month_range
from django import forms
from django.forms.forms import DeclarativeFieldsMetaclass
from django.utils import timezone
from django.utils.translation import ugettext_l... | ht(timezone.now())
start_date = end_date - relativedelta(**{unit: int(number)})
self.cleaned_data['start_date'] = start_date
self.cleaned_data['end_date'] = end_date
self.data['start_date'] = start_date
self.data['end_date'] = end_date... | e by one day so that results for all times during
# the end_date are accounted for in the query.
end_date = self.cleaned_data.get('end_date')
if end_date is not None:
self.cleaned_data['end_date'] = end_date + relativedelta(days=1)
return self.cleaned_data
class DataFieldF... |
ericmjl/bokeh | bokeh/io/output.py | Python | bsd-3-clause | 4,608 | 0.006293 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | -------------------------------------------------------------
__all__ = (
'output_file',
'output_notebook',
'reset_output',
)
#-----------------------------------------------------------------------------
# General API
#----------------------------------------------------------------- | ------------
def output_file(filename, title="Bokeh Plot", mode=None, root_dir=None):
'''Configure the default output state to generate output saved
to a file when :func:`show` is called.
Does not change the current ``Document`` from ``curdoc()``. File and notebook
output may be active at the same tim... |
partofthething/home-assistant | tests/components/pilight/test_init.py | Python | apache-2.0 | 14,678 | 0.000409 | """The tests for the pilight component."""
from datetime import timedelta
import logging
import socket
from unittest.mock import patch
from voluptuous import MultipleInvalid
from homeassistant.components import pilight
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
... | ]
assert str(service_data) in str(error_log_call)
@patch("pilight.pilight.Client", PilightDaemonSim)
@patch("homeassistant.components.pilight._LOGGER.error")
async def test_send_code_fail(mock_pilight_error, hass):
"""Check IOError exception error message."""
with assert_setup_component( | 4):
with patch("pilight.pilight.Client.send_code", side_effect=IOError):
assert await async_setup_component(
hass, pilight.DOMAIN, {pilight.DOMAIN: {}}
)
# Call with protocol info, should not give error
service_data = {"protocol": "test", "value":... |
matpow2/opensnd | frame2.py | Python | gpl-3.0 | 18,104 | 0.005689 | # Copyright (c) Mathias Kaerlev 2012.
# This file is part of OpenSND.
# OpenSND is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Op... | 3, self.get(Ini_7).get_value_item('MusicVolume'))
self.set_mod_volume(4, self.get(Ini_7).get_value_item('MusicVolume'))
self.cross_fade_mod(0, 0, 3000)
self.set_event_id(7)
if self.get(Name_5).get_value() == '':
self.get(Name_ | 5).set_value('Player')
pass
def loop_name(self):
self.set_event_id(21)
if (self.groups['Check name'] and
mid_string(self.get(Name_5).get_value(), self.get_loop_index('Name'), 1) != '[' and
mid_string(self.get(Name_5).get_value(), self.get_loop_index('Name'), 1) != ']' an... |
fsxfreak/esys-pbi | src/pupil/pupil_src/player/player_methods.py | Python | mit | 13,738 | 0.012957 | '''
(*)~---------------------------------------------------------------------------
Pupil - eye tracking platform
Copyright (C) 2012-2017 Pupil Labs
Distributed under the terms of the GNU
Lesser General Public License (LGPL v3.0).
See COPYING and COPYING.LESSER for license details.
-----------------------------------... | ec_ | object)
if converted_object != rec_object:
logger.info('Converted `{}` from bytes to unicode'.format(file))
save_object(rec_object, rec_file)
except (ValueError, IsADirectoryError):
continue
with open(meta_info_path, 'r' |
slideinc/notifier | pavement.py | Python | bsd-3-clause | 1,537 | 0.003253 | import errno
import os
from setuptools import Extension
from paver.easy import *
from paver.path import path
from paver.setuputils import setup
setup(
name="notifier",
description="A pre-connected mesh of servers for fast internal RPC",
version="1.0",
license="bsd",
author="Libor Michalek",
a... | ifier.egg-info', 'dist', 'build', 'MANIFEST.in')):
if p.exists() | :
if p.isdir():
p.rmtree()
else:
p.remove()
for p in path(__file__).abspath().parent.walkfiles():
if p.endswith(".pyc") or p.endswith(".pyo"):
try:
p.remove()
except OSError, exc:
if exc.args[0] =... |
open-synergy/opnsynid-hr | hr_timesheet_workflow_policy/__openerp__.py | Python | agpl-3.0 | 733 | 0 | # -*- coding: utf-8 -*-
# Copyright 2018 OpenSynergy Indonesia
# Copyright 2022 PT. Simetri Sinergi Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
# pylint: disable=locally-disabled, manifest-required-author
{
"name": "HR Timesheet - Workflow Policy",
"version": "8.0.1.0.0",
"cate... | ,
"hr_ | timesheet_sheet",
],
"data": [
"views/hr_attendance_config_setting_views.xml",
"views/hr_timesheet_sheet_views.xml",
],
}
|
sns-chops/multiphonon | multiphonon/backward/_sqe2dos_script_templates.py | Python | mit | 1,493 | 0 | # -*- Python -*-
#
# Jiao Lin <[email protected]>
#
plots_table = """
exp exp-sqe.h5
sim-singlephonon sp-sqe.h5
sim-multiphonon mp-sqe.h5
sim-multiple-scattering ms-sqe.h5
sim-correction sqe_correction.h5
exp-corrected-single-phonon corrected_sqe.h5
sim-total-inel total-inel-sqe.h5
exp-residual residual-sqe.h5
"""
p... | tplotlib as mpl
mpl.rcParams['figure.figsize'] = 12,9
from multiphonon.backward.plotutils import plot_intermediate_result_se as plot
plot(curdir)
from matplotlib import pyplot as plt
plt.show()
"""
plot_dos_iteration_code = """#!/usr/bin/env python |
import os
curdir = os.path.dirname(__file__)
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = 6,4.5
from multiphonon.backward.plotutils import plot_dos_iteration
plot_dos_iteration(curdir, %(total_rounds)d)
from matplotlib import pyplot as plt
plt.show()
"""
plot_residual_code = """#!/usr/bin/env python
i... |
quake0day/oj | kthPrimeNumber.py | Python | mit | 527 | 0.043643 | class Solution:
"""
@param k: The number k.
@r | eturn: The kth prime number as description.
"""
def kthPrimeNumber(self, k):
# write your code here
q = [1]
i3 = i5 = i7 = 0
while len(q)-1 < k:
m3, m5, m7 = q[i3] * 3, q[i5] * 5, q[i7] * 7
m = min(m3, m5, m7)
if m == m3:
i3 += 1
if m... | if m == m7:
i7 += 1
q.append(m)
return q[-1]
a = Solution()
print a.kthPrimeNumber(5) |
alexgorban/models | research/slim/nets/nasnet/nasnet_utils.py | Python | apache-2.0 | 20,826 | 0.007395 | # Copyright 2017 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... | l_size, layer_num + 1))
stride = 1
net = activation_fn(net)
net = slim.separable_conv2d(
net,
filter_size,
kernel_size,
depth_multiplier=1,
scope='separable_{0}x{0}_{1}'.format(kernel_size, num_layers),
stride | =stride)
net = slim.batch_norm(
net, scope='bn_sep_{0}x{0}_{1}'.format(kernel_size, num_layers))
return net
def _operation_to_pooling_type(operation):
"""Takes in the operation string and returns the pooling type."""
splitted_operation = operation.split('_')
return splitted_operation[0]
def _operati... |
roubert/python-phonenumbers | python/phonenumbers/shortdata/region_IE.py | Python | apache-2.0 | 1,071 | 0.008403 | """Auto-generated file, do not edit by hand. IE metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_IE = PhoneMetadata(id='IE', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='[159]\\d{2,5}', possible_number_pattern... | ),
emergency=PhoneNumberDesc(national_number_pattern='112|999', possible_number_pattern='\\d{3}', example_number='112'),
short_code=PhoneNumberDesc(national_number_pattern='11(?:2|6(?:00[06]|1(?:11|23)))|51210|999', possible_number_pattern='\\d{3,6}', example_number='112'),
standard_rate=PhoneNumberDesc(nat... | umber_pattern='51210', possible_number_pattern='\\d{5}'),
short_data=True)
|
aplicatii-romanesti/allinclusive-kodi-pi | .kodi/userdata/addon_data/plugin.video.p2p-streams/acestream/ace/ACEStream/Core/Statistics/VideoPlaybackCrawler.py | Python | apache-2.0 | 7,854 | 0.005857 | #Embedded file name: ACEStream\Core\Statistics\VideoPlaybackCrawler.pyo
from time import strftime
import cPickle
import sys
import threading
import zlib
from ACEStream.Core.BitTornado.BT1.MessageID import CRAWLER_VIDEOPLAYBACK_INFO_QUERY, CRAWLER_VIDEOPLAYBACK_EVENT_QUERY
from ACEStream.Core.CacheDB.SqliteVideoPlayback... | le_crawler_reply', error, message
self._file.write('; '.join((strftime('%Y/%m/%d %H:%M:%S'),
' EVENT | REPLY',
show_permid(permid),
str(error),
str(channel_data),
message,
'\n')))
self._file.flush()
elif selversion >= OLPROTO_VER_TENTH:
if DEBUG:
print >> sys.stderr, 'videoplaybackcrawler: handle_crawler_rep... |
zoeren/pygeocoder | pygeolib.py | Python | bsd-3-clause | 4,972 | 0.000603 | import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease fiel... | """
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""R | eturn a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
|
thedod/boilerplate-peewee-flask | application/sitepack/db.py | Python | gpl-3.0 | 204 | 0 | from peewee import * # no other wa | y to reach playhouse :(
from playhouse import flask_utils as peewee_flask_utils
from playhouse import signals as pee | wee_signals
database = peewee_flask_utils.FlaskDB()
|
jstitch/gift_circle | GiftCircle/circulo/apps.py | Python | gpl-3.0 | 89 | 0 | from | django.apps import AppConfig
class CirculoConfig(AppCon | fig):
name = 'circulo'
|
Valloric/hyde | hyde/ext/plugins/images.py | Python | mit | 5,652 | 0.000885 | # -*- coding: utf-8 -*-
"""
Contains classes to handle images related things
# Requires PIL
"""
from hyde.plugin import Plugin
import re
import Image
class ImageSizerPlugin(Plugin):
"""
Each HTML page is modified to add width and height for images if
they are not already specified.
"""
def __in... | mageSizerPlugin, self).__init__(site)
self.cache = {}
def _handle_img(self, resource, src, width, he | ight):
"""Determine what should be added to an img tag"""
if height is not None and width is not None:
return "" # Nothing
if src is None:
self.logger.warn("[%s] has an img tag without src attribute" % resource)
return "" # Nothing
... |
elenaod/PythonScrollingShooter | player.py | Python | gpl-3.0 | 743 | 0.004038 | from bases import *
from inanimate import Bullet
class Player(AnimateObject):
def __init__(self, x=0, y=0, hits=MAX_HEALTH, timer=TIMER, damage=1, score=0):
super(Player, self).__init__(x, | y, hits, timer)
self.damage = damage
self.score = score
def shoot(self):
if self.x - 1 >= 0:
return Bullet(self.x - 1, self.y, "player", self.damage)
def read(self, data):
super(Player, self).read(data)
values = data.split(" ")
self.s... | r(self.score)
return data
|
mikeboers/midx | midx/notify/__init__.py | Python | bsd-3-clause | 51 | 0 | f | rom midx.notify.common import iter_modified_fi | les
|
Ubiwhere/django-dbbackup | dbbackup/tests/testapp/urls.py | Python | bsd-3-clause | 305 | 0 | try:
from djang | o.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
# url(r'^admin/', include(admin.site.urls)),
)
except ImportError:
from django.conf.urls import include, url
urlpatterns = (
# url(r'^admin/', include(admin.site.urls | )),
)
|
rowanphipps/Cerberus | tests/conftest.py | Python | mit | 320 | 0 | """Configuration for pytest."""
import js | on
def pytest_generate_tests(metafunc):
"""Configure pytest to call each of the tests once for each test case."""
if "test_case" in metafunc.fixturenames:
tests = json.load(open("tests/test_data.json") | )["tests"]
metafunc.parametrize("test_case", tests)
|
brutasse/django-le-social | le_social/openid/tests/views.py | Python | bsd-3-clause | 714 | 0.002801 | try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from .. import views
class Common(object):
"""
Stuff shared by the two views.
"""
def get_return_url(self):
return reverse('openid_callback')
... | f, message):
return HttpResponse(message)
class Begin(Common, views.Begin):
template_name = 'le_social/openid/openid.html'
begin = Begin.as_view()
class Callback(Common, views.Callback):
def success(s | elf):
openid_url = self.openid_response.identity_url
return HttpResponse('OpenID association: %s' % openid_url)
callback = Callback.as_view()
|
JustinWingChungHui/okKindred | emailer/migrations/0005_remove_email_creation_date.py | Python | gpl-2.0 | 358 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db imp | ort models, migrations
class Migration(migrations.Migration):
dependencies = [
('emailer', '0004_auto_20150128_2202'),
]
operations = [
migrations.RemoveField(
model_name='email',
name=' | creation_date',
),
]
|
3cky/netdata | collectors/python.d.plugin/litespeed/litespeed.chart.py | Python | gpl-3.0 | 5,647 | 0.001948 | # -*- codin | g: utf-8 -*-
# Description: litespeed netdata python.d module
# Author: Ilya Mashchenko (ilyam8)
# SPDX-License-Identifier: GPL-3.0-or-later
import glob
import os
import re
from collections import namedtuple
|
from bases.FrameworkServices.SimpleService import SimpleService
update_every = 10
# charts order (can be overridden if you want less charts, or different order)
ORDER = [
'net_throughput_http', # net throughput
'net_throughput_https', # net throughput
'connections_http', # connections
'connections... |
Mariaanisimova/pythonintask | ISTp/2014/VOLKO_S_D/task-1-46.py | Python | apache-2.0 | 123 | 0.013889 | input ('Анук Эме - это псевдоним акт | рисы Франсуазы Юдит Сорья Дрейфу | с')
|
wenhuchen/ETHZ-Bootstrapped-Captioning | visual-concepts/eval.py | Python | bsd-3-clause | 11,962 | 0.006437 | from __future__ import division
from _init_paths import *
import os
import os.path as osp
import sg_utils as utils
import numpy as np
import skimage.io
import skimage.transform
import h5py
import pickle
import json
import math
import argparse
import time
import cv2
from collections import Counter
from json import encod... | ]
for i in range(top_ind.shape[0]):
tmp_concepts = []
for j in range(top_ind.shape[1]):
word_idx = top_ind[i, j]
prob_map = fc8_conv_probs[i, word_idx, :, :]
index = fc8_conv_arg[i, word_idx]
word = self.vocab['words'][word... | t in indexes:
i1, i2 = divmod(index, 12)
att_feat[i, len(indexes)] = feat_map[i,:,i1,i2]
indexes.append(index)
feat_probs[i, len(tmp_concepts)] = prob_map
tmp_concepts.append(word)
if len(tmp_... |
chubbymaggie/reverse | plasma/lib/arch/arm/utils.py | Python | gpl-3.0 | 4,197 | 0.004289 | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | TY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Se | e the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from capstone import CS_GRP_CALL, CS_GRP_RET
from capstone.arm import (ARM_CC_EQ, ARM_CC_NE, ARM_CC_HS, ARM_CC_LO,
... |
zamattiac/SHARE | providers/org/ncar/normalizer.py | Python | apache-2.0 | 3,649 | 0.00137 | from share.normalize import ctx, tools
from share.normalize.parsers import Parser
from share.normalize.utils import format_address
class WorkIdentifier(Parser):
uri = tools.RunPython('get_ncar_identifier', ctx)
class Extra:
description = tools.Try(ctx.Related_URL.Description)
url_content_type... | rser):
name = ctx
class ThroughTags(Parser):
tag = tools.Delegate(Tag, ctx)
class PersonnelAgent(Parser):
schema = tools.GuessAgentType(
| tools.RunPython('combine_first_last_name', ctx)
)
name = tools.RunPython('combine_first_last_name', ctx)
location = tools.RunPython('get_address', ctx['Contact_Address'])
class Extra:
role = tools.Try(ctx.Role)
url = tools.Try(ctx.Data_Center_URL)
def combine_first_last_name... |
librasungirl/openthread | tests/toranj/test-033-mesh-local-prefix-change.py | Python | bsd-3-clause | 3,956 | 0.000758 | #!/usr/bin/env python3
#
# Copyright (c) 2019, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... | -----------------------------------------------------------------------------------------------
# Test implementation
NET_NAME = | 'ml-change'
CHANNEL = 11
PANID = '0x1977'
XPANID = '1020031510006016'
KEY = '0123456789abcdeffecdba9876543210'
ML_PREFIX_1 = 'fd00:1::'
ML_PREFIX_2 = 'fd00:2::'
# Form a network on node1
node1.form(
NET_NAME,
channel=CHANNEL,
panid=PANID,
xpanid=XPANID,
key=KEY,
mesh_local_prefix=ML_PREFIX_1,... |
kfrye/SMM-MPI | utilities/results/ptdf_export.py | Python | gpl-3.0 | 2,213 | 0.004067 | #!/usr/bin/python
import json
class Tests(object):
def __init__(self, tests, name):
self.tests = tests
self.name = name
self.export_tests()
def export_tests(self):
with open(self.name + ".ptdf", "w+") as ptdf_file:
ptdf_file.write("Application " + self.name + '\n')... | e.write('Resource "time in seconds" metric\n')
for test_dictionary in self.tests:
execution = self.name.lower() + '-' + str(test_dictionary['START_TIME'])
ptdf_file.write("Execution " + execution + ' ' + self.name + '\n')
| for key in test_dictionary:
if key != 'TIME_IN_SECONDS':
ptdf_file.write("ResourceAttribute " + execution + ' ' +
key.lower() + ' "' + str(test_dictionary[key]) + '" string\n')
ptdf_file.write('PerfResult ' + execution ... |
chisholm/cti-pattern-validator | stix2patterns/grammars/STIXPatternListener.py | Python | bsd-3-clause | 91 | 0.010989 | # Update or remove for 2.0.0
from ..v20.grammars.STIXPatternL | istener import * # noqa | : F401 |
kjedruczyk/phabricator-tools | py/aon/aoncmd_taskupdate.py | Python | apache-2.0 | 5,958 | 0 | """Update a task in maniphest.
you can use the 'task id' output from the 'arcyon task-create' command as input
to this command.
usage examples:
update task '99' with a new title, only show id:
$ arcyon task-update 99 -t 'title' --format-id
99
"""
# ========================================================... | opt.add_argu | ment(
'--ccs',
'-c',
nargs="*",
metavar='USER',
help='a list of usernames to cc on the task',
type=str)
opt.add_argument(
'--projects',
nargs="*",
metavar='PROJECT',
default=[],
help='a list of project names to add the task to',... |
jcalazan/glucose-tracker | glucosetracker/subscribers/migrations/0001_initial.py | Python | mit | 1,627 | 0.00799 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Subscriber'
db.create_table(u'subscribers_subscriber', (
(u'id', self.gf('django... | 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'source_ip': ('django.db.models.fiel... | omplete_apps = ['subscribers'] |
cvegaj/ElectriCERT | venv3/lib/python3.6/site-packages/pbr/tests/test_commands.py | Python | gpl-3.0 | 3,688 | 0.000271 | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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... | and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# 3. The name of AURA and its representativ... | S'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL AURA BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMIT... |
Roastero/Openroast | openroast/views/recipeeditorwindow.py | Python | gpl-3.0 | 19,366 | 0.001962 | # -*- coding: utf-8 -*-
# Roastero, released under GPLv3
import os
import json
import time
import functools
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from openroast import tools
from openroast.views import customqtwidgets
from openroast import utils as utils
class RecipeEditor(QtW... | recipeRoastTypeLabel = QtWidgets.QLabel("Roast Type: ")
beanRegionLabel = QtWidgets.QLabel("Bean Region: ")
beanCountryLabel = QtWidgets.QLabel("Bean Country: ")
beanLinkLabel = QtWidgets.QLabel("Bean Link: ")
| beanStoreLabel = QtWidgets.QLabel("Bean Store Name: ")
# Create input fields.
self.recipeName = QtWidgets.QLineEdit()
self.recipeCreator = QtWidgets.QLineEdit()
self.recipeRoastType = QtWidgets.QLineEdit()
self.beanRegion = QtWidgets.QLineEdit()
self.beanCountry = ... |
Baguage/pyqualtrics | examples/import_panel_example.py | Python | apache-2.0 | 1,983 | 0.002017 | # This file is part of the pyqualtrics package.
# For copyright and licensing information about this package, see the
# NOTICE.txt and LICENSE.txt files in its top-level directory; they are
# available at https://github.com/Baguage/pyqualtrics
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma... | rg/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitatio... | # os.environ["QUALTRICS_USER"]
token = None # os.environ["QUALTRICS_TOKEN"]
if __name__ == "__main__":
print "This is an example of panel import"
print "Make sure you have set QUALTRICS_USER, QUALTRICS_TOKEN and QUALTRICS_LIBRARY_ID enviroment variable"
# Note is user and token are None, QUALTRICS_USER... |
aleaxit/pysolper | latrop/models.py | Python | apache-2.0 | 10,073 | 0.014196 | # -*- coding: utf-8 -*-
"""
models
~~~~~~~~~~~~~~~~~~~~
Top-level models for the entire app.
:copyright: 2011 by Google, Inc.
:license: Apache 2.0, see LICENSE for more details.
"""
# standard Python library imports
import datetime
import logging
import urllib
# App Engine imports
from google.ap... | operty
def last_modified(self):
"""Returns the timestamp at which this case was last modified."""
return datetime.datetime.now() - self.latest_action.timestamp
@property
def applicant_can_edit(self):
"""True iff an applicant can currently modify this case."""
re | turn self.state in APPLICANT_EDITABLE
@property
def reviewer(self):
"""Returns the case's current reviewer, or None."""
if self.state != CASE_STATES['under_review']:
return None
return CaseAction.query_by_case(self, 'Review').get().actor
@property
def submit_blockers(se... |
zaquestion/vendttp | server/CloseableThread.py | Python | gpl-2.0 | 447 | 0.035794 | import threading
class CloseableThread(threading.Thread):
running = false
def __init__(self, group = None, target = None, name = None, args=(), kwarg | s={}):
threading.Thread.__init_ | _(self, group = group, target = target, name = name, args=args, kwargs=kwargs)
def start():
Running = true
threading.Thead.start()
def stop(onStop=None):
Running = false
if (onStop):
onStop()
|
matrix-org/synapse | synapse/config/redis.py | Python | apache-2.0 | 1,857 | 0.000539 | # Copyright 2020 The Matrix.org Foundation C.I.C.
#
# 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 a... | ed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permi | ssions and
# limitations under the License.
from synapse.config._base import Config
from synapse.util.check_dependencies import check_requirements
class RedisConfig(Config):
section = "redis"
def read_config(self, config, **kwargs):
redis_config = config.get("redis") or {}
self.redis_enabled... |
sroche0/mfl-pyapi | modules/stats.py | Python | gpl-3.0 | 929 | 0.003229 | import bench
class Stats(bench.Bench):
def __init__(self, league):
bench.Bench.__init__(self)
self.league = league
self.type = 'stats'
def list(self, team=False, player=False):
"""
Lists all stats for the current season to date. Can be filtered by team or by player. De... | player: Unique ID of the player to filter for
:return:
"""
def get_player_stats(self, player, week=False):
"""
Lists the stat breakdown by week for a given player. Can also be filtered to only return a specific week or | a
range of weeks
:param player: Unique ID of the player to filter for
:param week: Optional. Can be a single week or a range ex: 1-4. If blank will default to season to date
:return:
"""
|
ludbek/amenu | setup.py | Python | mit | 546 | 0.001832 | fr | om distutils.core import setup
setup(
name='amenu',
version='1.0.3',
author='ludbek',
author_email='[email protected]',
packages= ['amenu', 'amenu.migrations', 'amenu.templatetags'],
scripts=[],
url='https://github.com/ludbek/amenu',
license='LICENSE.txt',
description='A menu plugin... | -classy-tags == 0.5.2",
],
include_package_data=True,
)
|
achillesrasquinha/spockpy | spockpy/app/config/server.py | Python | apache-2.0 | 381 | 0.013123 | # imports - compatibility imports
from __future__ | import absolute_import
# imports - standard imports
import os
# imports - module imports
from spockpy.app.config import BaseConfig
class ServerConfig(BaseConfig):
class Path(BaseConfig.Path):
ABSPATH_TEMPLATES = os.path.join(BaseConfig.Path.ABSPATH_VIEWS, 'templates')
HOST = '0.0.0.0'
PORT = int( | os.getenv('PORT', 3000))
|
DOV-Vlaanderen/pydov | tests/conftest.py | Python | mit | 15,105 | 0 | """Module grouping session scoped PyTest fixtures."""
import datetime
import glob
import os
import tempfile
import owslib
import pytest
from _pytest.monkeypatch import MonkeyPatch
from owslib.etree import etree
from owslib.feature.schema import _construct_schema, _get_elements
from owslib.iso import MD_Metadata
from ... | f:
data = f.read()
if not isinstance(data, bytes):
data = data.encode('utf-8')
return MD_Metadata(etree.fromstring(data).find(
'./{http://www.isotc211.org/2005/gmd}MD_Metadata'))
monkeymodule.setattr(pydov.util.owsutil, 'get_remo | te_metadata',
__get_remote_md)
@pytest.fixture(scope='module')
def mp_remote_fc(monkeymodule, request):
"""Monkeypatch the call to get the remote feature catalogue.
This monkeypatch requires a module variable
``location_fc_featurecatalogue`` with the path to the fc_featurecatalog... |
gambl0r/roguebowl | rbowl.py | Python | unlicense | 14,250 | 0.007509 | import libtcod.libtcodpy as libtcod
from random import randint
SCREEN_WIDTH = 40
SCREEN_HEIGHT = 20
LIMIT_FPS = 20
MAP_WIDTH = 80
MAP_HEIGHT = 45
ROOM_MAX_SIZE = 10
ROOM_MIN_SIZE = 10
MAX_ROOMS = 30
MAX_ROOM_MONSTERS = 3
FOV_ALGO = libtcod.FOV_SHADOW
FOV_LIGHT_WALLS = True
TORCH_RADIUS = 8
void_color = libtcod.Co... | elif ord('d') in self.pressed:
self.screen.move(1, 0)
if self.state == 'playing':
if libtcod.con | sole_is_key_pressed(libtcod.KEY_UP):
self.player.move(0, -1)
self.fov_recompute = True
elif libtcod.console_is_key_pressed(libtcod.KEY_DOWN):
self.player.move(0, 1)
self.fov_recompute = True
elif libtcod.console_is_key_pressed(libtc... |
mre/tracker | face.py | Python | lgpl-3.0 | 3,699 | 0.012976 | import cv, cv2
import rectangle
from numpy import concatenate
import logging
class Face(object):
def __init__(self, config = {}):
self.config = {
"top_offset" : 1.0,
"bottom_offset" : 1.0,
"left_offset" : 0.0,
"right_offset" : 0.0,
"haar_confidence" : 3,
"min_fac... | sed += 1
# Speedup. Only redetect after a certain delay.
if self.faces_invalid():
self.recalculate(img)
return self.face_positions
def faces_invalid(self):
"""
Check if we can still use the old face positions or
if the delay is | over and we need to find the face again in the image.
"""
if not self.face_positions:
# No previous face detection. Declare invalid.
return True
if self.frames_passed > self.face_delay:
# The delay has passed. Invalidate previous detection
return True
# Everything ok. We can use ... |
acdh-oeaw/dig_ed_cat | digital_editions/settings/dev.py | Python | mit | 533 | 0 | from .base import *
# Quick-start development s | ettings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/chec | klist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!i%7s@1+v&293zcy*kljuke=_l176nqpj2-3dtms()pw^et!we'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3'... |
tweiss1234/Cras | strings.py | Python | apache-2.0 | 824 | 0.003641 | class Strings:
ADD_SUPERVISOR = "You are now connected with "
START_MONITORING = " wants to monitor you, click to allow"
ACCEPTED_MONITORING= "You started monitoring "
STOP_MONITORING_SUPERVISE = " canceled monitoring"
STOP_MONITORING_SUPERVISOR = " is no longer monitoring you"
APPLICATION_ANOMA... | 1rYLapfmii62coTWgNvCMnqq1q8LIxsvNNByT-iPrU-EledwiKHyT7zzCFbPMkbqbZvdb-YVidkQq0u6jvOk_1RZs | vK-Q1_XuM3gavyU63GvbgjNcgd5_Ws1Z-H4Xs_l"
|
FluidityProject/multifluids | tests/square-convection-parallel-trivial/src/genmesh.py | Python | lgpl-2.1 | 254 | 0 | #!/usr/bin/env python
import fluidity.diagnostics.annulus_mesh as mesh
import fluidity.diagnostics.triangletools | as tt
div = mesh.SliceCoordsConstant(0.0, 1.0, 3)
m = mesh.GenerateRectangleMesh(div, div)
tt. | WriteTriangle(m, "square-structured-linear")
|
swiftstack/swift | swift/common/middleware/s3api/s3request.py | Python | apache-2.0 | 62,988 | 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... | ucket_name
from swift.common.middleware.s3api.acl_utils import handle_acl_header
# List of sub-resources that must be maintained as part of the HMAC
# signature string.
ALLOWED_SUB_RESOURCES = sorted([
'acl', 'delete', 'lifecycle', 'location', 'logging', 'notification',
'partNumber', 'policy', 'requestPayment... | ent-disposition',
'response-content-encoding', 'response-content-language',
'response-content-type', 'response-expires', 'cors', 'tagging', 'restore'
])
MAX_32BIT_INT = 2147483647
SIGV2_TIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%S'
SIGV4_X_AMZ_DATE_FORMAT = '%Y%m%dT%H%M%SZ'
SERVICE = 's3' # useful for mocking out i... |
Micronaet/micronaet-accounting | account_invoice_multipartner/multipartner.py | Python | agpl-3.0 | 2,506 | 0.004789 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP module
# Copyright (C) 2010 Micronaet srl (<http://www.micronaet.it>)
#
# Italian OpenERP Community (<http://www.openerp-italia.com>)
#
#####################################################... | return res
_columns = {
'extra_address' | : fields.selection([
('none', 'None'),
('contact', 'Contact'),
('partner', 'Partner'), ],
'Extra address', select=True, readonly=False, required=True),
'partner_ids': fields.many2many(
'res.partner', 'invoice_partner_rel', 'invoice_id', 'partner_i... |
avihad/ARP-Storm | src/arp_open_flow/pox/misc/of_tutorial.py | Python | apache-2.0 | 4,582 | 0.006547 | # Copyright 2012 James McCauley
#
# 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 writi... | in.total_len)).
def act_like_switch (self, packet, packet_in):
"""
Implement switch-like behavior.
"""
""" # DELETE THIS LINE TO START WORKING ON THIS (AND THE ONE BELOW!) #
# Here's some psuedocode to start you off implementing a learning
# switch. You'll need to rewrite it as real Pytho... | tination MAC of the packet is known:
# Send packet out the associated port
self.resend_packet(packet_in, ...)
# Once you have the above working, try pushing a flow entry
# instead of resending the packet (comment out the above and
# uncomment and complete the below.)
log.debug("Ins... |
ccto/python-demos | 06-requests/framework.py | Python | apache-2.0 | 303 | 0.030508 | import requests
def getHTMLText(url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.tex | t
except:
return "产生异常"
if __name__=="_ | _main__":
url="http://www.baidu.com"
print(getHTMLText(url)) |
dato-code/how-to | triple_apply_weighted_pagerank.py | Python | cc0-1.0 | 2,161 | 0.006478 | import graphlab as gl
import time
def pagerank_update_fn(src, edge, dst):
if src['__id'] != dst['__id']: # ignore self-links
dst['pagerank'] += src['prev_pagerank'] * edge['weight']
return (src, edge, dst)
def sum_weight(src, edge, dst):
if src['__id'] != dst['__id']: # ignore self-links
s... | ertices['total_weight'] = 0.0
g = g.triple_apply(sum_weight, ['total_weight'])
g = g.triple_apply(normalize_weight, ['weight'])
del g.vertices['total_weight']
# initialize vertex field
g.vertices['prev_pagerank'] = 1.0
it = 0
total_l1_delta = len(g.vertices)
start = time.time()
whil... | ['pagerank'])
g.vertices['pagerank'] = g.vertices['pagerank'] * (1 - reset_prob) \
+ reset_prob
g.vertices['l1_delta'] = (g.vertices['pagerank'] - \
g.vertices['prev_pagerank']).apply(lambda x: abs(x))
t... |
NeuroRoboticTech/Jetduino | Software/Python/grove_electricity_sensor.py | Python | mit | 2,751 | 0.003999 | #!/usr/bin/env python
#
# Jetduino Example for using the Grove Electricity Sensor (http://www.seeedstudio.com/wiki/Grove_-_Electricity_Sensor)
#
# The Jetduino connects the Jetson and Grove sensors. You can learn more about the Jetduino here: http://www.NeuroRoboticTech.com/Projects/Jetduino
#
# Have a question about... | THERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import time
import jetduino
from jetduino_pins import *
# Connect the Grove Electricity Sensor to analog port A0
# SIG,NC,NC,GND
sensor = ARD_A0
jetduino.pinMode(sensor, INPUT_PIN)
# Vcc of the grove... |
while True:
try:
# Get sensor value
sensor_value = jetduino.analogRead(sensor)
# Calculate amplitude current (mA)
amplitude_current = (float)(sensor_value / 1024 * grove_vcc / 800 * 2000000)
# Calculate effective value (mA)
effective_value = amplitude_current / 1.4... |
ecreall/nova-ideo | novaideo/core.py | Python | agpl-3.0 | 25,754 | 0.000427 | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
import colander
import venusian
from BTrees.OOBTree import OOBTree
from persistent.list import PersistentList
from persistent.dict import PersistentDict
from webob.multi... | 'validator': ob.validator,
'tags': ob.tags
#TODO add validator ob.validator
}
info = venusian.attach(wrapped, callback, cate... | ope == 'class':
# if the decorator was attached to a method in a class, or
# otherwise executed at class scope, we need to set an
# 'attr' into the settings if one isn't already in there
if settings['attr'] is None:
settings['attr'] = wrapped.__name__
... |
miljkovicivan/MicroComments | app/healthcheck.py | Python | bsd-3-clause | 222 | 0 | """
| Health check endpoint
"""
from flask import Blueprint
HEALTHCHECK = Blueprint('healthcheck', __name__)
@HEALTHCHECK.ro | ute('/comments/health_check')
def healthcheck():
"""
Returns 200
"""
return 'OK'
|
eviljeff/zamboni | mkt/files/models.py | Python | bsd-3-clause | 11,351 | 0 | import hashlib
import json
import os
import unicodedata
import uuid
from django.conf import settings
from django.core.files.storage import default_storage as storage
from django.core.urlresolvers import reverse
from django.db import models
from django.dispatch import receiver
from django.template.defaultfilters import... | ce.version.addon.update_version(ignore=instance.version)
else:
instance.version.addon.update_version()
except models.ObjectDoesNotExist:
pass
def update_status_delete(sender, instance, **kw):
kw['delete'] = True
return update_status(sender, instance, **kw)
mod... | n_update_status')
models.signals.post_delete.connect(
update_status_delete, sender=File, dispatch_uid='version_update_status')
@receiver(models.signals.post_delete, sender=File,
dispatch_uid='cleanup_file')
def cleanup_file(sender, instance, **kw):
""" On delete of the file object from the database,... |
Mphaya/heasy | heasy/utility_scripts/display_top_prons.py | Python | apache-2.0 | 4,406 | 0.00749 | #!/usr/bin/env python
#
# Copyright 2013 CSIR Meraka HLT and Multilingual Speech Technologies (MuST) North-West University
#
# 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
#
# ht... |
print "Error: unknown word %s" % word
else:
break
out_file.close()
#------------------------------------------------------------------------------
if __name__ == "__main__":
if len(sys.argv) == 5:
trans_list_name = str(sys.argv[1])
| dict_name = str(sys.argv[2])
top_n = int(sys.argv[3])
out_name = str(sys.argv[4])
print "Displaying the %d most frequent words" % top_n
display_top_prons(trans_list_name, dict_name, top_n, out_name)
else:
print "\nDisplay the dictionary pronunciations of the most fr... |
tyler-elric/misc | rss.py | Python | gpl-3.0 | 6,353 | 0.030222 | import xml.etree.ElementTree as ET
from email.utils import parsedate as parsedate_
from time import mktime
import datetime
def parsedate(d):return datetime.datetime.fromtimestamp(mktime(parsedate_(d)))
def element_value(el,default):
return ((el.text + el.tail) if el is not None else "").strip()
def date_value(dv):
... | ion>Before man travels to Mars, NASA hopes to design new engines that will let us fly through the Solar System more quickly. The proposed VASIMR engine would do that.</description>
<pubDate>Tue, 27 May 2003 08:37:32 GMT</pubDate>
<guid>http://liftoff.msfc.nasa.gov/2003/05/27.html | #item571</guid>
</item>
<item>
<title>Astronauts' Dirty Laundry</title>
<link>http://liftoff.msfc.nasa.gov/news/2003/news-laundry.asp</link>
<description>Compared to earlier spacecraft, the International Space Station has many luxuries, but laundry facilities are not one of them. ... |
trec-dd/trec-dd-simulation-harness | trec_dd/harness/truth_data.py | Python | mit | 4,988 | 0.002005 | '''Generate truth data from a truth_data_file.
A truth_data_file may be produced by a human being, so sometimes
it should be considered truth data. This file provides
utilities for turning a truth_data_file of a certain format into
truth data the harness understands.
'''
from __future__ import absolute_import
import ... | bels_to_put) >= batch_size:
label_store.put(*labels_to_put)
labels_to_put = []
if len(labels_to_put) > 0:
label_store.put(*labels_to_put)
def main():
parser = argparse.ArgumentParser('test tool for checking that we can | load '
'the truth data as distributed by NIST for '
'TREC 2015')
parser.add_argument('truth_data_path', help='path to truth data file')
modules = [yakonfig, kvlayer]
args = yakonfig.parse_args(parser, modules)
logging.basicConfig(... |
johndeu/amspy | amspy/examples/analytics/indexer_v2/indexer_v2.py | Python | mit | 14,879 | 0.01566 | """
Copyright (c) 2016, John Deutscher
Description: Sample Python script for Azure Media Indexer V2
License: MIT (see LICENSE.txt file for details)
Documentation : https://azure.microsoft.com/en-us/documentation/articles/media-services-process-content-with-indexer2/
"""
import os
import json
import amspy
import time
im... | CODE AGAINST YOUR PRODUCTION AMS ACCOUNT, YOU CAN LOSE
# DATA, AND/OR PUT YOUR AMS SERVICES IN A DEGRADED OR UNAVAILABLE STATE. BE WARNED!
###########################################################################################
##### DISCLA | IMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER #####
###########################################################################################
# Load Azure app defaults
try:
with open('../../config.json') as configFile:
configData = json.load(configFile)
except FileNotFoundError:
print... |
openstack/smaug | karbor/services/protection/protection_plugins/server/nova_protection_plugin.py | Python | apache-2.0 | 20,349 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | a about AZ
server = nova_client.servers.get(server_id)
availability_zone = getattr(server, "OS-EXT-AZ:availability_zone")
# get metadata about network, flavor, key_name, security_groups
addresses = getattr(server, "addresses")
networks = []
floati... |
for network_info in network_infos:
addr = network_info.get("addr")
mac = network_info.get("OS-EXT-IPS-MAC:mac_addr")
network_type = network_info.get("OS-EXT-IPS:type")
if network_type == 'fixed':
por... |
Tocknicsu/nctuoj | backend/test/api/problem/guest.py | Python | mit | 1,488 | 0.005376 | #!/usr/bin/env python3
import sys
import requests
import json
import unittest
import datetime
from util import TestCase
import config
import common
class TestApiProblemGuest(TestCase):
url = '%s/api/groups/3/problems/'%(config.base_url)
token = common.get_user_info({'account': config.user_admin_account, 'passw... | "status_code": 403,
"body": {
"msg": "Permission Denied",
}
}
self.assertEqualR(res, expect_result)
def test_get_invisible(self):
data = {
"token": self.token,
}
| res = requests.get("%s%s/"%(self.url,10005), data=data)
res.connection.close()
expect_result = {
"status_code": 403,
"body": {
"msg": "Permission Denied",
}
}
self.assertEqualR(res, expect_result)
|
Open-E-WEB/django-powerpages | powerpages/cachekeys.py | Python | mit | 1,418 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import hashlib
from django.utils import six
URL_LIST_CACHE = 'powerpages:url_list'
SITEMAP_CONTENT = 'powerpages:sitemap'
def get_cache_name(prefix, name):
"""
Cache name constructor. Uses the same methods as django cache system
... | ate:{0}'.format(page_pk)
def rendered_source_for_user(page_pk, user_id):
"""Create cache key for rendered page source based on current user"""
return 'powerpages:rendered_source_user:{0}:{1}'.format(page_pk, user_id)
def rendered_source_for_lang(page_pk, lang):
"""Create cache key for rendered page sour... | r url of CMS page or standard Django URL
based on hashed serialized name with optional *args and **kwargs
"""
serialized_url = json.dumps([name, args, kwargs], sort_keys=True)
return get_cache_name('powerpages:urls', serialized_url)
|
open-forcefield-group/openforcefield | openff/toolkit/tests/test_toolkits.py | Python | mit | 163,747 | 0.002449 | #!/usr/bin/env python
# =============================================================================================
# MODULE DOCSTRING
# =============================================================================================
"""
Tests for cheminformatics toolkit wrappers
"""
# ==============================... | =========================================================
def get_mini_drug_bank(toolkit_class, xfail_mols=None):
"""Read the mini drug bank sdf file with t | he toolkit and return the molecules"""
# This is a work around a weird error where even though the test is skipped due to a missing toolkit
# we still try and read the file with the toolkit
if toolkit_class.is_available():
toolkit = toolkit_class()
molecules = Molecule.from_file(
... |
Ziftr/counterpartyd | test/unit_test.py | Python | mit | 1,568 | 0.007015 | #! /usr/bin/python3
import sys, os, time, tempfile
import pytest
import util_test
from util_test import CURR_DIR
from fixtures.vectors import UNITTEST_VECTOR
from fixtures.params import DEFAULT_PARAMS as DP
from lib import (config, util, api)
import counterpartyd
def setup_module():
counterpartyd.set_options(data... | break
elif attempt == 4999:
raise Exception("Timeout: RPC server not ready after 5s")
else:
time.sleep(0.001)
def teardown_module(function):
util_test.remove_database_files(config.DATABASE)
@pytest.fixture
def counterpartyd_db(request):
| db = util.connect_to_db()
cursor = db.cursor()
cursor.execute('''BEGIN''')
request.addfinalizer(lambda: cursor.execute('''ROLLBACK'''))
return db
def test_vector(tx_name, method, inputs, outputs, error, records, counterpartyd_db):
if method == 'parse':
util_test.insert_transaction(inputs[0]... |
ZG-Tennis/django-ckeditor | ckeditor/utils.py | Python | bsd-3-clause | 8,404 | 0.004522 | import uuid
import os
import shutil
import urlparse
import re
import hashlib
from lxml import html
from PIL import Image, ImageFile
from django.conf import settings
import views
ImageFile.MAXBLOCKS = 10000000
def match_or_none(string, rx):
"""
Tries to match a regular expression and returns an integer if it... | )
# Get images
imgs = tree.xpath('//img[starts-with(@src, "%s")]' % settings.STATIC_URL)
for img in imgs:
orig_url = img.attrib['src']
| orig_path = get_local_path(orig_url)
width, height = get_dimensions(img)
rendered_path = re_render(orig_path, width, height)
# If we haven't changed the image, move along.
if rendered_path == orig_path:
continue
# Flip to the rendered
img.attrib['data-... |
JustinSGray/pyCycle | setup.py | Python | apache-2.0 | 386 | 0.005181 | from distutils.core | import setup |
setup(name='pycycle',
version='3.9.9',
packages=[
'pycycle',
'pycycle/thermo',
'pycycle/thermo/cea',
'pycycle/thermo/cea/thermo_data',
'pycycle/elements',
'pycycle/maps',
'pycycle/thermo/tabular'
],
install_requires=[
... |
cuedpc/edpcmentoring | edpcmentoring/projectlight/__init__.py | Python | mit | 60 | 0 | defa | ult_app_config = 'projectlight.apps.Projec | tlightConfig'
|
Pikecillo/genna | external/PyXML-0.8.4/xml/xslt/TextElement.py | Python | gpl-2.0 | 2,357 | 0.003818 | ########################################################################
#
# File Name: TextElement.py
#
#
"""
Implementation of the XSLT Spec text stylesheet element.
WWW: http://4suite.com/4XSLT e-mail: [email protected]
Copyright (c) 1999-2000 Fourthought Inc, USA. All Rights Reserved.
See htt... | xception(Error.ILLEGAL_TEXT_CHILD)
self.normalize()
return
def instantiate(self, context, processor):
if not self.firstChild:
| return (context,)
if context.processorNss != self._nss:
origState = context.copyNamespaces()
context.setNamespaces(self._nss)
else:
origState = None
value = self.firstChild and self.firstChild.data or ''
if self._disable_output_escaping:
... |
timabell/gpodder | src/gpodder/gtkui/frmntl/portrait.py | Python | gpl-3.0 | 8,012 | 0.002122 | # -*- coding: utf-8 -*-
#
# gPodder - A media aggregator and podcast client
# Copyright (c) 2005-2010 Thomas Perl and the gPodder Team
#
# gPodder 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... | entation)
# Save the current orientation for "automatic" mode later on
self._last_dbus_orientation = orient | ation
|
QuLogic/meson | mesonbuild/compilers/mixins/clike.py | Python | apache-2.0 | 59,114 | 0.002436 | # Copyright 2012-2017 The Meson development team
# 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 agree... | re'
# Check if we need to add --start/end-group for circular dependencies
# between static libraries, and for recursively searching for symbols
# needed by static libraries that are provided by object files or
# shared libraries.
self.flush_pre_post()
if copy:
| new = self.copy()
else:
new = self
# This covers all ld.bfd, ld.gold, ld.gold, and xild on Linux, which
# all act like (or are) gnu ld
# TODO: this could probably be added to the DynamicLinker instead
if isinstance(self.compiler.linker, (GnuLikeDynamicLinkerMixin, ... |
codecakes/random_games | implement_hash_map.py | Python | mit | 5,289 | 0.016449 | ## for learning | purpose only
from collections import deque
##The making of a hash Table
def hash_string(keyword,buckets):
'''
# takes as inputs a keyword
# (string) and a number of buckets,
# and returns a number representing
# the bucket for that keyword.
'''
return sum(map(ord, keyword | ))%buckets
##Testing Hash string distribution using hash str function
def test_hash_func(fn, keys, bucSize):
results = [0] * bucSize
keys_used = set()
for key in keys:
if key and key not in keys_used:
results[fn(key, bucSize)] += 1
keys_used.add(key)
return results
## ... |
higee/project_euler | 21-30/21.py | Python | mit | 860 | 0.010465 | class amicable():
def d(self, n):
if n == 1:
return 0
else:
sum_of_factors = 0
for i in range(1, int(n**0.5)+1):
if n % i == 0:
sum_of_factors += i
if n/i != n:
sum_... | _factors += int(n/i)
return sum_of_factors
def __call__(self, n):
sum_of_amicable = 0
for i in range(1, n):
original = i, amicable.d(self, i)
inverse = amicable.d(self, amicable.d(self, i)), amicable.d(self, i)
if (original == inv... | sum_of_amicable += i
return sum_of_amicable
def main():
euler_21 = amicable()
n=10000
print(euler_21(n))
if __name__ == "__main__":
main()
|
Informatik-AG-KGN-2016/Dokumente | 2016-11-14/input.py | Python | gpl-3.0 | 503 | 0 | # introduction
print("Bitte füllen Sie das folgende Formular aus")
# get name
name = input("Vorname: ")
lastname = input("Nachname: ")
| fullname = name + ' ' + lastname
# get birth info
birth_year = int(input("Geburtsjahr: "))
birth_place = input("Geburtsort: ")
# calculate age
age = 2016 - birth_year
print("\n")
# print generated info
print("Hallo", fullname + ",")
print("Sie sind", age, "Jahre alt und wurden in", birth | _place, "geboren.")
print("Vielen Dank für Ihre Teilnahme an der Umfrage.")
|
TRex22/Sick-Beard | cherrypy/lib/auth.py | Python | gpl-3.0 | 3,288 | 0.007603 | import cherrypy
from cherrypy.lib import httpauth
def check_auth(users, encrypt=None, realm=None):
"""If an authorization header contains credentials, return True, else False."""
request = cherrypy.serving.request
if 'authorization' in request.headers:
# make sure the provided credentials ... | d Request')
if not encrypt:
encrypt = httpauth.DIGEST_AUTH_ENCODERS[httpauth.MD5]
if hasattr(users, '__call__'):
try:
# backward compatibility
users = users() # expect it to return a dictionary
... | he user password
password = users.get(ah["username"], None)
except TypeError:
# returns a password (encrypted or clear text)
password = users(ah["username"])
else:
if not isinstance(users, dict):
raise ValueError("Aut... |
fotcorn/liveinconcert | manage.py | Python | mit | 250 | 0 | #!/usr/bin/env python
import os
import sys
|
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "concert.settings")
from django.core.mana | gement import execute_from_command_line
execute_from_command_line(sys.argv)
|
HeavenlySword/INTINT | intint/intwriter.py | Python | mit | 12,384 | 0.006137 | import os
import json
import pyodbc
import psycopg2
import psycopg2.extras
from psycopg2.pool import ThreadedConnectionPool
import datetime
from concurrent.futures import ThreadPoolExecutor, wait
import multiprocessing
import sys
import hashlib
from utils import *
THREADNUM = 16
class IntWriter:
def __init__(self... | as delta
ob | j['delta'] = True
if self.cache_dict[obj['ddochash']].tobytes() == obj['dcontenthash']:
# Can update some field here with a timestamp to guaranteee that data is actual
self.convtime += datetime.datetime.now() - st
return 0
# Ear... |
yardsalecoin/yardsalecoin | contrib/bitrpc/bitrpc.py | Python | mit | 7,836 | 0.038157 | from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:9554")
else:
access = Ser... | try:
pwd = raw_input("Enter wallet passphrase: ")
access.walletpassphrase(pwd, 60)
print "\n---Wallet unlocked---\n"
except:
print "\n---An error occurred---\n"
elif cmd == "walletpassphrasechange":
try:
pwd = raw_input | ("Enter old wallet passphrase: ")
pwd2 = raw_input("Enter new wallet passphrase: ")
access.walletpassphrasechange(pwd, pwd2)
print
print "\n---Passphrase changed---\n"
except:
print
print "\n---An error occurred---\n"
print
else:
print "Command not found or not supported"
|
fooelisa/netmiko | netmiko/__init__.py | Python | mit | 1,198 | 0.003339 | from __future__ import unicode_literals
import logging
# Logging configuration
log = logging.getLogger(__name__) # noqa
log | .addHandler(logging.NullHandler()) # noqa
from netmiko.ssh_dispatcher import ConnectHandler
from netmiko.ssh_dispatcher import ssh_dispatcher
from netmiko.ssh_dispatcher import redispatch
from netmiko.ssh_dispatcher import platforms
from netmiko.ssh_dispatcher import FileTransfer
from netmiko.scp_handler import SCPCon... | rom netmiko.ssh_exception import NetMikoTimeoutException
from netmiko.ssh_exception import NetMikoAuthenticationException
from netmiko.ssh_autodetect import SSHDetect
from netmiko.base_connection import BaseConnection
# Alternate naming
NetmikoTimeoutError = NetMikoTimeoutException
NetmikoAuthError = NetMikoAuthentica... |
jakubtuchol/epi | test/test_greedy_algorithms.py | Python | mit | 2,161 | 0 | from src.greedy_algorithms import find_ample_city
from src.greedy_algorithms import find_majority_element
from src.greedy_algorithms import GasCity
from src.greedy_algorithms import three_sum
from src.greedy_algorithms import trapped_water
from src.greedy_algorithms import two_sum
class TestTwoSum(object):
"""
... | to_next | =900),
GasCity(id='B', gas=20, to_next=600),
GasCity(id='C', gas=5, to_next=200),
GasCity(id='D', gas=30, to_next=400),
GasCity(id='E', gas=25, to_next=600),
GasCity(id='F', gas=10, to_next=200),
GasCity(id='G', gas=10, to_next=100),
]
... |
filbranden/systemd | tools/make-autosuspend-rules.py | Python | gpl-2.0 | 938 | 0 | #!/usr/bin/env python3
# SPDX-License-Identifier: LGPL-2.1+
# Generate autosuspend rules for devices that have been tested to work properly
# with autosuspend by the Chromium OS team. Based on
# https://chromium.googlesource.com/chromiumos/platform2/+/master/power_manager/udev/gen_autosuspend_rules.py
import chromium... | PCI_IDS:
| vendor, device = entry.split(':')
vendor = int(vendor, 16)
device = int(device, 16)
print('pci:v{:08X}d{:08X}*'.format(vendor, device))
print('# usb:v<VEND>p<PROD> (4 uppercase hexadecimal digits twice')
for entry in chromiumos.gen_autosuspend_rules.USB_IDS:
vendor, product = entry.split(':')
vend... |
h4ck3rm1k3/gcc-ontology | lib/ontologies/org/w3/_2000/_10/swap/pim/doc.py | Python | gpl-3.0 | 265 | 0.011321 |
import rdf | lib
from rdflib import Namespace
from ontology import Ontology
class DOC(Ontology, ):
def __init__(self):
Ontology.__init__(self, rdflib.term.URIRef(u'http://www.w3.org/2000/10/swap/pim/doc#'))
prefix = 'd | oc'
doc = DOC()
ontology = doc
|
danalec/dotfiles | sublime/.config/sublime-text-3/Packages/Anaconda/anaconda_lib/workers/process.py | Python | mit | 636 | 0 |
# Copyright (C) 2013 - 2016 - Oscar Campos <[email protected]>
# This program is Free Software see LICENSE file for details
from .local_process import LocalProcess
from .re | mote_process import StubProcess
from .vagrant_ | process import VagrantProcess
class WorkerProcess(object):
"""Return a right processer based in the scheme
"""
_processers = {'tcp': StubProcess, 'vagrant': VagrantProcess}
def __init__(self, interpreter):
self._interpreter = interpreter
def take(self):
scheme = self._interprete... |
Zlash65/erpnext | erpnext/manufacturing/doctype/operation/test_operation.py | Python | gpl-3.0 | 258 | 0.007752 | # Copyright | (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
test_records = frappe.get_test_records('Operation')
class TestOperation(unittes | t.TestCase):
pass
|
gopythongo/gopythongo | src/py/gopythongo/tests/debversion.py | Python | mpl-2.0 | 3,559 | 0.006185 | # -* encoding: utf-8 *-
# This Source Code Form is subject | to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from unittest.case import TestCase
from gopythongo.utils.debversion import debian_substr_compare, split_versio | n_parts, DebianVersion, \
InvalidDebianVersionString
class DebianVersionTests(TestCase):
def test_debian_substr_compare(self) -> None:
self.assertEqual(debian_substr_compare("", "a"), -1)
self.assertEqual(debian_substr_compare("09", "10"), -1)
self.a... |
veltzer/riddling | instances/cover_subset/solution.py | Python | gpl-3.0 | 1,036 | 0 | import random
import numpy
large_set_size = 1000
small_set_size = 20
print_diff = 100
stat_num = 1000
stats = [[], [], []]
for _ in range(stat_num):
lset = set()
sset = set()
stop = False
i = 0
large_set_count = None
small_set_count | = None
large_set_size_when_small_set_complete = None
while not stop:
# if i % print_diff == 0:
# print(len(lset), len(sset))
r = random.randrange(large_set_size)
if r < small_set_size:
sset.add(r)
lset.add(r)
if len(sset) == small_set_size and small... | i
large_set_size_when_small_set_complete = len(lset)
if len(lset) == large_set_size:
large_set_count = i
stop = True
i += 1
stats[0].append(large_set_size_when_small_set_complete)
stats[1].append(large_set_count)
stats[2].append(small_set_count)
print(num... |
bernieyangmh/spider | spider_y/items.py | Python | gpl-3.0 | 1,245 | 0.00241 | # -*- coding: utf-8 -*-
# Defin | e here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.item import Item | , Field
from scrapy.loader.processors import Join, MapCompose, TakeFirst
from scrapy.loader import ItemLoader
from w3lib.html import remove_tags
class SpiderYItem(Item):
# define the fields for your item here like:
# name = scrapy.Field()
img = Field()
name = Field()
def filter_price(value):
if v... |
kdz/test | VEdit.py | Python | mit | 735 | 0.005442 | __author__ = 'kdsouza'
import traits.api as tr
import traitsui.api as trui
from traitsui.editors import *
class VEdit(tr.HasTraits):
"""
Container class for value, editor type, and editor | specifications.
"""
value = tr.Any
editor = trui.EditorFactory
kwargs = tr.Dict(key_trait=tr.Str, value_trait=tr.Any)
# item_kwargs = tr.Dict(key_trait=tr.Str, value_trait=tr.Any) # default hide label, custom style?
def __init__(self, value, editor, kwargs=dict()):
super(VEdit, self)... | itor, self.kwargs = value, editor, kwargs
def __eg__(self, other):
return isinstance(other, VEdit) and (self.val == other.val) and (self.editor == other.editor)
|
ESOedX/edx-platform | lms/djangoapps/program_enrollments/api/tests/test_writing.py | Python | agpl-3.0 | 574 | 0.001742 | """
(Future home of) Tests for program enrollment | writing Python API.
Currently, we do not directly unit test the functions in api/writing.py.
This is okay for now because they are all used in
`rest_api.v1.views` and is thus tested through `rest_api.v1.tests.test_views`.
Eventually it would be good to directly test the Python API function and just use
mocks in the vi... | port absolute_import, unicode_literals
|
rosenvladimirov/odoo | anglo_saxon_dropshipping/__init__.py | Python | agpl-3.0 | 1,071 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# C | opyright (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 Affero General Public License as
# published by | the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GN... |
tensorflow/tensorflow | tensorflow/python/framework/traceable_stack_test.py | Python | apache-2.0 | 5,145 | 0.003693 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ')
expected_lifo_peek = ['hope', 42.0]
self.assertEqual(expected_lifo_peek, list(t_stack.peek_objs()))
self.assertEqual('hope', t_stack.pop_obj())
self.assertEqual(42.0, t_stack.pop_obj())
def testPushPeekTopObj(self):
t_stack = traceable_stack.TraceableStack()
t_stack.push_obj(42.0)
t_... | .push_obj(0)
t_stack.push_obj(1)
t_stack.push_obj(2)
t_stack.push_obj(3)
obj_3 = t_stack.pop_obj()
obj_2 = t_stack.pop_obj()
obj_1 = t_stack.pop_obj()
obj_0 = t_stack.pop_obj()
self.assertEqual(3, obj_3)
self.assertEqual(2, obj_2)
self.assertEqual(1, obj_1)
self.assertEqual... |
kevinlioi/GenOpt | examples/constrained_optimization.py | Python | mit | 762 | 0.045932 | import numpy
from GenOpt import GeneticOptimizer
##Booths Function but with an additional slack variable to show the constraint feature.
def BoothsFnc(x):
return (x[:, | 0] + 2*x[:, 1] - 7)**2 + (2*x[:, 0] + x[:, 1] - 5)**2
InitialSolutions = [numpy.array([numpy.random.uniform(), numpy.random.uniform(), numpy.random.uniform()]) for i in range(1000)]
InitialSolutions = numpy.vstack([10*z/sum(z) for z in InitialSolutions])
G2 = GeneticOptimizer(InitialSolutions = InitialSolutions,
... | lb = [0,0,0],
Sense = 'min',
MutationType = 'Sum Constraint',
Crossover = 'Weighted Average')
R = G2.GA() |
UTAlan/PhotosByMallie | mallie/home/views.py | Python | gpl-2.0 | 361 | 0.019391 | from | django.shortcuts import render_to_response
from django.template import RequestContext
from home.models import HomeImage
def index(request):
info = {}
info['homeImages'] = HomeImage.objects.all().order_by('title').order_by(' | order')
return render_to_response('home/index.html', { 'info': info }, context_instance=RequestContext(request))
|
oelson/concordance | lib/BibleParser/xml.py | Python | gpl-2.0 | 17,962 | 0.001689 | #-*- coding: utf-8 -*-
__all__ = ["XML_BibleParser", "reference"]
import re
import xml.etree.ElementTree as ET
from BibleParser.abstract import parser as abstract_parser, reference as abstract_reference
from BibleParser.error import *
from BibleParser.Numbers import Number
class parser(abstract_parser):
"""
... | ):
"""
Retourne la taille du chapitre passé en argument (noeud DOM).
"""
return self.get_greatest_element_index(
chapter_element,
"v"
)
def _parse_verse(self, book_element, chapter_element, verse_element):
"""
Vérifie qu'un verset ... | ) satisfait les exigences de
la recherche par mots-clés.
Si oui, alors les correpondances sont éventuellement mises en
surbrillance.
Retourne une paire consistant en un objet de type "reference"
et son texte.
"""
if verse_element.text is None:
return
... |
OpenWinCon/OpenWinNet | web-gui/myvenv/lib/python3.4/site-packages/setuptools/py31compat.py | Python | apache-2.0 | 1,184 | 0.005068 | __all__ = ['get_config_vars', 'get_path']
try:
# Python 2.7 or >=3.2
from sysconfig import get_config_vars, get_path
except ImportError:
from distutils.sysconfig import get_config_vars, get_python_lib
def get_path( | name):
if name not in ('platlib', 'purelib'):
raise ValueError("Name must be purelib or platlib")
return get_python_lib(name=='platlib')
try:
# Python >=3.2
from tempfile import TemporaryDirectory
except ImportError:
import shutil
import tempfile
class TemporaryDirectory... | ll try to delete afterward, but will also ignore OS and similar
errors on deletion.
"""
def __init__(self):
self.name = None # Handle mkdtemp raising an exception
self.name = tempfile.mkdtemp()
def __enter__(self):
return self.name
def __exit... |
gengwg/leetcode | 226_invert_binary_tree.py | Python | apache-2.0 | 1,673 | 0.001267 | # -*- coding: utf-8 -*-
# 226. Invert Binary Tree
#
# Invert a binary tree.
#
# 4
# / \
# 2 7
# / \ / \
# 1 3 6 9
#
# to
#
# 4
# / \
# 7 2
# / \ / \
# 9 6 3 1
#
# Trivia:
# This problem was inspired by this original tweet by Max Howell:
#
# Google: 90% of our engineers u... | 交换,
# 这种时候很容易想到的就是递归的方法。
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
# http://www.tangjikai.com/alg... | """
:type root: TreeNode
:rtype: TreeNode
"""
if root:
tmp = root.left
root.left = root.right
root.right = tmp
self.invertTree(root.left)
self.invertTree(root.right)
return root
def invertTree2(self, root):
... |
MykeMcG/SummerRoguelike | src/utils.py | Python | gpl-3.0 | 2,363 | 0.003809 | import libtcodpy as libtcod
import consts
def find_closest_target(caster, entities, range):
closest_target = None
closest_dist = range + 1
for obj | in entities:
if obj.fighter and obj != caster: |
dist = caster.distance_to(obj)
if dist < closest_dist:
closest_target = obj
closest_dist = dist
return closest_target
def random_choice(chances):
dice = libtcod.random_get_int(0, 1, sum(chances))
running_sum = 0
choice = 0
for c in chances:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.