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 |
|---|---|---|---|---|---|---|---|---|
sandow-digital/django-mptt-sandow | tests/myapp/models.py | Python | mit | 2,252 | 0.003552 | from django.db import models
from mptt2.models import MPTTModel
from mptt2.managers import TreeManager
class CustomTreeManager(TreeManager):
pass
class Category(MPTTModel):
name = models.CharField(max_length=50)
parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
def... |
retur | n self.name
class Tree(MPTTModel):
parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
class Person(MPTTModel):
name = models.CharField(max_length=50)
parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
# just testing it's actually possi... |
sim1234/Versioning | py_versioning/db/__init__.py | Python | gpl-2.0 | 103 | 0.019417 | #from .engine import CheckVersion | , CreateVersion
from .ver | sioner import DBVersioner, DBVersionCommander |
xuewei4d/scikit-learn | sklearn/datasets/_covtype.py | Python | bsd-3-clause | 6,567 | 0 | """Forest covertype dataset.
A classic dataset for classification benchmarks, featuring categorical and
real-valued features.
The dataset page is available from UCI Machine Learning Repository
https://archive.ics.uci.edu/ml/datasets/Covertype
Courtesy of Jock A. Blackard and Colorado State University.
"""
# Au... | il_Type_{i}" for i in range(40)]
TARGET_NAMES = ["Cover_Type"]
@_deprecate_positional_args
def fetch_covtype(*, data_home | =None, download_if_missing=True,
random_state=None, shuffle=False, return_X_y=False,
as_frame=False):
"""Load the covertype dataset (classification).
Download it if necessary.
================= ============
Classes 7
Samples total ... |
ctu-yfsg/2015-a-grass-reclass | reclassify/Layout/ReclassifyPanel.py | Python | gpl-2.0 | 3,344 | 0.008373 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Subclass of wx.Panel"""
#-----------------------------------------------------------------------------------------
#Import
try:
#wxPython
import wx
import wx.grid
import wx.lib.scrolledpanel
#python std library
import sys
#our modules and pa... | CENTER)
self.tablePanel.SetSizer(box)
#-----------------------------------------------------------------------------------------
def __buildButtonPanel(self):
"""
Creates delete entry button and add | entry button.
:return: void
"""
self.buttonPanel = wx.Panel(self, wx.NewId())
self.addButton = wx.Button(self.buttonPanel, wx.NewId(), "Add", size=(100, -1))
self.deleteButton = wx.Button(self.buttonPanel, wx.NewId(), "Delete", size=(100, -1))
self.previewButton = wx.But... |
indigo-dc/im | test/loadtest/LoadTestRESTR.py | Python | gpl-3.0 | 5,151 | 0.000777 | #! /usr/bin/env python
#
# IM - Infrastructure Manager
# Copyright (C) 2011 - GRyCAP - Universitat Politecnica de Valencia
#
# 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 t... | e that it will be useful,
# but WITHOUT | ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from multiproce... |
sergpolly/FluUtils | FluDB_coding_aln/DEPRECEATED/cluster_msa_processing.py | Python | mit | 2,495 | 0.00521 | import re
import os
import sys
from Bio import Seq
from Bio import SeqIO
import pandas as pd
import itertools
import numpy as np
path = "/home/venevs/fludb_pH1N1"
# seg5-GenomicFastaResults.fasta
# seg7.afa
centroids = SeqIO.par | se(os.path.join(path,"nr.fasta"),"fasta")
clust_msa = SeqIO.parse(os.path.join(path,"seg1.afa"),"fasta")
# just check how centroids are aligned in the clust_msa:
# select centroids and find them in clust_msa -> extract their alignemnt ...
centroids = SeqIO.to_dict(centroids)
clust_msa = SeqIO.to_dict(clust_msa)
# ... | re present in clust_msa ...
all_match = all([(sid in clust_msa) for sid in centroids])
if not all_match:
raise ValueError("All ids from centroids must match ids in clust_msa ...")
# now extract aligned centroid sequences ...
centroids_aligned = [clust_msa[sid] for sid in centroids]
# output the alignment now ...
Se... |
mozilla/dragnet | dragnet/dll/forms.py | Python | bsd-3-clause | 534 | 0 | from django import forms
from dragnet.dll.models import File, Comment
class FileForm(forms.ModelForm):
"""Using a model form to expedite the crea | tion of DLL records"""
class Meta:
model = File
exclude = ('date_created', 'date_modified', 'created_by',
| 'modified_by', )
class CommentForm(forms.ModelForm):
"""Comment form for DLL comments"""
class Meta:
model = Comment
exclude = ('user', 'date', 'dll')
class SearchForm(forms.Form):
term = forms.CharField()
|
kedder/ofxstatement | src/ofxstatement/ui.py | Python | gpl-3.0 | 275 | 0 | import logging
log = logging. | getLogger(__name__)
class UI:
def status(self, message: str) -> None:
log.info(message)
def warning(self, message: str) -> None:
log.warn(message)
def error(self, message: str) -> None:
| log.error(message)
|
JanBerktold/redis-simpler-cache | redis_cache/rediscache.py | Python | bsd-3-clause | 11,363 | 0.032122 | """
A simple redis-cache interface for storing python objects.
"""
from functools import wraps
import pickle
import json
import hashlib
import redis
import logging
DEFAULT_EXPIRY = 60 * 60 * 24
class RedisConnect(object):
"""
A simple object to store and pass database connection information.
This makes the Simple... |
while self.connection.scard(set_name) >= self.limit:
del_key = self.connection.spop(set_name)
self.connection.delete(self.make_key(del_key))
pipe = self.connection.pipeline()
if expire is None:
expire = self.expire
if (isinstance(expire, int) and expire <= 0) or (expire is None):
pipe.set(self.ma... | ethod expires all keys in the namespace of this object.
At times there is a need to invalidate cache in bulk, because a
single change may result in all data returned by a decorated function
to be altered.
Method returns a tuple where first value is total number of keys in
the set of this object's namespace a... |
AHaymanDev/CS453DjangoProj | bookrental/views.py | Python | gpl-2.0 | 8,027 | 0.003114 | from django.shortcuts import render, render_to_response
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.views.generic import ListView
from bookrental.forms import UserCreateForm
from bookrental.models import Book
f... | out the user
logout(request)
# go back to the login page
return render(request, 'bookrental/Login.html')
# Register a new user with a custom form, log them in, and redirect to the Warning page.
def new_user(request):
if request.method == 'POST':
# when they hit submit, check if their form is c... | d2()
user_form.save()
user = authenticate(username=username1, password=password)
login(request, user)
# update current session
request.session['username'] = username1
return HttpResponseRedirect(reverse('warning'))
user_form = UserCreateForm(... |
kbluck/pytws | tws/_Execution.py | Python | bsd-3-clause | 1,064 | 0.006579 | '''Execution data structure.'''
__copyright__ = "Copyright (c) | 2008 Kevin J Bluck"
__version__ = "$Id$"
class Execution(object):
'''Data structure to describe a trade execution.
'''
def __init__(self, order_id=0, client_id=0, exec_id="", time="", acct_number="", exchange="", side="",
shares=0, price=0.0, perm_id=0, liquidation=0, cum_qty=0,... | self.m_orderId = order_id
self.m_clientId = client_id
self.m_execId = exec_id
self.m_time = time
self.m_acctNumber = acct_number
self.m_exchange = exchange
self.m_side = side
self.m_shares = shares
self.m_price = price
self.m_permId = perm_id
... |
kkuunnddaannkk/vispy | vispy/visuals/mesh.py | Python | bsd-3-clause | 12,882 | 0 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2015, Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -------------------------------------------------------------------------... | v_light_color;
varying vec4 v_base_color;
void main() {
//DIFFUSE
float diffusek = dot(v_light_vec, v_normal_vec);
//clamp, because 0 < theta < pi/2
diffusek = clamp(diffusek, 0, 1);
vec4 diffuse_color = v_light_color * diffusek;
//diffuse_color.a = 1.0;
//SPECULAR
//reflect light ... | _light_vec, v_normal_vec), v_eye_vec);
speculark = clamp(speculark, 0, 1);
//raise to the material's shininess, multiply with a
//small factor for spread
speculark = 20 * pow(speculark, 200.0);
vec4 specular_color = v_light_color * speculark;
gl_FragColor =
v_base_color * (v_ambientk +... |
yunshichen/dblog | src/dblog/handler/urls.py | Python | apache-2.0 | 2,005 | 0 | #! /usr/bin/python
# -*- coding: UTF-8 -*-
from dblog.handler import index_handler
from dblog.handler import cat_handler
from dblog.handler import back_article_handler
from dblog.handler import ckeditor_handler
from dblog.handler import front_handler
urls = [
# -------- 博客首页
(r"/", front_handler.FrontIndex),
... | x", index_handler.Index),
| (r"/admin/ajax/login", index_handler.LoginAjax),
(r"/admin/logout", index_handler.Logout),
# -------- 分类
(r"/admin/cat/index", cat_handler.Index),
(r"/admin/ajax/cat/save", cat_handler.Save),
(r"/admin/ajax/cat/page", cat_handler.Page),
(r"/admin/ajax/cat/get", cat_handler.Get),
(r"/admin/... |
mancoast/CPythonPyc_test | fail/312_test_fractions.py | Python | gpl-3.0 | 22,695 | 0.000485 | """Tests for Lib/fractions.py."""
from decimal import Decimal
from test.support import run_unittest
import math
import numbers
import operator
import fractions
import unittest
from copy import copy, deepcopy
from pickle import dumps, loads
F = fractions.Fraction
gcd = fractions.gcd
class DummyFloat(object):
"""Du... | """Asserts that callable(*args, **kwargs) raises exc_type(message)."""
try:
callable(*args, **kwargs)
except exc_type as e:
self.assertEquals(message, str(e))
el | se:
self.fail("%s not raised" % exc_type.__name__)
def testInit(self):
self.assertEquals((0, 1), _components(F()))
self.assertEquals((7, 1), _components(F(7)))
self.assertEquals((7, 3), _components(F(F(7, 3))))
self.assertEquals((-1, 1), _components(F(-1, 1)))
s... |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/scripts/populate-distroseriesdiff.py | Python | agpl-3.0 | 394 | 0 | #!/usr/bin/python -S
#
# Copyright 2011 Canonic | al Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
__metaclass__ = type
import _pythonpath
from lp.registry.scripts.populate_distroseriesdiff import (
Popu | lateDistroSeriesDiff,
)
if __name__ == '__main__':
PopulateDistroSeriesDiff('populate-distroseriesdiff').run()
|
tuzzer/ai-gym | atari_breakout/atari_breakout_dqn_cntk.py | Python | mit | 11,222 | 0.003386 | import random
import numpy as np
import math
from time import perf_counter
import os
import sys
from collections import deque
import gym
import cntk
from cntk.layers import Convolution, MaxPooling, Dense
from cntk.models import Sequential, LayerStack
from cntk.initializer import glorot_normal
env = gym.make("Break... | lers = deque(maxlen=capacity)
self.capacity = capacity
def add(self, sample):
self.examplers.append(sample)
def get_random_samples(self, num_samples):
num_samples = min(num_samples, len(self.exa | mplers))
return random.sample(tuple(self.examplers), num_samples)
def get_stack(self, start_index, stack_size):
end_index = len(self.examplers) - stack_size
if end_index < 0:
stack = list(self.examplers) + [self.examplers[-1] for _ in range(-end_index)]
else:
... |
jeremiahyan/lammps | examples/SPIN/test_problems/validation_damped_exchange/plot_precession.py | Python | gpl-2.0 | 1,111 | 0.023402 | #!/usr/bin/env python3
import numpy as np, pylab, tkinter
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from decimal import *
import sys, string, os
argv = sys.argv
if len(argv) != 3:
print("Syntax: ./plot_precession.py res_lammps.dat res_llg.dat")
sys.exit( | )
lammps_file = sys.argv[1]
llg_file = sys.argv[2]
t_lmp,Sx_lmp,Sy_lmp,Sz_lmp,e_lmp = np.loadtxt(lammps_file,skiprows=0, usecols=(1,2,3,4,7),unpack=True)
t_llg,Sx_llg,Sy_llg,Sz_llg,e_llg = np.loadtxt(llg_file,skiprows=0, usecols=(0,1,2,3,4),unpack=True)
plt.figure()
plt.subplot(411)
plt.ylabel('Sx')
plt.plot(t_ | lmp, Sx_lmp, 'b-', label='LAMMPS')
plt.plot(t_llg, Sx_llg, 'r--', label='LLG')
plt.subplot(412)
plt.ylabel('Sy')
plt.plot(t_lmp, Sy_lmp, 'b-', label='LAMMPS')
plt.plot(t_llg, Sy_llg, 'r--', label='LLG')
plt.subplot(413)
plt.ylabel('Sz')
plt.plot(t_lmp, Sz_lmp, 'b-', label='LAMMPS')
plt.plot(t_llg, Sz_llg, 'r--', labe... |
bluetiki/pylab | telnet2.py | Python | bsd-2-clause | 657 | 0.009132 | #!/usr/bin/env python
import telnetlib
import time
def main():
ip = '50.76.53.27'
port = 23
timeout = 3
user = 'pyclass'
passwd = '88newclass'
conn = telnetlib.Telnet(ip, port, timeout)
conn.read_until("sername:", timeout)
conn.write(user + '\n')
conn.read_until("assword:", ... | time.sleep(1)
out | = conn.read_very_eager()
print out
conn.close()
if __name__ == "__main__":
main()
|
vmturbo/nova | nova/tests/unit/test_service.py | Python | apache-2.0 | 14,578 | 0.00048 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... | ock_create.assert_called_once_with()
def test_service_check_create_race_topic_exists(self):
ex = exception.ServiceTopicExists(host='foo', topic='bar')
self._test_service_check_create_ | race(ex)
def test_service_check_create_race_binary_exists(self):
ex = exception.ServiceBinaryExists(host='foo', binary='bar')
self._test_service_check_create_race(ex)
@mock.patch.object(objects.Service, 'create')
@mock.patch.object(objects.Service, 'get_by_host_and_binary')
@mock.patch... |
larsks/cloud-init | tests/unittests/test_vmware/test_guestcust_util.py | Python | gpl-3.0 | 2,910 | 0 | # Copyright (C) 2019 Canonical Ltd.
# Copyright (C) 2019 VMware INC.
#
# Author: Xiaofeng Wang <xiaofengw@vmware.com>
#
# This file is part of cloud-init. See LICENSE file for license information.
from cloudinit import util
from cloudinit.sources.helpers.vmware.imc.guestcust_util import (
get_tools_config,
)
from ... | get_tools_config('section', 'key', 'defaultVal'), 'defaultVal')
def test_get_tools_config_internal_exception(self):
"""
This test is designed to verify the behavior if internal exception
is raised.
"""
with mock.patch.object(util, 'which', return_value='/dummy/p | ath'):
with mock.patch.object(util, 'subp',
return_value=('key=value', b''),
side_effect=util.ProcessExecutionError(
"subp failed", exit_code=99)):
# verify return value is 'defaultVa... |
mrachinskiy/jewelcraft | op_gem_map/draw_handler.py | Python | gpl-3.0 | 1,672 | 0 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# JewelCraft jewelry design toolkit for Blender.
# Copyright (C) 2015-2022 Mikhail Rachinskiy
#
# 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, eith... | height = self.region.height
x = self.view_padding_left
y = self.view_padding_top
# Gem map
# -----------------------------
if not self.use_navigate:
gpu.state.blend_set("ALPHA")
draw_texture_2d(self.offscreen.texture_color, (0, 0), widt | h, height)
# Onscreen text
# -----------------------------
y = onscreen_text.onscreen_gem_table(self, x, y)
y -= self.view_margin
if self.show_warn:
y = onscreen_text.onscreen_warning(self, x, y)
y -= self.view_margin
view3d_lib.options_display(self, context, x, y)
# Res... |
hgl888/chromium-crosswalk | infra/scripts/legacy/scripts/common/env.py | Python | bsd-3-clause | 12,777 | 0.009783 | #!/usr/bin/env python
# Copyright 2015 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.
"""Implements a standard mechanism for Chrome Infra Python environment setup.
This library provides a central location to define Chrom... |
Within a cooperating script, the environment can be setup by importing this
module and running its 'Install' method:
# Install Chrome-Infra environment (replaces 'sys.path').
sys.path.insert(0,
os.path.join(os.path.dirname(__file__), os.pardir, ...))
# (/path/to/build/scripts)
import common.env
c... | valid
PYTHONPATH clause.
In addition, this module has several functions to construct the path.
The goal is to deploy this module universally among Chrome-Infra scripts,
BuildBot configurations, tool invocations, and tests to ensure that they all
execute with the same centrally-defined environment.
"""
import argpar... |
DiogoDantas/tourgastronomico | projetoIA/urls.py | Python | mit | 172 | 0 | from django.conf.urls im | port include, url
from django.contrib import adm | in
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('agenteIA.urls'))
]
|
folivetti/PI-UFABC | AULA_02/Python/PedraPapelTesoura.py | Python | mit | 690 | 0.010145 | # -*- coding: cp1252 -*-
'''
PedraPapelTesoura.py
* Dada duas entradas nos valores 0 (pedra), 1 (papel) ou 2 (tesoura),
* verificar quem ganho o jogo.
* Entrada: jogador1, jogador2 (int)
* Saída: jogador1 ganhou, jogador2 ganhou, empate
Autor: Fabrício Olivetti de França
Disciplina Processamento da Informação
Un... | ogador2 = int( raw_input("Pedra (0), Papel (1) ou Tes | oura (2)? ") )
if jogador1 > jogador2 or jogador1==0 and jogador2 == 2:
print "Jogador 1 venceu"
elif jogador2 > jogador1 or jogador1==2 and jogador2 == 0:
print "Jogador 2 venceu"
else:
print "Empate"
|
yyamnk/cec2013single | setup.py | Python | gpl-3.0 | 1,178 | 0.013582 | from setuptools import setup, find_packages, Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize
# for unix
cec2013single = Extension("cec2013single.cec2013",
["cec2013single/cec2013.pyx", "cec2013single/cec2013_func.c"],
libraries=["m"]) # Unix-like specific... | cec2013single',
version='0.1',
author='Daniel Molina',
author_email='daniel.molina@uca.es',
description='Package for benchmark for the Real Single Objective Optimization session on IEEE Congress on Evolutionary Computation CEC\'2013',
long_description=open('README.rst').read(),
... | 3',
packages=['cec2013single'],
install_requires=['cython', 'numpy'],
ext_modules=cythonize(cec2013single),
# ext_modules=cythonize('benchmarks.pyx', annotated=True),
cmdclass={'build_ext': build_ext},
# Packaging options.
#include_package_data = True,
# Tests
#tests_require=['pytest... |
glensc/osquery-python | tests/test_config_plugin.py | Python | bsd-3-clause | 1,735 | 0.002882 | """This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import... | ExtensionManager()
ext_manager.add_plugin(MockConfigP | lugin)
response = ext_manager.call("config",
"foobar",
{"action":"genConfig"})
self.assertEqual(0, response.status.code)
self.assertTrue(len(response.response) > 0)
self.assertTrue("source_1" in response.response[0])... |
umitproject/umpa | umit/umpa/utils/net.py | Python | lgpl-2.1 | 2,096 | 0.006679 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2009 Adriano Monteiro Marques.
#
# Author: Bartosz SKOWRON <getxsick at gmail dot com>
#
# This library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free S... |
argument. If the result is 0, then the ckecksum has not detected an error.
@type data: C{int}
@param data: the data from which checksum is calculated.
@type cksum: C{int}
@param cksum: already calculated checksum for comparision (default: 0)
@rtype: C{int}
@return: calculated checksum.
... | i] << 8) & 0xff00) + (pieces[i+1] & 0xff)
cksum += xxx
while cksum >> 16:
cksum = (cksum & 0xffff) + (cksum >> 16)
cksum = ~cksum
return int(cksum & 0xffff)
def parse_ipv4(ip):
"""
Return 4 numbers of an IPv4
192.168.1.2 -> [192, 168, 1, 2]
@type ip: C{str}
@para... |
zeroonegit/python | runoob/basic_tutorial/template.py | Python | mit | 64 | 0.015625 | #!/usr/bin/e | nv python3
# -*- coding: utf-8 -*-
# Filen | ame: .py
|
wuan/bo-python | blitzortung/dataimport/__init__.py | Python | apache-2.0 | 571 | 0.001751 | from .base import FileTransport, HttpFileTransport, Blitzort | ungDataPath, BlitzortungDataPathGenerator
from .raw_signal import RawSignalsBlitzortungDataProvider
from .station import StationsBlitzortungDataProvider
from .strike import StrikesBlitzortungDataProvider
def strikes(): |
from .. import INJECTOR
return INJECTOR.get(StrikesBlitzortungDataProvider)
def stations():
from .. import INJECTOR
return INJECTOR.get(StationsBlitzortungDataProvider)
def raw():
from .. import INJECTOR
return INJECTOR.get(RawSignalsBlitzortungDataProvider)
|
VanushVaswani/amcparser | tests/test_motion.py | Python | mpl-2.0 | 702 | 0 | from . import skeleton_path, m_walking_path
from numpy.testing import assert_allclose
from amcparser import Skeleton, SkelMotion
def test_motion_root():
sk = Skeleton(skeleton_path)
skm = | SkelMotion(sk, m_walking_path, (1.0 / 120.0))
skm.traverse('root', 0, 10)
root_pos = sk.root.xyz_data
assert_allclose(root_pos[0, :], map(float, skm.data['root'][0][0:3]))
assert_allclose(root_pos[9, :], map(float, skm.data['root'][9][0:3]))
def test_motion_bone():
sk = Skeleton(skeleton_path)
... | bone_pos.shape[0] == 1741
|
mdurrant-b3/acos-client | setup.py | Python | apache-2.0 | 1,390 | 0.017266 | #!/usr/bin/env python
# flake8: noqa
from setuptools import find_packages, setup
setup(
na | me = "acos-client",
version = "1.4.6",
packages = find_packages(),
author = "A10 Networks",
author_email = "mdurrant@a10networks.com",
description = "A10 Networks ACOS API Client",
license = "Apache",
| keywords = "a10 axapi acos adc slb load balancer",
url = "https://github.com/a10networks/acos-client",
long_description = open('README.md').read(),
classifiers = [
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS ::... |
mjcollin/idigphylo | api/api_stub.py | Python | mit | 5,084 | 0.004917 | from __future__ import absolute_import
import sys
sys.path.append("../lib")
sys.path.append("../workers")
from database import Database, Sequence
from tree.tree import build
from align.align import msa
from align.align import pipeline
import idigbio
opts = {}
opts["data_file"] = "data.nex"
#raw_seqs = {}
#raw_seqs... | ACAATATCATGCCCCCTTTCACCCGAGAAAATACATTAATAATCATACACCTATTTCCCTTAATCCTACTATCTACCAACCCCAAAGTAATTATAGGAACCATGTACTGTAAATATAGTTTAAACAAAACATTAGATTGTGAGTCTAATAATAGAAGCCCAAAGATTTCTTATTTACCAAGAAAGTA-TGCAAGAACTGCTAACTCATGCCTCCATATATAACAATGTGGCTTTCTT-ACTTTTAAAGGATAGAAGTAATCCATCGGTCTTAGGAACCGAAAA-ATTGGTGCAACTCCAAATAAAAGTAATAAATTTATT... | CACTCTTAATTACCCCATTTATTATTACAACAACTAAAAAATATGAAACACATGCATACCCTTACTACGTAAAAAACTCTATCGCCTGCGCATTTATAACAAGCCTAGTCCCAATGCTCATATTTCTATACACAAATCAAGAAATAATCATTTCCAACTGACATTGAATAACGATTCATACTATCAAATTATGCCTAAGCTT"
#raw_seqs["Lemur_catta"] = "AAGCTTCATAGGAGCAACCATTCTAATAATCGCACATGGCCTTACATCATCCATATTATTCTGTCTAGCCAACTCTAACTACGAACGA... |
yanyao/openstack-ansible | doc/source/conf.py | Python | apache-2.0 | 12,061 | 0.000497 | #!/usr/bin/env python3
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software... | idebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this d... | that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_f... |
freeitaly/Trading-System | vn.trader/ctaAlgo/ctaSetting.py | Python | mit | 614 | 0.002381 | # encoding: UTF-8
'''
在本文件中引入所有希望在系统中使用的策略类
|
这个字典中保存了需要运行的策略的名称和策略类的映射关系,
用户的策略类写好后,先在该文件中引入,并设置好名称,然后
在CTA_setting.json中写入具体每个策略对象的类和合约设置。
'''
from ctaDemo import DoubleEmaDemo
from strategyTickBreaker import TickBreaker
from strategyRock import | RockStrategy
STRATEGY_CLASS = {}
STRATEGY_CLASS['TickBreaker'] = TickBreaker
STRATEGY_CLASS['DoubleEmaDemo'] = DoubleEmaDemo
STRATEGY_CLASS['RockStrategy'] = RockStrategy |
kczapla/pylint | pylint/checkers/newstyle.py | Python | gpl-2.0 | 5,166 | 0.001161 | # Copyright (c) 2006, 2008-2011, 2013-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
# Copyright (c) 2012-2014 Google, Inc.
# Copyright (c) 2013-2018 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2014 Michal Nowikowski <godfryd@gmail.com>
# Copyright (c) 2014 Brett Cannon <brett@python.org>
# Copyright (... | for stmt in node.nodes_of_class(astroid.Call):
if node_frame_class(stmt) != node_frame_class(node):
# Don't look down in other scopes.
continue
expr = stmt.func
if not isinstance(expr, astroid.Attribute):
continue
call = e... | and call.func.name == "super"
):
continue
if not klass.newstyle and has_known_bases(klass):
# super should not be used on an old style class
continue
else:
# super first arg should be the class
... |
CLVsol/clvsol_odoo_addons | clv_family_aux/wizard/__init__.py | Python | agpl-3.0 | 281 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
# License AGPL-3.0 or later ( | http://www.gnu.org/licenses/agpl).
from . import family_aux_mass_edit
from . import family_associate_to_family_aux |
from . import family_aux_associate_to_address_aux
|
eth-cscs/production | spack/reframe/src/spack_util/spacklib.py | Python | gpl-3.0 | 10,153 | 0.002068 | import copy
import re
import semver
import glob
import os
import re
def parse_version(version_str):
intel_version_style = re.search(r'^(\d+)\.(\d+)\.(\d+)\.(\d+)$', version_str)
major_minor_style = re.search(r'^(\d+)\.(\d+)$', version_str)
if intel_version_style:
major = intel_version_style.group(... | odulerc_file) as f:
lines = f.read()
matches = reg.findall(lines)
if matches:
return matches[0]
raise ValueError(f'cannot get module version for {package_name}')
def get_spack_generated_compilers(compiler_type, spack_compilers):
ret = {}
if not 'compilers' in spack_comp... | com = compiler['compiler']
if not 'spec' in com:
continue
spec = com['spec']
if compiler_type in spec:
version = spec.split('@')[1]
# excluding the duplicate entries that have empty modules
# this happens with the cray supported compiler... |
mccxj/leetcode | projecteuler/p0039_test.py | Python | apache-2.0 | 483 | 0.00207 | import unittest
class Test0039(unittest.TestCase):
def test_prob | lem(self):
m, num = 0, 0
for p in range(12, 1001):
total = 0
for a in range(1, p / 3 + 1):
for b in range(a + 1, (p - a) / 2 + 1):
c = p - a - b
if a * a + b * b == c * c:
total += 1
if m ... | m, 840) |
ixc/glamkit-blogtools | blogtools/models.py | Python | bsd-3-clause | 3,335 | 0.004198 | import datetime
from django.conf import settings
from django.db import models
from django.template.defaultfilters import slugify
from django.utils import timezone
from blogtools.utils.embargo import EmbargoedContent, EmbargoedContentPublicManager, EmbargoedContentPrivateManager
#TODO, put this in glamkit somewhere.
... | ef get_absolute_url(self):
# NB that URLs need exactly 2-digit months and dates, so use strftime.
return ('%s:detail' % (self.url_namespace or self._meta.app_label),
[self.byline_date.year, self.slug,]
)
def save(self, *args, **kwargs):
| if not self.slug:
self.slug = slugify(self.title)
# Append the pk to slugs which have a collision with a pre-existing slug.
if type(self).objects.filter(slug=self.slug).exclude(pk=self.pk).exists():
self.slug = '%s-%s' % (self.slug, slugify(self.pk))
super(EntryModel, sel... |
hdinsight/hue | apps/beeswax/src/beeswax/api.py | Python | apache-2.0 | 26,505 | 0.012752 | #!/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... | _form = parameterization_form_cls(prefix="parameterization")
response['parameters'] = [{'parameter': field.html_name, 'name': field.name} for field in parameterization_form]
response['status']= 0
else:
response['parameters'] = []
response['status']= 0
return JsonResponse(response)
@error_handler... | quest, design.id)
parameters = kwargs.pop('parameters', None)
db = dbms.get(request.user, query_server)
database = query.query.get('database', 'default')
db.use(database)
history_obj = db.execute_query(query, design)
watch_url = reverse(get_app_name(request) + ':api_watch_query_refresh_json', kwargs={'id'... |
naBe-/ants_visualization | board.py | Python | gpl-2.0 | 2,771 | 0.000361 | """
Gameboard representation
"""
import pygame
from ant import Ant
from tile import Tile, TILE_SIZE
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
YELLOW = (255, 255, 0)
BROWN = (102, 51, 0)
class Board(object):
def __init__(self, width, height, colony, food):
self.width = width
s... | self.screen = pygame.display.set_mode(screen_size)
self.screen.fill(WHITE)
self.tiles = []
self.ants = {}
# Populate grid
for w in range(0, width):
for h in range(0, height):
square = Tile(w*TILE_SIZE, h*TILE_SIZE)
self.tiles.append(... | or = square.render()
pygame.draw.rect(self.screen, color, rect)
# Place colony
pygame.draw.rect(self.screen, GREEN, self.colony)
# Place food
food_pos = food['position']
pile = [[food_pos[0]*TILE_SIZE+TILE_SIZE/2, food_pos[1]*TILE_SIZE],
[food_pos[... |
KaroDievas/car-sound-classification-with-keras | Main.py | Python | mit | 88 | 0.011364 | from M | odels import DataModel
dataModel = DataModel.DataModel()
dataModel.prepare | _data() |
OmeGak/indico | indico/modules/users/controllers.py | Python | mit | 29,032 | 0.003169 | # This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from collections import namedtuple
from io import BytesIO
from op... | .orm.exc import StaleDataError
from webargs import validate
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from indico.core import signals
from indico.core. | auth import multipass
from indico.core.db import db
from indico.core.db.sqlalchemy.util.queries import get_n_matching
from indico.core.marshmallow import mm
from indico.core.notifications import make_email, send_email
from indico.legacy.common.cache import GenericCache
from indico.modules.admin import RHAdminBase
from ... |
franek/weboob | modules/parolesmania/backend.py | Python | agpl-3.0 | 1,772 | 0.000564 | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Julien Veyssier
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the Li | cense, or
# (at your option) any later version.
#
# weboob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied w | arranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
from weboob.capabilities.lyrics import ICapLyrics... |
rwl/traitsbackendpyjamas | enthought/traits/ui/pyjd/__init__.py | Python | mit | 1,896 | 0.002637 | #------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# Copyright (c) 2009, Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# d... | --------------------------------
""" Defines the concrete implementations of the traits T | oolkit interface for
the Pyjamas web application user interface.
"""
__import__('pkg_resources').declare_namespace(__name__)
#------------------------------------------------------------------------------
# Define the reference to the exported GUIToolkit object:
#-------------------------------------------------... |
svdgraaf/appie | appie/api.py | Python | gpl-2.0 | 1,743 | 0.001721 | import requests
class Api(object):
_username = ''
_password = ''
_cookies = {}
_logged_in = False
_shoppinglist = 0
_list = None
def __init__(self, username, password, login=True):
self._username = username
self._password = password
self.login(username, password)... | url = 'http://www.ah.nl/service/rest/shoppinglists/0/'
response = requests.get(url, cookies=self._cookies, json=payload)
self._list = response.json()
return self._list
@property
def list(self):
return self._list
def is_o | n_list(self, product_id):
if self._list:
self._update_list()
counter = 0
for item in self._list['items']['_embedded']['items']:
if item['item']['id'] == product_id:
return item['id']
# @TODO: return proper exception?
return None
|
gpalsingh/dspbooksspider | dspbooks/pipelines.py | Python | mit | 1,349 | 0.003706 | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import scrapy
import os
from scrapy.pipelines.files import FilesPipeline
from urllib import unquote, quote
class DspbooksPipe... | l as first argument
if not isinstance(request, scrapy.Request):
_warn()
url = request
else:
url = request.url
# detect if file_key() method has been overridden
if not hasattr(self.file_key, '_base'):
_warn()
return self.file_ke... | |
googleads/google-ads-python | google/ads/googleads/v9/services/services/feed_placeholder_view_service/client.py | Python | apache-2.0 | 19,093 | 0.001257 | # -*- coding: utf-8 -*-
# Copyright 2020 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... | s requested, return that one.
if label:
return cls._transport_registry[label]
# No transport | is requested; return the default (that is, the first one
# in the dictionary).
return next(iter(cls._transport_registry.values()))
class FeedPlaceholderViewServiceClient(
metaclass=FeedPlaceholderViewServiceClientMeta
):
"""Service to fetch feed placeholder views."""
@staticmethod
def... |
vgrem/SharePointOnline-REST-Python-Client | office365/sharepoint/helpers/querystring_builder.py | Python | mit | 1,822 | 0.001647 | import logging
from office365.sharepoint.helpers.utils import to_camel
logger = logging.getLogger(__name__)
class QueryStringBuilder:
"""class to map web-querystring dictionary to sharepoint-querystring"""
date_operators = ['ge', 'gt', 'le', 'lt']
mapping_operator = {
'gte': 'ge',
'gt': ... | ing_operator.get(querystring_operator, 'eq')
# filter
filter_name = to_camel(filter_name.split('__')[0])
if operator in self.date_operators:
values = ["{}T00:00:00Z".format(filter_value)] # 2016-03-26
query = ' or '.join([f"{filter_name} {operator} da... | if operator == 'substringof':
values = filter_value.split(',')
query = ' or '.join([f"{operator}('{value}', {filter_name})" for value in values])
else:
values = filter_value.split(',')
query = ' or '.join([f"{filter_name} {operator} '{value}'"... |
Tchanders/socorro | socorro/unittest/collector/test_wsgi_breakpad_collector.py | Python | mpl-2.0 | 17,334 | 0.001154 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import hashlib
import StringIO
import gzip
import web
import mock
from nose.tools import eq_, ok_
from datetime import ... | .ProductName = 'FireSquid'
rawform.Version = '99'
| rawform.dump = DotDict({'value': 'fake dump', 'file': 'faked file'})
rawform.aux_dump = DotDict({'value': 'aux_dump contents', 'file': 'silliness'})
rawform.some_field = '23'
rawform.some_other_field = ObjectWithValue('XYZ')
rawform.uuid = '332d798f-3cx\x0042-47a5-843f-a0f892140107'
... |
pkimber/login | example_login/base.py | Python | apache-2.0 | 6,137 | 0.000815 | # -*- encoding: utf-8 -*-
"""
Django settings for login project.
"""
from django.core.urlresolvers import reverse_lazy
DEBUG = True
TESTING = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
# We use the 'SITE_NAME' for the name of the database and the name of the
# cloud files container.
SITE_NAME = '... | rent locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_RO | OT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your... |
sdpython/ensae_teaching_cs | _unittests/ut_td_1a/test_classique_permutation.py | Python | mit | 794 | 0.001259 | """
@brief test log(time=1s)
"""
import unittest
import itertools
from ensae_teaching_cs.td_1a.construction_classique import enumerate_permutations_recursive, enumerate_permutations
class TestClassiquesPermutation(unittest.TestCase):
def test_permutation(self):
self.maxDiff = None
ens = list... | s_rec | ursive(ens))
self.assertEqual(len(lt), 120)
res = list(tuple(p) for p in itertools.permutations(ens))
self.assertEqual(len(res), 120)
self.assertEqual(set(res), set(lt))
res = list(tuple(p) for p in enumerate_permutations(ens))
self.assertEqual(len(res), 120)
self... |
datafiniti/Diamond | src/collectors/nfs/nfs.py | Python | mit | 8,613 | 0 | # coding=utf-8
"""
The NfsCollector collects nfs utilization metrics using /proc/net/rpc/nfs.
#### Dependencies
* /proc/net/rpc/nfs
"""
import diamond.collector
import os
class NfsCollector(diamond.collector.Collector):
PROC = '/proc/net/rpc/nfs'
def get_default_config_help(self):
config_help ... |
results['v4.ds_write'] = line[48]
except IndexError:
pass
try:
results['v4.ds | _commit'] = line[49]
except IndexError:
pass
try:
results['v4.getdevlist'] = line[50]
|
rth/PyAbel | examples/example_all_O2.py | Python | mit | 4,354 | 0.005282 | # -*- coding: utf-8 -*-
# This example compares the available inverse Abel transform methods
# currently - direct, hansenlaw, and basex
# processing the O2- photoelectron velocity-map image
#
# Note it transforms only the Q0 (top-right) quadrant
# using the fundamental transform code
from __future__ import absolute_... | bright pixels
mask = np.zeros(Q0.shape, dtype=bool)
mask[500:512, 358:365] = True
# process Q0 quadrant using each method --------------------
iabelQ = [] # keep inverse Abel transformed image
sp = [] # speed distributions
meth = [] # methods
for q, method in enumerate(transforms.keys()):
Q0 = Q0fresh.co... | hod'
IAQ0 = transforms[method](Q0, direction="inverse", dr=0.1)
print (" {:.1f} sec".format(time()-t0))
# polar projection and speed profile
radial, speed = abel.tools.vmi.angular_integration(IAQ0, origin=(0, 0),
dr=0.1)
#... |
teamCarel/EyeTracker | setup.py | Python | lgpl-3.0 | 1,584 | 0.015152 | import sys,os
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
shared_modules_base=os.path.join(os.path.abspath(__file__).rsplit(__file__, 1)[0], 'src', 'shared_modules')
capture_base=os.path.join(os.path.abspath(__file__).rsplit(__file__, 1)[0], 'src', ... | les_base, 'video_capture'))
sys.path.append(os.path.join(eyetracker_base,''))
sys.path.append(os.path.join(eyetracker_base, 'GUI'))
sys.path.append(os.path.join(capture_base,''))
sys.path.append(os.path.join(capture_base, 'pupil_detectors'))
build_exe_options = {"packages": ["os", "multiprocessing", "glfw", "OpenGL",... | cations require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup( name = "eyetracker",
version = "0.1",
description ="Application for eyetracking.",
options = {"build_exe": build_exe_options},
... |
drawquest/drawquest-web | website/canvas/tests/test_views.py | Python | bsd-3-clause | 6,390 | 0.001878 | import copy
import logging
import random
import urllib
from django.contrib.sessions.backends.cache import SessionStore
from django.contrib.sessions.models import Session
from django.core.urlresolvers import reverse
from django.http import Http404
import facebook
from apps.canvas_auth.models import User, AnonymousUser... | sp = self.get('/unsubscribe?' + urllib.urlencode({
'token': util.token(user.email),
'email': user.email,
}))
self.assertNumCssMatches(0, resp, 'input[name="user_id"]')
def test_unsubscribe_pa | ge_with_user_id(self):
user = create_user()
resp = self.get('/unsubscribe?' + urllib.urlencode({
'token': util.token(user.email),
'email': user.email,
'user_id': user.id,
}))
selector = 'input[name="user_id"]'
self.assertNumCssMatches(1, resp, ... |
svenstaro/uni-projekt | hardware/registerbank.py | Python | gpl-3.0 | 674 | 0.008902 | from myhdl import *
def registerbank(clk, reset, we, addrx, addry, addrz, xout, yout, zin, amount = 16, bitwidth = 32, protect0=True):
reg_da | ta = [Signal(intbv(0)[bitwidth:]) for _ in range(amount)]
@always_seq(clk.posedge, reset=reset)
def write():
assert addrx < amount
assert addry < amount
assert addrz < amount
if we and not(protect0 and addrz == 0):
reg_data[addrz].next = zin[bitwidth:]
@always_... | assert addry < amount
assert addry < amount
xout.next = reg_data[addrx]
yout.next = reg_data[addry]
return write, read
|
kevinhikali/ml_kevin | backup/unet/layers.py | Python | gpl-3.0 | 2,726 | 0.013206 | # tf_unet 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.
#
# tf_unet is distributed in the hope that it will be useful,
# but WITHOUT... | , W,stride):
x_shape = tf.shape(x)
output_shape = tf.stack([x_shape[0], x_shape[1]*2, x_shape[2]*2, x_shape[3]//2])
return tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='VAL | ID')
def max_pool(x,n):
return tf.nn.max_pool(x, ksize=[1, n, n, 1], strides=[1, n, n, 1], padding='VALID')
def crop_and_concat(x1,x2):
x1_shape = tf.shape(x1)
x2_shape = tf.shape(x2)
# offsets for the top left corner of the crop
offsets = [0, (x1_shape[1] - x2_shape[1]) // 2, (x1_shape[2] - x2_sh... |
Ouranosinc/Magpie | magpie/alembic/versions/2021-04-19_00c617174e54_unique_user_emails.py | Python | apache-2.0 | 450 | 0 | """
Unique user emails.
Revision ID: 00c617174e54
Revises: dea413e13a8a
Create Date: 2021-04-19 12:45:55.439916
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "00c617174e54"
down_revision = "dea413e13a8a"
branch_labels = None
depends_on = None
def upgrade():
op.create_unique_con... | rs", ["email"])
def downgrade( | ):
op.drop_constraint("uq_users_email", "users", type="unique")
|
elc1798/chessley-tan | app.py | Python | mit | 5,117 | 0.006449 | import os
import module
from flask import Flask, render_template, request, session, redirect, url_for, send_from_directory
from werkzeug import secure_filename
from functools import wraps
app = Flask(__name__)
# Configure upload locations
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['ALLOWED_EXTENSIONS'] = se... | ef decorated_function(*args, **kwargs):
if "authenticated" in session and session["authenticated"]:
return redirect(url_for("profile"))
return f(*args, **kwargs)
return decorated_function
############### APPLICATION SITE ROUTES ###############
@app.route("/" | )
@app.route("/home")
@app.route("/home/")
@redirect_if_logged_in
def home():
return render_template("home.html")
@app.route("/login", methods=["GET","POST"])
@app.route("/login/", methods=["GET","POST"])
@redirect_if_logged_in
def login():
if request.method == "POST":
REQUIRED = ["username", "pass"]
... |
ajrichards/bayesian-examples | hypothesis-testing/binomial_prob.py | Python | bsd-3-clause | 1,308 | 0.009174 | #!/usr/bin/env python
"""
Let's say we play a game where I keep flipping a coin until I get
heads. If the first time I get heads is on the nth coin, then I pay
you 2n-1 dollars. How much would you pay me to play this game?
You should end up with a sequence that you need to find the closed
form of. If you don't know ho... | = False
return num_flips
if __name__ == '__main__':
## simulate
flips = [coin() for k in xrange(10000)]
## get the distribution of counts condition on the number of flips
range_flips = range(1, max(flips) + 1)
counts = np.array([flips.count(k)*1. for k in range_flips])
fig = plt.figure(... | bel("counts")
ax.set_xlabel("num flips to win")
#print [int(i) for i in counts]
winnings = sum([counts[k - 1]*(2*(k)-1)/sum(counts) for k in range_flips])
#print range_flips
print winnings
plt.show()
|
openstack/senlin | senlin/tests/unit/profiles/test_profile_base.py | Python | apache-2.0 | 38,181 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed unde... | ertEqual('value1', spec_data['properties']['key1'])
self.assertEqual(2, spec_data['properties']['key2'])
self.assertEqual('value1', profile.properties['key1'])
self.assertEqual(2, profile.properties['key2'])
self.assertEqual({'foo': 'bar'}, profile.context)
self.assertIsNone(pro... | sertIsNone(profile._block_storageclient)
@mock.patch.object(senlin_ctx, 'get_service_credentials')
def test_init_with_context(self, mock_creds):
mock_creds.return_value = {'foo': 'bar'}
profile = self._create_profile('test-profile',
pid='FAKE_ID', context=... |
anhstudios/swganh | data/scripts/templates/object/draft_schematic/clothing/shared_clothing_ith_backpack_field_06.py | Python | mit | 468 | 0.047009 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
| result = Intangible()
result.template = "object/draft_schematic/cl | othing/shared_clothing_ith_backpack_field_06.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
bmya/odoo-infrastructure | infrastructure_mass_mailing/__openerp__.py | Python | agpl-3.0 | 618 | 0 | # -*- coding: utf-8 -*-
{
'name': 'Infrastructure Mass Mailing Integration',
'version': '8.0.1.0.0',
'description': u'Infrastructure Mass Mailing Integration',
'category': u'base.module_category_knowledge_management',
'author': u'ADHOC SA',
'website': 'www.adhoc.com.ar',
'license': 'AGPL-3'... | 'sequence': 14,
'summary': '',
'installable': True,
'auto_install': True,
'application': False,
'images': [],
'data': | [
'mass_mailing_view.xml',
],
'demo': [],
'test': [],
}
|
infobloxopen/infoblox-netmri | infoblox_netmri/api/broker/v3_8_0/iprg_broker.py | Python | apache-2.0 | 54,667 | 0.002232 | from ..broker import Broker
class IprgBroker(Broker):
controller = "iprgs"
def show(self, **kwargs):
"""Shows the details for the specified iprg.
**Inputs**
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` True
| ... | ault:`` None
:param IprgNumber: The HSRP or VRRP group | number.
:type IprgNumber: Integer
| ``api version min:`` 2.5
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param IprgNumber: The HSRP or VRRP group number.
:type IprgNumber: Array of Integer
... |
mhvk/numpy | numpy/f2py/cfuncs.py | Python | bsd-3-clause | 48,940 | 0.001798 | #!/usr/bin/env python3
"""
C declarations, CPP macros, and C functions for f2py2e.
Only required declarations/macros/functions will be used.
Copyright 1999,2000 Pearu Peterson all rights reserved,
Pearu Peterson <pearu@ioc.ee>
Permission to use, modify, and distribute this software is given under the
terms of the Num... | ': '/*need_commonhooks*/',
'initcommonhooks': '/*need_initcommonhooks*/',
}
############ Includes ###################
includes0['math.h'] = '#include <math.h>'
includes0['string.h'] | = '#include <string.h>'
includes0['setjmp.h'] = '#include <setjmp.h>'
includes['Python.h'] = '#include "Python.h"'
needs['arrayobject.h'] = ['Python.h']
includes['arrayobject.h'] = '''#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API
#include "arrayobject.h"'''
includes['arrayobject.h'] = '#include "fortranobject.h"'
includ... |
mlosch/pytorch-stats | stats/estimation/mm.py | Python | mit | 4,418 | 0.003395 | import numpy as np
import torch
from torch.autograd import Variable
from stats.tensor import tensor
def fit(pdfs, parameters, observations, iter, lr):
"""Estimates the parameters of a mixture model via maximum likelihood maximization.
Uses gradient descent for optimization.
Parameters
----------
... | ist(x, 100, normed=True)
# plot distributions
np_pdf = lambda x, mean, std: 1./np.sqrt(2.0*np.pi*std*std) * np.exp(- ((x-mean)**2) / (2.0 * std*std))
xx = np.linspace(np.min(x), np.max(x), 1000)
for k in range(K):
true_y = np_pdf(xx, true_params[k][0], true_params[k][1])
estimated_y = ... | ='Target pdf k=%d'%(k+1))
plt.plot(xx, estimated_y, '-', label='Estimated pdf %d' % (k+1))
plt.legend()
plt.show()
|
Naeka/vosae-app | www/timeline/models/base.py | Python | agpl-3.0 | 1,805 | 0.002216 | # -*- coding:Utf-8 -*-
from django.utils.timezone import now as datetime_now
from mongoengine import DynamicDocument, fields
from django.conf import settings
from realtime.utils import emit_to_channel
__all__ = (
'TimelineEntry',
)
class TimelineEntry(DynamicDocument):
tenant = fields.ReferenceField("Tena... | n = fields.StringField()
see_permission = fields.StringField()
meta = {
"indexes": ["tenant", "access_permission", "see_permission"],
"ordering": ["-id"],
"allow_inheritance": True
}
@classmethod
def post_save(self, sender, document, **kwa | rgs):
"""
Post save hook handler
Emits timeline entry through the realtime service
"""
from core.models import VosaeUser
from timeline.api.resources import TimelineEntryResource
ter = TimelineEntryResource()
perms = []
if document.access_permissio... |
google-research/google-research | rrlfd/adroit_ext/hammer_v0.py | Python | apache-2.0 | 1,602 | 0.001873 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... | camera_id=self._camera_id)
qp = self.physics.data.qpos.ravel().copy()
qv = np.clip(self.physics.data.qvel.ravel(), -1.0, 1.0).copy()
palm_pos = self. | physics.data.site_xpos[self.S_grasp_sid].ravel().copy()
sensordata = np.clip(
self.physics.data.sensordata.ravel().copy()[:41], -5.0, 5.0)
original_obs = super().get_obs()
return {'rgb': rgb, 'qpos': qp[:-6], 'qvel': qv[:-6], 'palm_pos': palm_pos,
'tactile': sensordata, 'original_obs': o... |
azumimuo/family-xbmc-addon | zips/plugin.video.youtube/resources/lib/kodion/impl/mock/mock_context.py | Python | gpl-2.0 | 2,846 | 0.001054 | import time
__author__ = 'bromix'
import tempfile
from ..abstract_context import AbstractContext
from .mock_settings import MockSettings
from .mock_context_ui import MockContextUI
from .mock_system_version import MockSystemVersion
from ...logging import log
class MockContext(AbstractContext):
def __init__(self... | ontext._favorite_list = self._favorite_list
new_context._watch_later_list = self._watch_later_list
new_context._access_manager = self._access_manager
return new_context
def execute(self, command):
log("execute '%s'" % command)
pass
def sleep(self, milli_second | s):
time.sleep(milli_seconds/1000.0)
pass
pass |
mmanhertz/elopic | sample_code/pixelator.py | Python | bsd-2-clause | 9,517 | 0.00063 | #!/usr/bin/env python
############################################################################
#
# Copyright (C) 2004-2005 Trolltech AS. All rights reserved.
#
# This file is part of the example classes of the Qt Toolkit.
#
# This file may be used under the terms of the GNU General Public
# License version 2.0... | e, self).__init__(parent)
self.pixelSize = 12
def paint(self, painter, option, index):
if option.state & QtGui.QStyle.State_Selected:
painter.fillRect(option.rect, option.palette.highlight())
size = min(option.rect.width(), option.rect.height())
brightness = index.mode... | radius = (size / 2.0) - (brightness / 255.0 * size / 2.0)
if radius == 0.0:
return
painter.save()
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setPen(QtCore.Qt.NoPen)
if option.state & QtGui.QStyle.State_Selected:
painter.setBrush(optio... |
procangroup/edx-platform | pavelib/assets.py | Python | agpl-3.0 | 34,154 | 0.002225 | """
Asset compilation and collection.
"""
from __future__ import print_function
import argparse
import glob
import os
import traceback
from datetime import datetime
from functools import wraps
from threading import Timer
from paver import tasks
from paver.easy import call_task, cmdopts, consume_args, needs, no_help,... | timed
# setup baseline paths
ALL_SYSTEMS = ['lms', 'studio']
COFFEE_DIRS = ['lms', 'cms', 'common']
LMS = 'lms'
CMS = 'cms'
SYSTEMS = {
'lms': LMS,
'cms': CMS,
'studio': CMS
}
# Common lookup paths that are added to the lookup paths for all sass compilations
COMMON_LOOKUP_PATHS = [
path("common/st... | les'),
path('node_modules/edx-pattern-library/node_modules'),
]
# A list of NPM installed libraries that should be copied into the common
# static directory.
# If string ends with '/' then all file in the directory will be copied.
NPM_INSTALLED_LIBRARIES = [
'backbone.paginator/lib/backbone.paginator.js',
... |
cryptoprojects/ultimateonlinecash | test/functional/signrawtransactions.py | Python | mit | 7,187 | 0.002644 | #!/usr/bin/env python3
# Copyright (c) 2015-2016 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 transaction signing using the signrawtransaction RPC."""
from test_framework.test_framework impor... | d (vin 1) and missing input (vin 2)
assert_equal(rawTxSigned['errors'][0]['txid'], inputs[1]['txid'])
assert_equal(rawTxSigned['errors'][0]['vout'], inputs[1]['vout'])
assert_equal(rawTxSigned['errors'][1]['txid'], | inputs[2]['txid'])
assert_equal(rawTxSigned['errors'][1]['vout'], inputs[2]['vout'])
assert not rawTxSigned['errors'][0]['witness']
# Now test signing failure for transaction with input witnesses
p2wpkh_raw_tx = "01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad... |
azogue/esiosdata | tests/test_perfiles_consumo_pvpc.py | Python | mit | 2,973 | 0.003712 | # -*- coding: utf-8 -*-
"""
Test Cases para el cálculo de los perfiles de consumo de referencia para la estimación del reparto horario
del consumo eléctrico, con el fin de calcular el PVPC a aplicar al periodo considerado.
"""
from unittest import TestCase
import pandas as pd
class TestsPerfilesConsumo(TestCase):
... | n intervalo.
Ejem | plo de generación de valores de consumo horario a partir de consumo total y perfiles de uso.
"""
from esiosdata.perfilesconsumopvpc import perfiles_consumo_en_intervalo
ts_0, ts_f = '2016-10-29', '2017-01-24'
consumo_total_interv_kwh = 836.916
print('Consumo horario estimado par... |
samn/spectral-workbench | webserver/public/lib/bespin-0.9a2/lib/dryice/tests/test_combiner.py | Python | gpl-3.0 | 2,130 | 0.000939 | # ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Softwa... | r the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of ei... | n by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
from cSt... |
migueldvb/piernik | bin/qa.py | Python | gpl-3.0 | 15,798 | 0.003735 | #!/usr/bin/env python
import re
import sys
import hashlib
import subprocess as sp
import numpy as np
debug = False
typ1 = np.dtype([('name', 'a50'), ('beg', 'i'), ('end', 'i'), ('type', 'a4')])
# starts with spaces or spaces and one of { 'end', 'pure', ... }
# if function it can have a type next goes subroutine or f... | :
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def disable(self):
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
| self.ENDC = ''
b = bcolors()
def remove_binaries(files):
list = []
for file in files:
checkFile = sp.Popen('file -bi ' + file, stdout=sp.PIPE, shell=True,
executable="/bin/bash")
if not checkFile.communicate()[0].startswith('text'):
print b.WARNING... |
Yelp/paasta | paasta_tools/mesos/cluster.py | Python | apache-2.0 | 2,143 | 0.000467 | # 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 u... | lt = await result
if result:
no_files_found = False
| yield result
except exceptions.SkipResult:
pass
if no_files_found:
raise exceptions.FileNotFoundForTaskException(
"None of the tasks in {} contain the files in list {}".format(
",".join([task["id"] for task in task_list]), ",".join(file... |
smidm/camera.py | docs/conf.py | Python | mit | 7,772 | 0.007334 | # -*- coding: utf-8 -*-
#
# camera.py documentation build configuration file, created by
# sphinx-quickstart on Fri Aug 8 12:43:10 2014.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... | ctory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use | os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here,... |
chelberserker/mipt_cs_on_python | lab 7/ex7.py | Python | gpl-2.0 | 275 | 0.054545 | import math
import numpy as np
import matplotlib.pyplot as plt
def f(x):
s = 0
b = 0.5
a = 3
for n in range(1, 50):
s += (b**n)*(math.cos((a**n)*(math.pi)*x))
| y = s
return y
x=np.arange(-2,2,0.01)
y = [f(_x) for _x in x]
plt.grid(True)
plt.plot(x, y)
plt.show()
| |
general-language-syntax/GLS | test/integration/ForEachKeyStart/for each key start.py | Python | mit | 36 | 0.027778 | #
for k | ey in container:
| # ...
#
|
jdber1/opendrop | opendrop/app/common/image_acquisition/image_acquisition.py | Python | gpl-3.0 | 3,443 | 0.001744 | # Copyright © 2020, Joseph Berry, Rico Tabor (opendrop.dev@gmail.com)
# OpenDrop is released under the GNU GPL License. You are free to
# modify and distribute the code, but always under the same license
#
# If you use this software in your research, please cite the following
# journal articles:
#
# J. D. Berry, M. J. ... | u.org/licenses/>.
from typing import Optional
from gi.repository import Gtk, GObject
from injector import inject
from opendrop.app.common.services.acquisition import AcquirerType, ImageAcquisitionService, ImageAcquirer
from opendrop.appfw import Presenter, TemplateChild, component
@component(
template_path='.... | eChild[Gtk.ComboBoxText]
@inject
def __init__(self, acquisition_service: ImageAcquisitionService) -> None:
self.acquisition_service = acquisition_service
self.event_connections = ()
def after_view_init(self) -> None:
self.populate_combobox()
self.event_connections = (
... |
VulcanoAhab/delphi | workers/serializers.py | Python | mit | 2,526 | 0.016627 | from rest_framework import serializers
from workers.models import (TaskConfig,
Task,
Job,
TaskProducer)
from grabbers.serializers import (MapperSerializer,
SequenceSerializer)
from grabbers.models impor... | proxy by api yet - missing fields::proxy,network_cap
fields=('name','driver','sequence','mapper','round_limit')
def create(self, validated_data):
'''
'''
name=validated_data['name']
try:
task_config=TaskConfig.objects.get(name=name)
print("[-] We al... | n db")
return task_config
except TaskConfig.DoesNotExist:
task_config=TaskConfig(name=name)
driver=_get_or_instance(Driver,'name',
validated_data['driver'],DriverSerializer)
sequence=_get_or_instance(Sequence,'name',
... |
flysmoke/ijizhang | ijizhang_prj/jizhang/tests.py | Python | mit | 74 | 0.013514 | #cod | ing=utf-8
from django.test import TestCase
# Create your tests here.
| |
rullmann/bundlewrap-collectd | items.py | Python | mit | 5,646 | 0.002657 | pkg_dnf = {
'collectd': {},
'collectd-chrony': {},
'collectd-curl': {},
'collectd-curl_json': {},
'collectd-curl_xml': {},
'collectd-netlink': {},
'rrdtool': {},
}
if node.os == 'fedora' and node.os_version >= (26):
pkg_dnf['collectd-disk'] = {}
svc_systemd = {
'collectd': {
... | node.metadata.get('collectd', {}).get('server', {}).get('firewalld_permitted_zone')
actions['firewalld_add_collectd_zone_{}'.format(zone)] = {
'command': 'firewall-cmd --permanent --zone={} --add-port={}/udp'.format(zone, port | ),
'unless': 'firewall-cmd --zone={} --list-ports | grep {}/udp'.format(zone, port),
'cascade_skip': False,
'needs': ['pkg_dnf:firewalld'],
'triggers': ['action:firewalld_reload'],
}
elif node.metadata.get('firewalld', {}).get('default_... |
erral/eitbapi | eitbapi/cors.py | Python | gpl-2.0 | 1,856 | 0.001078 | from pyramid.security impo | rt NO_PERMISSION_REQUIRED
def includeme(config):
config.add_directive("add_cors_preflight_handler", add_cors_preflight_handler)
config.add_route_predicate("cors_preflight", CorsPreflightPredicate)
confi | g.add_subscriber(add_cors_to_response, "pyramid.events.NewResponse")
class CorsPreflightPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return "cors_preflight = %s" % bool(self.val)
phash = text
def __call__(self, context, request):
if not ... |
patrickwolf/python-tutorial | pyintro_a_basics/i_string_operators.py | Python | mit | 338 | 0.017751 | '''
@summary: Python Intro - Operators
'''
# --------------------- | -
# operator + - concatenation
# ----------------------
print 5 + 10.2 # 15.2
print "abc" + "def" # abcdef
# ---------------------------
# operator * - repeat
# ---------------------------
print "abc,"*5 # abc,abc,abc,abc,abc,
print ( | 5,3,2)*2 # (5, 3, 2, 5, 3, 2)
|
lablup/sorna-manager | src/ai/backend/gateway/types.py | Python | lgpl-3.0 | 720 | 0 | from | __future__ import annotations
from typing import (
Any,
Awaitable, Callable, Iterable,
AsyncIterator,
Tuple,
Mapping,
)
from aiohttp import web
import aiohttp_cors
WebReq | uestHandler = Callable[
[web.Request],
Awaitable[web.StreamResponse]
]
WebMiddleware = Callable[
[web.Request, WebRequestHandler],
Awaitable[web.StreamResponse]
]
CORSOptions = Mapping[str, aiohttp_cors.ResourceOptions]
AppCreator = Callable[
[CORSOptions],
Tuple[web.Application, Iterable[WebMi... |
DraXus/andaluciapeople | blogapp/views.py | Python | agpl-3.0 | 5,160 | 0.014341 | from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _
from django.core.paginator import Paginator, InvalidPage
from django.core.exceptions import ObjectDoesNotExist
from blogapp.models import *
from blogapp.utilities import *
from ... | .get('page', 1))
except ValueError:
page_q = 1
try:
p = pg.page(page_q)
posts = p.object_list
except InvalidPage:
return not_found(request, message=_("Sorry, the page does not exist."))
context = {'posts': posts,
'page': p,
'options': options(),
... | (BLOG_TPL, context, context_instance=RequestContext(request))
def post_by_name(request, post_name):
try:
post = Post.objects.get(name=post_name)
except ObjectDoesNotExist:
return not_found(request, message=_("Sorry, the requested post does not exist."))
#check if comments are enabled
i... |
rossella/neutron | quantum/plugins/nec/agent/nec_quantum_agent.py | Python | apache-2.0 | 4,286 | 0 | #!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 NEC Corporation.
# Based on ryu/openvswitch agents.
#
# Copyright 2012 Isaku Yamahata <yamahata at private email ne jp>
# Copyright | 2011 Nicira Networks, 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 ap... | reed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# @author: Ryota MIBU
import soc... |
Mitali-Sodhi/CodeLingo | Dataset/python/pincode.py | Python | mit | 3,279 | 0.028667 | import tornado.ioloop
import tornado.web
import json
import MySQLdb
class MainHandler(tornado.web.RequestHandler):
# def fetch_states(self):
# pincode_file = open('pincode.json')
# pincode_json = json.load(pincode_file)
# state_list = {}
# state_list['states'] = []
# state_list['state_count'] = 0
# for... | _json = json.dumps(pin_list)
# pincode_file.close()
# return state_list_json
def fetch_pincode(self, pincode):
place_list = {}
place_list['status'] = 200
place_list['status_text'] = "Success"
place_list['count'] = 0
place_list['data'] = []
db = MySQLdb.connect(host="localhost", user="root", passwd="... | r.execute('SELECT * from pincode where pincode=%s', (pincode));
for row in cursor.fetchall():
s_list = {}
s_list['Office_Name'] = row[0]
s_list['Pincode'] = int(row[1])
s_list['Office_Type'] = row[2]
s_list['Delivery_Status'] = row[3]
s_list['Division_Name'] = row[4]
s_list['Region_Name'] = row[... |
johngumb/gb3wx | dtmf-generator/src/gb3wxsetup.py | Python | gpl-3.0 | 596 | 0.015101 | import sys
import | os
import subprocess
import time
import string
import datetime
import serial
if __name__=="__main__":
serport = '/dev/ttyUSB0'
ser = serial.Serial(serport)
if len(sys.argv) > 1:
val = True
else:
val = False
start=2730
for i in range(start, 100000):
ser.setRTS(Tru... | ()
time.sleep(0.7)
ser.setRTS(False)
time.sleep(0.4)
|
mercycorps/TolaTables | tola/forms.py | Python | gpl-2.0 | 3,291 | 0.003646 | from crispy_forms.helper import FormHelper
from crispy_forms.layout import *
from crispy_forms.bootstrap import *
from crispy_forms.layout import Layout, Submit, Reset, Div
from django import forms
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from silo.models import TolaUser
from django.contri... | lds = '__all__'
helper = For | mHelper()
helper.form_method = 'post'
helper.form_class = 'form-horizontal'
helper.label_class = 'col-sm-2'
helper.field_class = 'col-sm-6'
helper.form_error_title = 'Form Errors'
helper.error_text_inline = True
helper.help_text_inline = True
helper.html5_required = True
helper.layou... |
uclouvain/osis | ddd/logic/encodage_des_notes/soumission/domain/service/encoder_notes_en_lot.py | Python | agpl-3.0 | 6,960 | 0.003592 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | es_notes_a_encoder)
notes_par_identite = {n.entity_id: n for n in notes_a_encoder} # type: Dict[IdentiteNoteEtudiant, NoteEtudiant]
desinscriptions = inscription_examen_translator.search_desinscrits_pour_plusieurs_unites_enseignement(
codes_unites_enseignement={n.code_unite_enseignement for... |
notes_a_persister = []
for note_encodee_cmd in cmd.notes:
identite = identite_builder.build_from_encoder_note_command(cmd, note_encodee_cmd)
note_a_modifier = notes_par_identite.get(identite)
if note_a_modifier:
try:
_verifier_et... |
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/urbansim/gridcell/average_land_value_per_acre_from_buildings.py | Python | gpl-2.0 | 1,881 | 0.011164 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from opus_core.variables.variable import Variable
from variable_functions import my_attribute_label
from opus_core.misc import safe_array_divide
class average_land_value_per_acre_from_buil... | age_order=['urbansim'],
test_data={
"gridcell":{
"grid_id": array([1,2,3]),
"total_land_value_from_buil | dings":total_land_value,
"acres_of_land":acres_of_land
}
}
)
should_be = array([0.0, 10.0, 607.5757576])
tester.test_is_close_for_variable_defined_by_this_module(self, should_be)
if __name__=='__main__':
opus_unittest.main() |
roverdotcom/django-fuelsdk | django_fuelsdk/constants.py | Python | mit | 221 | 0 | from django.conf import settings
CLIENT_ID = getattr(settings, 'EXACT_TARGET_CL | IENT_ID', '')
CLIENT_SECRET = getattr(settings, 'EXACT_TARGET_CLIENT_SECRET', '')
WSDL_URL = getattr(settings, 'EXACT_TARGET | _WSDL_URL', '')
|
TalShor/SciLMM | scilmm/Matrices/SparseMatrixFunctions.py | Python | gpl-3.0 | 397 | 0 | import numpy as np
from scipy.sparse import csr_matrix
def save_sparse_csr(filename, | array):
np.savez(filename, data=array.data, indices=array.indices,
indptr=array.indptr, shape=array.shape)
def load_sparse_csr(filename):
loader = np.load(filename)
return csr_matrix((loader['data'], loader['indices'], loader['indptr']),
shape=loader['shape'])
| |
ctalbert/mozharness | test/test_base_python.py | Python | mpl-2.0 | 1,129 | 0.000886 | import os
import unittest
import mozha | rness.base.python as python
here = os.path.dirname(os.path.abspath(__file__))
class TestVirtualenvMixin(unittest.TestCase):
def test_package_versions(self):
example = os.path.join(here, 'pip-freeze.example.txt')
output = file(example).read()
mixin = python.VirtualenvMixin()
package... | 'PyYAML': '3.10',
'Tempita': '0.5.1',
'WebOb': '1.2b3',
'coverage': '3.5.1',
'logilab-astng': '0.23.1',
'logilab-common': '0.57.1',
'mozdevice': '0.2',
'mozhttpd': '0.3',
... |
imxana/Flask_init | apps/models.py | Python | mit | 3,510 | 0.004274 | # 'microblog' is an example, change the model for your own.
from flask import g
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
def register(app):
db = SQLAlchemy(app)
# flask command
@app.cli.command('in... | def __repr__(self):
return '<Post %r>' % self.title
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Strin | g(50))
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Category %r>' % self.name
# Flask-admin initialization here
admin = Admin(app, name='Admin', template_mode='bootstrap3')
class GlobalView(ModelView):
can_create = False
... |
rs2/pandas | pandas/tests/reshape/test_qcut.py | Python | bsd-3-clause | 8,222 | 0.000486 | import os
import numpy as np
import pytest
import pandas as pd
from pandas import (
Categorical,
DatetimeIndex,
Interval,
IntervalIndex,
NaT,
Series,
TimedeltaIndex,
Timestamp,
cut,
date_range,
isna,
qcut,
timedelta_range,
)
import pandas._testing as tm
from pandas.... | 1] * 10)
data_result = box([False, True, True, False, True] * 10)
expected = qcut(data_expected, bins, duplicates="drop")
result = qcut(data_result, bins, duplicates="drop")
compare(result, expected)
@pytest.mark.parametrize("q", [2, 5, 10])
def test_qcut_nullable_integer(q, any_numeric_ea_dtype):
... | = pd.array(np.arange(100), dtype=any_numeric_ea_dtype)
arr[::2] = pd.NA
result = qcut(arr, q)
expected = qcut(arr.astype(float), q)
tm.a |
infobloxopen/infoblox-netmri | infoblox_netmri/api/broker/v2_9_0/basic_services_broker.py | Python | apache-2.0 | 18,594 | 0.002797 | from ..broker import Broker
class BasicServicesBroker(Broker):
controller = "basic_services"
def authenticate(self, **kwargs):
"""Authenticates the user with NetMRI.
**Inputs**
| ``api version min:`` None
| ``api version max:`` None
| ``required:``... | versions_only_ind: Only include API version information in the output.
:type api_versions_only_ind: Boolean
**Outputs**
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:return n... | s appliance or virtual machine.
:rtype netmri_version: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:return latest_api_version: The most recent API version supported by this NetMRI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.