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 |
|---|---|---|---|---|---|---|---|---|
LouisLinY/mblog | mainsite/views.py | Python | apache-2.0 | 1,203 | 0.009975 | # -*- coding:utf-8 -*-
import sys
from datetime import dateti | me
from django.template.loader import get_template
from django.shortcuts import render,redirect
from django.http import HttpResponse
from | .models import Post
reload(sys)
sys.setdefaultencoding('utf-8')
# Create your views here.
def homepage(request):
template = get_template('index.html')
posts = Post.objects.all()
posts_lists = list()
now = datetime.now()
html = template.render(locals())
print sys.getdefaultencoding()
#for ... |
blaze33/django | django/utils/encoding.py | Python | bsd-3-clause | 9,166 | 0.001855 | from __future__ import unicode_literals
import codecs
import datetime
from decimal import Decimal
import locale
try:
from urllib.parse import quote
except ImportError: # Python 2
from urllib import quote
import warnings
from django.utils.functional import Promise
from django.utils import six
class Django... | ed with non-ASCII bytestring data without a
# working unicode method. Try to handle this without raising a |
# further exception by individually forcing the exception args
# to unicode.
s = ' '.join([force_text(arg, encoding, strings_only,
errors) for arg in s])
return s
def smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns ... |
IllusionRom-deprecated/android_platform_tools_idea | python/testData/refactoring/extractmethod/Statement.after.py | Python | apache-2.0 | 98 | 0.010204 | def foo(a_new, b_new):
print(a_new + b_new * 123)
de | f f():
a = 1
b = 1
fo | o(a, b) |
termie/openstack-dashboard | django-openstack/src/django_openstack/dash/urls.py | Python | apache-2.0 | 1,070 | 0.002804 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
from django.conf.urls.defaults import *
from django.conf import settings
INSTANCES = r'^(?P<tenant_id>[^/]+)/instances/(?P<instance_id>[^/]+)/%s$'
IMAGES = r'^(?P<tenant_id>[^/]+)/images/(?P<image_id>[^/]+)/%s$'
KEYPAIRS = r'^(?P< | tenant_id>[^/]+)/keypairs/%s$'
urlpatterns = patterns('django_openstack.dash.views.instances',
url(r'^(?P<tenant_id>[^/]+)/$', 'usage', name='dash_usage'),
url(r'^(?P<tenant_id>[^/]+)/instances/$', 'index', name='dash_instances'),
url(INSTANCES % 'console', 'console', name='dash_instances_console'),
ur... | nc', 'vnc', name='dash_instances_vnc'),
)
urlpatterns += patterns('django_openstack.dash.views.images',
url(r'^(?P<tenant_id>[^/]+)/images/$', 'index', name='dash_images'),
url(IMAGES % 'launch', 'launch', name='dash_images_launch'),
)
urlpatterns += patterns('django_openstack.dash.views.keypairs',
url(r'... |
jsmits/django-logutils | django_logutils/middleware.py | Python | bsd-3-clause | 4,098 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import time
from django.db import connection
from django_logutils.conf import settings
logger = logging.getLogger(__name__)
de... | log_msg = (
"%(remote_address)s | %(user_email)s %(method)s %(url)s %(status)d "
"%(content_length)d (%(request_time).2f seconds)"
)
if use_sql_info:
sql_time = sum(
float(q['time']) for q in connection.queries) * 1000
extra_log = {
'nr_queries': len(connection.queries),
'sql_time': sq... |
fritzo/distributions | distributions/tests/test_models.py | Python | bsd-3-clause | 20,478 | 0 | # Copyright (c) 2014, Salesforce.com, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions... | group1.score_value(shared, value)
module.sample_group(shared, 10)
group1.score_data(shared)
group2.score_data(shared)
@for_each_model(lambda module: hasattr(module.Shared, 'protobuf_load'))
def test_protobuf(module, EXAMPLE):
if not has_protobuf:
raise SkipTest('protobuf not availab... | hared.from_dict(EXAMPLE['shared'])
values = EXAMPLE['values']
Message = getattr(distributions.io.schema_pb2, module.NAME)
message = Message.Shared()
shared.protobuf_dump(message)
shared2 = module.Shared()
shared2.protobuf_load(message)
assert_close(shared2.dump(), shared.dump())
messag... |
jawilson/home-assistant | tests/components/volumio/__init__.py | Python | apache-2.0 | 41 | 0 | """Tests for the Volumio integration."" | "
| |
srgblnch/TangoDeviceWatchdog | tango-ds/dog.py | Python | gpl-3.0 | 27,005 | 0.000185 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distrib... | f.warn_stream("%s/%s rea | d exception: %r %s"
% (self.devName, attrName,
e[0].reason, e[0].desc))
except Exception as e:
self.error_stream("%s/%s read exception: %s"
% (self.devName, attrName, e))
raise Exception("%s/%s... |
alexlo03/ansible | lib/ansible/modules/utilities/logic/async_wrapper.py | Python | gpl-3.0 | 10,223 | 0.002152 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>, and others
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import json
import shlex
impo... | output around module JSON output, like messages from
tcagetattr, or where dropbear spews MOTD on every single command (which is nuts).
Filters leading lines before first line-starting occurrence of | '{' or '[', and filter all
trailing lines after matching close character (working from the bottom of output).
'''
warnings = []
# Filter initial junk
lines = data.splitlines()
for start, line in enumerate(lines):
line = line.strip()
if line.startswith(u'{'):
endchar... |
flavour/eden | modules/s3db/hrm.py | Python | mit | 471,286 | 0.010189 | # -*- coding: utf-8 -*-
""" Sahana Eden Human Resources Management
@copyright: 2011-2021 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the S... | oot_org()
if is_admin:
filter_opts = ()
elif root_org:
filter_opts = (root_org, None)
else:
filter_opts = (None,)
mix_staff = settings.get_hrm_mix_staff()
request = current.request
controller = request.controller
group | = request.get_vars.get("group", None)
if not group:
if mix_staff:
group = None
elif controller == "vol":
group = "volunteer"
elif controller == "deploy":
group = None
#elif controller in ("hrm", "org", "inv", "cr", "... |
adw0rd/lettuce-py3 | tests/functional/test_terrain.py | Python | gpl-3.0 | 2,378 | 0.002103 | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# | Copyright (C) <2010-2012> Gabriel Falcão <gabriel@nacaolivre.org>
#
# This program is f | ree software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRA... |
pelotoncycle/shared_memory_bloomfilter | setup.py | Python | gpl-3.0 | 572 | 0.012238 | try:
from setuptools import setup, Extension
except ImportError:
from distutils.core import setup, Extension
setup(name='peloton_bloomfilters',
auth | or = 'Adam DePrince',
author_email = 'adam@pelotoncycle.com',
url = 'https://github.com/pelotoncycle/peloton_bloomfilters',
version='0.0.1',
description="Peloton Cycle's Bloomin fast Bloomfilters",
ext_modules=(
[
Extension(
na | me='peloton_bloomfilters',
sources=['peloton_bloomfiltersmodule.c']),
]
)
)
|
gmimano/commcaretest | corehq/apps/telerivet/forms.py | Python | bsd-3-clause | 825 | 0.002424 | from django.forms.fields import *
from corehq.apps.sms.forms import BackendForm
from dimagi.utils.django.fields import TrimmedCharField
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
class Teleri | vetBackendForm(BackendForm):
api_key = TrimmedCharField()
project_id = TrimmedCharField()
phone_id = TrimmedCharField()
webhook_secret = TrimmedCharField()
def clean_webhook_secret(self):
# Circular import
| from corehq.apps.telerivet.models import TelerivetBackend
value = self.cleaned_data.get("webhook_secret", None)
backend = TelerivetBackend.by_webhook_secret(value)
if backend is not None and backend._id != self._cchq_backend_id:
raise ValidationError(_("Already in use."))
... |
deepmind/Temporal-3D-Pose-Kinetics | third_party/hmr/renderer.py | Python | apache-2.0 | 5,948 | 0.009247 | """Render meshes using OpenDR.
Code is from:
https://github.com/akanazawa/hmr/blob/master/src/util/renderer.py
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import cv2
import numpy as np
from opendr.camera import ProjectPoints
from... | .cos(angle), 0., np.sin(angle)], [0., 1., 0.],
[-np.sin(angle), 0., np.cos(angle)]])
return np.dot(points, ry | )
def simple_renderer(rn,
verts,
faces,
yrot=np.radians(120),
color=colors['light_pink']):
# Rendered model color
rn.set(v=verts, f=faces, vc=color, bgcolor=np.ones(3))
albedo = rn.vc
# Construct Back Light (on back right corner)... |
minidron/django-geoaddress | django_geoaddress/models.py | Python | gpl-2.0 | 3,479 | 0 | # --coding: utf8--
import requests
from django.contrib.gis.db import models
from django.contrib.gis.geos import GEOSGeometry
class Country(models.Model):
"""
Модель страны.
"""
title = models.CharField(
u'название', max_length=255)
class Meta:
verbose_name = u'страна'
ver... | urn None
def get_short_address(self):
return ', '.join(part for part in [self.a | rea, self.locality] if part)
class Region(models.Model):
"""
Класс для географического региона.
"""
name = models.CharField(u'название', max_length=255)
coordinates = models.PolygonField(u'координаты')
# Используем GeoManager, чтобы делать ГЕО запросы
objects = models.GeoManager()
cl... |
asgeirrr/word_cloud | setup.py | Python | mit | 469 | 0 | from distutils.core import setup
from distutils.extension import Extension
setup(
| name='wordcloud',
version='1.1.3',
url='https://github.com/amueller/word_cloud',
description='A little word cloud generator',
license='MIT',
ext_modules=[Extension("wo | rdcloud.query_integral_image",
["wordcloud/query_integral_image.c"])],
packages=['wordcloud'],
package_data={'wordcloud': ['stopwords', 'DroidSansMono.ttf']}
)
|
liyongsea/DIGITS | scripts/test_generate_docs.py | Python | bsd-3-clause | 2,056 | 0.005837 | # Copyright (c) 2015, NVIDIA CORPORATION. All rights reserved.
import os.path
import sys
import tempfile
import itertools
import unittest
try:
import flask.ext.autodoc
except ImportError as e:
raise unittest.SkipTest('Flask-Autodoc not installed')
try:
import digits
except ImportError:
# Add path fo... | kage
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import digits.config; digits.config.load_config()
from digits.webapp import app, _doc as doc
from . import generate_docs as _
def check_doc_fi | le(generator, doc_filename):
"""
Checks that the output generated by generator matches the contents of doc_filename
"""
with tempfile.NamedTemporaryFile(suffix='.md') as tmp_file:
generator.generate(tmp_file.name)
tmp_file.seek(0)
with open(doc_filename) as doc_file:
... |
LyanJin/J_lyan | New.py | Python | epl-1.0 | 44 | 0.022727 | # -*- coding:u | tf8 -*-
| a = 3
b = 4
print a+b |
ffu/DSA-3.2.2 | gr-wxgui/src/python/forms/converters.py | Python | gpl-3.0 | 5,122 | 0.029871 | #
# Copyright 2009 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... | s.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import eng_notation
import math
class abstract_converter(object):
def extern... |
Azure/azure-sdk-for-python | sdk/eventhub/azure-eventhub/azure/eventhub/aio/_eventprocessor/event_processor.py | Python | mit | 18,174 | 0.002531 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | le[None]]
] = None,
| loop: Optional[asyncio.AbstractEventLoop] = None
):
self._consumer_group = consumer_group
self._eventhub_client = eventhub_client
self._namespace = (
eventhub_client._address.hostname # pylint: disable=protected-access
)
self._eventhub_name = eventhub_client.... |
Azure/azure-sdk-for-python | sdk/managementpartner/azure-mgmt-managementpartner/azure/mgmt/managementpartner/models/_models.py | Python | mit | 7,226 | 0.00083 | # 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 ... | partner operation.
:type operation: str
:param description: the is management partner operation description.
:type description: str
"""
_attribute_map = {
'provider': {'key': 'provider', 'type': 'str'},
'resource': {'key': 'resource', 'type': | 'str'},
'operation': {'key': 'operation', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(OperationDisplay, self).__init__(**kwargs)
self.provider = kwargs.get('provider', None)
self.resour... |
SonienTaegi/CELLAR | Browser/views/__init__.py | Python | gpl-2.0 | 672 | 0.013393 | from django.http.response import HttpResponse
from django.shortcuts import render_to_response, render
from Browser.models import | UserInfo |
from Browser.views import cellar, administrator
def simple_response(request, *args, **kwargs):
template_name = kwargs["path"]
if kwargs["type"] :
template_name = kwargs["type"] + "/" + template_name
userInfo = UserInfo.getUserInfo(request)
context = {
"isMetic" : userInfo.is... |
brandsoulmates/incubator-airflow | airflow/operators/aws_emr_operator.py | Python | apache-2.0 | 5,997 | 0.001834 | import logging
import shlex
import subprocess
import json
from airflow.hooks.aws_emr import EMRHook
from airflow.hooks.S3_hook import S3Hook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflow.exceptions import AirflowException
from slackclient import SlackClient
fr... | logging.info("output_id: " + output)
return output
def execute(self, context):
s3_hook = S3Hook()
for bucket, key in self.download_these_files:
print(bucket)
print(key)
basename = os.path.basename(key)
prin | t(basename)
print(os.path.join(self.dn_dir, basename))
local_path = os.path.join(self.dn_dir, basename)
s3_hook.download_file(bucket, key, local_path)
job_monitor = EMRHook(emr_conn_id="S3_default")
if self.start_cluster:
output_id = self.exec_command(sel... |
chainer/chainercv | tests/links_tests/model_tests/deeplab_tests/test_aspp.py | Python | mit | 975 | 0 | import unittest
import chainer
from chainer import testing
from chainer.testing import attr
from chainercv.links.model.deeplab import SeparableASPP
class TestSeparableASPP(unittest.TestCase):
def setUp(self):
| self.in_channels = 128
self.out_channels = 32
self.link = SeparableASPP(
self.in_channels, self.out_channels)
def check_call(self):
xp = self.link.xp
x = chainer.Variable(xp.random.uniform(
low=-1, high=1, size=(2, self.in_channels, 64, 64)
).a... | self.assertEqual(y.shape, (2, self.out_channels, 64, 64))
@attr.slow
def test_call_cpu(self):
self.check_call()
@attr.gpu
@attr.slow
def test_call_gpu(self):
self.link.to_gpu()
self.check_call()
testing.run_module(__name__, __file__)
|
grengojbo/st2 | st2client/st2client/formatters/table.py | Python | apache-2.0 | 8,219 | 0.001095 | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | get_attribute_value(subject, attribute):
if isins | tance(subject, dict):
r_val = subject.get(attribute, None)
else:
r_val = getattr(subject, attribute, None)
if r_val is None:
return ''
if isinstance(r_val, list) or isinstance(r_val, dict):
return r_val if len(r |
diofant/diofant | diofant/combinatorics/permutations.py | Python | bsd-3-clause | 72,579 | 0.000096 | import functools
import random
from collections import defaultdict
from mpmath.libmp.libintmath import ifac
from ..core import Basic, Tuple, sympify
from ..core.compatibility import as_int, is_sequence
from ..matrices import zeros
from ..polys import lcm
from ..utilities import flatten, has_dups, has_variety
from ..u... | n range(3)]
[2, 0, 1]
See Also
========
rmul, _af_rmuln
"""
return [a[i] for i in b]
def _af_rmuln(*abc):
"""
Given [a, b, c, ...] return the product of ...*c*b*a using array forms.
The ith value is a[b[c[i]]].
Examples
========
>>> Permutation.print_cyclic = False
... | [1, 2, 0]
This handles the operands in reverse order compared to the ``*`` operator:
>>> a = Permutation(a)
>>> b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]
See Also
========
rmul, _af_rmul
"""
a = abc
m = len(a)
if m =... |
Martin09/E-BeamPatterns | 100 Wafers - 1cm Squares/Multi-Use Pattern/v1.2/MembraneDesign_100Wafer_v1.1.py | Python | gpl-3.0 | 17,018 | 0.002585 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 14:11:31 2015
@author: Martin Friedl
"""
from datetime import date
import numpy as np
from Patterns.GrowthTheoryCell import make_theory_cell
from Patterns.GrowthTheoryCell_100_3BranchDevices import make_theory_cell_3br
from Patterns.GrowthTheoryCell_100_4BranchDevic... | positions:
pamm_cell.add(marker_arm, origin=[pos, 0], rotation=90) # Top arms
pamm_cell.add(marker_arm, origin=[-pos, 0], rotation=90)
pamm_cell.add(marker_arm, origin=[pos, 0], rotation=-90) # Bottom arms
pamm_cell.add(marker_arm, origin=[-p | os, 0], rotation=-90)
# Make the 4 tick marks that mark the center of the array
h = 30.
w = 100.
tick_mrk = Rectangle([-w / 2., -h / 2.], [w / 2, h / 2.], layer=l)
tick_mrk_cell = Cell("TickMark")
tick_mrk_cell.add(tick_mrk)
pos = mrkr... |
jrmi/pypeman | pypeman/tests/settings/test_settings_sqlite_persist.py | Python | apache-2.0 | 164 | 0.006098 | """
Persist | ence configuration
"""
|
PERSISTENCE_BACKEND = 'pypeman.persistence.SqliteBackend'
PERSISTENCE_CONFIG = {"path":'/tmp/to_be_removed_849827198746.sqlite'}
|
blckshrk/Weboob | modules/minutes20/test.py | Python | agpl-3.0 | 982 | 0 | # -*- coding: utf-8 -*-
# Copyright(C) 2010-2011 Romain Bignon
#
# This file is part of weboob.
#
# weboob 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 you... | ass Minutes20Test(Back | endTest):
BACKEND = 'minutes20'
def test_new_messages(self):
for message in self.backend.iter_unread_messages():
pass
|
andrewbird/wader | plugins/devices/zte_mf180.py | Python | gpl-2.0 | 1,826 | 0.001644 | # -*- coding: utf-8 -*-
# Copyright (C) 2011-2012 Vodafone España, S.A.
# Author: Andrew Bird
#
# 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 o... | 180Wrapper(ZTEWrapper):
def send_ussd(self, ussd):
"""Sends the ussd command ``ussd``"""
# XXX: assumes it's the | same as 637U
# MF180 wants request in ascii chars even though current
# set might be ucs2
return super(ZTEMF180Wrapper, self).send_ussd(ussd, force_ascii=True)
class ZTEMF180Customizer(ZTEWCDMACustomizer):
wrapper_klass = ZTEMF180Wrapper
class ZTEMF180(ZTEWCDMADevicePlugin):
""":cla... |
bh/python-ddns-zones-updater | tests/test_core.py | Python | gpl-2.0 | 1,816 | 0 | from __future__ import absolute_import, unicode_literals
import mock
import pytest
from ddns_zones_updater.configreader import ConfigReader
from ddns_zones_updater.core import DDNSZoneUpdater
@pytest.fixture
def fake_config_reader_with_two_hosts():
host_1 = mock.Mock(do_update=mock.Mock())
host_2 = mock.Moc... | ()
@pytest.fixture
def | updater_without_calling_init(request):
patcher = mock.patch.object(DDNSZoneUpdater, "__init__", return_value=None)
patcher.start()
request.addfinalizer(patcher.stop)
return DDNSZoneUpdater("path/to/config.ini")
@mock.patch.object(ConfigReader, "read")
@mock.patch.object(ConfigReader, "__init__", retu... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.0/Lib/test/test_urllibnet.py | Python | mit | 6,937 | 0.001586 | #!/usr/bin/env python
import unittest
from test import support
import socket
import urllib.request
import sys
import os
import email.message
def _open_with_retry(func, host, *args, **kwargs):
# Connecting to remote hosts is flaky. Make it more robust
# by retrying the connection several times.
last_exc... | self.assert_(os.path.exists(file_location))
FILE = open(file_location, encoding='utf-8')
try:
self.assert_(FILE.read(), "reading from temporary file failed")
finally:
FILE.close()
os.unlink(file_location)
def test_header(self):
# Make sure heade... | e is good.
file_location, header = self.urlretrieve("http://www.python.org/")
os.unlink(file_location)
self.assert_(isinstance(header, email.message.Message),
"header is not an instance of email.message.Message")
def test_main():
support.requires('network')
suppor... |
HackCigriculture/cigriculture-ml | src/polygon.py | Python | gpl-3.0 | 2,316 | 0.002159 | import json
with open('data/78mm.json', 'r') as _78mm:
polygons78 = json.load(_78mm)["features"][0]["geometry"]["geometries"]
with open('data/100mm.json', 'r') as _100mm:
polygons100 = json.load(_100mm)["features"][0]["geometry"]["geometries"]
with open('data/130mm.json', 'r') as _130mm:
polygons130 = json... | ;}
def ang(x1, y1, x2, y2):
return
def arg(x1, y1, x2, y2):
DB a=ang(x,y);return~dett(x,y)?a:2*PI-a;}
return
'''
def intersect(lx1, ly1, lx2, ly2, rx1, ry1, rx2, ry2):
return 1 if (dett(lx1, ly1, lx2, ly2, rx1, ry1) * dett(lx1, ly1, lx2, ly2, rx2, ry2) <= 0 and
dett(rx1, ry1, rx2, ry... | se 0
def within(p, x, y):
z = 0
for i in range(0, len(p)-1):
if x == p[i][0] and y == p[i][1]:
continue
if x == p[i+1][0] and y == p[i+1][1]:
continue
z += intersect(x, y, -3232, -4344, p[i][0], p[i][1], p[i+1][0], p[i+1][1])
return 1 if z % 2 == 1 else 0
... |
oscardbpucp/Comp-Process-STPatterns | clean_and_pretreatment/datos_total_fase1v3-mod.py | Python | gpl-3.0 | 13,307 | 0.007139 | ## Copyright (C) 2017 Oscar Diaz Barriga
## This file is part of Comp-Process-STPatterns.
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your op... | will be useful,
## but WITHOUT ANY WARRANTY; w | ithout even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
# /* Tumbes */
# select cou... |
klahnakoski/TestLog-ETL | vendor/jx_sqlite/schema.py | Python | mpl-2.0 | 4,659 | 0.001502 | # 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 __future__ import absolute_import, division, unicode_literals
from jx_base.queries import ... | n self.snowflake.namespace.columns.find(self.snowflake.fact_name)
def column(self, prefix):
full_name = untyped_column(concat_field(self.nested_path, prefix))
return set(
c
for c in self.snowflake.namespace.columns.find(self.snowflake.fact_name)
for k, t in [unty... | full_name = concat_field(self.nested_path, prefix)
return set(
c
for c in self.snowflake.namespace.columns.find(self.snowflake.fact_name)
for k in [c.name]
if startswith_field(k, full_name) and k != GUID or k == full_name
if c.jx_type not in [OBJECT, ... |
jrichte43/ProjectEuler | Problem-0364/solutions.py | Python | gpl-3.0 | 808 | 0.006188 |
__problem_title__ = "Comfortable distance"
__problem_url___ = "https://projecteuler.net/problem=364"
__problem_description__ = "There are seats in a row. people come after each other to fill the " \
"seats according to the following rules: We can verify that T(10) = " \
... | 094. Find T(1 000 000) mod " \
"100 000 007."
import timeit
class Solution():
@staticmethod
def solution1():
pass
@staticmethod |
def time_solutions():
setup = 'from __main__ import Solution'
print('Solution 1:', timeit.timeit('Solution.solution1()', setup=setup, number=1))
if __name__ == '__main__':
s = Solution()
print(s.solution1())
s.time_solutions()
|
Havate/havate-openstack | proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/dashboards/admin/instances/forms.py | Python | apache-2.0 | 3,609 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Kylin OS, 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
#
#... | ,
| initial)
def populate_host_choices(self, request, initial):
hosts = initial.get('hosts')
current_host = initial.get('current_host')
host_list = [(host.hypervisor_hostname,
host.hypervisor_hostname)
for host in hosts
... |
foone/3dmmInternals | generate/lib/pyudd.py | Python | unlicense | 17,726 | 0.007221 | # -*- coding: Latin-1 -*-
#!/usr/bin/env python
"""PyUdd, a python module for OllyDbg .UDD files
Ange Albertini 2010, Public domain
"""
__author__ = 'Ange Albertini'
__contact__ = 'ange@corkami.com'
__revision__ = "$Revision$"
__version__ = '0.1 r%d'
import struct
HDR_STRING = "Mod\x00"
FTR_STRING... | F_["DDSTRING"]), #
("US?", "\nUs?", F_["DDSTRING"]), #?
("TracCond", "\nUsM", F_["DDSTRING"]), # tracing condition
("LogExplanation", "\nUs<", F_["DDSTRING"]), # logging bp explanation
("AssumedArgs", "\nUs=", F_["DDSTRING"]), # Assumed arguments
("CFA", "\nCfa", F_["DD2"]),... | G"]), #?
("CFI", "\nCfi", F_["DD2"]), #?
("US>", "\nUs>", F_["BIN"]), #?
("ANC", "\nAnc", F_["BIN"]), #?
("JDT", "\nJdt", F_["BIN"]), #?
("PRC", "\nPrc", F_["BIN"]), #?
("SWI", "\nSwi", F_["BIN"]), #?
]
#OllyDbg 2
chunk_types20 = [
("... |
bewest/glucodump | glucodump/stream.py | Python | gpl-2.0 | 3,981 | 0.017332 | #!/usr/bin/python
import sys, os
import select, socket
import usbcomm
import usb
_default_host = 'localhost'
_default_port = 23200
_READ_ONLY = select.POLLIN | select.POLLPRI
class Stream(object):
def __init__(self,
host=_default_host,
port=_default_port):
self.host = host
self.port = por... | _READ_ONLY):
# A readable server socket is ready to accept a connection
if s is self.server:
connection, client_address = s.accept()
self.add_client(connection)
# Data from serial port
elif s is self.usb:
| data = s.read( )
for client in self.clients:
client.send(data)
# Data from client
else:
data = s.recv(80)
# Client has data
print "send to usb"
if data: self.usb.write(data)
# Interpr... |
mcallaghan/tmv | BasicBrowser/scoping/migrations/0048_auto_20170209_1708.py | Python | gpl-3.0 | 658 | 0.00152 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-02-09 17:08 |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class M | igration(migrations.Migration):
dependencies = [
('scoping', '0047_auto_20170209_1626'),
]
operations = [
migrations.RemoveField(
model_name='query',
name='technology',
),
migrations.AddField(
model_name='query',
name='technol... |
datacommonsorg/tools | stat_var_renaming/stat_var_renaming_constants.py | Python | apache-2.0 | 13,060 | 0.001914 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | tations under
# the License.
"""
This file contains various constants and helper code to generate constants
that are used in the Statistical Variable renaming.
"""
import pandas as pd
import collections
import re
def capitalizeFirst(word):
"" | " Capitalizes the first letter of a string. """
return word[0].upper() + word[1:]
def standard_name_remapper(orig_name):
""" General renaming function for long strings into Pascal case.
Text inbetween trailing parentheses is removed.
Commas, dashes, and "ands" are removed. Then string is converted i... |
opnsense/core | src/opnsense/service/configd_ctl.py | Python | bsd-2-clause | 5,598 | 0.004287 | #!/usr/local/bin/python3
"""
Copyright (c) 2015-2019 Ad Schellevis <ad@opnsense.org>
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 th... | S; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-------------------------------------... | --------------------------
package : configd
function: commandline tool to send commands to configd (response to stdout)
"""
import argparse
import socket
import os.path
import traceback
import sys
import syslog
import time
from select import select
from modules import syslog_error, syslog_notice
__author__ ... |
Geoportail-Luxembourg/geoportailv3 | geoportal/geoportailv3_geoportal/admin/admin.py | Python | mit | 178 | 0 | from c2cgeoportal_admin.views.layertree import itemtypes_tables
itemtypes_tables.update({
'lu_int_wms': 'lux_layer_ | internal_wms',
'lu_ext_wms': 'lux_layer_external_wms',
})
| |
google/starthinker | examples/dcm_run_example.py | Python | apache-2.0 | 3,107 | 0.011265 | ###########################################################################
#
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/l... | s as they happen.", action="store_true")
parser.add_argument("-auth_read", help="Credentials used for reading data.", default='user')
parser.add_argument("-account", help="CM network id.", default='')
parser.add_argument("-report_id", help="CM report id, empty if using name.", d | efault='')
parser.add_argument("-report_name", help="CM report name, empty if using id instead.", default='')
args = parser.parse_args()
config = Configuration(
project=args.project,
user=args.user,
service=args.service,
client=args.client,
key=args.key,
verbose=args.verbose
)
reci... |
nop33/indico | indico/modules/cephalopod/blueprint.py | Python | gpl-3.0 | 1,345 | 0.003717 | # This fi | le is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico 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.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received... |
cjgrady/compression | src/matrix/matrix.py | Python | gpl-2.0 | 3,131 | 0.023315 | """
@summary: Module contain matrix base classes
| @author: CJ Grady
@version | : 1.0
@status: alpha
@license: gpl2
@copyright: Copyright (C) 2014, University of Kansas Center for Research
Lifemapper Project, lifemapper [at] ku [dot] edu,
Biodiversity Institute,
1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA
This program is free software; you ca... |
PolyCortex/pyMuse | pymuse/pipeline.py | Python | mit | 2,987 | 0.001339 | from pymuse.pipelinestages.pipeline_stage import PipelineStage
from pymuse.utils.stoppablequeue import StoppableQueue
from pymuse.signal import Signal
from pymuse.constants import PIPELINE_QUEUE_SIZE
class PipelineFork():
"""
This class is used to fork a Pipeline. Ex.: PipelineFork([stage1, stage2], [stage3])... | def __init__(self, input_signal: Signal, *stages):
self._output_queues = []
self._stages: list = list(stages)
self._link_stages(self._stages)
self._stages[0]._queue_in = input_signal.signal_queue
def get_output_queue(self, queue_index=0) -> StoppableQueue:
"""Return a ref... | ven by queue_index"""
return self._output_queues[queue_index].get()
def start(self):
"""Start all pipelines stages."""
self._start(self._stages)
def shutdown(self):
""" shutdowns every child thread (PipelineStage)"""
self._shutdown(self._stages)
def join(self):
... |
openstack/trove | trove/guestagent/common/guestagent_utils.py | Python | apache-2.0 | 5,574 | 0 | # Copyright 2015 Tesora Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | + [k], namespace_sep))
else:
ns = namespace_sep.join(keys)
flattened[ns] = target
return flattened
return flatten(target, [], namespace_sep)
def build_file_path(base_dir, base_name, *extensions):
"""Build a path to a file in a given directory.
The file may have a... | .ext2.ext3'
"""
file_name = os.extsep.join([base_name] + list(extensions))
return os.path.expanduser(os.path.join(base_dir, file_name))
def to_bytes(value):
"""Convert numbers with a byte suffix to bytes.
"""
if isinstance(value, str):
pattern = re.compile(r'^(\d+)([K,M,G]{1})$')
... |
mathLab/RBniCS | tests/unit/backends/dolfin/test_tensor_io.py | Python | lgpl-3.0 | 5,343 | 0.001684 | # Copyright (C) 2015-2022 by the RBniCS authors
#
# This file is part of RBniCS.
#
# SPDX-License-Identifier: LGPL-3.0-or-later
import pytest
from numpy import isclose
from dolfin import (assemble, dx, FiniteElement, FunctionSpace, inner, MixedElement, split, TestFunction,
TrialFunction, UnitSquare... | t_0 = VectorElement("Lagrange", mesh.ufl_cell(), 2)
element_1 = F | initeElement("Lagrange", mesh.ufl_cell(), 1)
element = MixedElement(element_0, element_1)
return (FunctionSpace(mesh, element), )
def generate_mixed_linear_form(V):
v = TestFunction(V)
(v_0, v_1) = split(v)
return v_0[0] * dx + v_0[1] * dx + v_1 * dx
def generate_mixed_bilinear_form_space(mesh):... |
timberline-secondary/hackerspace | src/profile_manager/migrations/0005_profile_get_messages_by_email.py | Python | gpl-3.0 | 484 | 0.002066 | # Generated by Django 2.0.13 on 2019-08-10 20:16
f | rom django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profile_manager', '0004_auto_20190729_2101'),
]
operations = [
migrations.AddField(
model_name='profile',
name='get_messages_by_ema | il',
field=models.BooleanField(default=True, help_text='If your teacher sends you a message, get an instance email.'),
),
]
|
zbyte64/django-dockit | dockit/backends/djangodocument/migrations/0002_auto__chg_field_registeredindex_query_hash.py | Python | bsd-3-clause | 7,475 | 0.007358 | # -*- 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):
# Changing field 'RegisteredIndex.query_hash'
db.alter_column('djangodocument_registeredindex', 'query_hash... | 'primary_key': 'True'}),
'param_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'db_index': 'True'}),
'value': ('django.db.models.fields.DateField', [], {'null': 'True'})
},
'djangodocument.datetimeindex': {
| 'Meta': {'object_name': 'DateTimeIndex'},
'document': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['djangodocument.RegisteredIndexDocument']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'param_name': ('django.db.models.fields... |
pkimber/kbsoftware_couk | settings/dev_test.py | Python | apache-2.0 | 247 | 0 | from .local import *
| DATABASES = {
'default': {
| 'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'temp.db',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
OPBEAT['APP_ID'] = None
|
Etxea/gestioneide | gestioneide/migrations/0020_auto_20160523_1329.py | Python | gpl-3.0 | 471 | 0 | # | -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-05-23 11:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gestioneide', '0019_auto_20160517_2232'),
]
operations = [
migrations.AlterFi... | ]
|
myth/trashcan | it3708/project3/modules/__init__.py | Python | gpl-2.0 | 116 | 0 | # -*- co | ding: utf8 -*-
#
# Created by 'myth' on 2/19/16
import matplotlib as mpl
import set | tings
mpl.use('TkAgg')
|
andela-bojengwa/team3 | monitorbot_api/app/main/users.py | Python | mit | 3,988 | 0.007773 | import json
from flask import g, jsonify, request, current_app, url_for
from ..models import User
from .. import db
from . import main
from .authentication import auth_user
from .errors import bad_request, unauthorized, forbidden, not_found
"""read all"""
@main.route('/<token>/users/', methods=['GET']) ... | orized("You have to be logged in to perform this action")
# get and return all:
users = User. | query.all()
list_of_dicts = [json.loads(user.to_json()) for user in users]
return json.dumps(list_of_dicts)
"""read one"""
@main.route('/<token>/users/<int:id>/', methods=['GET'])
def get_user(token, id):
if not auth_user(token):
return unauthorized("You have to be logged in to perform this actio... |
VandroiyLabs/FaroresWind | faroreswind/collector/ElectronicNose.py | Python | gpl-3.0 | 2,352 | 0.019133 | import serial
import numpy as np
import json
from datetime import datetime
class ElectronicNose:
def __init__(self, devAdd='/dev/ttyUSB0', baudrate=115200/3, \
tmax = 1000, outputFile = '', numSensors = 8):
## Creating the serial object
self.Sensor = serial.Serial(devAdd, baud... | avg[0,1:] += self.convert( r.split('\rV')[1].split(' | \n')[0][8:39] )
if nsamples_ > 0:
avg = avg/float(nsamples_)
now = datetime.now()
avg[0,0] = now.hour*3600 + now.minute*60 + now.second + now.microsecond/1.e6
self.memory = np.concatenate( (self.memory, np.reshape(avg, (1,11)) ), axis=0 )
return
... |
1ukash/horizon | horizon/dashboards/project/volumes/tests.py | Python | apache-2.0 | 14,507 | 0.001103 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... | n compliance with the License. You may obtain
# a copy of the License at
#
# http: | //www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing p... |
ellmetha/django-machina | tests/_testsite/apps/forum_conversation/migrations/0010_auto_20170120_0224.py | Python | bsd-3-clause | 644 | 0.001553 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-20 01:24
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| dependencies = [
('forum_conversation', '0009_auto_20160925_2126'),
]
operations = [
migrations.AlterField(
m | odel_name='topic',
name='first_post',
field=models.ForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='forum_conversation.Post', verbose_name='First post'),
),
]
|
PyQuake/earthquakemodels | code/gaModel/parallelGAModelP_AVR.py | Python | bsd-3-clause | 6,277 | 0.035686 | """
This GA code creates the gaModel with a circular island model
"""
from operator import attrgetter
# import sys
from deap import base, creator, tools
import numpy
from csep.loglikelihood import calcLogLikelihood as loglikelihood
from models.mathUtil import calcNumberBins
import models.model
import random
import arr... | #logBook
record = stats.compile(pop)
logbook.record(gen=g, **record)
# choose the best value
if rank == 0:
best_pop=tools.selBest(pop, 1)[0]
best_all_pop = list()
best_all_pop.append(best_pop)
for thread in range(size):
if (thread != 0):
# local_best = comm.recv(source=thread)
local_best = ... | est = req.wait()
best_all_pop.append(local_best)
maximum = float('-inf')
# for value, index in zip(best_all_pop, range(len(best_all_pop))):
for local_best in best_all_pop:
local_maximum = evaluationFunction(local_best, modelOmega, mean)
if maximum < local_maximum[0]:
# theBestIndex = index
maxi... |
PierreBdR/point_tracker | doc/source/conf.py | Python | gpl-2.0 | 7,170 | 0.006834 | # -*- coding: utf-8 -*-
#
# Point Tracker documentation build configuration file, created by
# sphinx-quickstart on Mon Oct 25 14:10:24 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#... | css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = Tru... | names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages... |
chris-j-tang/GLS | test/integration/ConstructorStart/simple.py | Python | mit | 24 | 0.083333 | -
d | ef __init__(self) | :
-
|
odin1314/sketchy | sketchy/controllers/tasks.py | Python | apache-2.0 | 16,270 | 0.004856 | # Copyright 2014 Netflix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | else:
c | apture_record.capture_status = '%s HTTP STATUS CODE' % (response.status_code)
# If URL doesn't return a valid status code or times out, raise an exception
except Exception as err:
capture_record.job_status = 'RETRY'
capture_record.capture_status = str(err)
capture_record.url_response_cod... |
jaredhasenklein/the-blue-alliance | tests/suggestions/test_media_url_parse.py | Python | mit | 9,927 | 0.004533 | import json
import unittest2
from google.appengine.ext import testbed
from consts.media_type import MediaType
from helpers.media_helper import MediaParser
from helpers.webcast_helper import WebcastParser
class TestMediaUrlParser(unittest2.TestCase):
def setUp(cls):
cls.testbed = testbed.Testbed()
... | self.assertEqual(details['model_image'], 'https://d2t1xqejof9utc.cloudfront.net/screenshots/pics/96268d5c5e6c1b7fe8892f713813bb40/card.jpg')
self.assertEqual(details['model_created'], '2016-09-19T11:52:23Z')
def test_instagram_image(self):
result = MediaParser.partial_media_dict_from_url("https://w... | aType.INSTAGRAM_IMAGE)
self.assertEqual(result['foreign_key'], "BUnZiriBYre")
details = json.loads(result['details_json'])
self.assertEqual(details['title'], "FRC 195 @ 2017 Battlecry @ WPI")
self.assertEqual(details['author_name'], '1stroboticsrocks')
self.assertIsNotNone(detail... |
guillaumelenoir/WAVEPAL | wavepal/tapering_window.py | Python | mit | 2,207 | 0.043045 | import numpy as np
from scipy.special import iv
def tapering_window(time,D,mywindow):
""" tapering_window returns the window for tapering a WOSA segment.
Inputs:
- time [1-dim numpy array of floats]: times along the WOSA segment.
- D [float]: Temporal length of the WOSA segment.
- mywindow [int]: Choice of ... | ow, defined as 0.54-0.46*np.cos(2.0*np.pi*time/D)
-> 8: 4-term Blackman-Harris window, with a0=0.35875 and a1=0.48829 and a2=0.14128 and a3=0.01168
-> 9: Kaiser-Bessel window, with parameter alpha=2.5
-> 1 | 0: Gaussian window, with standard dev. sigma=D/6.0
The terminology and formulas come from:
F. Harris. On the use of windows for harmonic analysis with the discrete fourier transform. Proceedings of the IEEE, 66(1):51-83, January 1978.
WARNING: Provide the vector 'time' such that for all k=0,...,time.size-1, we ha... |
Drob-AI/music-queue-rec | src/playlistsRecomender/gaPlaylistGenerator/__init__.py | Python | mit | 25 | 0.04 | from ga_star | ters | import * |
Thetoxicarcade/ac | congredi/utils/test/test_progress.py | Python | gpl-3.0 | 391 | 0 | #!/usr/bin/env | python
# -*- coding: utf-8 -*-
"""
progress test (count to 1000)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from ...utils.timing import TimedTestCase
from ..progress import together
class test_progress(Timed | TestCase):
def test_prog(self):
self.threshold = 0.1
together(1000)
|
lmazuel/azure-sdk-for-python | azure-servicefabric/azure/servicefabric/service_fabric_client_ap_is.py | Python | mit | 582,969 | 0.001683 | # 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 ... | er include i | nteger value obtained
from members or bitwise operations
on members of HealthStateFilter enumeration. Only applications that
match the filter are returned.
All applications are used to evaluate th |
ThomasTheSpaceFox/Desutezeoid | plugins/test2.dzup.py | Python | gpl-3.0 | 1,889 | 0.044997 | #!/usr/bin/env python
class PLUGIN_test_test2:
def __init__(self, screensurf, keylist, | vartree):
self.screensurf=screensurf
self.keylist=keylist
#best practice to init keyid variables during init, and default them to "0" (the null keyid)
self.keyid="0"
def fork(self, tagobj):
return
#core object. should either return None, or pygame Rect.
#if Rect is returned, the system will attempt to pars... | omponent, and associated related attributes...
#you may also want to use the provided click events in place of the standard act component.
#if you want hoverkey to be active, you MUST return a Rect!
#onkey/offkey masking is honored by the system regardless.
def core(self, tagobj):
if tagobj.tag=="test2":
self.... |
taogeT/flask-celery | example/celery_run.py | Python | bsd-2-clause | 101 | 0 | #!/us | r/bin/env python
# -*- coding: UTF-8 -*-
from app import create_app, celery
app = create_ap | p()
|
join2saurav/Lexical-syntax-semantic-analysis-of-Hindi-text- | test10.py | Python | apache-2.0 | 256 | 0.019531 | import collections
g=open("depth_29.txt","w")
with open('depth_28.txt') as infile:
counts = collections.Counter(l.strip() for l in infile)
|
for line, count in counts.most_common():
g.write(str(line))
| #g.write(str(count))
g.write("\n") |
thebjorn/dkcoverage | setup.py | Python | gpl-2.0 | 285 | 0 | from distutils.core import setup
setup(
name='dkcoverage',
version='0.0.0',
packages=[''],
url='https://github.com/thebjorn/dkc | overage',
license='GPL v2',
author='bjorn',
author_email='bp@datakor | tet.no',
description='Run tests and compute coverage.'
)
|
anhstudios/swganh | data/scripts/templates/object/mobile/shared_shear_mite_broodling.py | Python | mit | 444 | 0.047297 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS | MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_shear_mite_broodling.iff"
result.attribute_template_id = 9
result.stfName("monster_name","shear_mite")
#### BEGIN ... | rn result |
robertbreker/sm | drivers/devscan.py | Python | lgpl-2.1 | 14,406 | 0.00833 | #!/usr/bin/env python
#
# Copyright (C) Citrix Systems Inc.
#
# 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; version 2.1 only.
#
# This program is distributed in the hope that it will ... | for line in util.doexec(cmd)[1].split('\n'):
if line.find(arr) != -1:
rec = line.split()[0]
cmd2 = ['/usr/sbin/mppUtil', '-g',rec]
li = []
for newline in util.doexec(cmd2)[1].split | ('\n'):
if newline.find('hostId') != -1:
li.append(_parseHostId(newline))
mppdict[dev.split('/')[-1]] = li
except:
continue
return mppdict
def match_hbadevs(s, filterstr):
driver_name = _get_driver_n... |
welch/rasl | tests/inner_test.py | Python | mit | 4,843 | 0.00351 | # test rasl inner loop on simulated data
#
# pylint:disable=import-error
from __future__ import division, print_function
import numpy as np
from rasl.inner import inner_ialm
from rasl import (warp_image_gradient, EuclideanTransform,
SimilarityTransform, AffineTransform, ProjectiveTransform)
def setup... | 2 - 1) * dx, |
(np.random.random() * 2 - 1) * dtheta,
(np.random.random() * 2 - 1) * ds + 1,
(np.random.random() * 2 - 1) * dx,
(np.random.random() * 2 - 1) * dh,
(np.random.random() * 2 - 1) * dh]
for _ in range(N)]
inner_jittered([Pr... |
cigroup-ol/metaopt | metaopt/objective/integer/failing/__init__.py | Python | bsd-3-clause | 209 | 0 | # -*- coding: utf-8 -*-
"""
Package of failing integer functi | ons.
"""
from metaopt.objective.integer.failing.f import | f as f
from metaopt.objective.integer.failing.g import f as g
FUNCTIONS_FAILING = [f, g]
|
coreycb/horizon | openstack_dashboard/test/integration_tests/tests/test_floatingips.py | Python | apache-2.0 | 4,543 | 0 | # Copyright 2015 Hewlett-Packard Development Company, L.P
# 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.... | lpers.TestCase):
"""Checks that the user is able to allocate/release floatingip."""
def test_floatingip(self):
floatingip_page = \
self.home_pg.go_to_compute_accessandsecurity_floatingipspage()
floating_ip = floatingip_page.allocate_f | loatingip()
self.assertTrue(
floatingip_page.find_message_and_dismiss(messages.SUCCESS))
self.assertFalse(
floatingip_page.find_message_and_dismiss(messages.ERROR))
self.assertTrue(floatingip_page.is_floatingip_present(floating_ip))
floatingip_page.release_floati... |
uw-it-aca/myuw | myuw/views/page.py | Python | apache-2.0 | 6,010 | 0 | # Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
import logging
import traceback
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from django.contrib.auth import logout as django_logout
from restclients_core.exceptions import DataFailu... | from myuw.dao import is_action_disabled
from myuw.dao.affiliation import get_all_affiliations
from myuw.dao.em | aillink import get_service_url_for_address
from myuw.dao.exceptions import (
EmailServiceUrlException, BlockedNetidErr)
from myuw.dao.gws import in_myuw_test_access_group
from myuw.dao.quicklinks import get_quicklink_data
from myuw.dao.card_display_dates import get_card_visibilty_date_values
from myuw.dao.messages ... |
rusenask/stubo-app | stubo/static/cmds/tests/ext/auto_mangle/skip_xml/ignore.py | Python | gpl-3.0 | 867 | 0.00692 | import logging
from stubo.ext.xmlutils import XPathValue
from stubo.ext.xmlexit import XMLManglerExit
log = logging.getLogger(__name__)
elements = dict(year=XPathValue('//dispatchTime/dateTime/year'),
month=XPathValue('//dispatchTime/dateTime/month'),
day=XPathValue('//dispatchTime/dat... | its(request, context):
ret | urn ignore.get_exit(request, context)
|
GeotrekCE/Geotrek-admin | geotrek/core/migrations/0001_initial.py | Python | bsd-2-clause | 14,022 | 0.004921 | from django.conf import settings
from django.db import migrations, models
import mapentity.models
import django.contrib.gis.db.models.fields
import django.db.models.deletion
import geotrek.common.mixins
import geotrek.authent.models
class Migration(migrations.Migration):
dependencies = [
('authent', '000... | options={
'ordering': ['source'],
'db_table': 'l_b_source_troncon',
'verbose_name': 'Path source',
'verbose_name_plural': 'Path sources',
},
),
migrations.CreateModel(
name='Stake',
fields=[
... | umn='enjeu')),
('structure', models.ForeignKey(db_column='structure', on_delete=django.db.models.deletion.CASCADE, default=geotrek.authent.models.default_structure_pk, verbose_name='Related structure', to='authent.Structure')),
],
options={
'ordering': ['id'],
... |
motealle/python | 01.py | Python | gpl-2.0 | 53 | 0 | a = ' | sdlbapm'
b = 'alam'
for d in a:
pr | int d + b
|
dario-chiappetta/Due | due/models/test_tfidf.py | Python | gpl-3.0 | 3,631 | 0.024787 | import unittest
from datetime import datetime
import tempfile
import os
from due.agent import Agent
from due.episode import Episode
from due.event import Event
from due.persistence import serialize, deserialize
fr | om due.models.tfidf import TfIdfAgent
from due.models.dummy im | port DummyAgent
class TestTfIdfAgent(unittest.TestCase):
def test_save_load(self):
agent = TfIdfAgent()
agent.learn_episodes(_get_train_episodes())
saved_agent = agent.save()
with tempfile.TemporaryDirectory() as temp_dir:
path = os.path.join(temp_dir, 'serialized_tfidf_agent.due')
serialize(saved_ag... |
florence-nocca/spanish-elections | retrieve-accounts/searx.py | Python | mit | 4,109 | 0.004138 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unicodedata
from urlparse import urlparse
from threading import Thread
import httplib, sys
from Queue import Queue
import itertools
import codecs
import csv
import sys
import ssl
import re
if len(sys.argv) < 3:
print "Usage: %s <csv database> <out csv>" % (sys.argv... | s, region, party = q.get()
clean_names = cleanNames(stripAccents(names).split(" "))
handles = []
for comb in allCombinations(clean_names):
query = | comb.replace(" ", "+") + "+" + region + "+" + party + "+site:twitter.com"
url = base + "/?format=csv&q=" + query
fetchHandles(url, handles)
with codecs.open(sys.argv[2], "a", "utf-8") as out:
out.write("%s, %s\n" % (names, handles))
print "%s, %s" % (names, handles)
... |
Kate-Willett/HadISDH_Build | TestLeap.py | Python | cc0-1.0 | 632 | 0.006329 | #!/usr/local/sci/bin/python
# PYTHON2.7
# import TestLeap
# TestVal = TestLeap.TestLeap(year)
import numpy as np
def TestLeap(year):
'''function to test if a year is a leap year'''
'''returns 0.0 if it is a leap year'''
'''returns a non-zero number if it is not a leap year'''
'''ONLY WORKS WITH SCAL... | np.round(year/4.)
# second test - if it is divisible by 100 | . then is it also divisible by 400?
if (((year/100.) - np.round(year/100.)) == 0.):
leapoo = leapoo + ((year/400.) - np.round(year/400.))
return leapoo
|
colinsheppard/beam | aws/src/main/python/updateBeamAMI/lambda_function.py | Python | gpl-3.0 | 2,524 | 0.009113 | # coding=utf-8
import time
import json
import boto3
from botocore.errorfactory import ClientError
def lambda_handler(event, context):
instance_id = event.get('instance_id')
region_id = event.get('region_id', 'us-east-2')
image_name = 'beam-automation-'+time.strftime("%Y-%m-%d-%H%M%S", time.gmtime())
... | opy_image(Name=image_name,
SourceImageId=image_id,
| SourceRegion='us-east-2')
# wait4image(ec2, res['ImageId'])
return res['ImageId']
def wait4image(ec2, image_id):
waiter = ec2.get_waiter('image_available')
waiter.wait(Filters=[{'Name': 'state', 'Values': ['available']}],
ImageIds=[image_id])
def u... |
kaji-project/pynag | pynag/Parsers/__init__.py | Python | gpl-2.0 | 129,457 | 0.001808 | # -*- coding: utf-8 -*-
#
# pynag - Python Nagios plug-in and configuration environment
# Copyright (C) 2010 Drew Stinnet
#
# 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 th... | se this function if you don't want specify path to the nagios binary
in your code and you are confident that it is located in a common
location
Checked locations are as follows:
* /usr/bin/nagios
* /usr/sbin/nagios
* /usr/local/ | nagios/bin/nagios
* /nagios/bin/nagios
* /usr/bin/icinga
* /usr/sbin/icinga
* /usr/bin/naemon
* /usr/sbin/naemon
* /usr/local/naemon/bin/naemon.cfg
* /usr/bin/shinken
* /usr/sbin/shinken
Returns:
str. Path to the nagios binary
... |
evan-rusin/fly-project | mygoals/views.py | Python | bsd-2-clause | 6,398 | 0.00297 | from datetime import datetime, timedelta, timezone
from django.shortcuts import render
from django.core.management import call_command
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext_lazy as _
from fly_project import set... | count_days_between_today_and(dt2):
# Detect whether the unlocked time has elapsed and load the appropriate
# UI associated with this.
now = datetime.now(timezone.utc) # Standardize date to a specific time-zone
# Count how many days are left | from today to the unlocked date.
return count_days_between(now,dt2)
@login_required(login_url='/authentication')
def mygoals_page(request):
return render(request, 'mygoals/type/view.html',{
'settings': settings,
})
@login_required(login_url='/authentication')
def savings_goals_page(request):
... |
quantumlib/Cirq | cirq-google/cirq_google/line/placement/optimization.py | Python | apache-2.0 | 4,663 | 0.001501 | # Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | at],
temp_initial: float = 1.0e-2,
te | mp_final: float = 1e-6,
cooling_factor: float = 0.99,
repeat: int = 100,
trace_func: Callable[[T, float, float, float, bool], None] = None,
) -> T:
"""Minimize solution using Simulated Annealing meta-heuristic.
Args:
initial: Initial solution of type T to the problem.
cost_func: Cal... |
buchwj/xvector | client/xVClient/ErrorReporting.py | Python | gpl-3.0 | 4,145 | 0.002413 | # xVector Engine Client
# Copyright (c) 2011 James Buchwald
# 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 pr... | in Qt message boxes.
'''
def __init__(self, parent=None):
'''
Creates a new handler.
@type parent: QtGui.QWi | dget
@param parent: Parent widget for errors to be displayed under.
'''
super(ErrorMessageHandler,self).__init__()
self.Parent = parent
'''Parent widget for errors to be displayed under.'''
def _ShowError(self, message):
'''
Shows an error message and ret... |
melvin0008/pythoncodestrial | trybs4.py | Python | apache-2.0 | 697 | 0.030129 | from bs4 import BeautifulSoup
import xlsxwriter
workbook= xlsxwriter.Workbook("data.xlsx")
worksheet = workbook.add_worksheet()
f = open('rough.html',"r")
data=f.read()
soup=BeautifulSoup(data)
div = soup.find('div', {"class":'dataTables_scroll'})
table=div.find('table')
tbody=div.find('tbody')
rows=tbody.find_all('tr... | et.write(rowno, 3, a[3].text)
worksheet.write(rowno, 4, a[4].text)
worksheet.write(rowno, 5, a[3].text)
worksheet.write(rowno, 6, td | [6].text)
rowno=rowno+1
workbook.close()
print "Done"
|
DailyActie/Surrogate-Model | 01-codes/scikit-learn-master/sklearn/datasets/setup.py | Python | mit | 658 | 0 | import os
import numpy
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('datasets', parent_package, top | _path)
config.add_data_dir('data')
config.add_data_dir('descr')
config.add_data_dir('images')
config.add_data_dir(os.path.join('tests', 'data'))
config.add_extension('_svmlight_format',
sources=['_svmlight_format.c'],
include_dirs=[numpy.get_include(... | setup(**configuration(top_path='').todict())
|
jwodder/qypi | test/test_main.py | Python | mit | 30,735 | 0.000488 | import json
from traceback import format_exception
from click.testing import CliRunner
import pytest
from qypi.__main__ import qypi
def show_result(r):
if r.exception is not None:
return "".join(format_exception(*r.exc_info))
else:
return r.output
def test_list(mocker):
spinstance = mock... | ["Maintainer", "quux"],
],
}
)
spclass = mocker.patch("qypi.api.ServerProxy", return_value=spinstance)
r = CliRunner().invoke(qypi, ["owned", "luser"])
assert r.exit_code == 0, show_result(r)
assert r.output == (
"{\n"
' "luser": [\n'
" {\n... | "role": "Owner"\n'
" },\n"
" {\n"
' "package": "quux",\n'
' "role": "Maintainer"\n'
" }\n"
" ]\n"
"}\n"
)
spclass.assert_called_once_with("https://pypi.org/pypi")
assert spinstance.method_calls == [mocker... |
wang1352083/pythontool | python-2.7.12-lib/test/test_extcall.py | Python | mit | 7,975 | 0.000251 | # -*- coding: utf-8 -*-
"""Doctest for method/function calls.
We're going the use these types for extra testing
>>> from UserList import UserList
>>> from UserDict import UserDict
We're defining four helper functions
>>> def e(a,b):
... print a, b
>>> def f(*a, **k):
... print a, t... | ter ** must be a mapping, not function
>>> None(**h)
Traceback (most recent call last):
...
TypeError: NoneType object argument after ** must be a mapping, \
not function
>>> dir(b=1, **{'b': 1})
Traceback (most recent call last):
... |
TypeError: dir() got multiple values for keyword argument 'b'
Another helper function
>>> def f2(*a, **b):
... return a, b
>>> d = {}
>>> for i in xrange(512):
... key = 'k%d' % i
... d[key] = i
>>> a, b = f2(1, *(2,3), **d)
>>> len(a), len(b), b == d
(3, 512, Tr... |
sebnorth/extended_user | mysite/settings.py | Python | bsd-3-clause | 5,917 | 0.001183 | import os
# Django settings for mysite project.
DEBUG = True
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
SITE_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
DATABASES = {
'default': {
'ENGINE... | CKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(SITE_ROOT, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
# list if you haven't customize... | s.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
... |
wangxiangyu/horizon | openstack_dashboard/test/api_tests/nova_rest_tests.py | Python | apache-2.0 | 11,121 | 0 | # Copyright 2014, Rackspace, US, 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 agreed to in w... | '{"items": [{"id": "one"}, {"id": "two"}]}')
nc.keypair_list.assert_called_once_with(request)
@mock.patch.object(nova.api, 'nova')
def test_keypair_create(self, nc):
request = self.mock_rest_request(body='''{"name": "Ni!"}''')
new = nc.keypair_create.return_value
new.to_dict... | n_value = {'name': 'Ni!', 'public_key': 'sekrit'}
new.name = 'Ni!'
with mock.patch.object(settings, 'DEBUG', True):
response = nova.Keypairs().post(request)
self.assertStatusCode(response, 201)
self.assertEqual(response.content,
'{"name": "Ni!", "publ... |
clovemfeng/studydemo | 20140617/userlist_data.py | Python | gpl-2.0 | 657 | 0.024353 | #!/usr/bin/python3
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
retu | rn(time_string)
(mins, secs) = time_string.strip().split(splitter)
return(mins + '.' + secs)
def get_coach_data(filename):
try:
with open(filename) as fn:
data = fn.readline()
return(data.strip().split(','))
except IOError as ioerr:
print('File Error:' + str(ioerr))
return(None)
sarah ... | ah]))[0:3]))
|
donkeysharp/elvispy | elvis/climanager.py | Python | mit | 889 | 0.00225 | import os
def create_peanut(peanut_name):
peanut_dir = './peanuts/%s' % peanut_name
if os.path.exists(peanut_dir):
print('Peanut already exists')
return
os.mkdir(peanut_dir)
os.mkdir(peanut_dir | + '/templates')
f = open(peanut_dir + '/__init__.py', 'w')
f.write('')
f.flush()
f.close()
f = open(peanut_dir + '/main.py', 'w')
f.write('\n__META__ = {\n')
f.write(" 'displayName': '%s',\n" % peanut_name)
f.write(" 'description': 'Peanut description',\n")
f. | write(" 'version': '0.1',\n")
f.write(" 'enabled': True,\n")
f.write("}\n\n")
f.write('def load(peanut):\n')
f.write(" print('Loading peanut %s')\n" % peanut_name)
f.flush()
f.close()
def clean():
if os.path.exists('./.__tmp__') and os.path.isdir('./.__tmp__'):
import shuti... |
RESTfactory/presence | presence/migrations/0002_session.py | Python | gpl-3.0 | 830 | 0.00241 | # -*- c | oding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-11-03 14:52
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| dependencies = [
('presence', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Session',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('start', models.DateTimeF... |
tortugueta/multilayers | multilayers.py | Python | gpl-3.0 | 70,824 | 0.000706 | # -*- coding: utf-8 -*-
"""
Name : multilayers
Author : Joan Juvert <trust.no.one.51@gmail.com>
Version : 1.0
Description : A class library to simulate light propagation in
: multilayer systems.
Copyright 2012 Joan Juvert
This program is free software: you can redistribute it and... | cterize the index of refraction
of the medium.
comments : str, optional
The character used t | o indicate the start of a comment;
default: '#'.
delimiter : str, optional
The string used to separate values. By default, this is any
whitespace.
converters : dict, optional
A dictionary mapping column number to a function that will
convert t... |
meisamhe/GPLshared | Programming/MPI — AMath 483 583, Spring 2013 1.0 documentation_files/average_top_3_scores.py | Python | gpl-3.0 | 1,767 | 0.001132 | import sys
import operator
import collections
import random
import string
import heapq
# @include
def | find_student_with_highest_best_of_three_scores(name_score_data):
student_scores = collections.defaultdict(list)
for line in name_score_data:
name, score = lin | e.split()
if len(student_scores[name]) < 3:
heapq.heappush(student_scores[name], int(score))
else:
heapq.heappushpop(student_scores[name], int(score))
return max([(sum(scores), name) for name, scores in student_scores.items()
if len(scores) == 3],
... |
meantheory/dotfiles | dos/src/dos/config.py | Python | mit | 2,504 | 0.000799 | from pathlib import Path
import os
import structlog
log = structlog.get_logger()
_config = None
def get():
global _config
if not isinstance(_config, _build_config):
_config = _build_config()
return _config
class _build_config:
def __init__(self):
self._config = {}
self.dos... | one)
def put(self, key, value, context="default"):
self.add_config_value(key, value, context=context)
def check(self, key):
| return key in self._config
def add_config_value(self, key, value, context="default"):
ctx_key = f"{context}_{key}"
self._config[ctx_key] = value
log.debug("set config", context=context, key=key, ctx_key=ctx_key)
def add_path_value(self, key, value, context):
self.add_config_v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.