Datasets:
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 |
|---|---|---|---|---|---|---|---|---|
Eric89GXL/scipy | scipy/_lib/_ccallback.py | Python | bsd-3-clause | 6,196 | 0.001453 | from . import _ccallback_c
import ctypes
PyCFuncPtr = ctypes.CFUNCTYPE(ctypes.c_void_p).__bases__[0]
ffi = None
class CData(object):
pass
def _import_cffi():
global ffi, CData
if ffi is not None:
return
try:
import cffi
ffi = cffi.FFI()
CData = ffi.CData
except... | function : {PyCapsule, ctypes function pointer, cffi function pointer}
| Low-level callback function.
user_data : {PyCapsule, ctypes void pointer, cffi void pointer}
User data to pass on to the callback function.
signature : str, optional
Signature of the function. If omitted, determined from *function*,
if possible.
Attributes
----------
functi... |
QuantiModo/QuantiModo-SDK-Python | SwaggerPetstore/models/json_error_response.py | Python | gpl-2.0 | 1,773 | 0.00564 | #!/usr/bin/env python
# coding: utf-8
"""
Copyright 2015 SmartBear Software
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
Unle... | 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.
"""
class JsonErrorResponse(object):
"""
NOTE: This class is auto generated by the swagger code generator... | class manually.
"""
def __init__(self):
"""
Swagger model
:param dict swaggerTypes: The key is attribute name and the value is attribute type.
:param dict attributeMap: The key is attribute name and the value is json key in definition.
"""
self.swagger_types = {... |
BlueHouseLab/sms-openapi | python-requests/conf.py | Python | apache-2.0 | 324 | 0.003521 | # -*- coding: utf-8 -*-
appid = 'example'
apikey = 'c5dd7e7dkjp27377l903c42c032b413b'
sender = '01000000000' | # FIXME - MUST BE CHANGED AS REAL PHONE NUMBER
receivers = ['01000000000', ] # FIXME - MUST BE CHANGED AS REAL PHONE NU | MBERS
content = u'나는 유리를 먹을 수 있어요. 그래도 아프지 않아요'
|
ULHPC/easybuild-easyblocks | easybuild/easyblocks/generic/cmakemake.py | Python | gpl-2.0 | 4,702 | 0.002552 | ##
# Copyright 2009-2017 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... |
if builddir is not None:
self.log.nosupport("CMakeMake.configure_step: named argument | 'builddir' (should be 'srcdir')", "2.0")
# Set the search paths for CMake
include_paths = os.pathsep.join(self.toolchain.get_variable("CPPFLAGS", list))
library_paths = os.pathsep.join(self.toolchain.get_variable("LDFLAGS", list))
setvar("CMAKE_INCLUDE_PATH", include_paths)
set... |
asiroliu/MyTools | MyArgparse.py | Python | gpl-2.0 | 2,738 | 0.004018 | # coding=utf-8
from __future__ import unicode_literals
"""
Name: MyArgparse
Author: Andy Liu
Email : andy.liu.ud@hotmail.com
Created: 3/26/2015
Copyright: All rights reserved.
Licence: This program is free software: you can redistribute it
and/or modify it under the te... | help='Add different values to list')
args = parser.parse_args()
logging.debug('NoPre = %r' % args.NoPre)
logging.debug('simple_value = %r' % args.simple_value)
logging.debug('constant_value = %r' % args.constant_value)
logging.debug('boolean_switch = %r' % args.boolean... | llection)
logging.debug('const_collection = %r' % args.const_collection)
return args
if __name__ == '__main__':
from MyLog import init_logger
logger = init_logger()
parse_command_line()
|
chrigu6/vocabulary | vocabulary/trainer/admin.py | Python | gpl-3.0 | 195 | 0 | from django.contrib import admin
from trai | ner.models import Language, Word, Card, Set
admin.site.register(Language)
admin.site.register(Word)
admin.site.register(Card)
admin.site.regist | er(Set)
|
tomashaber/raiden | raiden/network/protocol.py | Python | mit | 24,753 | 0.000485 | # -*- coding: utf-8 -*-
import logging
import random
from collections import (
namedtuple,
defaultdict,
)
from itertools import repeat
import cachetools
import gevent
from gevent.event import (
_AbstractLinkable,
AsyncResult,
Event,
)
from ethereum import slogging
from raiden.exceptions import (
... | out of values.
Returns:
bool: True if the message was acknowledged, False otherwise.
"""
async_result = protocol.send_raw_with_result(
data,
receiver_address,
)
event_quit = event_first_of(
asyn | c_result,
event_stop,
)
for timeout in timeout_backoff:
if event_quit.wait(timeout=timeout) is True:
break
protocol.send_raw_with_result(
data,
receiver_address,
)
return async_result.ready()
def wait_recovery(event_stop, event_health... |
kernsuite-debian/lofar | SAS/ResourceAssignment/ResourceAssignmentEditor/config/default.py | Python | gpl-3.0 | 967 | 0 | # Copyright (C) 2012-2015 ASTRON (Netherlands Institute for Radio Astronomy)
# P.O. Box 2, 7990 AA Dwingeloo, The Netherlands
#
# This file is part of the LOFAR software suite.
# The LOFAR software suite is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as p... | he LOFAR software suite is distributed in the hope that it will b | e 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 a copy of the GNU General Public License along
# with the LOFAR software suite. If not, see <http://www.g... |
mediafactory/yats | modules/yats/caldav/storage.py | Python | mit | 12,605 | 0.002697 | # -*- coding: utf-8 -*-
import json
import logging
import vobject
from datetime import datetime
from contextlib import contextmanager
from radicale import ical
from yats.shortcuts import get_ticket_model, build_ticket_search_ext, touch_ticket, remember_changes, mail_ticket, jabber_ticket, check_references, add_histo... | NENT') and settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT:
tic.component_id = settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT
tic.show_start = cd['show_start']
tic.uuid = cal.vtodo.uid.value
tic.save(user=request.user)
... | for ele in form.changed_data:
form.initial[ele] = ''
remember_changes(request, form, tic)
touch_ticket(request.user, tic.pk)
mail_ticket(request, tic.pk, form, rcpt=settings.TICKET_NEW_MAIL_RCPT, is_api=True)
ja... |
our-city-app/oca-backend | src/rogerthat/bizz/payment/to.py | Python | apache-2.0 | 1,164 | 0.000859 | # -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance | with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in | writing, software
# distributed under the 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.
#
# @@license_version:1.7@@
from mcfw.properties import... |
laurent-george/weboob | modules/cmso/__init__.py | Python | agpl-3.0 | 788 | 0 | # -*- coding: utf-8 -*-
# | Copyright(C) 2012 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 your option) any later version.
#
# weboob 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 PARTIC... |
pculture/mirocommunity | localtv/models.py | Python | agpl-3.0 | 55,425 | 0.000902 | import datetime
import itertools
import re
import urllib2
import mimetypes
import operator
import logging
import sys
import traceback
import warnings
import tagging
import tagging.models
import vidscraper
from bs4 import BeautifulSoup
from django.conf import settings
from django.contrib.auth.models import User
from dj... | ing)
return True
class WidgetSettingsManager(SiteRelatedManager):
def _new_entry(self, site, using):
ws = super(WidgetSettingsManager, self)._new_entry(site, using)
try:
site_settings = SiteS | ettings.objects.get_cached(site, using)
except SiteSettings.DoesNotExist:
pass
else:
if site_settings.logo:
site_settings.logo.open()
ws.icon = site_settings.logo
ws.save()
return ws
class WidgetSettings(Thumbnailable):
... |
caseyrollins/osf.io | api/base/versioning.py | Python | apache-2.0 | 5,741 | 0.003135 | from rest_framework import exceptions as drf_exceptions
from rest_framework import versioning as drf_versioning
from rest_framework.compat import unicode_http_header
from res | t_framework.utils.mediatypes import _MediaType
from api.base import exceptions
from api.base import utils
from api.base.renderers import BrowsableAPIRendererNoForms
from api.base.settings import LATEST_VERSIONS
def get_major_version(version):
ret | urn int(version.split('.')[0])
def url_path_version_to_decimal(url_path_version):
# 'v2' --> '2.0'
return str(float(url_path_version.split('v')[1]))
def decimal_version_to_url_path(decimal_version):
# '2.0' --> 'v2'
return 'v{}'.format(get_major_version(decimal_version))
def get_latest_sub_version... |
Guidobelix/pyload | module/plugins/accounts/FilerioCom.py | Python | gpl-3.0 | 407 | 0.014742 | # -*- coding: utf-8 -*-
from module.plugins.internal.XFSAccount import XFSAccount
class FilerioCom(XFSAccount): |
__name__ = "FilerioCom"
__type__ = "account"
__version__ = "0.07"
__status__ = "testing"
__description__ = """FileRio.in account plugin"""
__license__ = "GPLv3"
__authors__ = [("zoidberg", "zoidberg@mujmail.cz")]
PLUGIN_ | DOMAIN = "filerio.in"
|
ray-project/ray | python/ray/train/tests/test_results_preprocessors.py | Python | apache-2.0 | 7,269 | 0.001238 | import pytest
from ray.train.callbacks.results_preprocessors import (
ExcludedKeysResultsPreprocessor,
IndexedResultsPreprocessor,
SequentialResultsPreprocessor,
AverageResultsPreprocessor,
MaxResultsPreprocessor,
WeightedAverageResultsPreprocessor,
)
def test_excluded_keys_results_preprocess... | results_preprocessor1 = WeightedAverageResultsPreprocessor(["a"], "b")
expected1 = deepcopy(results1)
for res in expected1:
res.update({"weight_avg_b(a)": 2.5})
assert results_preprocessor1.p | reprocess(results1) == expected1
assert (
"Averaging weight `b` is not reported by all workers in `train.report()`."
in caplog.text
)
assert "Use equal weight instead." in caplog.text
# test case 2: metric key `a` (to be averaged) is not reported from all workers
results_preprocesso... |
g2p/tranquil | tranquil/__init__.py | Python | bsd-3-clause | 1,717 | 0.041351 | import re
from django.core.exceptions import ImproperlyConfigured
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import sessionmaker
from tranquil.models import Importer
__all__ = ( 'engine', 'meta', 'Session', )
class EngineCache(object):
__shared_state = dict(
engine = None,
meta = None,
... | raise ImproperlyConfigured( 'Unknown database engine: %s' % settings.DATABASE_ENGINE )
url = '{protocol}://{user}:{pass}@{host}{port}/{name}'
for p in options:
if p == 'port' and len( options[p] ) > 0:
url = re.sub( '{%s}' % p, ':%s' % options[p], url )
else:
url = re.sub( '{%s}' % p, options[... | )
self.Session = sessionmaker( bind=self.engine, autoflush=True, autocommit=False )
self.importer = Importer(self.meta)
cache = EngineCache()
engine = cache.engine
meta = cache.meta
Session = cache.Session
|
jku/telepathy-gabble | tests/twisted/jingle/initial-audio-video.py | Python | lgpl-2.1 | 7,213 | 0.004298 | """
Tests outgoing calls created with InitialAudio and/or InitialVideo, and
exposing the initial contents of incoming calls as values of InitialAudio and
InitialVideo
"""
import operator
from servicetest import (
assertContains, assertEquals, assertLength,
wrap_channel, EventPattern, call_async, make_channel_... | EL_TYPE_STREAMED_MEDIA ]
assertLength(1, media_classes)
fixed, allowed = media_classes[0]
assertContains(cs.INITIAL_AU | DIO, allowed)
assertContains(cs.INITIAL_VIDEO, allowed)
check_neither(q, conn, bus, stream, remote_handle)
check_iav(jt, q, conn, bus, stream, remote_handle, True, False)
check_iav(jt, q, conn, bus, stream, remote_handle, False, True)
check_iav(jt, q, conn, bus, stream, remote_handle, True, True)
... |
markflyhigh/incubator-beam | sdks/python/apache_beam/io/textio_test.py | Python | apache-2.0 | 43,198 | 0.006898 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | datetime
import glob
import gzip
import logging
import os
import shutil
import sys
import tempfile
import unittest
import zlib
from builtins import range
import apache_beam as beam
import apache_beam.io.source_test_utils as source_test_utils
from apache_beam import coders
from apach | e_beam.io import ReadAllFromText
from apache_beam.io import iobase
from apache_beam.io.filesystem import CompressionTypes
from apache_beam.io.textio import _TextSink as TextSink
from apache_beam.io.textio import _TextSource as TextSource
# Importing following private classes for testing.
from apache_beam.io.textio impo... |
awg24/pretix | src/pretix/plugins/paypal/signals.py | Python | apache-2.0 | 267 | 0 | from django.dispatch import receiver
from pretix.base.signals import register_payment_providers
@receiver(reg | ister_payment_providers, dispatch_uid="payment_paypal")
def register_payment_provider(sender, **kwargs):
from .payment import Paypal
return | Paypal
|
idlesign/django-admirarchy | admirarchy/tests/testapp/models.py | Python | bsd-3-clause | 633 | 0.00158 | from django.db import models
class AdjacencyListModel(models.Model):
title = models.CharField(max_length=100)
parent = models.ForeignKey(
'self', related_name='%(class)s_parent', on_delete=models.CASCADE, db_index=True, null=True, blank=True)
def __str__(self):
return 'adjacencylistmode... | SetModel(models.Model):
title = | models.CharField(max_length=100)
lft = models.IntegerField(db_index=True)
rgt = models.IntegerField(db_index=True)
level = models.IntegerField(db_index=True)
def __str__(self):
return 'nestedsetmodel_%s' % self.title
|
lkmhaqer/gtools-python | netdevice/migrations/0007_auto_20190410_0358.py | Python | mit | 567 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2019-04-10 03:58
from __future__ | import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('netdevice', '0006_auto_20190409_0325'),
]
operations = [
migrations.RenameField(
model_name='vrf',
old_name='vrf_name', |
new_name='name',
),
migrations.RenameField(
model_name='vrf',
old_name='vrf_target',
new_name='target',
),
]
|
doffm/dbuf | src/dbuf/util.py | Python | bsd-3-clause | 3,108 | 0.026705 | from functools import reduce
class ScopedString (object):
def __init__ (self):
self._stack = []
def push (self, frame):
self._stack.append (frame)
def pop (s | elf):
frame = self._stack.pop()
return frame
def __str__ | (self):
return '.'.join (self._stack)
class ScopedList (object):
def __init__ (self, stack=None):
if stack:
self._stack = stack
else:
self._stack = []
self.push()
def push (self):
... |
ebilionis/py-best | best/random/_student_t_likelihood_function.py | Python | lgpl-3.0 | 2,586 | 0.001933 | """A likelihood function representing a Student-t distribution.
Author:
Ilias Bilionis
Date:
1/21/2013
"""
__all__ = ['StudentTLikelihoodFunction']
import numpy as np
import scipy
import math
from . import GaussianLikelihoodFunction
class StudentTLikelihoodFunction(GaussianLikelihoodFunction):
"""An... | The data or a proper mean_funciton is
preassumed.
name --- A name for the likelihood function.
"""
self.nu = nu
super(StudentTLikelihoodFunction, self).__init__(num_input=num_input,
... | data=data,
mean_function=mean_function,
cov=cov,
name=name)
def __call__(self, x):
"""Evaluate the function at x."""
mu = s... |
Azure/azure-sdk-for-python | sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_operations_async.py | Python | mit | 3,884 | 0.00309 | # 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.
# --------------------------------------------------------------------... | ame="state", type=SearchFieldDataType.String),
], collection=True)
]
cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60)
scoring_profile = ScoringProfile(
name="MyProfile"
)
scoring_profiles = []
scoring_profiles.append(scoring_profile)
index = SearchInd... | fields=fields,
scoring_profiles=scoring_profiles,
cors_options=cors_options)
result = await client.create_or_update_index(index=index)
# [END update_index_async]
async def delete_index():
# [START delete_index_async]
name = "hotels"
await client.delete_index(name)
# [END delet... |
bohdon/maya-pulse | src/pulse/scripts/pulse/colors.py | Python | mit | 381 | 0 | def RGB01ToHex(rgb):
"""
Return an RGB color value as a hex color string.
"""
return '#%02x%02x%02x' % tuple([int(x * 255) for x in rgb])
def hexToRGB01(hexColor):
"""
Return a hex color string as an RGB tuple of floats in the | range 0..1
"""
h = hexColor.lstrip('#')
return tuple([x / 255.0 for x in [int(h[i:i + 2], 16) | for i in (0, 2, 4)]])
|
arenadata/ambari | ambari-server/src/main/resources/stacks/HDP/2.3.ECS/services/ECS/package/scripts/service_check.py | Python | apache-2.0 | 1,514 | 0.004624 | """
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... | import params
env.set_params(params)
# run fs list command to make sure ECS client can talk to ECS backend
list_command = format("fs -ls /")
if params.security_enabled:
Execute(forma | t("{kinit_path_local} -kt {hdfs_user_keytab} {hdfs_principal_name}"),
user=params.hdfs_user
)
ExecuteHadoop(list_command,
user=params.hdfs_user,
logoutput=True,
conf_dir=params.hadoop_conf_dir,
try_sleep=3,
trie... |
abo-abo/edx-platform | common/djangoapps/mitxmako/middleware.py | Python | agpl-3.0 | 1,006 | 0 | # Copyright (c) 2008 Mikeal Rogers
#
# Licensed under the Apache License, Version 2.0 (the "Licen | se");
# | you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribuetd under the License is distributed on an "AS IS" BASIS,
# WITHOUT W... |
maciejkula/spotlight | spotlight/cross_validation.py | Python | mit | 6,519 | 0 | """
Module with functionality for splitting and shuffling datasets.
"""
import numpy as np
from sklearn.utils import murmurhash3_32
from spotlight.interactions import Interactions
def _index_or_none(array, shuffle_index):
if array is None:
return None
else:
return array[shuffle_index]
de... | d for the shuffle.
Returns
-------
interactions: :class:`spotlight.interactions.Interactions`
The shuffled interactions.
"""
if random_state is None:
random_state = np.random.RandomState()
shuffle_indices = np.arange(len(interactions.user_ids))
random_state.shuffle(shuffl... | nteractions.ratings,
shuffle_indices),
timestamps=_index_or_none(interactions.timestamps,
shuffle_indices),
weights=_index_or_none(interactions.weights,
... |
alirizakeles/memopol-core | memopol/meps/migrations/0017_auto__del_field_mep_stg_office.py | Python | gpl-3.0 | 12,677 | 0.008046 | # encoding: utf-8
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'MEP.stg_office'
db.delete_column('meps_mep', 'stg_office')
def backwards(self, orm):
# User chose to not deal... | 'False'}),
'countries': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['meps.Country']", 'through': "orm['meps.CountryMEP']", 'symmetrical': 'False'}),
'delegations': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['meps.Delegation']", 'through': "orm['m... | onRole']", 'symmetrical': 'False'}),
'ep_debates': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'ep_declarations': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'ep_id': ('django.db.models.fields.IntegerField', [], {'unique': 'True'}),
... |
SqueezeStudioAnimation/dpAutoRigSystem | dpAutoRigSystem/Scripts/dpArm.py | Python | gpl-2.0 | 3,972 | 0.007301 | # importing libraries:
import maya.cmds as cmds
import maya.mel as mel
# global variables to this module:
CLASS_NAME = "Arm"
TITLE = "m028_arm"
DESCRIPTION = "m029_armDesc"
ICON = "/Icons/dp_arm.png"
def Arm(dpAutoRigInst):
""" This function will create all guides needed to compose an arm.
"""
# chec... | RigInst.guide.Finger.editUserName(ringFingerInstance, checkText=dpAutoRigInst.langDic[dpAutoRigInst.langName]['m034_ring'])
pinkFingerInstance = dpAutoRigInst.initGuide('dpFinge | r', guideDir)
dpAutoRigInst.guide.Finger.editUserName(pinkFingerInstance, checkText=dpAutoRigInst.langDic[dpAutoRigInst.langName]['m035_pink'])
thumbFingerInstance = dpAutoRigInst.initGuide('dpFinger', guideDir)
dpAutoRigInst.guide.Finger.editUserName(thumbFingerInstance, checkText=dpAutoRigIns... |
madprime/genevieve | genevieve_client/migrations/0004_auto_20160328_1526.py | Python | mit | 1,731 | 0.001733 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-28 15:26
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependen... | s.CharField(blank=True, max_length=30)),
('refresh_token', models.CharField(blank=True, max_length=30)),
('token_expiration', models.DateTimeField(null=True)),
| ('connected_id', models.CharField(max_length=30, unique=True)),
('openhumans_username', models.CharField(blank=True, max_length=30)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
... |
dr-bigfatnoob/quirk | language/functions.py | Python | unlicense | 1,698 | 0.009423 | from __future__ import print_function, division
import sys
import os
sys.path.append(os.path.abspath("."))
sys.dont_write_bytecode = True
from distribution import *
import operator as o
from utils.lib import gt, lt, gte, lte, neq, eq
__author__ = "bigfatnoob"
def sample(values, size=100):
return np.random.choice(v... | "normalCI": NormalCI,
"uniform": Uniform,
"random": Random,
"exp": Exponential,
"binomial": Binomial,
"geometric": Geometric,
"triangular": Triangular
} |
operations = {
"+": o.add,
"-": o.sub,
"*": o.mul,
"/": o.div,
"|": max,
"&": o.mul,
">": to_int(gt),
"<": to_int(lt),
">=": to_int(gte),
"<=": to_int(lte),
"==": to_int(eq),
"!=": to_int(neq)
}
|
timohtey/mediadrop_copy | mediacore_env/Lib/site-packages/distribute-0.7.3/setup.py | Python | gpl-3.0 | 1,879 | 0.000532 | #!/usr/bin/env python
"""Distutils setup file, used to install or test 'setuptools'"""
import textwrap
import sys
try:
import setuptools
except ImportError:
sys.stderr.write("Distribute 0.7 may only upgrade an existing "
"Distribute 0.6 installation")
| raise SystemExit(1)
long_description = textwrap.dedent("""
Distribute - legacy package
This package is a simple c | ompatibility layer that installs Setuptools 0.7+.
""").lstrip()
setup_params = dict(
name="distribute",
version='0.7.3',
description="distribute legacy wrapper",
author="The fellowship of the packaging",
author_email="distutils-sig@python.org",
license="PSF or ZPL",
long_description=lon... |
shazadan/mood-map | tweets/management/commands/stream.py | Python | gpl-2.0 | 361 | 0.00554 | from django.core.mana | gement.base import BaseCommand, CommandError
from tweets.tasks import stream
|
#The class must be named Command, and subclass BaseCommand
class Command(BaseCommand):
# Show this when the user types help
help = "My twitter stream command"
# A command must define handle()
def handle(self, *args, **options):
stream()
|
yytang2012/novels-crawler | novelsCrawler/spiders/piaotian.py | Python | mit | 1,931 | 0.000518 | #!/usr/bin/env python
# coding=utf-8
"""
Created on April 15 2017
@author: yytang
"""
from scrapy import Selector
from libs.misc import get_spider_name_from_domain
from libs.polish import polish_title, polish_subtitle, polish_content
from novelsCrawler.spiders.novelSpider import NovelSpider
class PiaotianSpider(No... | ngs = {
# 'DOWNLOAD_DELAY': 0.3,
# }
def parse_title(self, response):
sel = Selector(response)
title = sel.xpath('//h1/text()').extract()[0]
title = polish_title(title, self.name)
return title
def parse_episodes(self, response):
sel = Selector(response)
... | e(subtitle_selectors):
subtitle_url = subtitle_selector.xpath('@href').extract()[0]
subtitle_url = response.urljoin(subtitle_url.strip())
subtitle_name = subtitle_selector.xpath('text()').extract()[0]
subtitle_name = polish_subtitle(subtitle_name)
episodes.app... |
signed/intellij-community | python/testData/inspections/PyTupleAssignmentBalanceInspectionTest/unpackNonePy3.py | Python | apache-2.0 | 65 | 0.076923 | a, b = <warning d | escr="Need more values to unpa | ck">None</warning> |
dhoomakethu/apocalypse | apocalypse/server/__init__.py | Python | mit | 86 | 0.011628 | """
@author: dhoomakethu
"""
from __futur | e__ import absolute_import, u | nicode_literals |
rokubun/android_rinex | setup.py | Python | bsd-2-clause | 547 | 0.007313 | #!/usr/env/bin/ python3
from setuptools import setup, Extension
#
#CXX_FLAGS = "-O3 -std=gnu | ++11 -Wall -Wno-comment"
#
## List of C/C++ sources that will conform the library
#sources = [
#
# "andrnx/clib/android.c",
#
#]
setup(name="andrnx",
version="0.1",
description="Package to convert from GNSS logger to Rinex files",
author='Miquel Garcia',
author_ema | il='info@rokubun.cat',
url='https://www.rokubun.cat',
packages=['andrnx'],
test_suite="andrnx.test",
scripts=['bin/gnsslogger_to_rnx'])
|
ulikoehler/FreeCAD_drawing_dimensioning | InitGui.py | Python | gpl-3.0 | 3,832 | 0.008351 | class DrawingDimensioningWorkbench (Workbench):
# Icon generated using by converting linearDimension.svg to xpm format using Gimp
Icon = '''
/* XPM */
static char * linearDimension_xpm[] = {
"32 32 10 1",
" c None",
". c #000000",
"+ c #0008FF",
"@ c #0009FF",
"# c #000AFF",
"$ c ... | .",
". .",
". .",
". .",
". .",
". | .",
". .",
". ."};
'''
MenuText = 'Drawing Dimensioning'
def Initialize(self):
import importlib, os
from dimensioning import __dir__, debugPrint, iconPath
import linearDimension
import linearDimension_stack
... |
gilshwartz/tortoisehg-caja | tortoisehg/hgqt/filelistmodel.py | Python | gpl-2.0 | 7,732 | 0.002069 | # Copyright (c) 2009-2010 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# 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, o... | stype in _subrepoType2IcoMap:
ic = geticon(_subrepoType2IcoMap[stype])
ic = getoverlaidicon(ic, icOverlay)
subrepoIcoDict[stype] = ic
return subrepoIcoDict
class HgFileListModel(QAbstractTableModel):
"""
Model used for listing (modi | fied) files of a given Hg revision
"""
showMessage = pyqtSignal(QString)
def __init__(self, parent):
QAbstractTableModel.__init__(self, parent)
self._boldfont = parent.font()
self._boldfont.setBold(True)
self._ctx = None
self._files = []
self._filesdict = {}
... |
pyblish/pyblish-mindbender | mindbender/maya/pythonpath/userSetup.py | Python | mit | 488 | 0 | """Maya initialis | ation for Mindbender pipeline"""
from maya import cmds
def setup():
assert __import__("pyblish_maya").is_setup(), (
"pyblish-mindbender depends on pyblish_maya which has not "
"yet been setup. Run pyblish_maya.setup()")
from pyblish import api
api.register_gui("pyblish_lite")
from m... | import api, maya
api.install(maya)
# Allow time for dependencies (e.g. pyblish-maya)
# to be installed first.
cmds.evalDeferred(setup)
|
balancehero/kinsumer | kinsumer/checkpointer.py | Python | mit | 1,882 | 0.000531 | """:mod:`kinsumer.checkpointer` --- Persisting positions for Kinesis shards
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
import abc
import json
import os.path
from typing import Optional, Dict
class Checkpointer(abc.ABC, object):
"""Checkpointer is the interface for persisting ... | d] = sequence
def get_checkpoint(self, shard_id: str) -> Optional[str]:
return self._checkpoints.get(shard_id)
class FileCheckpointer(InMemoryCheckpointer):
def __init__(self, file: str) -> None:
| super().__init__()
self.file = os.path.expanduser(file)
if os.path.exists(self.file):
with open(self.file, 'rb') as f:
self._checkpoints = json.load(f)
def checkpoint(self, shard_id: str, sequence: str) -> None:
super().checkpoint(shard_id, sequence)
... |
gribvirus74/Bee-per | Error.py | Python | gpl-3.0 | 534 | 0.035581 | class ParametrizedError(Exception):
def __i | nit__(self, problem, invalid):
self.problem = str(problem)
self.invalid = str(invalid)
def __str__(self):
print('--- Error: {0}\n--- Caused by: {1}'.format(self.problem, self.invalid))
class InvalidToken(ParametrizedError):
pass
class ToneError(ParametrizedError):
pass
class IntervalError(Para... | etrizedError):
pass |
F5Networks/f5-common-python | f5/bigip/tm/cm/test/functional/test_failover_status.py | Python | apache-2.0 | 1,104 | 0.000906 | # Copyright 2016 F5 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 required by applicable law or agreed to in writi... | 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.
#
class TestFailoverStatus(object):
def test_get_status(se... | m/failover-status/")
failover_status.refresh()
des =\
(failover_status.entries['https://localhost/mgmt/tm/cm/failover-status/0']
['nestedStats']
['entries']
['status']
['description'])
assert des == "ACTIVE"
|
OpenMined/PySyft | tests/integration/smpc/tensor/share_tensor_test.py | Python | apache-2.0 | 975 | 0 | # third party
# third party
import numpy as np
import pytest
# syft absolute
# absolute
from syft.core.tensor.smpc.share_tensor import ShareTensor
@pytest.mark.smpc
def test_bit_extraction() -> None:
share = ShareTensor(rank=0, parties_info=[], ring_size=2**32)
data = np | .array([[21, 32], [-54, 89]], dtype=np.int32)
share.child = data
exp_res1 = np.array([[False, False], [True, False]], dtype=np.bool_)
res = share.bit_extraction(31).child
assert (res == exp_res1).all()
exp_res2 = np.array([[True, False], [False, False]], dtype=np.bool_)
| res = share.bit_extraction(2).child
assert (res == exp_res2).all()
@pytest.mark.smpc
def test_bit_extraction_exception() -> None:
share = ShareTensor(rank=0, parties_info=[], ring_size=2**32)
data = np.array([[21, 32], [-54, 89]], dtype=np.int32)
share.child = data
with pytest.raises(Exception):... |
nsalomonis/BAM-to-Junction-BED | multiBAMtoBED.py | Python | apache-2.0 | 19,040 | 0.024685 | ### hierarchical_clustering.py
#Author Nathan Salomonis - nsalomonis@gmail.com
#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... | ir,destination_file))
except Exception: pass
### If a single BAM file is indicated
| if bam_file != None:
output_filename = string.replace(bam_file,'.bam','')
output_filename = string.replace(output_filename,'=','_')
destination_file = output_filename+'__exon.bed'
paths_to_run = [(bam_file,refExonCoordinateFile,bed_reference_dir,destination_file)]
if 'reference'... |
kagenZhao/cnBeta | CnbetaApi/CnbetaApis/views.py | Python | mit | 3,183 | 0.002513 | #!/usr/bin/env python3
from django.shortcuts import render
# Create your views here.
from CnbetaApis.datas.Models import *
from CnbetaApis.datas.get_letv_json import get_letv_json
from CnbetaApis.datas.get_youku_json import get_youku_json
from django.views.decorators.csrf import csrf_exempt
from django.http import... | .GET.get('limit') or 20
session = DBSession()
datas = None
if lastID:
datas = session.query(Article).order_by(desc( | Article.id)).filter(and_(Article.introduction != None, Article.id < lastID)).limit(limit).all()
else:
datas = session.query(Article).order_by(desc(Article.id)).limit(limit).all()
values = []
for data in datas:
values.append({
'id': data.id,
'title': data.title,
... |
fbradyirl/home-assistant | tests/components/google/test_calendar.py | Python | apache-2.0 | 11,260 | 0.000977 | """The tests for the google calendar platform."""
import copy
from unittest.mock import Mock, patch
import httplib2
import pytest
from homeassistant.components.google import (
CONF_CAL_ID,
CONF_CLIENT_ID,
CONF_CLIENT_SECRET,
CONF_DEVICE_ID,
CONF_ENTITIES,
CONF_NAME,
CONF_TRACK,
DEVICE_... | _of_event + dt_util.dt.timedelta(minutes=60)
start = middle_of_event.isoformat()
end = end_event.isoformat()
event = copy.deepcopy(TEST_EVENT)
event["start"]["dateTime"] = start
event["end"]["dateTime"] = end
mock_next_event.return_value.event = event
assert await async_setup_component(hass... | })
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY)
assert state.name == TEST_ENTITY_NAME
assert state.state == STATE_ON
assert dict(state.attributes) == {
"friendly_name": TEST_ENTITY_NAME,
"message": event["summary"],
"all_day": False,
"offse... |
capoe/espressopp.soap | src/Int3D.py | Python | gpl-3.0 | 3,721 | 0.017468 | # Copyright (C) 2012,2013
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ is free software: you can redistr | ibute it and/or modify
# it under th | e 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.
#
# ESPResSo++ is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY ... |
areeda/gwpy | gwpy/plot/tests/test_segments.py | Python | gpl-3.0 | 5,755 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) Duncan Macleod (2018-2020)
#
# This file is part of GWpy.
#
# GWpy 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)... | re details.
#
# You should have received a copy of the GNU General Public License
# along with GWpy. If not, see <http://www.gnu.org/licenses/>.
"""Tests for `gwpy.plot.segments`
"""
import pytest
import numpy
from matplotlib import rcParams
from matplotlib.colo | rs import ColorConverter
from matplotlib.collections import PatchCollection
from ...segments import (Segment, SegmentList, SegmentListDict,
DataQualityFlag, DataQualityDict)
from ...time import to_gps
from .. import SegmentAxes
from ..segments import SegmentRectangle
from .test_axes import Tes... |
kumar303/rockit | vendor-local/boto/mturk/qualification.py | Python | bsd-3-clause | 6,761 | 0.005177 | # Copyright (c) 2008 Chris Moyer http://coredumped.org/
#
# 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 to use, copy, modify, ... | accepted. The value is an integer between 0 and 100.
"""
def __init__(self, comparator, integer_value, required_to_preview=False):
Requirement.__init__(self, qualification_type_id="00000000000000000070", comparator=comparator, integer_value=integer_value, required_to_preview=required_to_preview)
class... | dRequirement(Requirement):
"""
The percentage of assignments the Worker has returned, over all assignments the Worker has accepted. The value is an integer between 0 and 100.
"""
def __init__(self, comparator, integer_value, required_to_preview=False):
Requirement.__init__(self, qualification_t... |
ammzen/SolveLeetCode | 9PalindromeNumber.py | Python | mit | 727 | 0.008253 | # Determine whether an integer is a palindrome. Do this without extra space.
class Solution:
# @return a boolean
def isPalindrome1(self, x):
if x < 0 or x % 10 == 0 and x:
return False
xhalf = 0
while x > xhalf:
xhalf = xhalf | * 10 + x % 10
x /= 10
return (x == xhalf or x == xhalf/10
)
def isPalindrome(self, x):
if x < 0:
return False
size, xreverse = x, 0
while size:
xreverse = xreverse * 10 + size % 10
si | ze = (size - (size % 10)) / 10
return True if xreverse==x else False
if __name__ == '__main__':
s = Solution()
print s.isPalindrome1(0) |
Trinak/PyHopeEngine | src/pyHopeEngine/event/guiEvents.py | Python | gpl-3.0 | 550 | 0.007273 | '''
Created o | n Aug 27, 2013
@author: Devon
Define gui events
'''
from pyHopeEngine import BaseEvent
class Event_ButtonPressed(BaseEvent):
'''Sent when a button is pressed'''
eventType = "ButtonPressed"
def __init__(self, value):
'''Contains a value identifying the button'''
self.value = value
... | self.height = height |
gandalf-the-white/foundation | amaryl/scripts/initdatabase.py | Python | mit | 1,705 | 0.021114 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import mysql.connector
import time
import datetime
conn = mysql.connector.connect(host="localhost",user="spike",password="valentine", database="drupal | ")
cann = mysql.connector.connect(host="localhost",user="spike",password="valentine", database="content_delivery_weather")
cursor = conn.cursor()
cursar = cann.cursor()
cursor.execute("""SELECT uid, mail FROM users""")
rows = cursor.fetchall()
for row in rows:
if row[0] != 0:
p | rint('{0} : {1} '.format(row[0], row[1]))
#print('UPDATE new_v4_users_probes_edit SET email = {0} WHERE uid = {1}'.format(row[1], row[0]))
cursar.execute("""UPDATE new_v4_users_probes_edit SET email = %s WHERE userid = %s""",(row[1], row[0]))
cursar.execute("""SELECT probename, probeid FROM new_v4_sonde"... |
marchdf/dotfiles | mypython/mypython/mytermcolor.py | Python | mit | 5,928 | 0.000337 | # I made some modifications to termcolor so you can pass HEX colors to
# the colored function. It then chooses the nearest xterm 256 color to
# that HEX color. This requires some color functions that I have added
# in my python path.
#
# 2015/02/16
#
#
# coding: utf-8
# Copyright (c) 2008-2011 Volvox Development Team
... | ue, magenta, cyan, white.
Available text highlights:
on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.
Available attributes:
| bold, dark, underline, blink, reverse, concealed.
Example:
colored('Hello, World!', 'red', 'on_grey', ['blue', 'blink'])
colored('Hello, World!', 'green')
"""
if os.getenv("ANSI_COLORS_DISABLED") is None:
fmt_str = "\033[%dm%s"
if color is not None:
if "#" in ... |
shub0/algorithm-data-structure | python/find_minimum.py | Python | bsd-3-clause | 1,730 | 0.004046 | #! /usr/bin/python
'''
Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
'''
class Solution:
# @param num, a list of integer
# @return an integer
# You may assume no duplicate exists in the array.
def fi... | 2**32)
size = len(num)
if size == 0:
return INT_MIN_VALUE
elif size == 1:
return num[0]
low_index = 0
high_index = size - 1
while (low_index < high_index - 1):
mid_index = low_index + (high_index - low_index) / 2
if (num[mid... | high_index -= 1
return min(num[low_index], num[high_index])
if __name__ == '__main__':
solution = Solution()
print solution.findMinDuplicate([3,3,1,2,2])
|
End of preview. Expand in Data Studio
github python code fim
Generated from tomekkorbak/python-github-code, limiting context length to 8192.
- Downloads last month
- 39