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 |
|---|---|---|---|---|---|---|---|---|
rfleschenberg/django-shop | shop/rest/renderers.py | Python | bsd-3-clause | 1,657 | 0.003018 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.template import RequestContext
from rest_framework import re | nderers
class CMSPageRenderer(renderers.TemplateHTMLRenderer):
"""
Modified TemplateHTMLRenderer, which is able to render CMS pages containing the templatetag
`{% render_placeholder ... %}`, and which accept ordinary Python objects in th | eir rendering
context.
The serialized data object, as available to other REST renderers, is explicitly added to the
context as ``data``. Therefore keep in mind that templates for REST's `TemplateHTMLRenderer`
are not compatible with this renderer.
"""
def render(self, data, accepted_media_type=N... |
dol-sen/portage | pym/_emerge/PackageArg.py | Python | gpl-2.0 | 689 | 0.015965 | # Copyright 1999-2011 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
from _eme | rge.DependencyArg import DependencyArg
from _emerge.Package import Package
import portage
from portage._sets.base import InternalPackageSet
from portage.dep import _repo_separator
class PackageArg(DependencyArg):
def __init__(self, package=None, **kwargs):
DependencyArg.__init__(self, **kwargs)
self.package = pac... | epo=True)
self.pset = InternalPackageSet(initial_atoms=(self.atom,),
allow_repo=True)
|
KhronosGroup/COLLADA-CTS | Scripts/FMaya.py | Python | mit | 16,662 | 0.006482 | # Copyright (c) 2012 The Khronos Group Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publis... | nScript(workingDir) -> None
Implements FApplication.BeginScript()
"""
melFilename = ("script" + str(self.applicationIndex) +
FMaya.__MEL_SCRIPT_EXTENSION)
pyFilename = ("script" + str(self.applicationIndex) +
| FMaya.__SCRIPT_EXTENSION)
self.__melScript = open(os.path.join(workingDir, melFilename) , "w")
self.__script = open(os.path.join(workingDir, pyFilename), "w")
self.WriteCrashDetectBegin(self.__script)
self.__melScript.write(
"int $descriptor;\n" +
... |
clouserw/zamboni | mkt/ratings/tests/test_views.py | Python | bsd-3-clause | 32,940 | 0 | # -*- coding: utf-8 -*-
from datetime import datetime
import json
from urlparse import urlparse
from django.core.urlresolvers import reverse
from django.db import reset_queries
from django.http import QueryDict
from django.test.utils import override_settings
import mock
from mock import patch
from nose.tools import ... | _kw=dict(status=mkt.STATUS_PUBLIC))
self.app.u | pdate_version()
reset_queries()
res, data = self._get_url(self.list_url, app=self.app.pk,
client=client)
eq_(len(data['objects']), 2)
self._compare_review_data(client, data['objects'][0], rev2)
self._compare_review_data(client, data['objects'][1... |
danielrichman/snowball-ticketing | deploy/gunicorn_config_admin.py | Python | gpl-3.0 | 208 | 0 | import multiproc | essing
bind = "unix:/run/www-sockets/www-ticketing/admin.sock"
pidfile = "/run/www-sockets/www-ticketing/admin.pid"
workers = 1
syslog = True
syslog_facility = "local5"
pythonpath = 'deploy | '
|
jdweaver/ds_sandbox | homework2/homework_3_chipotle.py | Python | apache-2.0 | 6,038 | 0.016562 | '''
Python Homework with Chipotle data
https://github.com/TheUpshot/chipotle
'''
'''
BASIC LEVEL
PART 1: Read in the file with csv.reader() and store it in an object called 'file_nested_list'.
Hint: This is a TSV file, and csv.reader() needs to be told how to handle it.
https://docs.python.org/2/library/csv.html... | om collections import defaultdict
chips = defaultdict(int)
f | or row in data:
if "Chips" in row[2]:
chips[row[2]] += int(row[1])
|
volkhin/ycmd | ycmd/hmac_plugin.py | Python | gpl-3.0 | 3,445 | 0.024673 | # Copyright (C) 2014 Google Inc.
#
# This file is part of ycmd.
#
# ycmd 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.
#
# ycmd is di... | MAC.' )
abort( reque | sts.codes.unauthorized, 'Unauthorized, received bad HMAC.' )
return
body = callback( *args, **kwargs )
SetHmacHeader( body, self._hmac_secret )
return body
return wrapper
def HostHeaderCorrect( request ):
host = urlparse( 'http://' + request.headers[ _HOST_HEADER ] ).hostname
return ... |
kubeflow/pipelines | backend/api/python_http_client/kfp_server_api/models/api_resource_type.py | Python | apache-2.0 | 3,054 | 0.000327 | # coding: utf-8
"""
Kubeflow Pipelines API
This file contains REST API specification for Kubeflow Pipelines. The file is autogenerated from the swagger definition.
Contact: kubeflow-pipelines@google.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import s... | """ApiResourceType - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self.discriminator = None
def to_dict(self):
"""Returns the mod... | ttr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "t... |
JohanComparat/pyEmerge | bin_cluster/lc_add_clusters.py | Python | unlicense | 1,223 | 0.012265 | import h5py # HDF5 support
import os
import glob
import numpy as n
from scipy.interpolate import interp1d
import sys
from astropy.cosmology import FlatLambdaCDM
import astropy.units as u
cosmoMD = FlatLambdaCDM(H0=67.77*u.km/u.s/u.Mpc, Om0=0.307115, Ob0=0.048206)
#status = 'create'
status = 'update'
path_to_lc = s... | ster_data/log_LceX_05_24'].value[is_gal]
percent_observed = 1.
lx_absorbed_05_24 = n.log10(10**lx * percent_observed)
d_L = cos | moMD.luminosity_distance(z)
dl_cm = (d_L.to(u.cm)).value
adjusting_factor = 0.35 # accounts for absorption for now !
fx_05_24 = 10**(lx_absorbed_05_24-adjusting_factor) / (4 * n.pi * dl_cm**2.)
fx_05_24_out = n.ones_like(f['/sky_position/redshift_S'].value)*-9999.
fx_05_24_out[is_gal] = fx_05_24
if status == 'create'... |
TaylorOshan/pysal | pysal/spreg/tests/test_ols_sparse.py | Python | bsd-3-clause | 4,960 | 0.021573 | import unittest
import numpy as np
import pysal
import pysal.spreg as EC
from scipy import sparse
from pysal.common import RTOL
PEGP = pysal.examples.get_path
class TestBaseOLS(unittest.TestCase):
def setUp(self):
db = pysal.open(PEGP('columbus.dbf'),'r')
y = np.array(db.by_col("HOVAL"))
s... | umbus.shp"))
def test_ols(self):
self.X = np.hstack((np.ones(self.y.shape),self.X))
self.X = sparse.csr_matrix(self.X)
ols = EC.ols.BaseOLS(self.y,self.X)
np.testing.ass | ert_allclose(ols.betas, np.array([[
46.42818268], [ 0.62898397], [ -0.48488854]]))
vm = np.array([[ 1.74022453e+02, -6.52060364e+00, -2.15109867e+00],
[ -6.52060364e+00, 2.87200008e-01, 6.80956787e-02],
[ -2.15109867e+00, 6.80956787e-02, 3.33693910e-02]])
np... |
eduble/panteda | sakura/client/apiobject/databases.py | Python | gpl-3.0 | 1,593 | 0.008161 | from sakura.common.errors import APIObjectDeniedError
from sakura.client.apiobject.base import APIObjectBase, APIObjectRegistry
from sakura.client.apiobject.tables import APITable
from sakura.client.apiobject.grants import APIGrants
from sakura.common.tools import create_names_dict, snakecase
class APIDatabase:
de... | ants(remote_obj)
def __get_remote_info__(self):
return remote_obj.info()
return APIDatabaseImpl()
def get_databases(remote_api):
d = create_names | _dict(
((remote_db_info['name'], APIDatabase(remote_api, remote_db_info)) \
for remote_db_info in remote_api.databases.list()),
name_format = snakecase
)
return APIObjectRegistry(d, 'Sakura databases registry')
|
TriumphLLC/FashionProject | modules/draw/wires.py | Python | gpl-3.0 | 183 | 0.005464 | # im | port bpy
# def draw_wire(context):
# area = context.area
# if context.area.type == 'VIEW_3D':
# target = bpy.context.area.spaces.active
# | # target.draw_handler_add() |
PyFilesystem/pyfilesystem | fs/expose/dokan/libdokan.py | Python | bsd-3-clause | 8,967 | 0.014609 | # Copyright (c) 2009-2010, Cloud Matrix Pty. Ltd.
# Copyright (c) 2016-2016, Adrien J. <liryna.stark@gmail.com>.
# All rights reserved; available under the terms of the MIT License.
"""
| fs.expose.dokan.libdokan: low-level ctypes interface to D | okan
"""
from ctypes import *
try:
DokanMain = windll.Dokan1.DokanMain
DokanVersion = windll.Dokan1.DokanVersion
except AttributeError:
raise ImportError("Dokan DLL not found")
from ctypes.wintypes import *
ULONG64 = c_ulonglong
PULONGLONG = POINTER(c_ulonglong)
PVOID = c_void_p
PULONG = POINTER(c_ulon... |
AevumDecessus/fragforce.org | ffsfdc/models.py | Python | gpl-2.0 | 15,743 | 0.003049 | from django.db import models
from django.utils import timezone
class Hcmeta(models.Model):
hcver = models.IntegerField(blank=True, null=True)
org_id = models.CharField(max_length=50, blank=True, null=True)
details = models.TextField(blank=True, null=True)
class Meta:
managed = False
d... | ass Meta:
managed = False
db_table = '_trigger_log_archive'
class SiteAccount(models.Model):
jigsaw = models.CharField(max_length=20, blank=True, null=True)
shippinglongitude = models.FloatField(blank=True, null=True)
shippingstate = models.CharField(max_length=80, blank=True, null=True)
| youtubeid = models.CharField(db_column='youtubeid__c', max_length=80, blank=True, null=True)
numberofemployees = models.IntegerField(blank=True, null=True)
parent = models.ForeignKey('SiteAccount', to_field='sfid', db_column='parentid',
on_delete=models.CASCADE,
... |
LaercioAsano/gae-filtered-forwarding | handle_email.py | Python | mit | 1,480 | 0.005405 | from datetime import datetime
import webapp2
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext import ndb
from models import Email, Subscriber
from google.appengine.api import mail
class LogSenderHandler(InboundMailHandler):
def receive(self, message):
... | if word in email.content:
subscriber.forwarded.append(email)
subscriber.put()
mail.send_mail(sender="forwarder@email-processor-sample.appspotmail.co | m",
to=subscriber.email,
subject=email.subject,
body=content)
break
app = webapp2.WSGIApplication([LogSenderHandler.mapping()], debug=True)
|
shaded-enmity/dnf | dnf/conf/parser.py | Python | gpl-2.0 | 9,101 | 0.00044 | # parser.py
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY... | e stuff on it
line = readline from file on top of stack
pop and continue if line is EOF
if line starts with 'include=' then
error if file is recursive or duplicate
| otherwise open file, push on stack
continue
else
return line
return EOF
"""
# set line to EOF initially.
line = ''
while len(self._incstack) > 0:
# peek at the file like object on top of t... |
getpelican/pelican | pelican/tests/dummy_plugins/namespace_plugin/pelican/plugins/ns_plugin/__init__.py | Python | agpl-3.0 | 53 | 0 | NAME = 'namespace | plugin'
def register():
pass | |
ppizarror/Ned-For-Spod | bin/internal/langeditor/_delspecial.py | Python | gpl-2.0 | 283 | 0.021201 | #importacion de librerias
import sys
reload(sys)
sys.setdefaultencoding('UTF8')
if len(sys.argv)>1: #si el argumento existe
| archive = open(sys.argv[1],"r")
text = []
for i in archive:
text.append(i)
for j in i:
p | rint unicode(j) |
ReactiveX/RxPY | reactivex/operators/_bufferwithtime.py | Python | mit | 619 | 0 | from typing import Callable, List, Optional, TypeVar
from reactivex import Observable, abc, compose
from reactivex import operators as ops
from reactivex import typing
_T = TypeVar("_T")
def buffer | _with_time_(
timespan: typing.RelativeTime,
timeshift: Optional[typing.RelativeTime] = None,
sch | eduler: Optional[abc.SchedulerBase] = None,
) -> Callable[[Observable[_T]], Observable[List[_T]]]:
if not timeshift:
timeshift = timespan
return compose(
ops.window_with_time(timespan, timeshift, scheduler),
ops.flat_map(ops.to_list()),
)
__all__ = ["buffer_with_time_"]
|
linkedin/WhereHows | metadata-ingestion/src/datahub/ingestion/source/aws/aws_common.py | Python | apache-2.0 | 3,857 | 0.000259 | from functools import reduce
from typing import TYPE_CHECKING, List, Optional, Union
import boto3
from boto3.session import Session
from datahub.configuration import ConfigModel
from datahub.configuration.common import AllowDenyPattern
from datahub.emitter.mce_builder import DEFAULT_ENV
if TYPE_CHECKING:
from m... | lf.aws_secret_access_key
and self.aws_session_token
):
return Session(
aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
aws_session_token=self.aws_session_token,
region_name=self.aw... | ws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
region_name=self.aws_region,
)
elif self.aws_role:
if isinstance(self.aws_role, str):
credentials = assume_role(self.aws_role, self.aws_region)
... |
hal0x2328/neo-python | neo/Prompt/Commands/tests/test_output_config.py | Python | mit | 1,549 | 0.003873 | from neo.logging import log_manager
from neo.Prompt.Commands.Config import start_output_config
from mock import patch
from neo.Utils.NeoTestCase import NeoTestCase
from neo.Prompt.PromptPrinter import pp
import logging
import io
class TestOutputConfig(NeoTestCase):
@patch('sys.stdout', new_callable=io.StringIO)
... | # setup logging for 3 components
logger_generic = log_manager.getLogger()
logger_network = log_manage | r.getLogger('network')
logger_db = log_manager.getLogger('db')
# we expect to be prompted for 3 components (generic, network and db) setup at INFO level by default
# and then we choose option 1 twice (option 1 = DEBUG level) and something invalid the 3rd time.
mocked_prompt.side_effect ... |
wikimedia/operations-debs-python-diamond | src/collectors/libvirtkvm/libvirtkvm.py | Python | mit | 5,381 | 0.000372 | # coding=utf-8
"""
Uses libvirt to harvest per KVM instance stats
#### Dependencies
* python-libvirt, xml
"""
import diamond.collector
try:
from xml.etree import ElementTree
ElementTree # workaround for pyflakes issue #13
except ImportError:
import cElementTree as ElementTree
try:
import libvir... | 'path': 'libvirt-kvm',
'sort_by_uuid': False,
'uri': 'qemu:/// | system',
'cpu_absolute': False
})
return config
def get_devices(self, dom, type):
devices = []
# Create a XML tree from the domain XML description.
tree = ElementTree.fromstring(dom.XMLDesc(0))
for target in tree.findall("devices/%s/target" % type):
... |
edx/edx-e2e-tests | regression/pages/lms/__init__.py | Python | agpl-3.0 | 1,126 | 0 | """
Create base url for lms page objects.
While creating the url, basic authentication
username and basic authentication password
should be used.
"""
import os
from regression.pages import | BASIC_AUTH_PASSWORD, BASIC_AUTH_USERNAME
LMS_STAGE_BASE_U | RL = 'courses.stage.edx.org'
# LMS_SANDBOX_BASE_URL = 'business.sandbox.edx.org'
ECOM_STAGE_BASE_URL = 'ecommerce.stage.edx.org'
# ECOM_SANDBOX_BASE_URL = 'ecommerce-business.sandbox.edx.org'
LMS_BASE_URL = os.environ.get('LMS_BASE_URL', LMS_STAGE_BASE_URL)
ECOM_BASE_URL_STR = os.environ.get('ECOM_STAGE_BASE_URL', ECO... |
ic-hep/DIRAC | src/DIRAC/DataManagementSystem/DB/FileCatalogComponents/FileMetadata/FileMetadata.py | Python | gpl-3.0 | 27,517 | 0.001454 | """ DIRAC FileCatalog plugin class to manage file metadata
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__RCSID__ = "$Id$"
import six
from DIRAC import S_OK, S_ERROR
from DIRAC.Core.Utilities.Time import queryTime
from DIRAC.Core.Utilities.List impor... | OK"]:
return result
if result["Value"]["Successful"]:
fileID = result["Value"]["Successful"][path]["FileID"]
else:
return S_ERROR("File %s not found" % path)
failedMeta = {}
for meta in metadata:
if meta in metaFields:
| # Indexed meta case
req = "DELETE FROM FC_FileMeta_%s WHERE FileID=%d" % (meta, fileID)
result = self.db._update(req)
if not result["OK"]:
failedMeta[meta] = result["Value"]
else:
# Meta parameter case
... |
zepheira/zenpub | test/testwiki/wikiserver.py | Python | apache-2.0 | 1,250 | 0.004 | #!/usr/bin/env python
"""
Start script for the standalone Wiki server.
@copyright: 2007 MoinMoin:ForrestVoight
@license: GNU GPL, see COPYING for details.
"""
import sys, os
# a) Configuration of Python's code search path
# If you already have set up the PYTHONPATH environment variable for the
# st... | ')
# a2) Path of the directory where wikiconfig.py / farmconfig.py is loca | ted.
moinpath = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
sys.path.insert(0, moinpath)
os.chdir(moinpath)
# b) Configuration of moin's logging
# If you have set up MOINLOGGINGCONF environment variable, you don't need this!
# You also don't need this if you are happy with the builtin default... |
lafranceinsoumise/api-django | agir/donations/form_fields.py | Python | agpl-3.0 | 1,946 | 0.001542 | import json
from d | ecimal import Decimal
from django import forms
class MoneyField(forms.DecimalField):
def __init__(self, **kwargs):
kwargs["decimal_places"] = 2
for f in ["min_value", "max_value"]:
if f in kwargs:
kwargs[f] = Decimal(kwargs[f]) / 100
super().__init__(**kwargs)
... | , value):
if isinstance(value, int):
return Decimal(value) / 100
return value
def clean(self, value):
value = super().clean(value)
return value and int(value * 100)
class AskAmountField(forms.DecimalField):
def __init__(
self, *, amount_choices=None, show_t... |
nkanish2002/pyredis-cache | redis_cache/__init__.py | Python | mit | 66 | 0 | from .simp | le import CacheClient
from .hash import HashCac | heClient
|
euccas/CodingPuzzles-Python | course/ucsd_algorithm_toolbox/max_pairwise_product.py | Python | mit | 154 | 0 | # | Uses python3
n = int(input())
a = [int(x) for x in input().split()]
assert(len(a) == n)
result = 0
a.sort()
result = a[n-1] * a[n-2]
p | rint(result)
|
StackStorm/st2 | st2common/st2common/policies/concurrency.py | Python | apache-2.0 | 1,533 | 0 | # Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, 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 ... | 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
# limitations under the License.
from __future__ import absolute_import
from st2common.constants import action as action_constants
from st... |
simmetria/sentry | src/sentry/web/forms/__init__.py | Python | bsd-3-clause | 1,903 | 0.002627 | """
sentry.web.forms
~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
|
from sentry.interfaces import Http
from sentry.web.forms.fields import RadioFieldRenderer
class ReplayForm(forms.Form):
url = forms.URLField(widget=forms.TextInput(attrs={'class': 'span8'}))
method = forms.ChoiceField(choices=((k, k) for k in Http.METHODS))
data = forms.CharField(required=False, widget=f... | rs={'class': 'span8'}))
def clean_headers(self):
value = self.cleaned_data.get('headers')
if not value:
return
return dict(line.split(': ') for line in value.split('\n'))
class BaseUserForm(forms.ModelForm):
email = forms.EmailField()
first_name = forms.CharField(requ... |
briancheung/Peano | peano/utils.py | Python | mit | 5,009 | 0.001797 | import numpy as np
def index2onehot(n_labels, index):
return np.eye(n_labels)[index]
# From https://github.com/lisa-lab/DeepLearningTutorials/blob/master/code/utils.py
def scale_to_unit_interval(ndar, eps=1e-8):
""" Scales all values in the ndarray ndar to be between 0 and 1 """
ndar = ndar.copy()
nda... | ile_spacing[1]
out_shape = [
(ishp + tsp) * tshp - tsp
for ishp, tshp, tsp in zip(img_shape, tile_shape, tile_spacing)
]
if isinstance(X, tuple):
assert len(X) == 4
# Create an output numpy ndarray to store the image
if output_pixel_vals:
out_arra | y = np.zeros((out_shape[0], out_shape[1], 4),
dtype='uint8')
else:
out_array = np.zeros((out_shape[0], out_shape[1], 4),
dtype=X.dtype)
#colors default to 0, alpha defaults to 1 (opaque)
if output_pixel_vals:
... |
tjcsl/ion | intranet/apps/users/migrations/0003_merge.py | Python | gpl-2.0 | 196 | 0.005102 | # -*- coding: utf-8 -*-
from django.db import migrations
class Migration(migrations.Migration):
|
dependencies = [('users', '0002_auto_201504 | 02_1847'), ('users', '0002_auto_20150404_1622')]
|
SpaceGroupUCL/qgisSpaceSyntaxToolkit | esstoolkit/external/pyqtgraph/graphicsItems/tests/test_GraphicsItem.py | Python | gpl-3.0 | 802 | 0.003741 | import gc
import weakref
try:
import faulthandler
faulthandler.enable()
except ImportE | rror:
pass
import pyqtgraph as pg
pg.mkQApp()
def test_getViewWidget():
view = pg.PlotWidget()
vref = weakref.ref(view)
item = pg.InfiniteLine()
view.addItem(item)
assert item.getViewWidget() is view
del view
gc.collect()
assert vref() is None
assert item.getViewWidget() is Non... | tWidget()
item = pg.InfiniteLine()
view.addItem(item)
assert item.getViewWidget() is view
# Arrange to have Qt automatically delete the view widget
obj = pg.QtGui.QWidget()
view.setParent(obj)
del obj
gc.collect()
assert not pg.Qt.isQObjectAlive(view)
assert item.getViewWid... |
Neppord/py2py | py2py_lib/out/op.py | Python | mit | 1,894 | 0.042767 |
from visitor import Visitor
class OperatorOut(Visitor):
@classmethod
def visit_Add (self, ast, *a, **k):
return "+"
@classmethod
def visit_Sub (self, ast, *a, **k):
return "-"
@classmethod
def visit_Mult (self, ast, *a, **k):
return "*"
@classmethod
def visit_Div (self, ast, *a, **k):
... | ast, *a, **k):
return "is not"
@classmethod
def visit_In (self, ast, *a, **k):
return "in"
@classmethod
def visit_NotIn (self, ast, *a, **k): |
return "not in"
|
Jordan-Zhu/RoboVision | scratch/testingColorImg.py | Python | gpl-3.0 | 2,023 | 0.007909 | import cv2
import numpy as np
np.set_printoptions(threshold=np.nan)
import util as util
import edge_detect
import lineseg
import drawedgelist
# img = cv2.imread("img/Slide2.jpg", 0)
img = cv2.imread("unsorted/Unit Tests/lambda.png", 0)
im_size = img.shape
returnedCanny = cv2.Canny(img, 50, 150, apertureSize = 3)
cv2.... | HE CURVATURE LINES (CONVEX/CONCAVE).
LineFeature, ListPoint = Lseg_to_Lfeat_v4.create_linefeatures(seglist, res, im_size)
Line_new, ListPoint_new, line_merged = merge_lines_v4.merge_lines(LineFeature, ListPoint, 10, im_size)
#print(Line_new, "line new")
print(len(Line_new), "len line new")
util.draw_lf(Line_new, blank... | , ListPoint_new, 11)""" |
agdavis/contextual_features | gen_user_followers.py | Python | gpl-2.0 | 1,139 | 0.03863 | from datetime import *
from Tweetstream import *
from UserAnalyser import *
from TimeAnalyser import *
import math
import sys
import pickle
#Frequency over the common
def load_list(filein):
d = dict()
for l in filein:
l = eval(l)
d[l[0]] = l[1]
return d
if __name__ == "__main__":
follow = load_list(open(sys.... | Tweetstream(jsonfilee=sys.argv[3], jsonformat=False, keywords=keywords)
topicstream = Tweetstream(jsonfilee=sys.argv[1], jsonformat=False, keywords=keywords)
ua = UserAnalyser (sys.argv[4], keywords = keywords)
ua.load_usersVectors()
ua.load_idf()
ua.load_usersScore()
rank = dict()
# normalizar pelo numero d... | 0
if t['user_id'] in follow:
c += 1
for fuser in follow[t['user_id']]:
if fuser in ua.usersScore:
rank[t['id']] += ua.usersScore[fuser]
n += 1
if n > 0: rank[t['id']] /= n
print c
#prinit score, nwindow
pickle.dump(rank, open(sys.argv[4]+"_rank_USER_followers.pick", 'w'), pickle.HIGHEST_PROT... |
romanz/electrum | lib/wallet.py | Python | mit | 85,717 | 0.002053 | # Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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 Software without restriction,
# including without limitation the rights t... | _pos) tuple. Access with self.lock.
self.verified_tx = storage.get('verified_tx3', {})
# there is a difference between wallet.up_to_date and interface.is_up_to_date()
# interface.is_up_to_date() returns true when all requests have been answered and processed
# wallet.up_to_date is true... | nchronized (stronger requirement)
self.up_to_date = False
# locks: if you need to take multiple ones, acquire them in the order they are defined here!
|
stewartsmith/bzr | bzrlib/tests/per_tree/test_get_file_with_stat.py | Python | gpl-2.0 | 2,105 | 0.000475 | # Copyright (C) 2008, 2009, 2010 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is dis... | tatvalue = tree.get_file_with_stat('foo-id')
self.addCleanup(file_obj.close)
if | statvalue is not None:
expected = os.lstat('foo')
self.assertEqualStat(expected, statvalue)
self.assertEqual(["contents of foo\n"], file_obj.readlines())
def test_get_file_with_stat_id_and_path(self):
work_tree = self.make_branch_and_tree('.')
self.build_tree(['foo']... |
robotics-silver-surfer/surfer-main | lab3/angPos_PID/build/catkin_generated/generate_cached_setup.py | Python | mit | 1,291 | 0.004648 | from __future__ import print_function
import argparse
import os
import stat
import sys
# find the import for catkin's python package - either from source space or from an installed underlay
if os. | path.exists(os.path.join('/opt/ros/groovy/share/catkin/cmake', 'catkinConfig.cmake.in')):
sys.path.insert(0, os.path.join('/opt/ros/groovy/share/catkin/cmake', '..', 'python'))
try:
from catkin.environment_cache import generate_environment_script
except ImportError:
# search for catkin package in all worksp... | th.join(python_path, 'catkin')):
sys.path.insert(0, python_path)
break
from catkin.environment_cache import generate_environment_script
code = generate_environment_script('/projects/ros/surfer-main/lab3/angPos_PID/build/devel/env.sh')
output_filename = '/projects/ros/surfer-main/lab3/angPo... |
TUW-GEO/SMDC-performance | smdc_perftests/datasets/ascat.py | Python | bsd-3-clause | 9,343 | 0.000535 | # Copyright (c) 2015,Vienna University of Technology,
# Department of Geodesy and Geoinformation
# All rights reserved.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND F... | img[v][img['ssf'] != 1] = np.nan
img[v] = np.nanmean(img[v], axis=0)
return img
def get_data(self, date_start, date_end, cellID=None):
"""
Reads date cube from dataset
Parameters
---- | ------
date_start: datetime
start date of t |
shawncaojob/LC | PY/200_number_of_island.py | Python | gpl-3.0 | 6,084 | 0.011506 | # 200. Number of Islands Add to List
# Description Submission Solutions
# Total Accepted: 92945
# Total Submissions: 281078
# Difficulty: Medium
# Contributors: Admin
# Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjace... | """
:type grid: List[List[str]]
:rtype: int
"""
if not grid or not grid[0]: return 0
m, n = len(grid), len(grid[0])
roots = [ i for i in xrange(m * n) ]
cnt = 0
for i in xrange(m):
for j in xrange(n):
#print(i, j, ... |
r1 = self.find(roots, i * n + j)
cnt += 1
for pair in [[0, -1], [-1, 0]]:
xx, yy = i + pair[0], j + pair[1]
if xx >= 0 and xx < m and yy >= 0 and yy < n and grid[xx][yy] == "1":
r2 = self.find(... |
emmanuel-santos/GEM | trucoGemSite/truco/views.py | Python | mit | 4,850 | 0.009278 | from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import logout
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.http import HttpResponseRedirect, HttpResponse
from truco.forms import *
from truco.models import Partida, Jugador... | try:
partida = Partida.objects.get(id = ident)
except Partida.DoesNotExist:
return HttpResponseRedirect('/')
jugador = partida.jugador(request.user)
equipo = jugador.equipo
partida.equipos.exclude(id=equipo.id).update(puntos_partida=3 | 0)
partida.terminada = True
partida.save()
return HttpResponseRedirect('/')
def new_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(form.cleaned_data['username'], 'default@default.com', fo... |
VladKha/CodeWars | 7 kyu/Sort array by string length/solve.py | Python | gpl-3.0 | 57 | 0 | def sort_by_length(a | rr):
return sorted(ar | r, key=len)
|
Upande/MaMaSe | apps/mamasemedia/migrations/0008_auto_20160525_1056.py | Python | apache-2.0 | 506 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-25 10:56
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
| dependencies = [
('mamasemedia', '0007_auto_20160517_1341'),
]
operations = [
migrations.RemoveField(
model_n | ame='mediaindexpage',
name='name',
),
migrations.RemoveField(
model_name='mediapage',
name='name',
),
]
|
papedaniel/oioioi | oioioi/forum/models.py | Python | gpl-3.0 | 6,577 | 0.000456 | import datetime
from django.db import models
from django.db.models.signals import post_save, post_delete
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.dispatch import receiver
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _... | dels import Contest
from oioioi.contests.date_registration import date_registry
@date_registry.register('lock_date',
name_generator=(lambda obj: _("Lock the forum")))
@date_registry.register('unlock_date',
name_generator=(lambda obj: _("Unlock the forum")))
class Forum(... | Field(default=True,
verbose_name=
_("forum is visible after lock"))
lock_date = models.DateTimeField(blank=True, null=True,
verbose_name=_("autolock date"))
unlock_date = models.DateTimeField(blank=True, nul... |
gsr-shanks/nexus | nexus/plugins/restraint.py | Python | gpl-2.0 | 12,372 | 0.003637 | #!/usr/bin/python
# Copyright (c) 2015 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing
# to use, modify, copy, or redistribute it subject to the terms
# and conditions of the GNU General Public License version 2.
#
# You should have received a copy of the GNU General... | self.job_name)
f = open(self.restraint_xml, 'w')
f.write(m)
f.close()
if self.git_refspec:
logger.l | og.info("GERRIT_REFSPEC found in evnironment variable")
tree = ET.parse(self.restraint_xml)
root = tree.getroot()
p = root.find("recipeSet")
fetches = p.getiterator("fetch")
for i in fetches:
git_repo_url = i.attrib['url'].split('#')[0]
... |
hryamzik/ansible | lib/ansible/plugins/connection/persistent.py | Python | gpl-3.0 | 5,401 | 0.003888 | # 2017 Red Hat Inc.
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
author: Ansible Core Team
connection: persistent
short_description: Us... | rt json
import subprocess
import sys
from ansible import constan | ts as C
from ansible.plugins.connection import ConnectionBase
from ansible.module_utils._text import to_text
from ansible.module_utils.six.moves import cPickle
from ansible.module_utils.connection import Connection as SocketConnection
from ansible.errors import AnsibleError
try:
from __main__ import display
except... |
donkirkby/djsquash | fruit/migrations/0002_cranberry_bacon.py | Python | mit | 583 | 0.001715 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-06-08 17:57
from __future__ import unicode_literals
from django.db import migra | tions, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('fruit', '0001_initial'),
('meat', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='cranberry',
name='bacon',
... | s.deletion.CASCADE, to='meat.Bacon'),
),
]
|
xcthulhu/periphondemand | src/bin/commandline/projectcli.py | Python | lgpl-2.1 | 32,354 | 0.013414 | #! /usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Name: ProjectCli.py
# Purpose:
# Author: Fabien Marteau <fabien.marteau@armadeus.com>
# Created: 23/05/2008
#-----------------------------------------------------------------------------
... | letelist(line,text,l | istfile)
def do_load(self,line):
"""\
Usage : projectload <projectfilename>.xml
Load a project
"""
try:
self.checkargs(line,"<projectfilename>.xml")
except Error,e:
print e
return
if sy.dirExist(line):
head,projectname = os.path... |
itsjeyd/edx-platform | lms/djangoapps/grades/signals/signals.py | Python | agpl-3.0 | 2,050 | 0.002439 | """
Grades related signals.
"""
from django.dispatch import Signal
# Signal that indicates that a user's score for a problem has been updated.
# This signal is generated when a scoring event occurs either within the core
# platform or in the Submissions module. Note that this signal will be triggered
# regardless of ... | score is higher than previous.
]
)
# Signal that indicates that a user's score for a subsection has been updated.
# This is a downstream signal of PROBLEM_SCORE_CHANGED sent for each affected containing
# subsection.
SUBSECTION_SCORE_CHANGED = Signal(
providing_args=[
'course', # Course object
... | 'subsection_grade', # SubsectionGrade object
]
)
|
abo-abo/edx-platform | lms/djangoapps/instructor_task/subtasks.py | Python | agpl-3.0 | 17,270 | 0.004864 | """
This module contains celery task functions for handling the management of subtasks.
"""
from time import time
import json
from celery.utils.log import get_task_logger
from celery.states import SUCCESS, READY_STATES, RETRY
from django.db import transaction
from django.core.cache import cache
from instructor_task.... | rmat(task_id)
succeeded = cache.add(key, 'true', SUBTASK_LOCK_EXPIRE)
if not succeeded:
TASK_LOG.warning("task_id '%s': already locked. Contains value '%s'", task_id, cache.get(key))
return succeeded
def _release_subtask_lock(task_id):
"""
Unmark the specified task_id as being no longe | r in progress.
This is most important to permit a task to be retried.
"""
# According to Celery task cookbook, "Memcache delete is very slow, but we have
# to use it to take advantage of using add() for atomic locking."
key = "subtask-{}".format(task_id)
cache.delete(key)
def check_subtask_is... |
malaterre/ITK | Modules/Segmentation/LevelSets/wrapping/test/GeodesicActiveContourImageFilterTest.py | Python | apache-2.0 | 6,301 | 0.000794 | #==========================================================================
#
# Copyright NumFOCUS
#
# 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/l... | Name=argv[2])
def rescaleAndWrite(filter, fileName):
caster = itk.RescaleIntensityImageFilter[
InternalImageType,
| OutputImageType].New(
filter,
OutputMinimum=0,
OutputMaximum=255)
itk.imwrite(caster, os.path.join(outputDirectory, fileName))
rescaleAndWrite(smoothing, "GeodesicActiveContourImageFilterOutput1.png")
rescaleAndWrite(
gradientMagnitude,
"GeodesicAct... |
vakaras/nmadb-academics | src/nmadb_academics/models.py | Python | lgpl-3.0 | 3,878 | 0.000516 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from nmadb_students.models import Student
class Section(models.Model):
""" Information about section.
"""
title = models.CharField(
max_length=45,
unique=True,
verbose_name=_(u'title'... | ue,
verbose_name=_(u'comment'),
)
class Meta(object):
ordering = [u'student', u'section',]
def __unicode__(self):
return u'{0.student} {0.section}'.format(self)
class Meta(object):
verbose_name = _(u'academic')
verbose_name_plural = _(u'academics')
... | onal'),),
(u'I', _(u'international'),),
)
PLACES = (
(0, _(u'other'),),
(1, _(u'honorable mention'),),
(2, _(u'third'),),
(3, _(u'second'),),
(4, _(u'first'),),
)
student = models.ForeignKey(
Student,
... |
tlapicka/2013-2014.3A | funkce.py | Python | gpl-3.0 | 1,195 | 0.025707 | #!/usr/bin/python
# -*- coding: utf8 -*-
# Soubor: funkce.py
# Datum: 26.02.2014 08:50
# Autor: Marek Nožka, nozka <@t> spseol <d.t> cz
# Autor: Marek Nožka, marek <@t> tlapicka <d.t> net
# Licence: GNU/GPL
############################################################################
def jmeno(a,b,c):
a=a*... | spatne(a):
# global bagr
# print bagr
bagr=a*a
"""do bagr přiřazuj | i, proto je to LOKÁLNÍ proměnná"""
return bagr
bagr=44
print spatne(16)
print bagr
|
usc-isi/extra-specs | nova/tests/api/openstack/compute/contrib/test_cloudpipe.py | Python | apache-2.0 | 7,279 | 0.000137 | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | ted_at': '1981-10-20T00:00:00Z'}]}
self.assertEqual(res_dict, response)
def test_cloudpipe_list(self):
def network_api_get(context, network_id):
self.assertEqual(context.project_id, 'other')
return {'vpn_public_address': '127.0.0.1',
'vpn_public_port': 2... | instance):
return fake_network.fake_get_instance_nw_info(self.stubs,
spectacular=True)
self.stubs.Set(common, "get_nw_info_for_instance",
common_get_nw_info_for_instance)
self.stubs.Set(self.controller.network_... |
BhallaLab/moose-examples | neuroml/lobster_pyloric/synapses/GluSyn_STG.py | Python | gpl-2.0 | 2,442 | 0.015561 |
# -*- coding: utf-8 -*-
import sys
import math
from pylab import *
try:
import moose
except ImportError:
print("ERROR: Could not import moose. Please add the directory containing moose.py in your PYTHONPATH")
import sys
sys.exit(1)
from moose.utils import * # for BSplineFill
class GluSyn_STG(moose.... | )/Delta))) \
| for vm in arange(-70e-3,0.00001e-3,70e-3/1000.)] )
inhtautable.vector = array(tau)
inhtautable.connect("lookupOut",self,"setTau1")
# Graded synapse activation
inhsyntable.xmin = -70e-3 # V
inhsyntable.xmax = 0e-3 # V
act = [0.0] # at -70 mV
act.extend( [1/(... |
keon/algorithms | algorithms/strings/reverse_words.py | Python | mit | 396 | 0 |
def reverse(array, i, j):
while i < j:
array[i], array[j] = array[j], array[i]
i += 1
j -= 1
def reverse_words(string):
arr = string.strip().split() # arr is list of words
n = len(arr)
reverse(arr, 0, n-1)
return " ".join(arr)
if __name__ == "__main__":
| test = "I | am keon kim and I like pizza"
print(test)
print(reverse_words(test))
|
chrislit/abydos | tests/distance/test_distance_clark.py | Python | gpl-3.0 | 2,001 | 0 | # Copyright 2019-2020 by Christopher C. Little.
# This file is part of Abydos.
#
# Abydos 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 versio... | lic License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Abydos. If not, see <http://www.gnu.org/licenses/>.
"""abydos.tests.distance.test_distance_clark.
This module contains unit tests for abydos.distance.Clark
"""
import unittest
from abydos.distance import... | ark
"""
cmp = Clark()
def test_clark_dist(self):
"""Test abydos.distance.Clark.dist."""
# Base cases
self.assertEqual(self.cmp.dist('', ''), 0.0)
self.assertEqual(self.cmp.dist('a', ''), 1.0)
self.assertEqual(self.cmp.dist('', 'a'), 1.0)
self.assertEqual(sel... |
alubbock/pysb | setup.py | Python | bsd-2-clause | 2,077 | 0.001444 | from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
import versioneer
import os
def main():
this_directory = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(this_directory, 'README.rst'), 'r') as f:
long_description = f.read()
cmdclass = versioneer.... | tures; python_version == "2.7"'],
setup_requires=['nose'],
tests_require=['coverage', 'pygraphviz', 'm | atplotlib', 'pexpect',
'pandas', 'h5py', 'mock', 'cython',
'python-libsbml', 'libroadrunner'],
cmdclass=cmdclass,
keywords=['systems', 'biology', 'model', 'rules'],
classifiers=[
'Development Status :: 5 - Production/Stable',
... |
rarellano/socializa | backend/player/migrations/0010_auto_20170129_0814.py | Python | agpl-3.0 | 752 | 0.00266 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-29 08:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('player', '0009_player_ia'),
]
operations = [
migrations.AddField(
| model_name='meeting',
name='secret',
field=models.CharField(blank=True, default=None, max_length=16, null=True),
),
migrations.AddField(
model_name='meeting',
name='status',
field=models.CharField(choices=[('connected', 'connected'),... | ', max_length=16),
),
]
|
balamuruhans/avocado-vt | virttest/storage.py | Python | gpl-2.0 | 36,710 | 0.000109 | """
Classes and functions to handle storage devices.
This exports:
- two functions for get image/blkdebug filename
- class for image operates and basic parameters
"""
from __future__ import division
import errno
import logging
import os
import shutil
import re
import functools
import collections
from avocado.core... | irttest import ceph
from virttest import data_dir
from virttest.compat_52lts import decode_to_text
def preprocess_images(bindir, params, env):
# Clone master image form v | ms.
for vm_name in params.get("vms").split():
vm = env.get_vm(vm_name)
if vm:
vm.destroy(free_mac_addresses=False)
vm_params = params.object_params(vm_name)
for image in vm_params.get("master_images_clone").split():
image_obj = QemuImg(vm_params, bindir, image... |
912/M-new | virtualenvironment/experimental/lib/python2.7/site-packages/django/contrib/sitemaps/management/commands/ping_google.py | Python | gpl-2.0 | 402 | 0 | from django.core.management.base import BaseCommand
from django.contrib.sitemaps import ping_google
class Command(B | aseCommand):
help = "Ping Google with an updated sitemap, | pass optional url of sitemap"
def execute(self, *args, **options):
if len(args) == 1:
sitemap_url = args[0]
else:
sitemap_url = None
ping_google(sitemap_url=sitemap_url)
|
arenaoftitans/arena-of-titans-api | tests/game/test_player.py | Python | agpl-3.0 | 19,920 | 0.000954 | ################################################################################
# Copyright (C) 2015-2020 by Last Run Contributors.
#
# This file is part of Arena of Titans.
#
# Arena of Titans is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publ... | player.deck.play.assert_called_once_with(card)
end_square = player.current_square
player._gauge.move.assert_called_once_with(start_square, end_square, card)
assert not start_square.occupied
assert end_square.occupied
assert start_square.x != end_square.x and start_square.y != end_ | square.y
assert 3 == end_square.x
assert 1 == end_square.y
def test_play_card_no_move_left(board, player): # noqa: F811
player.deck.play = MagicMock()
player.deck.init_turn = MagicMock()
card = Card(board)
player._number_moves_played = player.MAX_NUMBER_MOVE_TO_PLAY
ret = player.play_car... |
RuchePI/Site | rpi/beehive/urls.py | Python | gpl-3.0 | 915 | 0 | from django.conf.urls import url
from rpi.beehive.views import AddBeehiveView, delete_readering_view, \
ChartReaderingView, export_view, ListReaderingView, DeleteBeehiveView, \
ModifyBeehiveView, summary_view
urlpatterns = [
url(r'^ajouter$', AddBeehiveView.as_view(), name='add-beehive'),
url(r'^(?P<... | iew, name='e | xport'),
url(r'^(?P<pk>\d+)/modifier/$', ModifyBeehiveView.as_view(),
name='modify-beehive'),
url(r'^(?P<pk>\d+)/supprimer/$', DeleteBeehiveView.as_view(),
name='delete-beehive'),
url(r'^supprimer-releve/(?P<pk>\d+)/$', delete_readering_view,
name='delete-readering'),
]
|
job/pypeer | lib/pypeer/ConfigDictionary.py | Python | mit | 1,699 | 0 | #!/usr/bin/env python
import ConfigParser
class ConfigDictionary:
def __init__(self, configfile='./etc/example.ini'):
self.localconfig = ConfigParser.RawConfigParser()
self.localconfig.read(configfile)
self.router_ip_dict = {}
self.router_loc_dict = {}
router_items = self... | elf.localconfig.get("auth", "password")
def get_router_ip(self, router_name):
return self.router_ip_dict[router_name]
def get_list_of_router_names(self):
return self.router_ip_dict.keys()
def get_type_from_localpref(self, localpref):
transitconfig = self.localconfig.get("localpref... | lconfig.get("localprefrange", "customer")
transitmin, transitmax = transitconfig.split('-')
peermin, peermax = peerconfig.split('-')
custmin, custmax = custconfig.split('-')
transitrange = range(int(transitmin), int(transitmax))
peerrange = range(int(peermin), int(peermax))
... |
markushutzler/cmdparse | cmdparse/__init__.py | Python | bsd-3-clause | 7,288 | 0 | # -*- coding: utf-8 -*-
# Copyright | (c) 2016, Markus Hutzler
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the followi... | following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWA... |
macarthur-lab/xbrowse | xbrowse_server/base/management/commands/add_coverage_to_project.py | Python | agpl-3.0 | 1,115 | 0.001794 | import os
from django.core.management.base import BaseCommand
from xbrowse_ | server.base.models import Project
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('args', nargs='*')
def handle(self, *args, **options):
project_id = args[0]
coverage_dir = args[1]
project = Project.objects.get(project_id=project_id)
| files = os.listdir(coverage_dir)
full_path_dir = os.path.abspath(coverage_dir)
for individual in project.individual_set.all():
indiv_id = individual.indiv_id
full_path = None
if '%s.callable.bed.gz' % indiv_id in files:
full_path = '%s/%s.callable.bed... |
aajjbb/contest-files | HackerEarth/Balls.py | Python | apache-2.0 | 389 | 0.010283 | N = int(raw_input())
L = list(map(int, raw_input().split(" ")))
ans = 0
L.sort()
for i in range(1, N + 1):
iv = i * i
l = 0
h = len(L) - 1
best = 0
|
w | hile l <= h:
m = (l + h) // 2
if L[m] < iv:
l = m + 1
else:
h = m - 1
best = m
ans = ans + max(0, i * i - L[best])
del L[best]
print(ans)
|
lewang0418/Django-Celery-Mongodb | Sample/settings.py | Python | apache-2.0 | 4,551 | 0.006812 | """
Django settings for Sample project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
imp... | .middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'Sample.urls'
WSGI_APPLICATION = 'Sample.wsgi.application'
# Database
# https://docs.djangoproject | .com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE... |
atareao/Picapy | src/picasamod.py | Python | gpl-3.0 | 3,598 | 0.000278 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is part of picapy
#
# Copyright (C) 2010-2016 Lorenzo Carbonell
# lorenzo.carbonell.cerezo@gmail.com
#
# 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 So... | color = colors[i]
if color in existing:
data[color] += 1
else:
existing.append(color)
data[color] = 1
print(data)
print(get_string_from_array_of_colors(colors, alpha))
if __name__ == '__main__':
entrada = '/home/atareao/Imágenes/0029_Tribler 6.0.0.p... | )
pixbufoutput = grayscale_pixbuf(pixbufinput)
pixbufoutput = rotate_pixbuf(pixbufoutput, CLOCKWISE)
pixbufoutput = flip_pixbuf(pixbufoutput, True)
pixbufoutput.savev(salida, 'png', [], [])
print('end')
exit(0)
|
oliver-sanders/cylc | cylc/flow/scripts/get_resources.py | Python | gpl-3.0 | 2,521 | 0 | #!/usr/bin/env python3
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# 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... | cylc.flow im | port LOG
import cylc.flow.flags
from cylc.flow.loggingutil import disable_timestamps
from cylc.flow.option_parsers import CylcOptionParser as COP
from cylc.flow.resources import get_resources, list_resources
from cylc.flow.terminal import cli_function
def get_option_parser():
parser = COP(
__doc__,
... |
mitnk/letsencrypt | acme/acme/challenges_test.py | Python | apache-2.0 | 15,928 | 0.000251 | """Tests for acme.challenges."""
import unittest
import mock
import OpenSSL
import requests
from six.moves.urllib import parse as urllib_parse # pylint: disable=import-error
from acme import errors
from acme import jose
from acme import test_util
CERT = test_util.load_comparable_cert('cert.pem')
KEY = jose.JWKRSA... | partial_json(self):
self.assertEqual(self.jobj, self.chall.to_partial_json())
def test_from_json(self):
from acme.challenges import UnrecognizedChallenge
| self.assertEqual(
self.chall, UnrecognizedChallenge.from_json(self.jobj))
class KeyAuthorizationChallengeResponseTest(unittest.TestCase):
def setUp(self):
def _encode(name):
assert name == "token"
return "foo"
self.chall = mock.Mock()
self.chall... |
spicykaiju/hexenbracken | hex.py | Python | mit | 3,875 | 0.003613 | import argparse
import os
import re
import string
import sys
import jinja2
import utfcsv
import hexmap as hm
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--format', dest='fmt', default='html',
help="Format of output: html or text")
parser.add_argument('CSV', help="The CSV file wi... | ' if x >= max_x or y <= 0 else "%02d%02d" % (x, y)
def se(location):
x, y = coordinates(location)
if x % 2 == 0:
y += 1
x += 1
return '' if x >= max_x or y >= max_y else "%02d%02d" % (x, y)
def sw(location):
x, y = coordinates(location)
if x % 2 ==1:
y += 1
x -= 1
retur... | if description[-1] not in string.punctuation:
description = description + '.'
if description[0].islower():
description = description.capitalize()
description = hex2link(description)
return description
env = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'))
env.filters['proce... |
programa-stic/barf-project | examples/misc/emulate_binary.py | Python | bsd-2-clause | 7,099 | 0.001268 | #! /usr/bin/env python
# Copyright (c) 2014, Fundacion Dr. Manuel Sadosky
# 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 notic... | coded addresses.
if binary.architecture == | ARCH_X86:
end = start + size - 1
if binary.architecture_mode == ARCH_X86_MODE_32:
atoi_addr = 0x8048380
printf_addr = 0x8048350
if binary.architecture_mode == ARCH_X86_MODE_64:
atoi_addr = 0x4004d0
printf_addr = 0x4004a0
if binary.architectu... |
doismellburning/django | django/contrib/contenttypes/migrations/0001_initial.py | Python | bsd-3-clause | 1,227 | 0.002445 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.contenttypes.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='ContentType',
fields=... | ),
],
| options={
'ordering': ('name',),
'db_table': 'django_content_type',
'verbose_name': 'content type',
'verbose_name_plural': 'content types',
},
bases=(models.Model,),
managers=[
('objects', django.co... |
mabdrabo/FlaskHero | app/proj.py | Python | mit | 380 | 0.018421 | # coding: | utf-8
import os, sys
reload(sys)
sys.setdefaultencoding("utf-8")
from flask import Flask, render_template, request, url_for
from datetime import datetime
_wd = os.path.dirname(os.path.realpath(__file__))
app = Flask(__name__, static_url_path='/static')
@app.route('/') |
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)
|
rmcgibbo/osprey | osprey/cli/main.py | Python | apache-2.0 | 1,526 | 0 | from __future__ import print_function, absolute_import, division
import sys
import argparse
from .. import __version__
from . import parser_dump
from . import parser_skeleton
from . import parser_worker
from . import parser_plot
from . import parser_currentbest
def main():
help = 'osprey is a tool for machine l... | configure_parser(sub_parsers)
parser_worker.configure_parser(sub_parsers)
parser_plot.configure_parser(sub_parsers)
parser_currentbest.configure_parser(sub_parsers)
if len(sys.argv) == 1:
sys.argv.append('-h')
args = p.parse_args()
args_func(args, p)
def args_func(args, p):
try:
... | or: %s" % e)
except Exception as e:
if e.__class__.__name__ not in ('ScannerError', 'ParserError'):
message = """\
An unexpected error has occurred with osprey (version %s), please
consider sending the following traceback to the osprey GitHub issue tracker at:
https://github.com/pandegro... |
mpirnat/hackday | hackday/wsgi.py | Python | mit | 1,137 | 0.00088 | """
WSGI config for trialrun project.
This module contains the WSGI ap | plication used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard D | jango WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.set... |
cgogolin/ncpol2sdpa | ncpol2sdpa/__init__.py | Python | gpl-3.0 | 1,560 | 0 | """Ncpol2SDPA
=====
Provides
1. A converter from a polynomial optimi | zation problems of commuting and
noncommuting variables to a semidefinite programming relaxation.
2. Helper functions to define physics problems.
"""
__version__ = "1.11.1 | "
from .faacets_relaxation import FaacetsRelaxation
from .sdp_relaxation import SdpRelaxation
from .steering_hierarchy import SteeringHierarchy
from .moroder_hierarchy import MoroderHierarchy
from .rdm_hierarchy import RdmHierarchy
from .nc_utils import generate_operators, generate_variables, get_monomials, \
... |
dwatrous/self-service-onboarding-openstack-cloudfoundry | automate_cf.py | Python | mit | 17,919 | 0.006697 | #-------------------------------------------------------------------------------
# Name: automate_cf
# Purpose: This module is designed to automated certain administrative
# cloudfoundry operations using the cloudfoundry API and some
# Stackato API functions
#
# Author: Daniel ... | uth_host }}":
self.configuration['auth_host'] = "aok.als-dev.hos.hpecorp.net"
if self.configuration['api_host'] == "{{ cf_api_host }}":
self.configuration['api_host'] = "api.als-dev.hos.hpecorp.net"
## Authentication functions
def load_access_token(self):
url = self.url_... | 'password': self.configuration['automation_password'], 'grant_type': 'password'}
response = requests.post(url, headers=headers, data=data, verify=self.configuration['verify_ssl'])
self.oauth = AttrDict(json.loads(response.text))
def get_access_token(self):
# if oauth isn't set the request a... |
buxx/intelligine | intelligine/synergy/object/ant/Ant.py | Python | apache-2.0 | 4,135 | 0.001935 | from intelligine.core.exceptions import MoleculeException
from intelligine.synergy.object.Bug import Bug
from intelligine.cst import CARRYING, TRANSPORTER, ATTACKER, COL_TRANSPORTER, COL_TRANSPORTER_NOT_CARRYING, \
COL_FIGHTER, MODE_EXPLO, MODE_GOHOME, BODY_PART_PHEROMONE_GLAND, TYPE, TYPE_ANT, \
COL_TRANSPORTE... | TER_NOT_CARRYING)
self._remove_col(COL_TRANSPORTER_CARRYING, allow_not_in=True)
self._remove_col(COL_FIGHTER)
def get_movement_molecule_gland(self):
return self.get_body_part(BODY_PART_PHEROMONE_GLAND)
def put_carry(self, obj, position=None):
if position is None:
po... | ._context.metas.states.remove(self.get_id(), CARRYING)
self._context.metas.value.unset(CARRY, self.get_id())
self._add_col(COL_TRANSPORTER_NOT_CARRYING)
self._remove_col(COL_TRANSPORTER_CARRYING)
def get_carried(self):
return self._carried
def carry(self, obj):
self._ca... |
vaas-krish/openthread | tests/scripts/thread-cert/Cert_5_6_09_NetworkDataForwarding.py | Python | bsd-3-clause | 5,202 | 0.000577 | #!/usr/bin/env python
#
# Copyright (c) 2016, 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
# ... | et_state('leader')
self.assertEqual(self.nodes[LEADER].get_state(), 'leader')
| self.nodes[ROUTER1].start()
time.sleep(5)
self.assertEqual(self.nodes[ROUTER1].get_state(), 'router')
self.nodes[ROUTER2].start()
time.sleep(5)
self.assertEqual(self.nodes[ROUTER2].get_state(), 'router')
self.nodes[ED].start()
time.sleep(5)
self.assertEq... |
Godin/coreclr | src/pal/automation/compile.py | Python | mit | 2,660 | 0.013158 | import logging as log
import sys
import getopt
import os
| import subprocess
import shutil
def RunCMake(workspace, target, platform):
# run CMake
print "\n==================================================\n"
returncode = 0
if platform == "windows":
print "Running: vcvarsall.bat x86_amd64 && " + workspace + "\ProjectK\NDP\clr\src\pal\\tools\gen-builds... | n"
sys.stdout.flush()
returncode = subprocess.call(["vcvarsall.bat", "x86_amd64", "&&", workspace + "\ProjectK\NDP\clr\src\pal\\tools\gen-buildsys-win.bat", workspace + "\ProjectK\NDP\clr"])
elif platform == "linux":
print "Running: " + workspace + "/ProjectK/NDP/clr/src/pal/tools/gen-builds... |
alexmcbride/pyinsim | pyinsim/core.py | Python | gpl-3.0 | 18,391 | 0.007177 | # core.py - core library module for pyinsim
#
# Copyright 2008-2015 Alex McBride <xandermcbride@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU Lesser General Public License version 3 or any later version.
#
# Dependencies
import socket
import asyncore
import traceback
impo... | cket receive loop.
Args:
background - Set true to run the loop in a background thread (for use in GUI app).
"""
if background:
threading.Thread(target=asyncore.loop, args=[_TIMEOUT]).start()
else:
asyncore.loop(timeout=_TIMEOUT)
def isrunning():
"""Determin if pyi... | running."""
return bool(asyncore.socket_map)
def closeall():
"""Close all open connections."""
asyncore.close_all(ignore_all=True)
class _TcpSocket(asyncore.dispatcher):
"""Class to handle a TCP socket."""
def __init__(self, dispatch_to):
asyncore.dis |
DiCarloLab-Delft/PycQED_py3 | pycqed/analysis_v2/tomo_functions.py | Python | mit | 6,955 | 0.00417 | import numpy as np
from functools import reduce
def flatten_list(l): return reduce(lambda x, y: x+y, l)
def compute_beta_matrix(num_qubits):
"""
Computes the matrix necesary to invert the beta coefficients.
"""
num_states = 2**num_qubits
matrix_B = np.zeros((num_states, num_states))
for i in r... | if op_letter == 'Z':
rotated_op_str += bases[i_ol]
elif op_letter == 'I':
rotated_op_str += 'I'
else:
raise ValueError("Tomo::operator_rotation Measurement operator is not undestood {} in {}".format(op_letter,op))
operator_str_base4 = rotated_op_str.replace('I'... | _op_idx = int(operator_str_base4,4) # transforms this into the integer in base 10
return rotated_op_idx, rotated_op_str
|
ganwell/ktasync | files/kyototycoon_orig.py | Python | agpl-3.0 | 7,463 | 0.013265 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Ulrich Mierendorff
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 Software without restriction, including without limitation
the right... | quest))
if flags & FLAG_NOREPLY:
return None
| magic, = struct.unpack('!B', self._read(1))
if magic == MB_SET_BULK:
recs_cnt, = struct.unpack('!I', self._read(4))
return recs_cnt
elif magic == MB_ERROR:
raise KyotoTycoonError('Internal server error 0x%02x' % MB_ERROR)
else:
raise KyotoTycoon... |
relic7/prodimages | python/jbmodules/http_tools/download_files/downloadfile_HTTPS_requests.py | Python | mit | 598 | 0.033445 | #!/usr/bin/env python
def dloader(url, stylenum, imgnum):
import os, sys, requests, re
regex = re.compile(r'^(http://.*?)\?dl\=\d{1,2}.*?$')
urlget = url
localpath = os.path.join('/Users/johnb/Pictures', stylenum + '_' + imgnum + '.jpg')
import subprocess
subprocess.call(['wget', url, '-o', localpath])
if re... | lget):
regexfnd = regex.findall(urlget)
print | regexfnd, '<--REGEX-FOUND--'
res = requests.get(urlget, stream=True, timeout=5)
with open(localpath, 'w') as f:
f.write(res.content)
f.close()
else:
pass
return
if __name__ == '__main__':
dloader() |
ryankanno/hitraffic-alert | tasks.py | Python | mit | 2,052 | 0.002437 | from celery import Celery
from celery.decorators import periodic_task
from celery.schedules import crontab
import datetime
import requests
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
app = Celery('tasks', backend='redis://localhost:6379/0', broker='redis://localhost:6379/0')
LAST_... | cident)
else:
notif | y_numbers[a["phone"]] = [incident]
except Exception as e:
pass
if notify_numbers:
for k,v in notify_numbers.iteritems():
logger.info(notify_numbers[k])
|
Gyfis/sequence-comparison | Modules/basic.py | Python | mit | 302 | 0.003311 | import tables
__author__ = 'Gyfis'
def generate_histogram(sequence, type=0):
table = tables.dna if type == 0 else tables.rna if type == 1 else tables.protein
hist = {c: 0 for c in table}
for c in sequence:
hist[c] += 1
return {c: hist[c] / float(len(sequence)) for c in | hist}
| |
elena/django | tests/db_functions/datetime/test_extract_trunc.py | Python | bsd-3-clause | 69,302 | 0.003146 | from datetime import datetime, timedelta, timezone as datetime_timezone
import pytz
try:
import zoneinfo
except ImportError:
try:
from backports import zon | einfo
except ImportError:
zoneinfo = None
from django.conf import settings
from django.db.models import (
DateField, DateTimeField, F, IntegerField, Ma | x, OuterRef, Subquery,
TimeField,
)
from django.db.models.functions import (
Extract, ExtractDay, ExtractHour, ExtractIsoWeekDay, ExtractIsoYear,
ExtractMinute, ExtractMonth, ExtractQuarter, ExtractSecond, ExtractWeek,
ExtractWeekDay, ExtractYear, Trunc, TruncDate, TruncDay, TruncHour,
TruncMinute, ... |
comger/migrant | doc/importnews.py | Python | mit | 1,183 | 0.019508 | # -*- coding:utf-8 -*-
"""
author comger@gmail.com
news spider
"""
import tornado
import urllib
from kpages import set_default_encoding
from pyquery import PyQuery as pyq
from tornado import httpclient
def main():
url = 'http://taiwan.huanqiu.com/news/'
#url = 'http://world.huanqiu.com/observation/'
... | pad20 li a')
for a in alist:
link = pyq(a).attr('href')
get_info(link)
def get_info(url):
doc = pyq(url=url)
params = dict(
title = doc('h1').text(),
author = '52847ffb1a7f5a7d80fd1ff7',
| category = 'policy',
city = '51d28ace931e334378000001',
body = doc('#text').html(),
labels = '测试',
)
body = urllib.urlencode(params)
def callback(res):
print 'ok'
tornado.ioloop.IOLoop.instance().stop()
http_client = httpclient.AsyncHTTPClient()
... |
koditraquinas/koditraquinas.repository | script.module.urlresolver/lib/urlresolver/plugins/nowvideo.py | Python | gpl-2.0 | 2,602 | 0.007686 | """
urlresolver Kodi plugin
Copyright (C) 2011 t0mm0
Updated by Gujal (C) 2016
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... | nowvideo.co', 'nowvideo.li', 'nowvideo.fo', 'nowvideo.at', 'nowvideo.ec']
pattern = '(?://|\.)(nowvideo\.(?:eu|ch|sx|co|li|fo|at|ec))/(?:video/|embed\.php\?\S*v=)([A-Za-z0-9]+)'
def __init__(self):
self.net = common.Net()
def get_media_url(self, host, media_id):
web_ur | l = self.get_url(host, media_id)
stream_url = ''
html = self.net.http_GET(web_url).content
try:
r = re.search('flashvars.filekey=(.+?);', html)
if r:
r = r.group(1)
try: filekey = re.compile('\s+%s="(.+?)"' % r).findall(html)[-1]
... |
Jaidan/jaidan-hab-home-assistant | homeassistant/components/notify/pushbullet.py | Python | mit | 1,541 | 0 | """
PushBullet platform for notify component.
"""
import logging
from homeassistant.helpers import validate_config
from homeassistant.components.notify import (
DOMAIN, ATTR_TITLE, BaseNotificationService)
from homeassistant.const import CONF_API_KEY
_LOGGER = logging.getLogger(__name__)
def get_service(hass, c... | self.pushbullet = PushBullet(api_ | key)
def send_message(self, message="", **kwargs):
""" Send a message to a user. """
title = kwargs.get(ATTR_TITLE)
self.pushbullet.push_note(title, message)
|
CallumCameron/pi-server | zz-vm-testing/test_05_media_server.py | Python | mit | 900 | 0.002222 | from typing import Dict
from urllib.parse import urlparse
from testinfra.host import Host
from conftest import for_host_types, WebDriver
class TestMediaServer:
@for_host_types('pi')
def test_media_server(self, hostname: str, hosts: Di | ct[str, Host], addrs: Dict[str, str]) -> None:
# For now we just d | o some basic checks
host = hosts[hostname]
assert host.service('minidlna').is_enabled
assert host.service('minidlna').is_running
assert host.process.filter(user='www-data', comm='minidlnad')
def test(this_addr: str) -> None:
with WebDriver() as driver:
... |
wikomega/wikodemo | test.py | Python | mit | 1,073 | 0.007456 |
import time
import multiprocessing
from flask import Flask
app = Flask(__name__)
backProc = None
def testFun():
print('Starting')
while True:
time.sleep(3)
print('looping')
time.sleep(3)
print('3 Seconds Later')
@app.route('/')
def root():
return 'Started a background pr... | ute('/active')
def active():
proc = multiprocessing.active_children()
arr = []
for p in proc:
print(p.pid)
arr.append(p.pid)
return str(arr)
@app.route('/start')
def start():
global backProc
backProc = multiprocessing.Process(target=testFun, args=(), daemon=True)
backProc.s... | f __name__ == '__main__':
app.run()
|
SportySpice/Collections | src/gui/ListItemTable.py | Python | gpl-2.0 | 11,659 | 0.020499 | from Tab import SETTING_COLUMN, SETTING_COLUMN_PAD
from Row import Row
from EnumButton import EnumMode
import colors
import pyxbmct.addonwindow as pyxbmct
from src.li.visual import FullTextSettings
from src.li.visual.FullTextSettings import Location
from src.li.visual import TextSettings
from src.tools.addonSettings im... |
def countlessExampleText():
return assignedFTS.fullText(countlessTitleExample, countlessSourceExample, count, maxChars, textIfNone2=textIfNone2)
# countTS = assignedFTS.countTS
# assignedFTS.countTS = None
# text = assignedFTS.fullText(countlessTi... | ountlessSourceExample)
#
# assignedFTS.countTS = countTS
# return text
example = Example(exampleText(), self)
countlessExample = Example(countlessExampleText(), self)
self.examples.append(example)
self.examples.append(countlessExa... |
google/gazoo-device | gazoo_device/primary_devices/esp32_matter_allclusters.py | Python | apache-2.0 | 4,394 | 0.003869 | # Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | S,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Device class for ESP32 Pigweed All Clusters de | vice."""
from gazoo_device import decorators
from gazoo_device import detect_criteria
from gazoo_device import gdm_logger
from gazoo_device.base_classes import esp32_matter_device
from gazoo_device.capabilities import pwrpc_button_default
from gazoo_device.capabilities import pwrpc_wifi_default
from gazoo_device.capabi... |
gotcha/Selenium2Library | src/Selenium2Library/locators/windowmanager.py | Python | apache-2.0 | 5,724 | 0.003669 | from types import *
| from robot import utils
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.common.exceptions import NoSuchWindowException
class WindowManager(object):
def __init__(self):
self._strategies = {
'title': self._select_by_title,
'name': self._select_by_name,
... | browser):
return [ window_info[1] for window_info in self._get_window_infos(browser) ]
def get_window_names(self, browser):
return [ window_info[2] for window_info in self._get_window_infos(browser) ]
def get_window_titles(self, browser):
return [ window_info[3] for window_info in sel... |
AltSchool/django-allauth | allauth/socialaccount/providers/jupyterhub/views.py | Python | mit | 1,219 | 0 | import requests
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.jupyterhub.provider import (
JupyterHubProvider,
)
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2L | oginView,
)
class JupyterHubAdapter(OAuth2Adapter):
provider_id = JupyterHubProvider.id
settings = app_settings.PROVIDERS.get(provider_id, {})
provider_base_url = settings.get("API_URL", '')
access_token_url = '{0}/hub/api/oauth2/token'.format(provider_base_url)
authorize_url = '{0}/hub/api/oaut... | token, **kwargs):
headers = {
'Authorization': 'Bearer {0}'.format(access_token)
}
extra_data = requests.get(self.profile_url, headers=headers)
user_profile = extra_data.json()
return self.get_provider().sociallogin_from_response(
request,
u... |
ethantang95/DIGITS | digits/config/caffe.py | Python | bsd-3-clause | 7,545 | 0.001856 | # Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
import imp
import os
import platform
import re
import subprocess
import sys
from . import option_list
from digits import device_query
from digits.utils import parse_version
def load_from_envvar(envvar):
"... |
# Strange issue with protocol buffers and pickle - see issue #32
sys.path.insert(0, os.path.join(
os.path.dirname(caffe.__file__), 'proto'))
# Turn GLOG output back on for subprocess calls
if GLOG_minloglevel is None:
del os.environ['GLOG_minloglevel']
else:
os.environ['GL... | nd_flavor(executable):
"""
Returns (version, flavor)
Should be called after import_pycaffe()
"""
version_string = get_version_from_pycaffe()
if version_string is None:
version_string = get_version_from_cmdline(executable)
if version_string is None:
version_string = get_versio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.