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 |
|---|---|---|---|---|---|---|---|---|
smartbgp/libbgp | setup.py | Python | apache-2.0 | 910 | 0 | from setuptools import setup, find_packages
from libbgp import __version__
with open('README.rst') as f:
long_description = f.read()
setup(
name='libbgp',
version=__version__,
url='https://github.com/smartbgp/libbgp',
license='Apache 2.0',
author='Peng Xiao',
author_email='xiaoquwl@gmail.c... | evelopers',
| 'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7'
]
)
|
biomodels/MODEL1006230025 | setup.py | Python | cc0-1.0 | 377 | 0.005305 | from setuptools import setup, find_packages
setup(name='MODEL1006230025',
version=20140916,
description='MODEL1006230025 from BioModels',
url='http://www.ebi.ac.uk/biomodels-main/MODEL1006230025',
maintainer='Stanley Gu',
maintainer_url='stanleygu@gmai | l.com',
packages | =find_packages(),
package_data={'': ['*.xml', 'README.md']},
) |
evonaut/bolzplatz | bolzplatz/users/models.py | Python | gpl-2.0 | 581 | 0 | from django.conf import settings
from django.db import models
class Group(models | .Model):
slug = models.SlugField(max_length=30, unique=True)
about = models.TextField()
def __str__(self):
return self.slug
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
group = models.ForeignKey(Group)
slug = models.SlugField(max_length=30, unique... | core = models.PositiveIntegerField(default=0)
about = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.user.get_username()
|
mpld3/mplexporter | mplexporter/tests/test_utils.py | Python | bsd-3-clause | 1,024 | 0.005859 | from numpy.testing import assert_allclose, assert_equal
from . import plt
from .. import utils
def test_path_data():
circle = plt.Circle((0, 0), 1)
vertices, codes = utils.SVG_path(circle.get_path())
assert_allclose(vertices.shape, (25, 2))
| assert_equal(codes, ['M', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'Z'])
def test_linestyle():
linestyles = {'solid': 'none', '-': 'none',
#'dashed': '6,6', '--': '6,6',
#'dotted': '2,2', ':': '2,2',
#'dashdot': '4,4,2,4', '-.': '4,4,2,4',
... | w_fixed_formatter():
positions, labels = [0, 1, 10], ['A','B','C']
plt.xticks(positions, labels)
props = utils.get_axis_properties(plt.gca().xaxis)
assert_equal(props['tickvalues'], positions)
assert_equal(props['tickformat'], labels)
|
MCLA-Cheminformatics/Kekulean | Graph.py | Python | gpl-2.0 | 17,898 | 0.036987 | from Face import *
from Vertex import *
from Tkinter import *
import sys
import copy
#add proper support for the R and W
#add proper support for sorting
#make comparison a static member
class Graph(object):
__slots__ = ['faceGraph', 'vertexGraph', 'doubleBonds', 'vertexRoots', 'lastAddPair', 'FriesNumber', 'ClarsNumb... | lf.doubleBonds[verts[Face.BOTTOM_RIGHT]] == verts[Face.TOP_RIGHT]:
pairs.append((20, 30, 20, 10, verts[Face.BOTTOM_RIGHT].required))
if verts[Face.BOTTOM] in self.doubleBonds:
if self.doubleBonds[verts[Face.BOTTOM]] == verts[Face.BOTTOM_RIGHT]:
pairs.append((10, 40, 20, 30, verts[Face.BOTTOM].required))
... | TTOM]] == verts[Face.BOTTOM_LEFT]:
pairs.append((10, 40, 0, 30, verts[Face.BOTTOM].required))
if verts[Face.BOTTOM_LEFT] in self.doubleBonds:
if self.doubleBonds[verts[Face.BOTTOM_LEFT]] == verts[Face.TOP_LEFT]:
pairs.append((0, 30, 0, 10, verts[Face.BOTTOM_LEFT].required))
elif self.doubleBonds[verts[... |
tjsavage/tmrwmedia | project/urls.py | Python | bsd-3-clause | 417 | 0.021583 | from django.conf.urls.defaults import *
urlpatterns = patterns('project.views',
(r'^$', 'index'),
(r'^new/$', 'new'),
(r'^(?P<project_id>\d+)/$', 'detail'),
(r'^(?P<project_id>\d+)/edit/$', 'edit'),
(r'^(?P<project_id>\d+)/groups/', include('project.groups.urls')),
(r'^(?P<project_id>\d+)/contacts/', include('pr... | rls')),
) | |
Qumeric/instabattle | tests/test_api.py | Python | mit | 5,128 | 0 | import unittest
import json
import re
from base64 import b64encode
from flask import url_for
from app import create_app, db
from app.models import User, Role
class APITestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
se... | ers('john@example.com', '123'))
self.assertTrue(response.status_code == 200)
json_response = json.loads(response.data.decode('utf-8'))
self.assertIsNotNone(json_response.get('token'))
token = json_response['token']
# issue a request with the token
response = self.client.... | ponse.status_code == 200)
def test_anonymous(self):
response = self.client.get(
url_for('api.battles'),
headers=self.get_api_headers('', ''))
self.assertTrue(response.status_code == 200)
def test_unconfirmed_account(self):
# add an unconfirmed user
r = R... |
raphaelvalentin/QTModel | examples/MyInductor/mybench.py | Python | gpl-2.0 | 1,574 | 0.005718 | ## Benches
from lib.inductor.rf import sp as Sp
from syntax import *
from functions.science import linspace
@setenv(type='bench', name='sp1')
class sp1():
def __init__(self, **parameters):
ls = parameters.get('ls', 1e-9)
rs = parameters.get('rs', 1.0)
cp = parameters.get('cp', 150e-15)
... | )
lib = myinductor(name='myinductor', rs=rs, ls=ls, cp=cp, cs=cs, rac=rac, ldc=ldc,
k1=k1, rsub=rsub)
dev = Device(model='myinductor', nodes=('plus', 'minus', '0'))
cir1 = Sp(library=lib, device=dev, freq=freq)
cir1.simulate(verbose=T... | 1, y12, y21, y22 = cir1.Y()
self.freq = freq
self.l11 = (1.0/y11).imag/(2.0*pi*freq)
self.r11 = (1.0/y11).real
self.q11 = (1.0/y11).imag/(1/y11).real
@setenv(type='bench', name='sp2')
class sp2():
def __init__(self, **parameters):
freq = linspace(0.1e9, 15e9, 101)
d... |
PARINetwork/pari | donation/migrations/0003_auto_20201113_1437.py | Python | bsd-3-clause | 469 | 0.002132 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class | Migration(migrations.Migration):
dependencies = [
('donation', '0002_auto_20190416_2318'),
]
operations = [
migrations.AlterField(
model_name='razorpayplans',
name='frequency',
field=models.CharField(max_length=16, choices=[('Month | ly', 'Monthly'), ('Yearly', 'Yearly')]),
),
]
|
aldian/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | apache-2.0 | 146,271 | 0.003678 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ps `w` before calling `fn`, so it calls `fn(w0)` on
device | `d0`, `fn(w1)` on device `d1`, etc. It then merges the return
values from `fn()`, which leads to one common object if the returned values
are the same object from every replica, or a `DistributedValues` object
otherwise.
* _Reductions_ and _all-reduce_: A _reduction_ is a method of aggregating
multiple values... |
coddingtonbear/d-rats | d_rats/reqobject.py | Python | gpl-3.0 | 1,990 | 0.001508 | #!/usr/bin/python
#
# Copyright 2008 Dan Smith <dsmith@danplanet.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | ",
buttons=("Retrieve", gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL),
parent=parent)
self.__list = miscwidgets.KeyedListWidget(\
[(gob | ject.TYPE_STRING, "_ID"),
(gobject.TYPE_STRING, "Name"),
(gobject.TYPE_STRING, "Info")])
self.__list.set_resizable(0, True)
self.__list.show()
sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
sw.add_with_viewport(self.... |
hamedtorky/django-starter-template | shaping_templeat/settings/base.py | Python | mit | 5,369 | 0 | """
Project main settings file. These settings are common to the project
if you need to override something do it in local.pt
"""
from sys import path
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
# PATHS
# Path containing the django project
BASE_DIR = os.path.dirname(os.path.dirna... | STATICFILES_DIRS.
# https://docs.djangoproject.com/en | /1.10/ref/settings/#static-root
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'public/static')
# URL prefix for static files.
# https://docs.djangoproject.com/en/1.10/ref/settings/#static-url
STATIC_URL = '/static/'
# Additional locations of static files
# https://docs.djangoproject.com/en/1.10/ref/settings/#staticfiles-d... |
gertingold/scipy | scipy/optimize/_constraints.py | Python | bsd-3-clause | 17,881 | 0.000503 | """Constraints definition for minimize."""
from __future__ import division, print_function, absolute_import
import | numpy as np
from ._hessian_update_strategy import BFGS
from ._differentiable_functions import (
VectorFunction, LinearVectorFunction, IdentityVectorFunction)
from .optimize import OptimizeWarning
from warnings import warn
from scipy._lib._numpy_compat import | suppress_warnings
from scipy.sparse import issparse
class NonlinearConstraint(object):
"""Nonlinear constraint on the variables.
The constraint has the general inequality form::
lb <= fun(x) <= ub
Here the vector of independent variables x is passed as ndarray of shape
(n,) and ``fun`` retur... |
prisae/empymod | examples/time_domain/cole_cole_ip.py | Python | apache-2.0 | 8,028 | 0 | r"""
Cole-Cole
=========
There are various different definitions of a Cole-Cole model, see for instance
Tarasov and Titov (2013). We try a few different ones here, but you can supply
your preferred version.
The original Cole-Cole (1941) model was formulated for the complex dielectric
permittivity. It is reformulated ... | ib.pyplot as plt
plt.style.use('ggplot')
###############################################################################
# Use empymod with user-def. func. to adjust :math:`\eta` and :math:`\zeta`
# -------------------------------------------------------------------------
#
# In principal it is always best to write yo... | odify it to your needs. Since ``empymod v1.7.4``,
# however, there is a hook which allows you to modify :math:`\eta_h, \eta_v,
# \zeta_h`, and :math:`\zeta_v` quite easily.
#
# The trick is to provide a dictionary (we name it ``inp`` here) instead of the
# resistivity vector in ``res``. This dictionary, ``inp``, has tw... |
shidarin/photosleuth | photosleuth/__init__.py | Python | mit | 4,340 | 0.000461 | #!/usr/bin/env python
"""
PhotoSleuth
===========
Uses Google with Selenium controlled browsers to perform reverse image search
and allow users to page through results.
## License
Original is by /u/touste
http://www.reddit.com/r/ScriptSwap/comments/26bdm8/python_reversesearch_each_image_of_a_website/
http://www.red... | wser):
"""Parses and returns all found images on a webpage"""
# Scroll until all the images have been found, which is
# useful for infinite scroll pages
prev_elems = 0
post_elems = browser.find_elements_by_tag_name("img" | )
while len(post_elems) > prev_elems:
prev_elems = len(post_elems)
browser.execute_script(
"window.scrollTo(0, document.body.scrollHeight);"
)
time.sleep(0.5)
post_elems = browser.find_elements_by_tag_name("img")
images = [elem.get_attribute('src') for elem ... |
Team4761/Scattergun | scattergun/scattergun_coreapp/views.py | Python | mit | 8,417 | 0.004039 | from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404, redirect
import numpy
from .admin import RoundReportResource, TeamResource, CompetitionResource
from .forms import TeamForm, RoundReportForm, CompetitionForm, CompetitionSelectForm
from .models import Team, RoundReport, Competi... | == "POST":
form = RoundReportForm(request.POST)
if | form.is_valid():
form.save()
return redirect('scattergun-roundreport-list')
else:
form = RoundReportForm()
return render(request, "roundreport_add.html", context={"form": form})
def roundreport_list_view(request):
reports = RoundReport.objects.all()
return render(reques... |
informatics-isi-edu/microscopy | youtube/youtubecli/setup.py | Python | apache-2.0 | 1,075 | 0.00093 | #
# Copyright 2017 University of Southern California
#
# 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... | ense for the specific language governing permissions and
# limitations under the License.
#
from distutils.core import setup
setup(name='youtubecli | ',
description='library for uploading a video file to YouTube',
version='0.1',
packages=['youtubecli'],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Topic :: Internet :: W... |
tensorflow/tpu | models/official/unet3d/tpu_executor.py | Python | apache-2.0 | 10,653 | 0.006195 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | , tpu_flags.as_dict())
if tpu_flags.use_tpu:
tpu_cluster_resolver = | tf.distribute.cluster_resolver.TPUClusterResolver(
tpu_flags.tpu, zone=tpu_flags.tpu_zone, project=tpu_flags.gcp_project)
tpu_grpc_url = tpu_cluster_resolver.get_master()
if not eval_master:
eval_master = tpu_grpc_url
tf.Session.reset(tpu_grpc_url)
else:
tpu_cluster_resolv... |
MerlijnWajer/whipper | whipper/common/program.py | Python | gpl-3.0 | 24,809 | 0 | # -*- Mode: Python; test-case-name: whipper.test.test_common_program -*-
# vi:si:et:sw=4:sts=4:ts=4
# Copyright (C) 2009, 2010, 2011 Thomas Vander Stichele
# This file is part of whipper.
#
# whipper is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publ... | rmal TOC table from a toc pickle or the drive.
| Also retrieves the cdrdao version
:param runner:
:type runner:
:param toc_pickle:
:type toc_pickle:
:param device:
:type device:
:returns:
:rtype: tuple of L{table.Table}, str
"""
def function(r, t):
r.run(t)
pto... |
snmishra/xcircuit-3.8 | lib/python/flatspice.py | Python | gpl-2.0 | 3,186 | 0.061205 | # flatspice.py
#-----------------------------------------------------------
# Python script which writes a SPICE-format netlist.
# Replaces the code formerly in "netlist.c" (deprecated).
# Python scripting is now the preferred method for handling
# netlist output formats.
#---------- | -------------------------------------------------
# Select the device string correspondi | ng to the given prefix.
# Return the body of the string, or an empty string if the prefix doesn't match.
def select(sstr, prefix):
ltext = ''
if sstr.startswith(prefix):
ltext += sstr[len(prefix) + 1:]
return ltext
# Generate an ASCII string from an xcircuit string (list)
def textprint(slist, params... |
cbuben/cloud-init | tests/unittests/test_datasource/test_azure.py | Python | gpl-3.0 | 17,037 | 0.000587 | from cloudinit import helpers
from cloudinit.util import load_file
from cloudinit.sources import DataSourceAzure
from ..helpers import populate_dir
import base64
import crypt
from mocker import MockerTestCase
import os
import stat
import yaml
def construct_valid_ovf_env(data=None, pubkeys=None, userdata=None):
i... | return []
def _pubkeys_from_crt_files(flist):
data['pubkey_files'] = flist
return ["pubkey_from: %s" % f for f in flist]
def _iid_from_shared_config(path):
data['iid_ | from_shared_cfg'] = path
return 'i-my-azure-id'
def _apply_hostname_bounce(**kwargs):
data['apply_hostname_bounce'] = kwargs
if data.get('ovfcontent') is not None:
populate_dir(os.path.join(self.paths.seed_dir, "azure"),
{'ovf-env.xml': data... |
abtawfik/Single-Column-Model | tests/animation_of_single_profile.py | Python | mit | 9,245 | 0.049757 | #!/bin/python
### Handling Arrays and Reading Grib package
import numpy as np
import numpy.ma as ma
import pandas as pd
### These are helper Fortran functions to speed things up
from HandyMet import *
### Plotting packages
from mpl_toolkits.basemap import Basemap , addcyclic
from matplotlib import pyplot as plt
fro... | = layerdepth( pres, temp[0], qhum[0], pres[0], height[0], missing )
evap = latent * dt / latent_heat_of_condensation(temp[0], missing)
# print(' 8')
newQ = inject_and_mix(pblp, evap, pres, qhum, dpress, missing)
qhum = newQ |
# print(' 9')
tbm,tdef,bclp,qbcl = hcfcalc(missing, temp, pres, qhum, height, pblp)
pressure_deficit = pblp - bclp
# print(' 10')
return pressure_deficit,temp,qhum,Theta,height,pblp,pblh
####################################################
##### Prepare profile dat... |
spektom/incubator-airflow | tests/providers/google/cloud/hooks/test_bigtable.py | Python | apache-2.0 | 22,575 | 0.002303 | #
# 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... | oviders.google.cloud.hooks.bigtable import BigtableHook
from tests.providers.google.cloud.utils.base_gcp_mock import (
GCP_PROJECT_ID_HOOK_UNIT_TEST, mock_base_gcp_hook_default_project_id,
mock_base_gcp_hook_no_default_project_id,
)
CBT_INSTANCE = 'instance'
CBT_CLUSTER = 'cluster'
CBT_ZONE = 'zone'
CBT_TABLE ... | ,
new=mock_base_gcp_hook_no_default_project_id):
self.bigtable_hook_no_default_project_id = BigtableHook(gcp_conn_id='test')
@mock.patch(
"airflow.providers.google.cloud.hooks.bigtable.BigtableHook.client_info",
new_callable=mock.PropertyMock
)
@mock.patc... |
cydenix/OpenGLCffi | OpenGLCffi/GLES3/EXT/EXT/draw_transform_feedback.py | Python | mit | 261 | 0.015326 | from OpenGLCff | i.GLES3 import params
@params(api='gles3', prms=['mode', 'id'])
def glDrawTransformFeedbackEXT(mode, id):
pass
@params(api='gles3', prms=['mode', 'id', 'instancecount'])
def glDrawTransformFeedbackInstancedEXT(mode, id, instancecount):
p | ass
|
uri-mog/dreampie | dreampielib/gui/subprocess_handler.py | Python | gpl-3.0 | 10,125 | 0.003062 | # Copyright 2009 Noam Yorav-Raphael
#
# This file is part of DreamPie.
#
# DreamPie 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.
# ... | ode('utf8', 'replace'))
# Read from socket
if self.wait_for_object(0):
try:
obj = recv_object(self._sock)
except IOError:
# Could hap | pen when subprocess exits. See bug #525358.
# We give the subprocess a second. If it shuts down, we ignore
# the exception, since on the next round we will handle that.
# Otherwise, the exception remains unexplained so we re-raise.
time.sleep(1)
... |
MattCCS/PyVault | pyvault/crypto/datetime_utils.py | Python | mit | 173 | 0 |
# standard
import datetime
def now():
return int(datetime.datetime.now().strftime("%s"))
def load(tim | estamp):
return datetime.datetime.fromtimestamp(ti | mestamp)
|
afronski/grammar-generator | grammar-generator/Elements/STG/Visible/VisibleSpecifiedColumnElementForStg.py | Python | mit | 433 | 0.025404 | from Element | s.STG.Base.IElementForStg import IElementForStg
class VisibleSpecifiedColumnElementForStg(IElementForStg):
def __init__(self, templates, settingsObject):
self.typeName = "Specified"
self.templateName = "SpecifiedVisibledColumn"
super(VisibleSpecifiedColumnElementForStg, self).__init__(templates, settingsObject... | lateName |
andredias/nikola | tests/test_command_import_wordpress.py | Python | mit | 22,852 | 0.00298 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import os
import unittest
import mock
import nikola
import nikola.plugins.command.import_wordpress
from .base import BaseTestCase
class BasicCommandImportWordpress(BaseTestCase):
def setUp(self):
self.module = nikola.plugi... | mportWordpressTest(BasicCommandImportWordpress):
def test_create_import_work_without_argument(self):
# Running this without an argument must not fail.
# It should show the proper usage of the command.
self.impo | rt_command.execute()
def test_populate_context(self):
channel = self.import_command.get_channel_from_file(
self.import_filename)
self.import_command.html2text = False
self.import_command.transform_to_markdown = False
self.import_command.transform_to_html = False
... |
masterkorp/obfsproxy | obfsproxy/test/transports/test_scramblesuit.py | Python | bsd-3-clause | 17,152 | 0.010028 | import unittest
import os
import base64
import shutil
import tempfile
import Crypto.Hash.SHA256
import Crypto.Hash.HMAC
import obfsproxy.common.log as logging
import obfsproxy.network.buffer as obfs_buf
import obfsproxy.common.transport_config as transport_config
import obfsproxy.transports.base as base
import obfs... |
prk = ("077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122e" + \
"c844ad7c2b3e5").decode('hex')
okm | = ("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db" + \
"02d56ecc4c5bf34007208d5b887185865").decode('hex')
self.runHKDF(ikm, salt, info, prk, okm)
def test2_HKDF_TestCase2( self ):
ikm = ("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c" + \
"1d1e1f202... |
pytorch/fairseq | tests/test_character_token_embedder.py | Python | mit | 1,678 | 0.000596 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
import torch
from fairseq.data import Dictionary
from fairseq.modules import CharacterTokenEmbedder
class TestCharacterToke... | = torch.LongTensor(len(test_sents), max_len + 2).fill_(vocab.pad())
for i in range(len(test_sents)):
input[i][0] = vocab.eos()
for j in range(len(test_sents[i])):
input[i][j + 1] = vocab.index(test_sents[i][ | j])
input[i][j + 2] = vocab.eos()
embs = embedder(input)
assert embs.size() == (len(test_sents), max_len + 2, 5)
self.assertAlmostEqual(embs[0][0], embs[1][0])
self.assertAlmostEqual(embs[0][0], embs[0][-1])
self.assertAlmostEqual(embs[0][1], embs[2][1])
self... |
scorphus/politicos | politicos/migrations/versions/32f5eec11778_create_mandate_table.py | Python | agpl-3.0 | 1,317 | 0.001519 | """Create mandate table
Revision ID: 32f5eec11778
Revises: 3a41443d8839
Create Date: 2015-06-29 22:49:29.941746
"""
# revision identifiers, used by Alembic.
revision = '32f5eec11778'
down_revision = '3a41443d8839'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'mandate'... | 'uk_mandate',
'mandate',
['legislator_id', 'political_office_id', 'date_start', 'date_end']
)
def | downgrade():
op.drop_constraint('fk_political_office', 'mandate', type_='foreignkey')
op.drop_constraint('fk_legislator', 'mandate', type_='foreignkey')
op.drop_constraint('uk_mandate', 'mandate', type_='unique')
op.drop_table('mandate')
|
nuagenetworks/bambou | bambou/__init__.py | Python | bsd-3-clause | 12,559 | 0.004539 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent Inc
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# no... | hild`.
> You may notice that an optional parameter `callback` is | present. This is because `MySDK` can work completely asynchronously.
### Converting to and from a Python Dictionary
`bambou.NURESTObject` allows quick and easy conversion from and to python dictionaries
* `bambou.NURESTObject.from_dict`
* `bambou.NURESTObject.to_dict`
> you never need to process to the actual JSO... |
ESOedX/edx-platform | lms/djangoapps/tests/test_utils.py | Python | agpl-3.0 | 1,155 | 0.004329 | """
Unit Tests for Utils Class
"""
from __future__ import absolute_import
from unittest import TestCase
import ddt
from opaque_keys.edx.keys import CourseKey, UsageKey
from lms.djangoapps.utils import _get_key
@ddt.ddt
class UtilsTests(TestCase):
@ddt.data(
['edX/DemoX/Demo_Course', CourseKey.from_str... | Key],
[CourseKey.from_string('course-v1:edX+DemoX+Demo_Course'),
CourseKey.from_string('course-v1:edX+DemoX+Demo_Course'), CourseKey],
['block-v1:edX+DemoX+Demo_Course+type@sequential+block@workflow',
UsageKey.from_string('block-v1:edX+DemoX+Demo_Course+type@sequential+block@workflow')... | mo_Course+type@sequential+block@workflow'), UsageKey],
)
@ddt.unpack
def test_get_key(self, input_key, output_key, key_cls):
self.assertEqual(_get_key(input_key, key_cls), output_key)
|
huxianglin/pythonstudy | week05-胡湘林/ATM/shop/shop_module/admin.py | Python | gpl-3.0 | 6,825 | 0.012409 | #!/usr/bin/env python
# encoding:utf-8
# __author__: huxianglin
# date: 2016-09-18
# blog: http://huxianglin.cnblogs.com/ http://xianglinhu.blog.51cto.com/
import os
from shop_conf import settings
from shop_module import auth
from shop_module import encry_passwd
from shop_module import db_handler
def admin(shop_log):... |
for i in ["password","privilege","username","freeze"]:
mod_user_data[i]=mod_info_list.pop()
db_handler.write_user(mod_user_id, mod_user_data)
shop_log.info("Modefy user ID: %s successful!"%mod_user_data["user_id"])
else:
pr... | _user__(shop_log):
while True:
for i, j in enumerate(auth.INIT_DATA["shop_user_list"], 1):
print(i, j)
queue_user_id = input("请输入要查询的用户ID,b返回:").strip()
if queue_user_id in auth.INIT_DATA["shop_user_list"]:
que_user_info=db_handler.read_user(queue_user_id)
... |
Schamnad/cclib | src/cclib/bridge/cclib2pyquante.py | Python | bsd-3-clause | 1,092 | 0.001832 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Bridge for using cclib | data in PyQuante (http://pyquante.sourceforge.net)."""
from __future__ import print_function
import sys
try:
from PyQuante.Molecule import Molecule
except ImportError:
# Fail silently for now.
pass
def makepyquante(atomcoords, atomnos, charge | =0, mult=1):
"""Create a PyQuante Molecule.
>>> import numpy
>>> from PyQuante.hartree_fock import hf
>>> atomnos = numpy.array([1,8,1],"i")
>>> a = numpy.array([[-1,1,0],[0,0,0],[1,1,0]],"f")
>>> pyqmol = makepyquante(a,atomnos)
>>> en,orbe,orbs = hf(pyqmol)
>>> print int(en *... |
kevinkahn/softconsole | hubs/isy/isyeventmonitor.py | Python | apache-2.0 | 21,759 | 0.027345 | import base64
import errno
import random
import ssl
import threading
import time
import copy
import websocket
import xmltodict
import config
import debug
from utils import exitutils
import hubs.isy.isycodes as isycodes
import logsupport
from controlevents import CEvent, PostEvent, ConsoleEvent, PostIfInterested
from ... | ame + " Failed Thread Restart", severity=ConsoleWarning)
else:
logsupport.Logs.Log(self.hubname + " Unknown ISY QH Thread state")
def PreRestartQHThread(self):
self.isy._HubOnline = False
self.THstate = 'restarting'
try:
if self.lasterror == 'ISYSocketTimeOut':
logsupport.Logs.Log(self.hubname + '(T... | ) Wait for likely router reboot or down',
severity=ConsoleWarning, tb=False)
self.delayedstart = 150
self.reinit()
return
if self.lasterror == 'ISYWSTimeOut':
logsupport.Logs.Log(self.hubname + ' WS restart after surprise close - short delay (15)',
severity=ConsoleWarning)
self... |
PaloAltoNetworks/minemeld-core | minemeld/ft/utils.py | Python | apache-2.0 | 6,146 | 0.000163 | # Copyright 2015 Palo Alto 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 agre... | raise ValueError('Invalid age out base %s' % base)
result['base'] = base
result['offset'] = age_out_in_millisec(toks[1].strip())
if result['offset'] is None:
raise ValueError('Invalid age out offset %s' % t)
return result
class GThrottled(object):
def __init__(self... | = f
self.wait = wait
def later(self):
self._previous = utc_millisec()
self._timeout = None
self.f(*self._args, **self._kwargs)
def __call__(self, *args, **kwargs):
now = utc_millisec()
remaining = self.wait - (now - self._previous)
if self._cancelled:... |
OLF-Bioinformatics/snp_analysis | binaries/snpTableMaker.py | Python | gpl-3.0 | 15,587 | 0.002759 | #!/usr/bin/env python
import os
import random
__author__ = 'duceppemo'
class SnpTableMaker(object):
"""
Everything is ran inside the class because data structures have to be
shared across parent and child process during multi threading
"""
def __init__(self, arg | s):
import os
import sys
import glob
import multiprocessing
# Define variables based on supplied arguments
self.args = args
self.ref = args.ref
if not os.path.isfile(self.ref):
sys.exit('Supplied reference genome file do | es not exists.')
self.vcf = args.vcf
if not os.path.isdir(self.vcf):
sys.exit('Supplied VCF folder does not exists.')
self.minQUAL = args.minQUAL
if not isinstance(self.minQUAL, (int, long)):
sys.exit('minQual value must be an integer')
self.ac1_report = a... |
Cibiv/Teaser | tools/samheader.py | Python | mit | 141 | 0.028369 | import sys
for line in open(sys.argv[1], "r").readl | ines():
if line.strip() == "":
continue
if line[0] == "@":
sys.stdout.wr | ite(line)
|
tiagocoutinho/bliss | bliss/scanning/acquisition/__init__.py | Python | lgpl-3.0 | 161 | 0 | '''Acquisition module
This module provides an acquisi | tion interface for existing devices
.. autosummary::
:toctree:
lima
| motor
musst
p201
'''
|
amaivsimau/electrum-ltc | lib/paymentrequest.py | Python | gpl-3.0 | 8,589 | 0.004424 | import hashlib
import httplib
import os.path
import re
import sys
import threading
import time
import traceback
import urllib2
try:
import paymentrequest_pb2
except:
print "protoc --proto_path=lib/ --python_out=lib/ lib/paymentrequest.proto"
raise Exception()
import urlparse
import requests
from M2Crypto ... | ing(paymntreq.serialized_payment_details)
if pay_det.expires and pay_det.expires < int(time.time()):
self.error = "ERROR: Payment Request has Expired."
return False
for o in pay_det.outputs:
addr = transaction.get_address_from_output_script(o.script)[1]
... | match:
print 'Signed By Trusted CA: ', CA_OU
print "payment url", pay_det.payment_url
return True
def send_ack(self, raw_tx, refund_addr):
pay_det = self.payment_details
if not pay_det.payment_url:
return
paymnt = paymentrequest_pb2.Payment()
... |
OpenXT/sync-client | pysynchronizer/oxt_dbus.py | Python | gpl-2.0 | 3,858 | 0.002592 | #
# Copyright (c) 2021 Daniel P. Smith, Apertus Solutions LLC
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This... | pi.Set(self.intf.dbus_interface, key, value))
class OXTDBusApi:
@staticmethod
def open_xenmgr():
"""Return a dbus proxy for the main xenmgr interface"""
try:
obj = ServiceObject(XENMGR_SERVICE, XENMGR_INTF, '/')
except:
obj = None
return obj
@staticm... | try:
obj = ServiceObject(XENMGR_SERVICE, XENMGR_UNRESTRICTED_INTF, '/')
except:
obj = None
return obj
@staticmethod
def open_host():
"""Return a dbus proxy for the main xenmgr host interface"""
try:
obj = ServiceObject(XENMGR_SERVICE, XENMGR_... |
khosrow/metpx | pxStats/bin/webPages/generateImageWebPage.py | Python | gpl-2.0 | 6,610 | 0.021936 | #! /usr/bin/env python
"""
######################### | #####################################################
##
##
## @Name : generateImageWebPage.py
##
## @license : MetPX Copyright (C) 200 | 4-2006 Environment Canada
## MetPX comes with ABSOLUTELY NO WARRANTY; For details type see the file
## named COPYING in the root of the source directory tree.
##
##
## @author: Nicholas Lemay
##
## @since: 22-11-2006, last updated on : 2008-04-30
##
##
## Description : Generates a web pages t... |
AltenSesto/linx4py | src/test/async_receiver_test.py | Python | lgpl-3.0 | 2,889 | 0.006231 | #-------------------------------------------------------------------------------
# Copyright (c) 2013 Alten AB.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the GNU Public License v3.0
# which accompanies this distribution, and is available at
# http://www.g... | e)
|
@classmethod
def tearDownClass(self):
self.server.stop()
def setUp(self):
linxInstance = self.open_linx("MyReceiver")
self.receiver = AsyncReceiver(linxInstance)
self.receiver.add_union_type(LINX_SIGNAL)
self.receiver.init_receive()
def tearDown(self):
... |
Braiiin/outline-logic | outline_logic/config.py | Python | apache-2.0 | 729 | 0 | """
Configurations
--------------
Various setups for different app instances
"""
class Config:
"""Default con | fig"""
DEBUG = False
TESTING = False
SESSION_STORE = 'session'
MONGODB_DB = 'default'
SECRET_KEY = 'flask+braiiin=<3'
L | IVE = ['v1']
STATIC_PATH = 'static'
HASHING_ROUNDS = 15
INIT = {
'port': 8006,
'host': '127.0.0.1',
}
class ProductionConfig(Config):
"""Production vars"""
INIT = {
'port': 80,
'host': '127.0.0.1',
}
class DevelopmentConfig(Config):
"""For local runs... |
MadeOfMagicAndWires/trackma | setup.py | Python | gpl-3.0 | 1,589 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
from trackma import utils
try:
LONG_DESCRIPTION = open("README.rst").read()
except IOError:
LONG_DESCRIPTION = __doc__
NAME = "Trackma"
REQUIREMENTS = []
EXTRA_REQUIREMENTS = {
'curses': ['urwid'],
'GTK': ['pygobject'],
'Qt': [],
}... | - Alpha',
'Intended Audience :: End Users/Desktop',
'Topic :: Inter | net',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Operating System :: POSIX',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
]
)
|
fastmonkeys/qstring | qstring/__init__.py | Python | mit | 133 | 0 | from .exc | import ParameterTypeError # noqa
from .nest import nest # noqa
from .unnest import unnest # noq | a
__version__ = '0.2.1'
|
florian-f/sklearn | sklearn/neighbors/unsupervised.py | Python | bsd-3-clause | 2,953 | 0 | """Unsupervised nearest neighbors learner"""
from .base import NeighborsBase
from .base import KNeighborsMixin
from .base import RadiusNeighborsMixin
from .base import UnsupervisedMixin
class NearestNeighbors(NeighborsBase, KNeighborsMixin,
RadiusNeighborsMixin, UnsupervisedMixin):
"""Unsu... | .neighbors import NearestNeighbors
>>> samples = [[0, 0, 2], [1, 0, 0], [0, 0, 1]]
>>> neigh = NearestNeighbors(2, 0.4)
>>> neigh.fit(samples) #doctest: +ELLIPSIS
NearestNeighbors(...)
>>> neigh.kneighbors([[0, 0, 1.3]], 2, return_distance=False)
... #doctest: +ELLIPSIS
arra... | 0, 0, 1.3], 0.4, return_distance=False)
array([[2]])
See also
--------
KNeighborsClassifier
RadiusNeighborsClassifier
KNeighborsRegressor
RadiusNeighborsRegressor
BallTree
Notes
-----
See :ref:`Nearest Neighbors <neighbors>` in the online documentation
for a discussio... |
e-gob/plataforma-kioscos-autoatencion | scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/network/ios/ios_ping.py | Python | bsd-3-clause | 5,640 | 0.007624 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# 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
ANSIBLE_METADATA = {'met | adata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: ios_ping
short_description: Tests reachability using ping from IOS sw | itch
description:
- Tests reachability using ping from switch to a remote destination.
author:
- Jacob McGill (@jmcgill298)
version_added: '2.4'
extends_documentation_fragment: ios
options:
count:
description:
- Number of packets to send.
required: false
default: 5
dest:
description:
- The I... |
plotly/plotly.py | packages/python/plotly/plotly/validators/contour/line/_color.py | Python | mit | 405 | 0.002469 | import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(self, plotly_name="color", pare | nt_name="contour.line", **kwargs):
super(ColorValidator, self).__init__(
plotly_name=plotly_n | ame,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "style+colorbars"),
**kwargs
)
|
ScatterHQ/eliot | eliot/_output.py | Python | apache-2.0 | 15,228 | 0.000591 | """
Implementation of hooks and APIs for outputting log messages.
"""
import sys
import traceback
import inspect
import json as pyjson
from threading import Lock
from functools import wraps
from io import IOBase
from pyrsistent import PClass, field
from . import _bytesjson as bytesjson
from zope.interface import Int... |
self._any_added = False
self._globalFields = {}
def addGl | obalFields(self, **fields):
"""
Add fields that will be included in all messages sent through this
destination.
@param fields: Keyword arguments mapping field names to values.
"""
self._globalFields.update(fields)
def send(self, message):
"""
Deliver... |
googleapis/python-aiplatform | google/cloud/aiplatform/explain/metadata/metadata_builder.py | Python | apache-2.0 | 1,054 | 0 | # -*- coding: utf-8 -*-
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | language governing permissions and
# limitations under the License.
"""Base abstract class for metadata builders."""
import abc
_ABC = abc.ABCMeta("ABC", (object,), {"__slots__": ()})
class MetadataBuilder(_ABC):
"""Abstract base class for metadata builder | s."""
@abc.abstractmethod
def get_metadata(self):
"""Returns the current metadata as a dictionary."""
@abc.abstractmethod
def get_metadata_protobuf(self):
"""Returns the current metadata as ExplanationMetadata protobuf"""
|
robb-brown/IntroToDeepLearning | 6_MRISegmentation/ccseg.py | Python | mit | 4,404 | 0.042688 | from tfs import *
from pylab import *
from numpy import *
import glob, os
import nibabel as nib
matplotlib.interactive(True)
session = tf.InteractiveSession()
dataPath = './corpusCallosum/'
# Class to serve up segmented images
def computePad(dims,depth):
y1=y2=x1=x2=0;
y,x = [numpy.ceil(dims[i]/float(2**depth))... | ],truth[slc][0])]
else:
image, truth = (image[slc][0],truth[slc][0])
return (image,truth)
def nex | t_batch(self,miniBatch=None):
if miniBatch is None or miniBatch==len(self.paths):
batch = arange(0,len(self.paths))
else:
batch = random.choice(arange(0,len(self.paths)),miniBatch)
images = [self.getSlices(self.paths[i]) for i in batch]
return list(zip(*images))
class Container(object):
def __init__... |
lamecksf/nix | mIP.py | Python | mit | 2,035 | 0.041278 | # NIx GeoIP Tool
# nv 1.2
# Modulo Identifier Protocol
import json
import urllib2
class Struct:
def __init__(self):
values = ''
s = Struct()
s.values = []
def geoIP(ip):
response = urllib2.urlopen('http://ip-api.com/json/'+ip)
dt = response.read()
dt_all = json.loads(dt)
#SET GEO IP-------------------------... | tatus():
return s.values[0]
def getCountry():
return s.values[1]
def getCountryCode():
return s.values[2]
def getRegion():
return s.values[3]
def getCity():
return s.values[4]
def getZip():
return s.values[5]
def getLat():
return s.values[6]
def getLon():
return s.values[7]
def getTimezone():
return s.values[8... | ues[12]
def getTry():
return '%43s'%'try :: nit.py --ip myip\n'
|
nwjs/chromium.src | tools/flags/generate_unexpire_flags_unittests.py | Python | bsd-3-clause | 1,062 | 0.00565 | #!/usr/bin/env python
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code | is governed by a BSD-style license that can be
# found in the LICENSE file.
import generate_unexpire_flags
import os
import unittest
class TestUnexpireGenerator(unittest.TestCase):
TEST_MSTONE = 123
def read_golden_file(self, extension):
return file(
| os.path.join(
os.path.dirname(__file__),
'unexpire_test.' + extension + '.expected')).read()
def testCcFile(self):
cc = generate_unexpire_flags.gen_features_impl('foobar', 123)
golden_cc = self.read_golden_file('cc')
self.assertEquals(golden_cc, cc)
def testHFile(self):... |
MoRgUiJu/morguiju.repo | plugin.video.pelisalacarta/platformcode/mct.py | Python | gpl-2.0 | 29,761 | 0.00859 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta 4
# Copyright 2015 tvalacarta@gmail.com
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#
# Distributed under the terms of GNU General Public License v3 (GPLv3)
# http://www.gnu.org/licenses/gpl-3.0.html
# --... | on_libtorrent import get_libtorrent
lt = get_libtorrent()
except Exception, e:
import libtorrent as lt
import xbmc
import xbmcgui
from core import config
from core import scrapertools
from core import filetools
def play(url, xlistitem, is_view=None, subtitle=""):
# -- Necesario para algunas webs ------... | sponse(url, header_to_get="location")
if len(t_file) > 0:
url = t_file
t_file = scrapertools.get_header_from_response(url, header_to_get="location")
if len(t_file) > 0:
url = t_file
# -- Crear dos carpetas en descargas para los archivos ------
save_path_video... |
hofors/autohub | ahc.py | Python | gpl-2.0 | 7,751 | 0.00529 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import getopt
import jsonrpclib
import os
import time
DEFAULT_HOST="localhost"
DEFAULT_PORT=3444
def usage(name):
print "%s [-s server] temp" % name
print "%s [-s server] temp set-name <sensor-id> <name>" % name
print "%s [-s server] temp del <sensor-i... | ate_str(switch[3]))
return 0
def get_switch_cmd(server, device_id=None, unit_id=None, name=None):
if name:
switch_exists, switch_state = server.get_switch_by_name(name)
else:
switch_exists, switch_state = \
server.get_switch(int(device_id, 16), int(unit_id, 10))
if switch_ex... | print "unknown"
return 1
def set_switch_cmd(server, state, device_id=None, unit_id=None,
name=None):
if state == "on":
state = 1
elif state == "off":
state = 0
else:
print 'A switch is "on" or "off"'
sys.exit(1)
if name:
if serv... |
vdloo/raptiformica | tests/unit/raptiformica/distributed/exec/test_try_machine_command.py | Python | mit | 6,531 | 0.000919 | from functools import partial
from mock import call
from raptiformica.shell.execute import COMMAND_TIMEOUT
from tests.testcase import TestCase
from raptiformica.distributed.exec import try_machine_command
class TestTryMachineCommand(TestCase):
def setUp(self):
self.log = self.set_up_patch('raptiformica... | _and_port_pairs, self.command, attempt_limit=2)
expected_command_as_list1 = ['/usr/bin/env', 'ssh', '-A',
'-o', 'ConnectTimeout=5',
'-o', 'StrictHostKeyChecking=no',
'-o', 'ServerAliveInterval=10',
... | '-o', 'PasswordAuthentication=no',
'root@1.2.3.4',
'-p', '2222', '/bin/true']
expected_command_as_list2 = ['/usr/bin/env', 'ssh', '-A',
'-o', 'ConnectTimeout=5',
... |
LucidAi/nlcd | nlcd/local.py | Python | mit | 2,115 | 0.000473 | # coding: utf-8
# Author: Vova Zaytsev <zaytsev@usc.edu>
import os
import json
def project_dir(dir_name):
return os.path.join(os.path.dirname(__file__), "..", dir_name)\
.replace("\\", "//")
# with open(project_dir("conf/dev.json"), "rb") as fp:
# CONF = json.load(fp)
SECRET_KEY = "h8(e(u3#k)l802(... | RL = "/webapp/"
STATICFILES_DIRS = (project_dir("webapp"),)
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
)
TEMPLATE_LOADERS = (
"django.template.loaders.filesystem.Loader",
"django.templa | te.loaders.app_directories.Loader",
)
TEMPLATE_DIRS = (
"webapp/templates",
)
LOGGING = {
"version": 1,
"handlers": {
"logfile": {
"class": "logging.handlers.WatchedFileHandler",
"filename": "log.txt"
},
},
"loggers": {
"django": {
"ha... |
upamune/weatherhist | tools/gen_table.py | Python | mit | 422 | 0.004739 | import json
f = open('stations.json')
dict = json.load(f)
f.clos | e()
tables = ["|station_id|group_id|name|type|", "|---:|---:|:--:|:--:|"]
row = "|%s|%s|%s|%s|"
stations = dict['stations']
for s in stations:
r = row % (s['station_id'], s['group_id'], s['station_name'], s['station_type'])
tables.append(r)
md = '\n'.join(tables)
md_file_name = "station.md"
with open(md_fi... | e(md)
|
BT-astauder/account-financial-reporting | account_financial_report/report/aged_partner_balance_xlsx.py | Python | agpl-3.0 | 10,980 | 0 |
# Author: Julien Coux
# Copyright 2016 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, models
class AgedPartnerBalanceXslx(models.AbstractModel):
_name = 'report.a_f_r.report_aged_partner_balance_xlsx'
_inherit = 'report.account_financial_report.abstrac... | for partner in account.partner_ids:
# Write partner title
self.write_array_title(partner.name)
# Display array header for move lines
self.write_array_header()
# Display account move lines
for li... | balance line for partner
self.write_ending_balan |
umitproject/tease-o-matic | sass/exceptions.py | Python | bsd-3-clause | 673 | 0.007429 | class SassConfigurationError(Exception):
"""
This ERROR should be used when there is a problem with the
configuration settings in the settings.py file.
"""
pass
class SassCommandArgumentError(Exception):
"""
This ERROR should be used when there is a problem with the
arguments being p... | ss SassGenerationErr | or(Exception):
"""
This ERROR is used when there was a problem using Sass to
generate css files. This could be caused by issues with the
sass file itself.
"""
pass
class SassException(Exception):
pass
class SassConfigException(Exception):
pass |
shivanshuag/gaea | listview.py | Python | mit | 706 | 0.012748 | import sys
from PyQt4 import QtCore, QtGui, uic
#import gaea
import globals
import repo
import commit
#import clint libraries
from clint.arguments import Args
from clint.textui import puts, colored, indent
form_class = uic.loadUiType("list.ui")[0] # Load the UI
class MyWindowClass(QtGui.QMainWindow, ... |
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
model = QtGui.QStringListModel()
model.setStringList(QtCore.QString("Item 1;Item 2;Item 3;Item 4").split(";"))
self.listView.setModel(model)
app = QtGui.QApplication(sys.argv)
myWi... | s(None)
myWindow.show()
app.exec_() |
ymero/pulsar | pulsar/apps/wsgi/html.py | Python | bsd-3-clause | 2,345 | 0 | from collections import Mapping
from pulsar.utils.structures import recursive_update
HTML_VISITORS = {}
__all__ = ['HtmlVisitor']
newline = frozenset(('meta', 'link', 'script', 'head', 'body', 'title'))
def html_visitor(tag):
return HTML_VISITORS.get(tag, base)
class HtmlType(type):
def __new__(cls, ... | if isinstance(target, Mapping):
return recursive_update(target, value)
data[key] = value
base = HtmlVisitor()
class Textarea(HtmlVisitor):
def get_form_valu | e(self, html):
return html.children[0] if html.children else ''
def set_form_value(self, html, value):
html.remove_all()
html.append(value)
class Select(HtmlVisitor):
def get_form_value(self, html):
values = []
for child in html.children:
if child.attr('se... |
AtelierSoude/shrooms | ShroomsAPI/ShroomsAPI/wsgi.py | Python | gpl-3.0 | 398 | 0 | """
WSGI config for ShroomsAPI project.
It exposes the WSGI callable as a module-level variable named ``application` | `.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
imp | ort os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ShroomsAPI.settings")
application = get_wsgi_application()
|
tensorflow/fairness-indicators | tensorboard_plugin/tensorboard_plugin_fairness_indicators/version.py | Python | apache-2.0 | 721 | 0 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (th | e "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WIT... | e version string of Fairness Indicators Tensorboard Plugin."""
# Note that setup.py uses this version.
__version__ = '0.39.0.dev'
|
tdpreece/ApprovalTests.Python | tests/__init__.py | Python | apache-2.0 | 57 | 0 | __author__ = 'Chris Lucian; Llewellyn Falco; Jim Cou | nts'
| |
Eksmo/calibre | src/calibre/gui2/store/stores/ebookpoint_plugin.py | Python | gpl-3.0 | 2,890 | 0.003461 | # -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import, print_function)
__license__ = 'GPL 3'
__copyright__ = '2011-2012, Tomasz Długosz <tomek3d@gmail.com>'
__docformat__ = 'restructuredtext en'
import re
import urllib
from contextlib import closing
from lxml import html
from ... | StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
pid = '5557Y'
url = 'http://ebookpoint.pl/view/' + pid
detail_url = None
if detail_item:
book_id = r | e.sub(r'http://ebookpoint.pl/ksiazki', '', detail_item)
if book_id:
detail_url = url + book_id
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_url if detail_url else url)))
else:
d = WebStoreDialog(self.g... |
plotly/python-api | packages/python/plotly/plotly/graph_objs/scatterternary/marker/_colorbar.py | Python | mit | 69,895 | 0.000973 | from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class ColorBar(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "scatterternary.marker"
_path_str = "scatterternary.marker.colorbar"
_valid_props = {
... | "bgco | lor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"len",
"lenmode",
"nticks",
"outlinecolor",
"outlinewidth",
"separatethousands",
"showexponent",
"showticklabels",
"showtickprefix",
"showticksuf... |
google/starthinker | examples/dynamic_costs_example.py | Python | apache-2.0 | 4,668 | 0.010711 | ###########################################################################
#
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/l... | tication) - Credentials used for reading data.
configuration_sheet_url (string) - NA
auth_write (authentication) - Credentials used for writing data.
bigquery_dataset (string) - NA
"""
dynamic_costs(config, {
'auth':auth_read,
'account':dcm_account,
'sheet':{
'template':{
... | QSmmQetJc/edit?usp=sharing',
'tab':'Dynamic Costs',
'range':'A1'
},
'url':configuration_sheet_url,
'tab':'Dynamic Costs',
'range':'A2:B'
},
'out':{
'auth':auth_write,
'dataset':bigquery_dataset
}
})
if __name__ == "__main__":
parser = argparse.Argum... |
osspeak/osspeak | buildit.py | Python | mit | 3,203 | 0.003746 | import subprocess
import sys
import shutil
import os
import os.path
import unittest
import json
import getpass
import requests
import zipfile
import argparse
import io
import tempfile
import time
import lark
from osspeak import version
OSSPEAK_MAIN_PATH = os.path.join('osspeak', 'main.py')
OSSPEAK_SRC_FOLDER = 'ossp... | ul()
def upload_release_folder(upload_url, auth, zip_name='windows-cli.zip'):
zip_bytes = write_release_zip()
headers = {
'Content-Type': 'application/zip',
'name': 'windows-cli.zip'
}
response = requests.post(
f'{upload_url}?name={zip_name}',
data=zip_bytes,
aut... | root_dir='dist', format='zip')
with open(fname, 'rb') as f:
zip_bytes = f.read()
os.close(fd)
os.remove(fname)
return zip_bytes
if __name__ == '__main__':
main() |
Fiile/qsctl | scenarios/steps/rb.py | Python | apache-2.0 | 1,677 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import sh
import yaml
from behave import *
from assertpy import asse | rt_that
from qingstor.sdk.config import Config
from qingstor.sdk.service.qingstor import QingStor
config = Config().load_user_config()
qingstor = QingStor(config)
test_config_file_path = os.path.abspath(
os.path.join(os.path.dirname(__file__), os.path.pardir)
)
with open(test_config_file_path + '/test_config.yaml... | t_name'], test_data['zone'])
bucket.put()
qsctl = sh.Command("qsctl")
@given(u'an empty QingStor bucket')
def step_impl(context):
context.empty_bucket = qingstor.Bucket(
test_data['bucket_name'] + "1", test_data['zone']
)
context.empty_bucket.put()
@when(u'delete bucket')
def step_impl(context):... |
mattcaldwell/django-storages-py3 | setup.py | Python | bsd-3-clause | 774 | 0.023256 | from setuptools import setup, find_packages
import storages
setup(
name = | 'django-storages',
version = storages.__version__,
packages = find_packages(),
author = 'David Larlet',
author_email = 'david@larlet.fr',
license = 'BSD',
descript | ion = 'Support for many storages (S3, MogileFS, etc) in Django.',
url='http://code.welldev.org/django-storages/',
classifiers = [
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD Li... |
resmo/ansible | test/units/modules/network/f5/test_bigip_appsvcs_extension.py | Python | gpl-3.0 | 2,904 | 0.001033 | # -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
if sys.version_info < (2... | tError:
from ansible.modules.network.f5.bigip_appsvcs_extension import ModuleParameters
from ansible.modules.network.f5.bigip_appsvcs_extension import ModuleManager
from ansible.modules.network.f5.bigip_appsvcs_extension | import ArgumentSpec
# Ansible 2.8 imports
from units.compat import unittest
from units.compat.mock import Mock
from units.modules.utils import set_module_args
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def load_fixture(name):
path = os.path.join(fixtu... |
jinnykoo/christmas | src/oscar/apps/dashboard/reviews/views.py | Python | bsd-3-clause | 6,380 | 0 | import datetime
from django.views import generic
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from oscar.views.generic import BulkEditMixin
from oscar.apps.dashboard.reviews import forms... | delta(days=1)
queryset = queryset.filter(
date_created__gte=date_from
).filter(
date_created__lt=date_to
)
self.desc_ctx['date_filter'] \
= _(" created between %(start_date)s and %(end_date)s") % {
'start... | 'end_date': format_datetime(date_to)
}
elif date_from:
queryset = queryset.filter(date_created__gte=date_from)
self.desc_ctx['date_filter'] \
= _(" created after %s") % format_datetime(date_from)
elif date_to:
# Add 24... |
kvaps/vdsm | vdsm/storage/lvm.py | Python | gpl-2.0 | 44,652 | 0.000112 | #
# Copyright 2010-2011 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... | he string is treated a single
# argument an converted into list, containing that string.
# Strings have not __iter__ attribute.
#
def _normalizeargs(args=None):
if args is None:
args = []
elif not hasattr(args, "__iter__"):
args = [args]
return args
def _tags2Tuple(sTags):
"""
Tag... | (*args):
guid = os.path.basename(args[1])
args += (guid,)
return PV(*args)
def makeVG(*args):
args = list(args)
# Convert tag string into tuple.
tags = _tags2Tuple(args[VG._fields.index("tags")])
args[VG._fields.index("tags")] = tags
# Convert attr string into named tuple fields.
#... |
franblas/pyAPI | src/setup.py | Python | mit | 784 | 0 | """
setup.py
@author: franblas
@url: https://github.com/franblas/pyAPI
"""
from setuptools import setup, find_packages
setup(
name='pyAPI',
version='0.0.1',
description='Data from multiple APIs with python',
url='https: | //github.com/franblas/pyAPI',
author='Francois Blas',
author_e | mail='francois_blas@hotmail.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Datascience :: Get Datas :: APIs',
'License :: MIT License',
'Programming Language :: Python :: 2.7',
... |
timgraham/django-cms | cms/templatetags/cms_admin.py | Python | bsd-3-clause | 8,515 | 0.002701 | # -*- coding: utf-8 -*-
from classytags.arguments import Argument
from classytags.core import Options, Tag
from classytags.helpers import InclusionTag
from cms.constants import PUBLISHER_STATE_PENDING
from cms.utils.admin import render_admin_rows
from django import template
from django.conf import settings
from django... | )
return mark_safe(content)
class TreePublishRow(Tag):
name = "tree_publish_row"
options = Options(
Argument('page'),
Argument('language')
)
def render_tag(self, context, page, language):
if page.is_published(language) and page.publisher_public_id and page.publisher_pub... | .is_published(language):
if page.is_dirty(language):
cls = "cms-pagetree-node-state cms-pagetree-node-state-dirty dirty"
text = _("unpublished changes")
else:
cls = "cms-pagetree-node-state cms-pagetree-node-state-published published"
... |
brabsmit/home-control | homecontrol/app/admin.py | Python | mit | 2,233 | 0.031348 | from django.contrib import admin
from app.models import Home, Room, Thermostat, Door, Light, Refrigerator
"""
Administrator interface customization
This module contains customization classes to the admin interface
rendered by Django. This file is interpreted at run time to serve
the custom administrator actions that ... | _display = ('name','room','is_on','pk')
search_fields = ('name','room')
class LightInline(admin.StackedInline):
"""
StackedInline
"""
model = Light
class RefrigeratorAdmin(admin.ModelAdmin):
"""
ModelAdmin
"""
list_display = ('name','room','fridge_set_temp','fridge_current_temp','freezer_s... |
class RoomAdmin(admin.ModelAdmin):
"""
ModelAdmin
"""
list_display = ('name','home','room_type','pk')
search_fields = ('name','home')
inlines = (DoorInline, LightInline, RefrigeratorInline,)
class RoomInline(admin.StackedInline):
"""
StackedInline
"""
model = Room
class HomeAdmin(admin... |
plotly/plotly.py | packages/python/plotly/plotly/validators/scattergeo/marker/colorbar/_minexponent.py | Python | mit | 503 | 0 | import _plotly_utils.basevalidators
class MinexponentVa | lidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self,
plotly_name="minexponent",
parent_name="scattergeo.marker.colorbar",
**kwargs
):
super(MinexponentValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name... | edit_type=kwargs.pop("edit_type", "calc"),
min=kwargs.pop("min", 0),
**kwargs
)
|
pyinvoke/invoke | invoke/context.py | Python | bsd-2-clause | 25,409 | 0 | import os
import re
from contextlib import contextmanager
from itertools import cycle
try:
from invoke.vendor.six import raise_from, iteritems, string_types
except ImportError:
from six import raise_from, iteritems, string_types
from .config import Config, DataProxy
from .exceptions import Failure, AuthFailur... | their documentation for details) may be
#: accessed like dictionary keys (``c.config['foo']``) or object
#: attributes (``c.config.foo``).
#:
#: As a convenience shorthand, the `.Context` object proxies to its
#: ``config`` | attribute in the same way - e.g. ``c['foo']`` or
#: ``c.foo`` returns the same value as ``c.config['foo']``.
config = config if config is not None else Config()
self._set(_config=config)
#: A list of commands to run (via "&&") before the main argument to any
#: `run` or `sudo` ca... |
ngannguyen/immunoseq | src/sampling.py | Python | mit | 13,290 | 0.01076 | #!/usr/bin/env python2.6
#nknguyen soe ucsc edu
#March 20 2012
#Input: input directory of fasta files
#Output: fasta files of a sampled subset of the original files with a specific size
import os, sys, re, random, copy
import immunoseq.lib.immunoseqLib as iseqlib
from sonLib.bioio import system
from optparse import O... | line in f:
line = line.strip()
if line[0] == '>':
if header != '' and seq != '':
addSeq( header, seq, seqs, minCount )
header = line.lstrip('>')
seq = ''
else:
seq = line
if seq != '' and header != '':
addSeq( header, s... | ir( indir )
samples = []
for file in files:
path = os.path.join(indir, file)
if os.path.isdir(path):
continue
sampleName = file.split('.')[0]
sample = Sample(sampleName)
seqs = readFile( path, minCount )
#Set frequencies
total = sum( [s.count ... |
shweta97/pyta | nodes/IfExp.py | Python | gpl-3.0 | 406 | 0 | """
IfExp astroid node
An if statement written in an expression form.
Attributes:
- test (Node)
- Holds a single node such as Compare. |
- Body (List[Node])
- A list of nodes that will execute if the condition passes.
- orelse (List[Node])
- The else clause.
Example:
- test -> True
- Body | -> [x = 1]
- orelse -> [0]
"""
x = 1 if True else 0
|
yasoob/PythonRSSReader | venv/lib/python2.7/dist-packages/Crypto/SelfTest/Signature/test_pkcs1_pss.py | Python | mit | 20,603 | 0.006892 | # -*- coding: utf-8 -*-
#
# SelfTest/Signature/test_pkcs1_pss.py: Self-test for PKCS#1 PSS signatures
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyon... | test
from Crypto.PublicKey imp | ort RSA
from Crypto import Random
from Crypto.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex
from Crypto.Hash import *
from Crypto.Signature import PKCS1_PSS as PKCS
from Crypto.Util.py3compat import *
def isStr(s):
t = ''
try:
t += s
except TypeError:
... |
acopar/crow-plot | crowpl/benchmark.py | Python | gpl-3.0 | 6,999 | 0.01043 | #!/usr/bin/env python
import os
import subprocess
import argparse
from utils import *
from parser import *
RESULTS = 'results'
EXPERIMENTS = [
('1x1', 'cpu'),
('1x1', 'gpu'),
('2x1', 'gpu'), ('1x2', 'gpu'),
('2x2', 'gpu'), ('4x1', 'gpu'), ('1x4', 'gpu'),
('4x2', 'gpu'), ('8x1', 'gpu'), ('1x8'... | =20):
data_file = to_path(RESULTS, '%s.csv' % dataset)
data = []
sp = ''
orthogonal = ''
| g = ''
bl = ''
FRANK = k
if sparse == 'sparse':
sp = ' -s'
if balanced == 'imbalanced':
bl = ' -m'
if context == 'gpu':
g = ' -g'
if method == 'nmtf_ding':
orthogonal = ' -o'
tr = ''
if not transfer:
tr = ' --no-transfer'
... |
YoeriNijs/CERTDataConverter | Converter.py | Python | gpl-2.0 | 2,605 | 0.019962 | #!/usr/bin/env python
# CERT Mean Program
# By Yoeri Nijs
# Master Thesis Human Aspects of Information Technology
# Tilburg University
#
# Read txt files provided by CERT (Computer Expression Recognition Toolbox)
# Process numbers of specific Action Units for the mean
# Store all means in a csv file
# Import libs
imp... | # Count items in AU list
total = float(0)
for i in AU:
total = float(total) + float(i)
# Calculate mean of AU
averageAU = total/len(AU)
# Return the mean of AU
return averageAU
# Directory with all CERT output files in .txt
path = 'COMPLETE FILE PATH/*.txt'
fi | les = glob.glob(path)
# For every file in the directory, get the mean of the given Action Units
for file in files:
try:
# Open data file
data = list(csv.reader(open(file, 'rb'), delimiter='\t'))
# Process data file
with open('COMPLETE FILE PATH/output.csv', 'ab')... |
synasius/backyard | rust/embed/python/embed.py | Python | unlicense | 112 | 0.008929 | from ctypes import cdll
lib = cdll.LoadLibrary("../target/relea | se/libembed.so")
lib.process()
print("done!")
| |
belatrix/BackendAllStars | administrator/views.py | Python | apache-2.0 | 30,608 | 0.000327 | from activities.models import Message
from categories.models import Category, Keyword
from constance import config
from employees.models import Employee, Location, Position, Role
from events.models import Event, EventActivity
from stars.models import Badge
from django.conf import settings
from django.contrib.sites.mode... | one):
"""
List all categories
---
parameters:
| - name: pagination
required: false
type: string
paramType: query
"""
categories = get_list_or_404(Category)
if request.GET.get('pagination'):
pagination = request.GET.get('pagination')
if pagination == 'true':
paginator... |
lmazuel/azure-sdk-for-python | azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/environment_variable.py | Python | mit | 1,151 | 0 | # 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 ... | ame: The name of the environment variable.
:type name: str
:param value: The value of the environment variable.
:type value: str
"""
_validation = {
'name': {'required': True},
'value': {'required': True},
}
| _attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'value': {'key': 'value', 'type': 'str'},
}
def __init__(self, name, value):
super(EnvironmentVariable, self).__init__()
self.name = name
self.value = value
|
futurepr0n/Books-solutions | Python-For-Everyone-Horstmann/Chapter8-Sets-and-Dictionaries/R8.18_test.py | Python | mit | 976 | 0.005123 | # Unit test for R8.18
# IMPORTS
import R8_18
import unittest
# main
class Print_Dictionary_Tests(unittest.TestCase):
def setUp(self):
self.dummy_dictionary = {"A": 8, "D": 3, "B": 15, "F": 2, "C": 6}
def test_print_keys(self):
self.assertEqual("A\nB\nC\nD\nF", R8_18.print_keys(self.dummy_dic... | n8\n15", R8_18.print_values(self.dummy_dictionary))
def test_print_pairs_sorted(self):
self.assertEqual("('A', 8)\n('B', 15)\n('C', 6)\n('D', 3)\n('F', 2)", R8_18.print_pairs(self.dummy_diction | ary))
def test_print_average_value(self):
self.assertEqual((8+3+15+2+6)/5, R8_18.print_average_value(self.dummy_dictionary))
def test_print_bar_charts(self):
self.assertEqual("A: ********\nB: ***************\nC: ******\nD: ***\nF: **", R8_18.print_bar_charts(self.dummy_dictionary))
# PROGRAM... |
ubccr/supremm | src/supremm/plugins/ArmPowerUsageTimeseries.py | Python | lgpl-3.0 | 4,476 | 0.006032 | #!/usr/bin/env python
""" Timeseries generator module """
from collections import Counter
import numpy
from supremm.plugin import Plugin
from supremm.subsample import TimeseriesAccumulator
from supremm.errors import ProcessingError
class ArmPowerUsageTimeseries(Plugin):
""" Generate the Power usage as a timeseri... |
@staticmethod
def compute | timepoint(data):
""" Get the power usage from the data """
if data[0][0] < numpy.finfo(numpy.float64).eps:
return None
return data[0][0]
def process(self, nodemeta, timestamp, data, description):
if self._job.getdata('perf')['active'] != True:
self._error =... |
kishoredbn/barrelfish | tools/harness/tests/mem_appel.py | Python | mit | 4,185 | 0.004779 | import tests, debug
from common import TestCommon
from results import PassFailResult, RowResults
import sys, re, numpy, os, datetime
class AppelLiBench(TestCommon):
'''Benchmark GC primitives with Appel Li benchmark'''
bench_core = 4
def setup(self, build, machine, testdir):
# gracefully handle ... | LiBench):
name = "appel_li_bench_full"
def get_modules(self, build, machine):
modules = super(AppelLiFull, self).g | et_modules(build, machine)
modules.add_module("benchmarks/mem_appel_ff", ["core=%d" % self.bench_core])
return modules
@tests.add_test
class AppelLiFullDI(AppelLiBench):
name = "appel_li_bench_full_di"
def get_modules(self, build, machine):
modules = super(AppelLiFullDI, self).get_modu... |
flavour/tldrmp | modules/s3/s3import.py | Python | mit | 156,657 | 0.002087 | # -*- coding: utf-8 -*-
""" Resource Import Tools
@copyright: 2011-13 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
... | .file_uploaded = "Import file uplo | aded"
messages.upload_submit_btn = "Upload Data File"
messages.open_btn = "Open"
messages.view_btn = "View"
messages.delete_btn = "Delete"
messages.item_show_details = "Display Details"
messages.job_total_records = "Total records in the Import Job"
messages.job_re... |
dimagi/commcare-hq | corehq/apps/api/tests/test_auth.py | Python | bsd-3-clause | 19,030 | 0.003731 | import base64
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponse
from django.test import TestCase, RequestFactory
from corehq.apps.api.resources.auth import LoginAuthentication, LoginAndDomainAuthentication, \
RequirePermissionAuthentication
from corehq.apps.domain.models im... | ls.domain, 'permission', cls.password, None, None,
role_id=cl | s.role_with_permission.get_id)
cls.user_without_permission = WebUser.create(cls.domain, 'no-permission', cls.password, None, None,
role_id=cls.role_without_permission.get_id)
cls.user_with_permission_but_no_api_access = WebUser.create(
cls... |
mahmoodkhan/ranewal | htdocs/eproweb/settings/base.py | Python | gpl-3.0 | 5,611 | 0.001604 | """
Django settings for eproweb project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build path... | 'success',
message.WARNING: 'warning',
message.ERROR: 'danger',}
# Using the Cosgin Authentication backend first.
AUTHENTICATION_BACKENDS = (
| 'djangocosign.cosign.CosignBackend',
'django.contrib.auth.backends.ModelBackend',
)
# Email setup
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
# formatting options reference: https://docs.python.org/2/library/logging.html#formatter-objects
LOGGING = {
'version': 1,
'disable_existing_loggers': F... |
ZhaoCJ/django | django/contrib/admin/widgets.py | Python | bsd-3-clause | 13,529 | 0.003104 | """
Form Widget classes specific to the Django admin site.
"""
from __future__ import unicode_literals
import copy
from django import forms
from django.contrib.admin.templatetags.admin_static import static
from django.core.urlresolvers import reverse
from django.forms.widgets import RadioFieldRenderer
from django.for... | ate_with_clear)
def url_params_from_lookup_dict(lookups):
"""
Converts the type of lookups specified in a ForeignKey limit_choices_to
attribute to a dictionary of query pa | rameters
"""
params = {}
if lookups and hasattr(lookups, 'items'):
items = []
for k, v in lookups.items():
if callable(v):
v = v()
if isinstance(v, (tuple, list)):
v = ','.join(str(x) for x in v)
elif isinstance(v, bool):
... |
Eric-Gaudiello/tensorflow_dev | tensorflow_home/tensorflow_venv/lib/python3.4/site-packages/tensorflow/python/ops/seq2seq.py | Python | gpl-3.0 | 39,692 | 0.004283 | # Copyright 2015 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 required by applicable law or a... | basic_rnn_seq2seq".
Returns | :
outputs: A list of the same length as decoder_inputs of 2D Tensors with
shape [batch_size x cell.output_size] containing the generated outputs.
states: The state of each decoder cell in each time-step. This is a list
with length len(decoder_inputs) -- one item for each time-step.
Each item i... |
apostrophest/ingroup | database.py | Python | mit | 382 | 0.007853 | i | mport os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import prefs
db = SQLAlchemy()
def create_flask_app():
app = Flask(__name__, template_folder=os.path.join(prefs.Config.APPLICATION_ROOT, 'templates'), static_folder=os.path.join(prefs.Config.APPLICATION_ROOT, 'static'))
app.config.... | om_object(prefs.Config)
db.init_app(app)
return app |
googleapis/python-datalabeling | google/cloud/datalabeling_v1beta1/types/evaluation.py | Python | apache-2.0 | 12,885 | 0.001707 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | sion matrix of predicted labels vs.
ground truth labels.
"""
pr_curve = proto.Field(proto.MESSAGE, number=1, message="PrCurve",)
confusion_matrix = proto.Field(proto.MESSAGE, number=2, message="ConfusionMatrix",)
class ObjectDetectionMetrics(proto.Message):
r"""Metrics calculated for an i... | gle.cloud.datalabeling_v1beta1.types.PrCurve):
Precision-recall curve.
"""
pr_curve = proto.Field(proto.MESSAGE, number=1, message="PrCurve",)
class PrCurve(proto.Message):
r"""
Attributes:
annotation_spec (google.cloud.datalabeling_v1beta1.types.AnnotationSpec):
The ... |
openbermuda/karmapi | karmapi/apis/base.py | Python | gpl-3.0 | 1,577 | 0.001268 | """ Karmapi base web api
"""
from pathlib import Path
from io import BytesIO
import pandas
from karmapi import base
from flask import request, make_response
from flask_restplus import Namespace, Resource, fields
api = Namespace("base", description="Base karmapi api")
txt = """
hello world
hello universe
"""
@api... | ata at path')
def get(self, path):
""" Get object at path as text """
ppath = Path(path)
# see if path has a suffix
suffix = ppath.suffix
if ppath.exists():
df = base.load(ppath)
else:
df = base.load(ppath.parent / ppath.stem)
if suf... | t/csv"
elif suffix == '.json':
result = df.to_json(orient='records')
ctype = "application/json"
elif suffix == '.gif':
result = df
ctype = "image/gif"
elif suffix == '.png':
result = df
ctype = "image/png"
elif suffi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.