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 |
|---|---|---|---|---|---|---|---|---|
hartwork/wnpp.debian.net | wnpp_debian_net/tests/factories.py | Python | agpl-3.0 | 984 | 0.001016 | # Copyright (C) 2021 Sebastian Pipping <[email protected]>
# Licensed under GNU Affero GPL v3 or later
from django.utils.timezone import now
from factory import LazyFunction, Sequence
from factory.django import DjangoModelFactory
from ..models import DebianLogIndex, DebianLogMods, DebianPopcon, DebianWnpp, IssueK... | ndexFactory(DjangoModelFactory):
class Meta:
model = DebianLogIndex
event_stamp = LazyFunction(now)
log_stamp = LazyFunction(now)
class DebianLogModsFactory(DjangoModelFactory):
class Meta:
model = DebianLogMods
class DebianPopconFactory(DjangoModelFactory):
class Meta:
... | DebianWnppFactory(DjangoModelFactory):
class Meta:
model = DebianWnpp
ident = Sequence(int)
cron_stamp = LazyFunction(now)
mod_stamp = LazyFunction(now)
open_stamp = LazyFunction(now)
kind = IssueKind.RFA.value # anything that matches the default filters
|
sidgan/whats_in_a_question | caffe/monitor/extract_seconds.py | Python | gpl-3.0 | 2,142 | 0.002334 | #!/usr/bin/env python
############################
### Reusing Existing code ##
# Reference:https://github.com/BVLC/caffe/blob/master/tools/extra/extract_seconds.py #
############################
import datetime
import os
import sys
def extract_datetime_from_line(line, year):
# Expected format: I0210 13:39:22.38... | ""
log_created_time = os.path.getctime(input_file)
log_created_year = datetime.datetime.fro | mtimestamp(log_created_time).year
return log_created_year
def get_start_time(line_iterable, year):
"""Find start time from group of lines
"""
start_datetime = None
for line in line_iterable:
line = line.strip()
if line.find('Solving') != -1:
start_datetime = extract_da... |
langerhans/dogecoin | qa/rpc-tests/rpcbind_test.py | Python | mit | 5,804 | 0.006203 | #!/usr/bin/env python
# Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Test for -rpcbind, as well as -rpcallowip and -rpcconnect
# Add python-bitcoinrpc to module search path:... | des(1, tmpdir, [base_args])
try:
# connect to node through non-loopback interface
url = "http://wowsuchtest:3kt4yEUdDJ4YGzsGNADvjYwubwaFhEEYjotPJDU2XMgG@%s:%d" % (rpchost, rpcport,)
node = AuthServiceProxy(url)
node.getinfo()
finally:
node = None # make sure connection wi... | ds()
def run_test(tmpdir):
assert(sys.platform == 'linux2') # due to OS-specific network stats queries, this test works only on Linux
# find the first non-loopback interface for testing
non_loopback_ip = None
for name,ip in all_interfaces():
if ip != '127.0.0.1':
non_loopback_ip = ... |
Azure/azure-sdk-for-python | sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2020_09_30/operations/_disk_encryption_sets_operations.py | Python | mit | 40,114 | 0.004961 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | cryptionSetName}')
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
"resourceGroupName": _SERIALIZER.url( | "resource_group_name", resource_group_name, 'str'),
"diskEncryptionSetName": _SERIALIZER.url("disk_encryption_set_name", disk_encryption_set_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[... |
cloudcomputinghust/IoT | test-component/receive_data_only.py | Python | mit | 1,140 | 0.003509 | #!/usr/bin/env python
import pika
import os
cloud_broker_host = os.environ.get('CLOUD_BROKER_HOST')
cloud_broker_port = os.environ.get('CLOUD_BROKER_PORT')
cloud_broker_auth = os.environ.get('CLOUD_BROKER_AUTH')
cloud_username = cloud_broker_auth.split(':')[0]
cloud_password = cloud_broker_auth.split(':')[1]
# Connect... | r_collector',
queue=queue_name)
print(' [*] Waiting for data. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r" % body)
channel.basic_consume(callback,
| queue=queue_name,
no_ack=True)
channel.start_consuming() |
ak110/pytoolkit | pytoolkit/applications/__init__.py | Python | mit | 117 | 0 | """Kerasの各種モデル。"""
# pylint: sk | ip-file
# flake8: noq | a
from . import darknet53, efficientnet, xception
|
usc-isi/extra-specs | nova/tests/test_xenapi.py | Python | apache-2.0 | 83,206 | 0.001058 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2010 Citrix Systems, 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/L... | k that the VM has a VBD attached to it
# Get XenAPI record for VBD
vbds = xenapi_fake.get_all('VBD')
vbd = xenapi | _fake.get_record('VBD', vbds[0])
vm_ref = vbd['VM']
self.assertEqual(vm_ref, vm)
def test_attach_volume_raise_exception(self):
"""This shows how to test when exceptions are raised."""
stubs.stubout_session(self.stubs,
stubs.FakeSessionForVolumeFailedTes... |
huangshiyu13/funnyLittleProgram | WhatKindofGirlYouLIke/labelImg/libs/pascal_voc_io.py | Python | apache-2.0 | 4,750 | 0.007789 | import sys
from xml.etree import ElementTree
from xml.etree.ElementTree import Element, SubElement
from xml.dom import minidom
from lxml import etree
class PascalVocWriter:
def __init__(self, foldername, filename, imgSize, databaseSrc='Unknown', localImgPath=None):
self.foldername = foldername
self... | depth.text = '1'
segmented = SubEleme | nt(top,'segmented')
segmented.text ='0'
return top
def addBndBox(self, xmin, ymin, xmax, ymax, name):
bndbox = {'xmin':xmin, 'ymin':ymin, 'xmax':xmax, 'ymax':ymax}
bndbox['name'] = name
self.boxlist.append(bndbox);
def appendObjects(self, top):
for each_object ... |
betzw/mbed-os | tools/targets/REALTEK_RTL8195AM.py | Python | apache-2.0 | 5,555 | 0.0036 | """
Realtek Semiconductor Corp.
RTL8195A elf2bin script
"""
import sys, array, struct, os, re, subprocess
import hashlib
import shutil
import time
import binascii
import elftools
from tools.paths import TOOLS_BOOTLOADERS
from tools.toolchains import TOOLCHAIN_PATHS
# Constant Variables
TAG = 0x81950001
VER = 0x8195... | dr
write_number(addr, 8, file_bin)
write_number(size, 8, file_bin)
# write load segment
file_bin.write(file_elf.read(size))
delta = size % 4
if delta != 0:
padding = 4 - delta
write_number(0x0, padding * 2, file_bin)
file_bin.close()
file_e... | am1_bin, ram2_bin):
# remove target binary file/path
if os.path.isfile(image_bin):
os.remove(image_bin)
else:
shutil.rmtree(image_bin)
RAM2_HEADER['tag'] = format_number(TAG, 8)
RAM2_HEADER['ver'] = format_number(VER, 8)
RAM2_HEADER['timestamp'] = format_number(epoch_timestamp(... |
chenkianwee/envuo | py4design/py3dmodel/export_collada.py | Python | gpl-3.0 | 18,035 | 0.014084 | # ==================================================================================================
#
# Copyright (c) 2016, Chen Kian Wee ([email protected])
#
# This file is part of py4design
#
# py4design is free software: you can redistribute it and/or modify
# it under the terms of the GNU General ... | (normal_id, numpy.array(normal_floats), ('X', 'Y', 'Z'))
geom = geometry.Geometry(mesh, "geometry" + str(shell_cnt), "geometry" + str(shell_cnt), [vert_src, normal_src])
input_list = source.InputList()
input_list.addInput(0, 'VERTEX', "#" | +vert_id)
#input_list.addInput(1, 'NORMAL', "#"+normal_id)
vcnt = numpy.array(vcnt)
indices = numpy.array(indices)
if face_rgb_colour_list!=None:
mat_name="materialref"+ str(shell_cnt)
polylist = geom.createPolylis... |
sivakuna-aap/superdesk-core | superdesk/io/commands/update_ingest.py | Python | agpl-3.0 | 22,300 | 0.003722 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logg... | r,
'rule_set': get_provider_rule_set(provider),
'routing_scheme': get_provider_routing_scheme(provider)
}
update_provider.apply_async(expires=get_task_ttl(provider), kwargs=kwargs)
@celery.task(soft_time_limit=1800, bind=True)
def update_provide... | t provider as per the configuration, ingests them into Superdesk and
updates the provider.
:param self:
:type self:
:param provider: Ingest Provider Details
:type provider: dict :py:class:`superdesk.io.ingest_provider_model.IngestProviderResource`
:param rule_set: Translation Rule Set if one is... |
mshunshin/SegNetCMR | pydicom/contrib/dicom_dao.py | Python | mit | 14,663 | 0.000341 | #!/usr/bin/python
""" dicom_dao
Data Access Objects for persisting PyDicom DataSet objects.
Currently we support couchdb through the DicomCouch class.
Limitations:
- Private tags are discarded
TODO:
- Unit tests with multiple objects open at a time
- Unit tests with rtstruct objects
- Support for mongodb (mong... | uploaded.
# I don't really like the extra HTTP GET and I think we can generate
# what we need without doing it. Don't | have time to work out how yet.
self._meta[dcm.SeriesInstanceUID]['doc'] = \
self._db[dcm.SeriesInstanceUID]
def __str__(self):
""" Return the string representation of the couchdb client """
return str(self._db)
def __repr__(self):
""" Return the canonical string re... |
rebase-helper/rebase-helper | rebasehelper/helpers/koji_helper.py | Python | gpl-2.0 | 14,918 | 0.001006 | # -*- coding: utf-8 -*-
#
# This tool helps you rebase your package to the latest version
# Copyright (C) 2013-2019 Red Hat, Inc.
#
# 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... | sk_label)
elif state == koji.TASK_STATES['FAILED']:
logger.info('%s failed', task_label)
elif state == koji.TASK_STATES['CANCELED']:
logger.info(' | %s was canceled', task_label)
else:
# shouldn't happen
logger.info('%s has not completed', task_label)
@classmethod
def watch_koji_tasks(cls, session, tasklist):
"""Waits for Koji tasks to finish and prints their states.
Args:
session (ko... |
pierky/ripe-atlas-monitor | pierky/ripeatlasmonitor/Helpers.py | Python | gpl-3.0 | 8,807 | 0.000114 | # Copyright (C) 2016 Pier Carlo Chiodi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed... | SN for the curre | nt msm AF
def __str__(self):
if self.asn is not None:
tpl = "probe ID {id} (AS{asn}, {cc})"
else:
tpl = "probe ID {id} ({cc})"
return tpl.format(
id=self.id,
asn=self.asn,
cc=self.country_code
)
class ProbesFilter(object)... |
Aravinthu/odoo | addons/base_import/__manifest__.py | Python | agpl-3.0 | 1,164 | 0 | {
'name': 'Base import',
'description': """
New extensible file import for Odoo
======================================
Re-implement Odoo's file import system:
* Server side, the previous system forces most of the logic into the
client which duplicates the effort (between clients), makes the
import system ... | ld their
own front-end to import from other file formats (e.g. OpenDocument
files) which may be simpler to handle in their work flow or from
their data production sources.
* In a module, so that administrators and users of Odoo who do not
need or | want an online import can avoid it being available to users.
""",
'depends': ['web'],
'category': 'Extra Tools',
'installable': True,
'auto_install': True,
'data': [
'security/ir.model.access.csv',
'views/base_import_templates.xml',
],
'qweb': ['static/src/xml/base_import.xml... |
patrickhoefler/linked-data-wizards | ldva/apps/visbuilder/codevizbackup.py | Python | agpl-3.0 | 6,354 | 0.012118 | """
Copyright (C) 2014 Kompetenzzentrum fuer wissensbasierte Anwendungen und Systeme
Forschungs- und Entwicklungs GmbH (Know-Center), Graz, Austria
[email protected]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the ... | dimUri = ""
for elements in dimension:
dimUri = elements['dimensionuri']
dim = elements ['dim']
dimUriObject = {'dimensionuri':dimUri, 'dim': dim }
dimUriArray.append(dimUriObject)
inProcessorObject=inprocessorauto.InProcessorAut... | t, dimUriArray)
resultArray = inProcessorObject.getVis()
#resultArray=inProcessorObject.resultArray
return HttpResponse(json.dumps(resultArray))
except Exception as inst:
msg = "ERROR (code - queryVisualization): [%s] %s"%(type(inst),inst)
print msg... |
flipjack/tecnoservicio | config/settings/celery.py | Python | bsd-3-clause | 588 | 0.003401 | from __future__ import absolute_import
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os | .environ.setdefault('DJANGO_S | ETTINGS_MODULE', 'config.settings.production')
from django.conf import settings
app = Celery('tecnoservicio.tareas')
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
... |
qedsoftware/commcare-hq | corehq/apps/programs/forms.py | Python | bsd-3-clause | 1,704 | 0.000587 | from crispy_forms.helper import FormHelper
from crispy_forms import layout as crispy
from django import forms
from corehq.apps.programs.models import Program
from django.utils.translation import ugettext as _
class ProgramForm(forms.Form):
name = forms.CharField(max_length=100)
def __init__(self, program, *a... | l_class = 'col-sm-3 col-md-4 col-lg-2'
self.helper.field_class = 'col-sm-4 col-md-5 col-lg-3'
# don't let users rename the uncategorized
# program
if program.default:
self.fields['name'].required | = False
self.fields['name'].widget.attrs['readonly'] = True
self.helper.layout = crispy.Layout('name')
def clean_name(self):
name = self.cleaned_data['name'].strip()
if not name:
raise forms.ValidationError(_('This field is required.'))
other_program_names... |
jpardobl/monscale | monscale/mappings/aws.py | Python | bsd-3-clause | 295 | 0.020339 | from boto.sns import connect_to_region, SNSConnection |
def publish_msg_to_sns_topic(region, aws_access_key, aws_secret_key, topic, message, subject):
connect_to_re | gion(region)
conn = SNSConnection(aws_access_key, aws_secret_key)
conn.publish(topic, message, subject)
|
ghbenjamin/TestingGui | TestingGui/TestWidget.py | Python | mit | 3,581 | 0.056967 | import wx
import Globals
from BaseWidget import BaseWidget
class TestWidget ( BaseWidget ):
def __init__( self, parent ):
BaseWidget.__init__ ( self, parent )
m_mainSizer = wx.BoxSizer( wx.VERTICAL )
m_mainSizer.AddSpacer( ( 0, 30), 0, 0, 5 )
m_statusSizer = wx.BoxSizer( wx.VERTICAL )
m_statusCont =... | ize, 0 )
self.m_testValue.Wrap( -1 )
m_infoGrid.Add( self.m_testValue, 0, wx.ALL, 5 )
self.m_groupLabel = wx.StaticText( self, wx.ID_ANY, u"Group:", wx.DefaultPosition, wx.DefaultS | ize, 0 )
self.m_groupLabel.Wrap( -1 )
m_infoGrid.Add( self.m_groupLabel, 0, wx.ALL, 5 )
self.m_groupValue = wx.StaticText( self, wx.ID_ANY, u"MyLabel", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_groupValue.Wrap( -1 )
m_infoGrid.Add( self.m_groupValue, 0, wx.ALL, 5 )
self.m_descLabel = wx.StaticText( s... |
raghuraju/Simple-Project-Management | src/users/migrations/0003_auto_20170414_1807.py | Python | apache-2.0 | 561 | 0.001783 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-14 18: | 07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20170414_1806'),
]
operations = [
migrations.AlterField(
model_name='manager',
... | ]
|
petrutlucian94/nova | nova/tests/functional/v3/test_remote_consoles.py | Python | apache-2.0 | 3,556 | 0.005624 | # Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# 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... | est_servers.ServersSampleBase):
extension_name = "os-remote-consoles"
extra_extensions_to_load = ["os-access-ips"]
_api_version = 'v2'
def _get_flags(self):
f = super(ConsolesSampleJsonTests, self)._get_flags()
f['osap | i_compute_extension'] = CONF.osapi_compute_extension[:]
f['osapi_compute_extension'].append(
'nova.api.openstack.compute.contrib.consoles.Consoles')
return f
def setUp(self):
super(ConsolesSampleJsonTests, self).setUp()
self.flags(vnc_enabled=True)
self.flags(ena... |
hlin117/statsmodels | statsmodels/datasets/stackloss/data.py | Python | bsd-3-clause | 1,907 | 0.007341 | """Stack loss data"""
__docformat__ = 'restructuredtext'
COPYRIGHT = """This is public domain. """
TITLE = __doc__
SOURCE = """
Brownlee, K. A. (1965), "Statistical Theory and Methodology in
Science and Engineering", 2nd edition, New York:Wiley.
"""
DESCRSHORT = """Stack loss plant data of Brownlee (19... | --------
Dataset instance:
See DATASET_PROPOSAL.txt for more information.
"""
data = _get_data()
return du.process_recarray(data, | endog_idx=0, dtype=float)
def load_pandas():
"""
Load the stack loss data and returns a Dataset class instance.
Returns
--------
Dataset instance:
See DATASET_PROPOSAL.txt for more information.
"""
data = _get_data()
return du.process_recarray_pandas(data, endog_idx=0, dtype=f... |
BTY2684/gitPy-snippets | testProj/ggplot_test.py | Python | gpl-2.0 | 2,273 | 0.042675 | #!/usr/bin/env python
# - | *- coding: utf-8 -*-
#
# ggplot_test.py
#
# Copyright 2014 Yang <yang@Leo-FamilyGuy>
#
# 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 op... | l be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free S... |
datakortet/django-cms | cms/test_utils/cli.py | Python | bsd-3-clause | 9,013 | 0.004217 | # -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import dj_database_url
gettext = lambda s: s
urlpatterns = []
def configure(db_url, **extra):
from django.conf import settings
os.environ['DJANGO_SETTINGS_MODULE'] = 'cms.test_utils.cli'
if not 'DATABASES' in extra:
DB = dj_d... | an')),
('pt-br', gettext('Brazilian Portuguese')),
('nl', gettext("Dutch")),
('es-mx', u'Español'),
),
CMS_LANGUAGES={
1: [
{
'code':'en',
'name':gettext | ('English'),
'fallbacks':['fr', 'de'],
'public':True,
},
{
'code':'de',
'name':gettext('German'),
'fallbacks':['fr', 'en'],
'public':True,
},
... |
Qwaz/solved-hacking-problem | SharifCTF/2016/elliptic.py | Python | gpl-2.0 | 1,402 | 0.009272 | p = 16857450949524777441941817393974784044780411511252189319
A = 16857450949524777441941817393974784044780411507861094535
B = 77986137112576
P = (5732560139258194764535999929325388041568732716579308775, 14532336890195013837874850588152996214121327870156054248)
Q = (2609506039090139098835068603396546214836589143940493... | d(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def addPoint(P, Q):
if P == (0, 0) or Q == (0, 0):
return (P[0]+Q[0], P[1]+Q[1])
x_1, y_1, x_2, y_2 = P[0], P[1], Q[0], Q[1]
if (x_1, y_1) == (x_2, y_2):
| if y_1 == 0:
return (0, 0)
# slope of the tangent line
m = (3 * x_1 * x_1 + A) * modinv(2 * y_1, p)
else:
if x_1 == x_2:
return (0, 0)
# slope of the secant line
m = (y_2 - y_1) * modinv((x_2 - x_1 + p) % p, p)
x_3 = (m*m - x_2 - x_1) % p
... |
gwangjin2/gwangcoin-core | share/qt/clean_mac_info_plist.py | Python | mit | 900 | 0.016667 | #!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the Litecoin-Qt.app contains the right plist (including the right version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./";
in... | /Info.plist"
version = "unknown";
fileForGrabbingVersion = bitcoinDir+"gwangcoin-qt.pro"
for line in open(fileForGrabbingVersion):
lineArr = line.replace(" ", "").split("=");
if lineArr[0].startswith("VERSION"):
version = lineArr[1].replace("\n", "");
fIn = open(inFile, "r")
fileContent = fIn.read()
s = Templa... | te.today().year)
fOut = open(outFile, "w");
fOut.write(newFileContent);
print "Info.plist fresh created"
|
BlackVegetable/starcraft-oracle | sc2reader-master/sc2reader/engine/plugins/selection.py | Python | mit | 3,813 | 0.002098 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals, division
class SelectionTracker(object):
""" Tracks a player's active selection as an input into other plugins.
In some situations selection tracking isn't perfect. The plugin will
detect these situa... | election_size
elif mode == 'OneIndices':
# Deselect objects according to indexes
clean_data = list(filter(lambda i: i < selection_size, data))
| new_selection = [u for i, u in enumerate(selection) if i < selection_size]
error = len(list(filter(lambda i: i >= selection_size, data))) != 0
elif mode == 'ZeroIndices':
# Select objects according to indexes
clean_data = list(filter(lambda i: i < selection_size, da... |
heyfaraday/rustcmb | py/examples/mcmc/image.py | Python | mit | 226 | 0 | from numpy import *
from pylab import *
plt.figure(figsize=(10, 8))
phi_1, phi_2, v1, v2 = genfromtxt(
'../../../../data/out/rust-examples/mcmc/sample.dat').T
plt.hist2d(phi_1, phi_2, bins=100)
plt.color | bar()
plt.show()
| |
yt-project/unyt | unyt/_version.py | Python | bsd-3-clause | 18,446 | 0 |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains t... | tinue
if verbose:
print("unable to run %s" % dispcmd)
print(e)
return None, None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
return None, None
stdout = p.communicate()[0].strip()
if sys | .version_info[0] >= 3:
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % dispcmd)
print("stdout was %s" % stdout)
return None, p.returncode
return stdout, p.returncode
def versions_from_parentdir(parentdir_prefix, root... |
nwangtw/statsite | integ/test_integ.py | Python | bsd-3-clause | 15,415 | 0.000843 | import os
import os.path
import socket
import textwrap
import shutil
import subprocess
import contextlib
import sys
import tempfile
import time
import random
try:
import pytest
except ImportError:
print >> sys.stderr, "Integ tests require pytests!"
sys.exit(1)
def pytest_funcarg__servers(request):
"R... | utput = servers
server.sendall(" | gd:-50|g\n")
server.sendall("gd:-50|g\n")
wait_file(output)
now = time.time()
out = open(output).read()
assert out in ("gauges.gd|-100.000000|%d\n" % now, "gauges.gd|-100.000000|%d\n" % (now - 1))
def test_counters(self, servers):
"Tests adding kv pairs"
serv... |
MACBIO/GIS-Scripts | EnvDatabaseFields.py | Python | gpl-3.0 | 2,669 | 0.002623 | print "loading arcpy"
import arcpy
import os
inFolder = r"C:\temp\shapes"
intersectFolder = os.path.join(inFolder, "int")
gridFile = r"C:\Users\Jonah\Documents\ArcGIS\Default.gdb\grid"
arcpy.env.workspace = r"C:\Users\Jonah\Documents\ArcGIS\Default.gdb"
layerName = r"C:\Users\Jonah\Documents\ArcGIS\Default.gdb... | , "area", "!shape.area!" , "PYTHON_9.3")
except BaseException as e:
print e
oldfieldName = f.split(os.extsep)[0]
newfieldName = os.path.basename(gridFile).split(os.extsep)[0] + "." + f.split(os.extsep)[0]
fieldList = [f.baseName for f in arcpy.ListFields(gridFile... | print "adding shapefile name field to grid"
arcpy.AddField_management(layerName, oldfieldName, "DOUBLE")
except BaseException as e:
print e
try:
print "joining shapefile to grid"
arcpy.AddJoin_management(layerName, "ID", intFi... |
tiredpixel/pikka-bird-server-py | pikka_bird_server/migrations/versions/d6ebfd0a1b_create_services.py | Python | mit | 653 | 0.01072 | """create_services
Revision ID: d6ebfd0a1b
Revises: 37440ef063
Create Date: 2015-04-04 16:57:3 | 4.406021
"""
# revision identifiers, used by Alembic.
revision = 'd6ebfd0a1b'
down_revision = '37440ef063'
from alembic import op
import sqlalchemy as sa
def upgrade():
sql_now = sa.text("timezone('utc'::text, now())")
op.create_table(
'services',
sa.Column('id', sa.Integer,
primar... | sa.Column('code', sa.String,
nullable=False, index=True, unique=True))
def downgrade():
op.drop_table('services')
|
accraze/bitcoin | qa/rpc-tests/replace-by-fee.py | Python | mit | 21,993 | 0.001273 | #!/usr/bin/env python2
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test replace by fee code
#
from test_framework.test_framework import BitcoinTestFramework
from test_... | 8')
def make_utxo(node, amount, confirmed=True, scriptPubKey=CScript([1])):
"""Create a txout with a given amount and scriptPubKey
Mines coins as needed.
confirmed - txouts created will be confirmed in the blockchain;
unconfirmed otherwise.
"""
fee = 1*COIN
while node.getbalan... | e)/COIN):
node.generate(100)
#print (node.getbalance(), amount, fee)
new_addr = node.getnewaddress()
#print new_addr
txid = node.sendtoaddress(new_addr, satoshi_round((amount+fee)/COIN))
tx1 = node.getrawtransaction(txid, 1)
txid = int(txid, 16)
i = None
for i, txout in enu... |
uilianries/conan-libusb | test_package/conanfile.py | Python | lgpl-2.1 | 829 | 0.002413 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile, CMake, tools, RunEnvironment
import os
class TestPackageConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "cmake"
def build(self):
cmake = CMake(self)
cmake.configure()
cmak... | with tools.environment_append(RunEnvironment(self).vars):
bin_path = os.path.join("bin", "test_package")
if self.settings.os == "Windows":
self.run(bin_path)
elif self | .settings.os == "Macos":
self.run("DYLD_LIBRARY_PATH=%s %s" % (os.environ.get('DYLD_LIBRARY_PATH', ''), bin_path))
else:
self.run("LD_LIBRARY_PATH=%s %s" % (os.environ.get('LD_LIBRARY_PATH', ''), bin_path))
|
Datateknologerna-vid-Abo-Akademi/date-website | members/tokens.py | Python | cc0-1.0 | 358 | 0 | import six
f | rom django.contrib.auth.tokens import PasswordResetTokenGenerator
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (
six.text_type(user.pk) + six.text_type(timestamp) +
six.text_type(user.username)
)
account_activation... | )
|
esistgut/django-content-toolkit | accounts/forms.py | Python | mit | 2,072 | 0.000483 | from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.utils.translation import ugettext_lazy as _
from .models import User
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
password2 = forms.Cha... | # field does not have access to the initial value
return self.initial["passwor | d"]
|
Jusedawg/SickRage | tests/sickrage_tests/providers/torrent/parsing_tests.py | Python | gpl-3.0 | 9,387 | 0.002983 | # coding=utf-8
# This file is part of SickRage.
#
# URL: https://SickRage.GitHub.io
# Git: https://github.com/SickRage/SickRage.git
#
# SickRage 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... | print_function, unicode_literals
from functools import wraps
import re
import sys
import unittest
from vcr_unittest impo | rt VCRTestCase
# Have to do this before importing sickbeard
sys.path.insert(1, 'lib')
import sickbeard
sickbeard.CPU_PRESET = 'NORMAL'
import validators
overwrite_cassettes = False
disabled_provider_tests = {
# ???
'Cpasbien': ['test_rss_search', 'test_episode_search', 'test_season_search'],
# api_main... |
altenia/taskmator | taskmator/task/text.py | Python | mit | 4,755 | 0.002313 | __author__ = 'ysahn'
import logging
import json
import os
import glob
import collections
from mako.lookup import TemplateLookup
from mako.template import Template
from taskmator.task.core import Task
class TransformTask(Task):
"""
Class that transform a json into code using a template
Uses mako as temp... | ype execution_context: ExecutionContext
| """
self.logger.info("Executing " + str(self))
src_dir = self._normalize_dir(self.getAttribute(self.ATTR_SRC_DIR, './'), './')
file_patterns = self.getAttribute(self.ATTR_SRC_FILES, '*.json')
file_patterns = file_patterns if file_patterns else '*.json'
# Convert to an ar... |
CareerVillage/slack-moderation | src/moderations/serializers.py | Python | mit | 701 | 0 | from rest_framework import serializers
from .models import Mode | rationAction
class ModerationSerializer(serializers.ModelSerializer):
content_key = serializers.CharField | (write_only=True)
content = serializers.CharField(write_only=True)
content_author_id = serializers.CharField(write_only=True)
auto_approve = serializers.NullBooleanField(default=False)
auto_flag = serializers.NullBooleanField(default=False)
class Meta:
model = ModerationAction
field... |
bukun/bkcase | script/mappad_script/script/place_file_by_sig.py | Python | mit | 563 | 0.001776 | # -*- coding:cp936 -*-
import os
import shutil
inws = r'D:\maplet_dvk\MapPicDir\raw\ÖйúÀúÊ·µØÍ¼¼¯_Ì·_8²á_dd006dd\ÖйúÀúÊ·µØÍ¼¼¯_·ÇÆ´½Ó\µÚ3²á\08Î÷½ú'
wfiles = os.listdir(inws) |
for wfile in wfiles:
infile = os.path.join(inws, wfile)
| if os.path.isfile(infile):
pass
else:
continue
sig_arr = wfile.split('_')
outws = os.path.join(inws, sig_arr[0])
if os.path.exists(outws):
pass
else:
os.mkdir(outws)
outfile = os.path.join(outws, wfile)
shutil.move(infile, outfile)
|
jvicu2001/alexis-bot | modules/simsimi.py | Python | mit | 3,655 | 0.001643 | from aiohttp import ClientSession, ContentTypeError
from bot import Command, categories, BotMentionEvent
class SimSimiException(Exception):
def __init__(self, msg=None, code=None):
super().__init__(msg)
self.code = code
class SimSimiCmd(Command):
__version__ = '1.0.1'
__author__ = 'makzk... | return ':speech_balloon: ' + resp['atext']
def load | _config(self):
self.on_loaded()
|
ovresko/erpnext | erpnext/selling/report/etude_des_prix_de_vente/etude_des_prix_de_vente.py | Python | gpl-3.0 | 16,610 | 0.045816 | # Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, erpnext, json
from frappe import _, _dict
from erpnext.stock.get_item_details import get_item_details
from frappe.utils import getdate, cstr, flt... | s)
for m in models_copy:
if m in models:
pass
else:
models.insert(len(models),m)
complements = frappe.get_all("Composant",filters={"parent":m,"parentfield":"articles"},fields=["parent","item"])
if complements:
parents = {i.item for i in complements}
if parents:
for t in parents:
_mod... | une resultat")
return columns, data
#models = list(set(models))
#models.sort()
for model in models:
_mitems = [item for item in items if item.variant_of == model]
origin_model = frappe.get_doc("Item",model)
mitems.append(origin_model)
mitems.extend(_mitems)
oids = {o.item_code for o in mite... |
lanyudhy/Halite-II | apiserver/apiserver/coordinator/storage.py | Python | mit | 4,017 | 0.000498 | import base64
import binascii
import io
import tempfile
import flask
import google.cloud.storage as gcloud_storage
import google.cloud.exceptions as gcloud_exceptions
from werkzeug.contrib.cache import FileSystemCache
from .. import config, model, util
from .blueprint import coordinator_api
# Cache the worker blo... | .values.get("user_id", None)
bot_id = flask.request.values.get("bot_id", None)
compile = flask.request.values.get("compile", False)
if compile:
bucket = model.get_compilation_bucket()
else:
bucket = model.get_bot_bucket()
# Retrieve from GCloud
t | ry:
botname = "{}_{}".format(user_id, bot_id)
blob = gcloud_storage.Blob(botname,
bucket, chunk_size=262144)
buffer = io.BytesIO()
blob.download_to_file(buffer)
buffer.seek(0)
return flask.send_file(buffer, mimetype="application/zip",
... |
dougwig/acos-client | acos_client/v30/slb/hm.py | Python | apache-2.0 | 3,696 | 0 | # Copyright 2014, Jeff Buttars, A10 Networks.
#
# 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 appli... | rl-path": "/",
},
HTTPS: {
"https": 1,
"web-port": 443,
"https-expect": 1,
"https-response-code": "200",
"https-url": 1,
"url-type": "GET",
"url-path": "/",
"disable-sslv2hello": 0
} | ,
TCP: {
"method-tcp": 1,
"tcp-port": 80
},
}
def get(self, name, **kwargs):
return self._get(self.url_prefix + name, **kwargs)
def _set(self, action, name, mon_method, interval, timeout, max_retries,
method=None, url=None, expect_code=None, por... |
clld/pycdstar | src/pycdstar/media.py | Python | apache-2.0 | 6,924 | 0.002022 | import os
import hashlib
from string import ascii_letters
import logging
from time import time, strftime
import subprocess
from tempfile import NamedTemporaryFile
import json
from mimetypes import guess_type
import pathlib
from unidecode import unidecode
import pycdstar
from pycdstar.resource import Bitstream
log =... | if self.mimetype == 'audio/mpeg':
# we only need an alias with correct name!
path = self.path
temporary = False
else:
path = self._convert()
temporary = True
return [File(path, name='web.mp3', type='web', temporary=temporary)]
class Imag... | ImageMagick's `convert` and `identify` commands to
create different resolutions of a file and determine its dimensions.
"""
resolutions = {
'thumbnail': '-thumbnail 103x103^ -gravity center -extent 103x103'.split(),
'web': '-resize 357x357'.split(),
}
def _convert(self, opts):
... |
Dawny33/Code | Hackerrank/101 Hack Sept/order.py | Python | gpl-3.0 | 346 | 0.020231 | T = int(input())
arr = []
dirr = {}
while(T):
T-=1
a,b = map(int, raw_input().split())
arr.append(a+b)
arr2 = sorted(arr)
fin = []
for i in range(len(arr2)):
for j in range(len(arr)):
if arr | [i] == arr2[j]:
fin.append(j+1)
#print arr |
#print arr2
print reduce(lambda x, y: str(x) + " "+ str(y), fin)
|
NateShoffner/PySnip | feature_server/scheduler.py | Python | gpl-3.0 | 2,339 | 0.002993 | # Copyright (c) Mathias Kaerlev 2012.
# This file is part of pyspades.
# pyspades 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 versi... | it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with pyspades. If not, see <http://www.g... | WeakSet
except ImportError:
# python 2.6 support (sigh)
from weakref import WeakKeyDictionary
class WeakSet(object):
def __init__(self):
self._dict = WeakKeyDictionary()
def add(self, value):
self._dict[value] = True
def remove(self, value):
... |
dorneanu/pyTCP2WS | lib/WebSocketServer.py | Python | bsd-3-clause | 3,326 | 0.000902 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import logging
import json
from threading import Thread
from queue import Queue
# Handle WebSocket clients
clients = []
### Handler ----------------------------------------------... | structor
| tornado.web.Application.__init__(self, handlers, **settings)
class HTTPServer():
""" Create tornado HTTP server serving our application """
def __init__(self, host, port, in_queue=Queue()):
# Settings
self.application = Application()
self.server = tornado.httpserver.HTTPServer(s... |
exildev/AutoLavadox | maq_autolavadox/bin/pildriver.py | Python | mit | 15,553 | 0.000064 | #!/home/dark/Exile/Git/AutoLavadox/maq_autolavadox/bin/python
"""PILdriver, an image-processing calculator using PIL.
An instance of class PILDriver is essentially a software stack machine
(Polish-notation interpreter) for sequencing PIL image
transformations. The state of the instance is the interpreter stack.
The ... | ground.paste(figure, (xoff, yoff), figure)
else:
ground.paste(figure, (xoff, yoff))
self.push(ground)
def do_resize(self):
"""usage: re | size <int:xsize> <int:ysize> <image:pic1>
Resize the top image.
"""
ysize = int(self.do_pop())
xsize = int(self.do_pop())
image = self.do_pop()
self.push(image.resize( |
desec-io/desec-stack | api/manage.py | Python | mit | 248 | 0 | #!/usr/bin/ | env python
import sys
import os
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.settings")
fr | om django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
tms1337/polls-app | django_polls/urls.py | Python | mit | 820 | 0 | """django_polls URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... | e
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib i... | in.site.urls),
url(r'^polls/', include('polls.urls'))
]
|
jorgenschaefer/healthmonitor | healthmonitor/settings_devel_fast.py | Python | agpl-3.0 | 240 | 0 | # Settings for running unittests. These are optimized for s | peed.
from .settings_devel import * # noqa
COMPRESS_ENABLED = False
COMPRESS_PRECOMPILERS = []
MIGRATION_MODULES = {
"wei | ght": "healthmonitor.migrations_not_used_in_tests"
}
|
googleads/googleads-python-lib | examples/ad_manager/v202202/proposal_line_item_service/get_all_proposal_line_items.py | Python | apache-2.0 | 1,904 | 0.007353 | #!/usr/bin/env python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | line_item['id'], proposal_line_item['name']))
statement.offset += statement.limit
else:
break
print('\nNumber of results found: %s' % response['totalResultSetSize'])
if __name__ == '__main__' | :
# Initialize client object.
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client)
|
hdzierz/Kaka | scripts/load_length_frequency_data.py | Python | gpl-2.0 | 2,940 | 0.003061 | # -*- coding: utf-8 -*-
from api.connectors import *
from seafood.models import *
from api.imports import *
import time
import datetime
from django.utils.timezone import get_current_timezone, make_aware
def convert_date(dt):
return time.strptime(dt, "%d.%m.%Y")
def convert_date_time(dt, default=datetime.datet... | yOb.objects.filter(datasource=ImportFish.ds).delete()
def load_data(fn):
conn = CsvConnector(fn, delimiter=',')
im = GenericImport(conn, ImportFish.study, ImportFish.ds)
im.load_op = Impo | rtFish.LoadFishDataOp
im.clean_op = ImportFish.CleanOp
im.Clean()
im.Load()
def init():
dt = datetime.datetime.now()
ds, created = DataSource.objects.get_or_create(
name='FishImp LengthFrequency',
supplieddate=dt
)
st = Study.get_or_create_from_name(
name='Fish Len... |
akretion/stock-logistics-workflow | stock_picking_manual_procurement_group/__init__.py | Python | agpl-3.0 | 149 | 0 | # -*- coding: utf-8 -*-
# Copyright 2016 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from | . import | models
|
johannv/pythonTestEasy | correction/Code.py | Python | mit | 5,151 | 0.003922 | # -*- coding: utf-8 -*-
'''
Created on 9 déc. 2012
@author: Vincent Bruneau, Johann Verbroucht
'''
import unicodedata
from Student import Student
from Teacher import Teacher
class Code(object):
'''
Pour réaliser ces exercices il n'y a pas besoin de modifier les autres
classes, il suffit d'écrire les fonc... | cice 4:
Développez la fonction qui renvoie la liste triée par ordre croissant.
'''
def sort_list(self, mylist):
return sorted(mylist)
'''
Exercice 5:
| Développez la fonction qui renvoie une liste sans nombres impairs.
'''
def delete_uneven(self, mylist):
evenlist = list()
for element in mylist:
if element % 2 == 0:
evenlist.append(element)
return evenlist
'''
Exercice 6:
Développez la foncti... |
activitycentral/statistics-consolidation | test/test_cons.py | Python | gpl-3.0 | 337 | 0.002967 | #!/usr/bin/env python
import sugar_stats_consolidation
from sugar_stats_consolidation.db import *
from sugar_stats_consolidation. | rrd_files import *
from sugar_stats_consolidation.consolidation import *
db = DB_Stats('statistics', 'root', 'gustavo')
db.create();
con = Consolidation('/var/lib/suga | r-stats/rrd', db)
con.process_rrds()
|
miketrumpis/compsense_demo | csdemo/demos/compsense_demo.py | Python | bsd-3-clause | 5,118 | 0.007425 | #!/usr/bin/env python
from time import time
import numpy as np
from scipy.sparse.linalg import LinearOperator, cg
from csdemo.utils.bdct_linapprox_ordering import bdct_linapprox_ordering
from csdemo.utils.psnr import psnr
from csdemo.measurements.dct2_xforms import A_dct2, At_dct2
from csdemo.measurements.lpnoiselet_x... | = 7
mu = 5
cg_tol = 1e-8
cg_maxiter = 800
# lowpass tv recovery
eps2 = 1e-3 * np.dot(y2,y2)**0.5
# make LinearOperators from Phi2, Phi2t
# Phi2 is (K1+K2, N)
A = LinearOperator( (K1+K2, N), matvec=Phi2, dtype=y2.dtype )
# Phi2t is (N, K1+K2)
At = LinearOperator( (N, K1+K2), mat... | loud=be_loud
)
xlptv.shape = (n,n)
# CS recovery
eps = 1e-3 * np.dot(y,y)**0.5
A = LinearOperator( (K1+K2, N), matvec=Phi, dtype=y.dtype )
At = LinearOperator( (N, K1+K2), matvec=Phit, dtype=y.dtype )
xp, tp = tvqc.logbarrier(
x0, A, At, y, eps, lb_tol, mu, cg_tol, cg_maxiter, b... |
nishworks/Flask-starter | flask_app/api/base.py | Python | mit | 995 | 0.001005 | from __future__ import absolute_import
import decimal
import json
import logging
import flask
log = log | ging.getLogger(__name__)
def json_handler(obj):
""" Handles non-serializable objects """
if isinstance(obj, decimal.Decimal):
return float(obj)
try:
return str(obj)
except TypeError:
return obj.__dict__
def json_response(response, status_code, message=None, errors=None, heade... | 'uri': flask.request.path,
'message': message,
'status': status_code,
'request-params': flask.g.request_args,
'request-method': flask.request.method,
'response': response,
'errors': errors
}
resp = flask.make_response(
json.dumps(response, default=js... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_03_01/models/application_gateway_authentication_certificate.py | Python | mit | 1,860 | 0.001075 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
from .sub_resource import SubResource
cl | ass ApplicationGatewayAuthenticationCertificate(SubResource):
"""Authentication certificates of an application gateway.
:param id: Resource ID.
:type id: str
:param data: Certificate public data.
:type data: str
:param provisioning_state: Provisioning state of the authentication
certificat... |
stan-dev/math | lib/boost_1.75.0/tools/build/src/build/property.py | Python | bsd-3-clause | 23,372 | 0.003637 | # Status: ported, except for tests.
# Base revision: 64070
#
# Copyright 2001, 2002, 2003 Dave Abrahams
# Copyright 2006 Rene Rivera
# Copyright 2002, 2003, 2004, 2005, 2006 Vladimir Prus
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENS... | <not-applicable-in-this-context> feature.
#
| # The underlying cause for this problem is that python port Property
# is more strict than its Jam counterpart and must always reference
# a valid feature.
p = LazyProperty(feature_name, value, condition=condition)
return p
def create_from_strings(string_list, allow_conditi... |
anthonynsimon/python-data-structures-algorithms | tests/test_parse_tree.py | Python | apache-2.0 | 686 | 0.001458 | import unittest
from lib.data_structures.trees.parse_tree import ParseTree
class TestParseTree(unittest.TestCase):
def evaluate(self, expression | , result):
parser = ParseTree()
parse_tree = parser.build_parse_tree(expressio | n)
self.assertEqual(parser.evaluate(parse_tree), result)
print(parse_tree)
def testParseTree(self):
self.evaluate("( ( 5 + ( 2 * ( 100 / 2 ) ) ) - 5 )", 100)
self.evaluate("( 10 + 5 )", 15)
self.evaluate("( 10 / 2 )", 5)
self.evaluate("( 5 * ( 5 * ( 5 * 5 ) ) ) )", 6... |
capitalone/cloud-custodian | tools/c7n_mailer/tests/test_slack.py | Python | apache-2.0 | 8,070 | 0.001859 | import unittest
import copy
import json
import os
from mock import patch, MagicMock
from common import RESOURCE_3, SQS_MESSAGE_5
from c7n_mailer.slack_delivery import SlackDelivery
from c7n_mailer.email_delivery import EmailDelivery
SLACK_TOKEN = "slack-token"
SLACK_POST_MESSAGE_API = "https://slack.com/api/chat.pos... | gger.debug.assert_called_with("Generating message for specified Slack channel.")
def test_map_sending_to_tag_channel_without_hash(self):
self.target_channel = 'tag-channel'
channel_name | = "#" + self.target_channel
slack = SlackDelivery(self.config, self.logger, self.email_delivery)
message_destination = ['slack://tag/SlackChannel']
self.resource['Tags'].append({"Key": "SlackChannel", "Value": self.target_channel})
self.message['action']['to'] = message_destination
... |
bobintetley/asm3 | src/asm3/lookups.py | Python | gpl-3.0 | 50,935 | 0.010405 |
import asm3.configuration
import asm3.financial
import asm3.utils
from asm3.i18n import _
import re
# Look up tables map
# tablename : ( tablelabel, namefield, namelabel, descfield, hasspecies, haspfspecies, haspfbreed, hasapcolour, hasdefaultcost, hasunits, hassite, canadd, candelete, canretire,(foreignkeys) )
# ta... | ciesID", "animallost.AnimalTypeID", "animalf | ound.AnimalTypeID")),
"stocklocation": (_("Stock Locations"), "LocationName", _("Location"), "LocationDescription", "add del ret", ("stocklevel.StockLocationID",)),
"stockusagetype": (_("Stock Usage Type"), "UsageTypeName", _("Usage Type"), "UsageTypeDescription", "add del ret", ("stockusage.StockUsageType... |
Clarity-89/clarityv2 | src/clarityv2/crm/migrations/0008_auto_20171108_2318.py | Python | mit | 1,542 | 0.002594 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-08 21:18
from __future__ import unicode_literals
from decimal import Decimal
from django.db import migrations, models
import django_countries.fields
class Migration(migrations.Migration):
dependencies = [
('crm', '0007_auto_20161219_1914'),... | ame='client',
old_name='vat',
new_name='vat_number',
),
migrations.RemoveField(
model_name='project',
name='tax_ | rate',
),
migrations.AddField(
model_name='project',
name='vat',
field=models.DecimalField(choices=[(Decimal('0.00'), 'no vat'), (Decimal('0.20'), 'standard vat rate')], decimal_places=2, default=Decimal('0.00'), max_digits=4, verbose_name='tax rate'),
),
... |
emtwo/redash_client | samples/ActivityStreamExperimentDashboard.py | Python | mpl-2.0 | 1,209 | 0.01158 | import os
from templates import event_rate
from redash_client import RedashClient
from constants import VizType, ChartType, VizWidth
class ActivityStreamExperimentDashboard(object):
DEFAULT_EVENTS = ["CLICK", "SEARCH", "BLOCK", "DELETE"]
DATA_SOURCE_ID = 5
def __init__(self, api_key, dash_name, exp_id, start_d... | trol {0} Rate".format(event)
query_string, fields = event_rate(event, self._start_date, self._experiment_id)
query_id = self.redash.new_query(query_name, query_string, self.DATA_SOURCE_ID)
viz_id = | self.redash.new_visualization(query_id, ChartType.LINE, {fields[0]: "x", fields[1]: "y", fields[2]: "series"})
self.redash.append_viz_to_dash(self._dash_id, viz_id, VizWidth.WIDE)
|
etherkit/OpenBeacon2 | macos/venv/lib/python3.8/site-packages/cmd2/table_creator.py | Python | gpl-3.0 | 39,315 | 0.003772 | # coding=utf-8
"""
cmd2 table creation API
This API is built upon two core classes: Column and TableCreator
The general use case is to inherit from TableCreator to create a table class with custom formatting options.
There are already implemented and ready-to-use examples of this below TableCreator's code.
"""
import c... | ValueError if width is less than 1
:raises: ValueError if max_data_lines is less than 1
"""
self.header = header
if width is None:
# Use the width of the widest line in the header or 1 if the header has no width
line_widths = [ansi.style_aware_wcswidth(line) for ... |
self.width = max(line_widths)
elif width < 1:
raise ValueError("Column width cannot be less than 1")
else:
self.width = width
self.header_horiz_align = header_horiz_align
self.header_vert_align = header_vert_align
self.data_horiz_align = data... |
JuezUN/INGInious | inginious/frontend/plugins/lti_register/pages/constants.py | Python | agpl-3.0 | 265 | 0.003774 | _use_minified = True
def set_us | e_m | inified(use_minified):
""" Define if use minified files """
global _use_minified
_use_minified = use_minified
def use_minified():
""" return a boolean to define if use minified files """
return _use_minified |
yongshengwang/builthue | desktop/libs/liboozie/src/liboozie/conf.py | Python | apache-2.0 | 2,552 | 0.009013 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | nse. 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 permissi... |
gst/amqpy | setup.py | Python | mit | 1,664 | 0 | #!/usr/bin/env python3
import sys
import os
from setuptools import setup, find_packages
import amqpy
if sys.version_info < (3, 2):
raise Exception('amqpy requires Python 3.2 or higher')
name = 'a | mqpy'
description = 'an AMQP 0.9.1 client library for Python >= 3.2.0'
keywords = ['amqp', 'rabbitmq', 'qpid']
classifiers = [
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Imp | lementation :: PyPy',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Topic :: Internet',
... |
Lindennerd/exercicios_luizpaulo_leandro | exercicios/ex_4.py | Python | apache-2.0 | 263 | 0.015385 | # coding=utf-8
#[3,2,4] >> 3² + 2² + 4² = 9 + 4 + 16 = 29
pow = lambda x: x**2
def exer(lista):
result = 0
for i in lista:
result = pow | (i)+result
return result
def f(a):
def g(b, c, d, e):
print(a, b, c, d, e) |
return g
|
GunnerJnr/_CodeInstitute | Stream-2/Back-End-Development/18.Using-Python-with-MySQL-Part-Three-Intro/3.How-to-Build-an-Update-SQL-String/database/mysql.py | Python | mit | 7,289 | 0.001921 | import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class ... | where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
... | or = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self,... |
MechanisM/djangodash2011 | test_project/test_app/urls.py | Python | bsd-3-clause | 1,313 | 0.003808 | from django.conf.urls.defaults import *
from staste.charts.views import PieChart, TimeserieChart, LatestCountAndAverageChart
from staste.middleware import response_time_metrica
from .views import IndexView
from .metrics import gender_age_me | trica
urlpatterns = patterns('',
url(r'^$', IndexView.as_view(), name="index"),
url(r'^pie/$',
PieChart.as_view(metrica=gender_age_metrica,
axis_keyword='gender'),
name='gen... | ),
url(r'^requests/pie/$',
PieChart.as_view(metrica=response_time_metrica,
axis_keyword='view'),
name='requests_pie'),
url(r'^requests/$',
LatestCou... |
bandarji/lekhan | python/reddit/palindrome.py | Python | apache-2.0 | 332 | 0.003012 | # https://www.reddit.com/r/learnpython/co | mments/82ucgu/calling_an_input_inside_a_def_function/
def main():
while True:
word = raw_input('Enter a word: ')
if word == '-1':
bre | ak
not_ = '' if word[:] == word[::-1] else ' not'
print "Word '%s' is%s a palindrome" % (word, not_)
main()
|
data-exp-lab/girder_ythub | plugin_tests/notebook_test.py | Python | bsd-3-clause | 8,231 | 0.000121 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import mock
from tests import base
from girder.models.model_base import ValidationExce | ption
def setUp | Module():
base.enabledPlugins.append('ythub')
base.startServer()
def tearDownModule():
base.stopServer()
class FakeAsyncResult(object):
def __init__(self):
self.task_id = 'fake_id'
def get(self):
return dict(
nodeId='123456',
volumeId='blah_volume',
... |
saurabh6790/omn-app | stock/doctype/stock_reconciliation/stock_reconciliation.py | Python | agpl-3.0 | 11,140 | 0.035458 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import webnotes
import webnotes.defaults
import json
from webnotes import msgprint, _
from webnotes.utils import cstr, flt, cint
from stock.stock_led... | nciliation_json)
for row_num, row in enumerate(data[data.index(self.head_row)+1:]):
row = webno | tes._dict(zip(row_template, row))
row["row_num"] = row_num
previous_sle = get_previous_sle({
"item_code": row.item_code,
"warehouse": row.warehouse,
"posting_date": self.doc.posting_date,
"posting_time": self.doc.posting_time
})
# check valuation rate mandatory
if row.qty != "" and not r... |
severb/flowy | flowy/swf/worker.py | Python | mit | 14,853 | 0.000269 | import os
import socket
import venusian
from botocore.exceptions import ClientError
from flowy.swf.client import SWFClient, IDENTITY_SIZE
from flowy.swf.decision import SWFActivityDecision
from flowy.swf.decision import SWFWorkflowDecision
from flowy.swf.history import SWFExecutionHistory
from flowy.utils import logg... | ks.append(callback)
def make_scanner(self):
return venusian.Scanner(
register_task=self.register_task,
add_remote_reg_callback=self.add_remote_reg_callback)
class SWFWorkflowWorker(SWFWorker):
categories = ['swf_workflow']
# Be explicit about w | hat arguments are expected
def __call__(self, name, version, input_data, decision, execution_history):
super(SWFWorkflowWorker, self).__call__(
name, version, input_data, decision, # needed for worker logic
decision, execution_history) # extra_args passed to proxies
def br... |
roramirez/qpanel | qpanel/asterisk.py | Python | mit | 4,629 | 0 | # -*- coding: utf-8 -*-
#
# Class Qpanel for Asterisk
#
# Copyright (C) 2015-2020 Rodrigo Ramírez Norambuena <[email protected]>
#
from __future__ import absolute_import
from Asterisk.Manager import Manager, ActionFailed, PermissionDenied
class ConnectionErrorAMI(Exception):
'''
This exception is raised ... | channel to create Originate action tu use ChanSpy
where_listen: str
channel where listen the spy action.
option: str
other option to add for execute distinct options.
whisper: w
barge: B
other string to add ChanSpy Command
T... | originate result command : Dictionary
if case the fail return return {'Response': 'failed',
'Message': str(msg)}
'''
options = ',q'
if option:
options = options + option
try:
# create a originate c... |
TomNeyland/err | errbot/backends/tox.py | Python | gpl-3.0 | 16,422 | 0.002131 | import codecs
import logging
import sys
from time import sleep
import os
from os.path import exists, join
import io
from errbot.backends import base
from errbot.errBot import ErrBot
from errbot.backends.base import Message, Identifier, Presence, Stream, MUCRoom
from errbot.backends.base import ONLINE, OFFLINE, AWAY, DN... | ber, file_size, filename):
log.debug("TOX: incoming file transfer %s : %s", friend_number, filename)
# make a pipe on which we will be able to write from tox
pipe = ToxStreamer()
# make the original stream with all the info
stream = Stream(self.friend_to_idd(friend_number), pipe,... | file_number)] = (pipe, stream)
# callback err so it will duplicate the stream and send it to all the plugins
self.backend.callback_stream(stream)
# always say ok, and kill it later if finally we don't want it
self.file_send_control(friend_number, 1, file_number, Tox.FILECONTROL_ACCEPT)
... |
hanleilei/note | python/vir_manager/utils/mail_utils.py | Python | cc0-1.0 | 2,926 | 0.000733 | import smtplib
from email.mime.text import MIMEText
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
def send_message(message):
"""
* desc 快捷发送邮件
* input 要发送的邮件信息
* output None
"""
mail_handler = SendMail()
mail_handler.send_mail(settings.REPORT_US... | 'Virtual Manager Warning'
from_email = settings.FMAIL
try:
to = [str(user) + "@huj | iang.com" for user in to_user.split(',')]
print(to)
content_msg = EmailMultiAlternatives(
subject, text_content, from_email, to)
html_content = u'<b>' + msg + '</b>'
content_msg.attach_alternative(html_content, 'text/html')
content_msg.send()
... |
dubzzz/py-mymoney | www/scripts/generate_db.py | Python | mit | 2,908 | 0.004814 | #!/usr/bin/python
# This script has to generate the sqlite database
#
# Requirements (import from):
# - sqlite3
#
# Syntax:
# ./generate_db.py
import sqlite3
import hashlib
import getpass
import sys
| from os import path, urandom
SCRIPT_PATH = path.dirname(__file__)
DEFAULT_DB = path.join(SCRIPT_PATH, "../mymoney.db")
def generate_tables(db=DEFAULT_DB):
conn = sqlite3.connect(db)
with conn:
c = conn.cursor()
# Drop tables if they exist
#c.execute('''DROP TABLE IF EXISTS... | P TABLE IF EXISTS node_expense''')
#c.execute('''DROP TABLE IF EXISTS users''')
# Create tables
c.execute('''CREATE TABLE IF NOT EXISTS node (
id INTEGER PRIMARY KEY,
parent_id INTEGER,
title TEXT NOT NULL,
... |
goldsborough/euler | 18.py | Python | mit | 1,380 | 0.000725 | #!/usr/bin/env python
# -*- coding: utf-8 -8-
"""
By starting at the top of the triangle below and moving to adjacent numbers
on the row below, t | he maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
"""
triangle = """
75
95 64
| 17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91... |
LLNL/spack | var/spack/repos/builtin/packages/py-pulp/package.py | Python | lgpl-2.1 | 768 | 0.001302 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyPulp(PythonPackage):
"""PuLP is an LP modeler written in Python. PuLP can generate MPS o... | COIN-OR CLP/CBC, CPLEX, GUROBI, MOSEK, XPRESS, CHOCO,
MIPCL, SCIP to solve linear problems."""
ho | mepage = "https://github.com/coin-or/pulp"
pypi = "PuLP/PuLP-2.6.0.tar.gz"
maintainers = ['marcusboden']
version('2.6.0', '4b4f7e1e954453e1b233720be23aea2f10ff068a835ac10c090a93d8e2eb2e8d')
depends_on('[email protected]:2.8,3.4:', type=('build', 'run'))
depends_on('py-setuptools', type='build')
|
wpjesus/codematch | ietf/message/resources.py | Python | bsd-3-clause | 1,927 | 0.008822 | # Autogenerated by the mkresources management command 2014-11-13 23:53
from tastypie.resources import ModelResource
from tastypie.fields import ToOneField, ToManyField
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from ietf import api
from ietf.message.models import * # pyflakes:ignore
from ietf.pers... | age.register(MessageResource())
from ietf.person.resources import PersonResource
class SendQueueResource(ModelResource):
by = ToOneField(PersonResource, 'by')
message = ToOneField(MessageResource, 'message')
class Meta:
queryset = SendQueue.objects.all()
serializer = ... | zer()
#resource_name = 'sendqueue'
filtering = {
"id": ALL,
"time": ALL,
"send_at": ALL,
"sent_at": ALL,
"note": ALL,
"by": ALL_WITH_RELATIONS,
"message": ALL_WITH_RELATIONS,
}
api.message.register(SendQueueReso... |
angelapper/edx-platform | common/djangoapps/third_party_auth/tasks.py | Python | agpl-3.0 | 9,113 | 0.004391 | # -*- coding: utf-8 -*-
"""
Code to manage fetching and storing the metadata of IdPs.
"""
import datetime
import logging
import dateutil.parser
import pytz
import requests
from celery.task import task
from lxml import etree
from onelogin.saml2.utils import OneLogin_Saml2_Utils
from requests import exceptions
from th... | n:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect']
except KeyError:
raise MetadataParseError("Unable to find SSO URL with HTTP-Redirect binding.")
return public_key, | ss |
jzbontar/mc-cnn | samples/load_bin.py | Python | bsd-2-clause | 249 | 0 | import numpy as np
left = np.memmap('../left.bin', dtype=np.float32, shape=(1, 70, 370, 1226))
right = np.memm | ap('../right.bin', dtype=np.float32, shape=(1, 70, 370, 1226))
disp = np.memmap('../disp.bin', dtype=np.float32, shape=(1, 1, 37 | 0, 1226))
|
tchellomello/home-assistant | tests/components/met/test_weather.py | Python | apache-2.0 | 2,271 | 0.000881 | """Test Met weather entity."""
from homeassistant.components.met import DOMAIN
from homeassistant.components.weather import DOMAIN as WEATHER_DOMAIN
async def test_tracking_home(hass, mock_weather):
"""Test we track home."""
await hass.config_entries.flow.async_init("met", context={"source": "onboarding"})
... | led by default
registry = await hass.helpers.entity_registry.async_get_registry()
state = hass.states.get("weather.test_home_hourly")
assert state is None
entry = registry.async_get("weather.test_home_hourly")
assert entry
assert entry.disabled
assert entry.disabled_by == "integration"
... | eather.mock_calls) == 8
entry = hass.config_entries.async_entries()[0]
await hass.config_entries.async_remove(entry.entry_id)
assert len(hass.states.async_entity_ids("weather")) == 0
async def test_not_tracking_home(hass, mock_weather):
"""Test when we not track home."""
# Pre-create registry en... |
streamlio/heron | heron/executor/tests/python/heron_executor_unittest.py | Python | apache-2.0 | 14,316 | 0.008103 | # Copyright 2016 Twitter. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | ckPOpen(), 'container_1_exclaim1_1',
get_expected_instance_command('exclaim1', 1, 1)),
ProcessInfo(MockPOpen(), 'container_1_exclaim1_2',
get_expected_instance_command('exclaim1', 2, 1)),
ProcessInfo(MockPOpen(), 'heron-shell-1', get_expected_shell_command(1)),
Proc... | pen(), 'metricsmgr-1', get_expected_metricsmgr_command(1)),
]
MockPOpen.set_next_pid(37)
expected_processes_container_7 = [
ProcessInfo(MockPOpen(), 'container_7_word_11', get_expected_instance_command('word', 11, 7)),
ProcessInfo(MockPOpen(), 'container_7_exclaim1_210',
|
LCOGT/valhalla | valhalla/accounts/migrations/0005_profile_terms_accepted.py | Python | gpl-3.0 | 406 | 0 | # Generated by Django 2.1.3 on 2019-02-22 22:41
from django.db import mig | rations, mode | ls
class Migration(migrations.Migration):
dependencies = [
('accounts', '0004_auto_20170418_0219'),
]
operations = [
migrations.AddField(
model_name='profile',
name='terms_accepted',
field=models.DateTimeField(blank=True, null=True),
),
]
|
carlegbert/wholenote | fnote/blueprints/page/__init__.py | Python | mit | 45 | 0 | from fnote. | blueprints.page.views import pa | ge
|
tonk/ansible | lib/ansible/playbook/collectionsearch.py | Python | gpl-3.0 | 2,597 | 0.00308 | # Copyright: (c) 2019, 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
from ansible.module_utils.six import string_types
from ansible.playbook.attribute import FieldAttr... | late import is_template, Environment
from ansi | ble.utils.display import Display
display = Display()
def _ensure_default_collection(collection_list=None):
default_collection = AnsibleCollectionLoader().default_collection
# Will be None when used as the default
if collection_list is None:
collection_list = []
# FIXME: exclude role tasks?
... |
ceball/param | tests/API1/testdefaults.py | Python | bsd-3-clause | 1,315 | 0.005323 | """
Do all subclasses of Parameter supply a valid default?
"""
from param.parameterized import add_metaclass
from param import concrete_descendents, Parameter
# import all parameter types
from param import * # noqa
from para | m import ClassSelector
from . import API1TestCase
positional_args = {
ClassSelector: (object,)
}
skip = []
try:
import numpy # noqa
except ImportError:
skip.append('Array')
try:
import pandas # noqa
except ImportError:
skip.append('D | ataFrame')
skip.append('Series')
class TestDefaultsMetaclass(type):
def __new__(mcs, name, bases, dict_):
def test_skip(*args,**kw):
from nose.exc import SkipTest
raise SkipTest
def add_test(p):
def test(self):
# instantiate parameter with ... |
Kortemme-Lab/klab | klab/scripting.py | Python | mit | 2,249 | 0.00578 | #!/usr/bin/env python2
import os, shutil, glob
from functools import wraps
def print_warning(message, *args, **kwargs):
from . import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message + '\n', color='red')
def print_error_and_die(message, *args, **kwargs):
... | @wraps(function)
def wrapper(*args, **kwargs):
with self:
return function(*args, **kwargs)
return wrapper
def use_path_completion():
import readline
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_complete... | user(text) + '*') + [None]
add_slash = lambda x: x + '/' if os.path.isdir(x) else x
return add_slash(globs[state])
def clear_directory(directory):
if os.path.exists(directory): shutil.rmtree(directory)
os.makedirs(directory)
def relative_symlink(target, link_name):
"""Make a symlink to target usin... |
hnakamur/my-fabfiles | fabfile/common/lib/template.py | Python | mit | 3,217 | 0.003108 | from datetime import datetime
import hashlib
import os
from StringIO import StringIO
from fabric.api import env, hide, put, settings
from fabric.contrib import files
from fabric.utils import apply_lcwd
from fabfile.common.lib.operations import run_or_sudo
from fabfile.common.lib import file
FABRIC_MANAGED_DEFAULT_FOR... | Upload the file.
put(
local_path=StringIO(text),
remote_path=destination,
use_sudo=use_sudo,
mirror_local_mode=mirror_local_mode,
mode=mode
)
return True
def modify_context(filename, destination, context=None, fabric_managed_format=FABRIC_MANAGED_DEFAULT_FORMAT):
... | = {}
context['fabric_managed'] = format_fabric_managed(filename, destination,
fabric_managed_format)
return context
def format_fabric_managed(filename, destination,
fabric_managed_format=FABRIC_MANAGED_DEFAULT_FORMAT):
return fabric_managed_format % {
'dest': destination,
's... |
flackr/quickopen | src/prelaunch_client_test.py | Python | apache-2.0 | 1,291 | 0.005422 | # Copyright 2011 Google 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 writing,... | aunch_client(self):
self.assertEquals(False, prelaunch_client.is_prelaunc | h_client([""]))
self.assertEquals(False, prelaunch_client.is_prelaunch_client(["", "search", "--wait"]))
self.assertEquals(False, prelaunch_client.is_prelaunch_client(["", "prelaunch", "--wait"]))
self.assertEquals(True, prelaunch_client.is_prelaunch_client(["", "prelaunch"]))
self.assertEquals(True, pr... |
okfn/jsontableschema-py | examples/table_sql.py | Python | mit | 998 | 0.004008 | # pip install sqlalchemy tableschema-sql
import sqlalchemy as sa
from tableschema import Table
# Create SQL database
db = sa.create_engine('sqlite://')
# Data from WEB, schema from MEMORY
SOURCE = 'https://raw.githubusercontent.com/frictionlessdata/tableschema-py/master/data/data_infer.csv'
SCHEMA | = {'fields': [{'name': 'id', 'type': 'integer'}, {'name': 'age', 'type': 'integer'}, {'name': 'name', 'type': 'string'}] }
# Open from WEB | save to SQL database
table = Table(SOURCE, schema=SCHEMA)
table.save('articles', backend='sql', engine=db)
# Open from SQL save to DRIVE
table = Table('articles', backend='sql', engine=db)
table.schema.save('tmp/articles.json')
table.save('tmp/articles.csv')
# Open from DRIVE print to CONSOLE
table = Table('tmp/artic... |
rymis/mrimpy | test/estest.py | Python | gpl-3.0 | 289 | 0.034602 | #!/usr/bin/env python
# EventServer test
import eserver
import sys
class EchoProtocol( | eserver.Protocol):
def processData(self, data):
self.send(data)
def main(argv):
S = eserver.EventServer( ('localhost', 9999), EchoPr | otocol )
S.start()
if __name__ == '__main__':
main(sys.argv)
|
occrp/id-backend | api_v3/models/attachment.py | Python | mit | 887 | 0 | from django.conf import settings
from django.db import models
from .ticket import Ticket
class Attachment(models.Model):
"""Ticket attachment model."""
ticket = models.ForeignKey(
Ticket, blank=False, related_name='attachments', db_index=True,
on_delete=models.DO_NOTHING)
user = models.F... | , db_index=True,
on_delete=models.DO_NOTHING)
upload = models.FileField(upload_to='attachments/%Y/%m/%d', max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
@classmethod
def filter_by_user(cls, user, queryset=None):
"""Returns any user accessible attachments.
... | er_by_user(user))
|
madgik/exareme | Exareme-Docker/src/exareme/exareme-tools/madis/src/lib/colorama/ansitowin32.py | Python | mit | 6,285 | 0.000318 | import re
import sys
from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style
from .win32 import windll
from .winterm import WinTerm, WinColor, WinStyle
if windll is not None:
winterm = WinTerm()
def is_a_tty(stream):
return hasattr(stream, 'isatty') and stream.isatty()
class StreamWrapper(object):
'''
... | term.fore, WinColor.GREY),
AnsiFore.RESET: (winterm.fore,),
AnsiBack.BLACK: (winterm.back, WinColor.BLACK),
AnsiBack.RED: (winterm.back, WinColor.RED),
AnsiBack.GREEN: (winterm.back, WinColor.GREEN),
AnsiBack.YELLOW: (winterm.back, WinColor... | term.back, WinColor.CYAN),
AnsiBack.WHITE: (winterm.back, WinColor.GREY),
AnsiBack.RESET: (winterm.back,),
}
def write(self, text):
if self.strip or self.convert:
self.write_and_convert(text)
else:
self.wrapped.write(text)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.