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 |
|---|---|---|---|---|---|---|---|---|
hakril/PythonForWindows | tests/test_debugger.py | Python | bsd-3-clause | 25,193 | 0.003533 | import pytest
import textwrap
import ctypes
import os
import windows
import windows.debug
import windows.generated_def as gdef
import windows.native_exec.simple_x86 as x86
import windows.native_exec.simple_x64 as x64
from .conftest import generate_pop_and_exit_fixtures, pop_proc_32, pop_proc_64
from .pfwtest import *... | assert dbg.current_process.pid == proc32_64_debug.pid
assert dbg.current_thread.context.pc == self.addr
| assert dbg.current_thread.context.Dr7 != 0
d.current_process.exit()
LdrLoadDll = get_debug_process_ndll(proc32_64_debug).exports["LdrLoadDll"]
d = windows.debug.Debugger(proc32_64_debug)
d.add_bp(TSTBP(LdrLoadDll))
d.loop()
@pytest.mark.timeout(DEFAULT_DEBUGGER_TIMEOUT)
def test_m... |
gplepage/gvar | tests/test_gvar.py | Python | gpl-3.0 | 91,671 | 0.014716 | """
test-gvar.py
"""
# Copyright (c) 2012-20 G. Peter Lepage.
#
# 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
# any later version (see <http://www.gnu.org/... | .,80.,155.,20.])
self.assert_arraysequal(v2.ad | d(v1,7,5).toarray(),[5.,80.,155.,20.])
def test_v_mul(self):
""" svec.mul """
v1 = svec(3) # [1,2,0,0,3]
v1.assign([1.,3.,2.],[0,4,1])
self.assert_arraysequal(v1.mul(10).toarray(),[10,20,0,0,30])
def test_pickle(self):
v = svec(4)
v.assign([1.,2.,5.,22], [3,5... |
Strubbl/dinorss | config.py | Python | gpl-3.0 | 483 | 0.010352 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
|
import config_sites
author = "Sven Fischer"
email = "wannaberss@linux4tw.de"
version = "0.1.0"
credits = ["Sven Fischer"]
rss_base_url = config_sites.deploy_base_url
sites = config_sites | .sites
max_rss_items = 10
max_site_caches = max_rss_items + 1 # if there more, latest will be deleted
cache_dir = 'cache/' # end with slash
sites_dir = cache_dir + 'sites' # do not end wit slash
rss_dir = cache_dir + 'rss' # do not end wit slash
|
zhangf911/common | test/testfileutils.py | Python | mit | 4,715 | 0.002333 | import os
import shutil
import biicode.common.test
from biicode.common.utils import file_utils as common_file_utils
def load(filepath):
"""Return binary load of given test resource."""
abspath = file_path(filepath)
with open(abspath, "rb") as f:
return f.read()
def read(filepath):
"""Return ... | with open(abspath, "r") as f:
return f.read()
def write(file_, content):
try:
os.makedirs(os.path.split(file_)[0])
except:
pass
with open(file_, "wb") as f:
return f.write(content)
test_resources = os.path.join(os.path.dirname(biicode.common.test.__file__),
... | list of files within given test folder
Paths are relative to test/resources/path"""
abs_paths = common_file_utils.get_visible_files_recursive(file_path(path))
base_path = os.path.join(test_resources, path)
return [os.path.relpath(p, base_path) for p in abs_paths]
def file_path(name):
"""Return fu... |
openatv/enigma2 | lib/python/Components/Netlink.py | Python | gpl-2.0 | 951 | 0.028391 | from __future__ import print_function
# Listen to hotplug events. Can be used to listen for hotplug events and
# similar things, like network connections be | ing (un)plugged.
import os
import socket
import six
class NetlinkSocket(socket.socket):
def __init__(self):
NETLINK_KOBJECT_UEVENT = 15 # hasn't landed in socket yet, see linux/netlink.h
socket.socket.__init__(self, socket.AF_NETLINK, socket.SOCK_DGRAM, NETLINK_KOBJECT_UEVENT)
self.bind((os.getpid(), -1))
de... | a.split('\x00'):
if not item:
# terminator
yield event
event = {}
else:
try:
k, v = item.split('=', 1)
event[k] = v
except:
event[None] = item
# Quick unit test (you can run this on any Linux machine)
if __name__ == '__main__':
nls = NetlinkSocket()
print("socket no:", nls.f... |
AustinTSchaffer/DailyProgrammer | AdventOfCode/2020/day_15/solution.py | Python | mit | 1,352 | 0.016272 | import collections
puzzle_input = (0,13,1,8,6,15)
test_inputs = [
([(0,3,6), 10], 0),
([(1,3,2)], 1),
([(2,1,3)], 10),
([( | 1,2,3)], 27),
([(2,3,1)], 78),
([(3,2,1)], 438),
([(3,1,2)], 1836),
# Expensive Tests
# ([(0,3,6), 30000000], 175594),
# ([(1,3,2), 30000000], 2578),
# ([(2,1,3), 30000000], 3544142),
# ([(1,2,3), 30000000], 261214),
| # ([(2,3,1), 30000000], 6895259),
# ([(3,2,1), 30000000], 18),
# ([(3,1,2), 30000000], 362),
]
def iterate(input_, iterations=2020) -> int:
turn = 0
turn_last_spoken = collections.defaultdict(int)
prev_number = None
for value in input_:
turn_last_spoken[prev_number] = turn
prev... |
Matthew-Arnold/slack-versebot | versebot/regex.py | Python | mit | 2,107 | 0 | """
VerseBot for Reddit
By Matthieu Grieger
Continued By Team VerseBot
regex.py
Copyright (c) 2015 Matthieu Grieger (MIT License)
"""
import re
def find_verses(message_body):
""" Uses regex to search comment body for verse quotations. Returns
a list of matches if found, None otherwise.
:param message_bo... |
if len(matches) == 0:
return None
else:
return matches
def find_already_quoted_verses(message_body):
""" Uses regex to search an existing VerseBot response for verse
quotations. Used for removing invalid statistics from database.
:param message_body: Body of message that possibly... | \((?P<translation>[\w\-\d]+)?\)")
matches = re.findall(regex, message_body)
if len(matches) == 0:
return None
else:
return matches
def find_default_trans(message_body):
""" Uses regex to search a private message for default translations
when a user sends a default translation requ... |
calpeyser/google-cloud-python | datastore/google/cloud/datastore/query.py | Python | apache-2.0 | 19,823 | 0 | # Copyright 2014 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | f kind(self, value):
"""Update the Kind of the Query.
:type value: str
| :param value: updated kind for the query.
.. note::
The protobuf specification allows for ``kind`` to be repeated,
but the current implementation returns an error if more than
one value is passed. If the back-end changes in the future to
allow multiple value... |
Sonblind/orchestra | orchestra/migrations/0011_auto_20150618_0003.py | Python | apache-2.0 | 1,311 | 0.003051 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('orchestra', '0010_merge'),
]
operations = [
migrations.AlterField(
model_name='project',
name='proce... | ment_experiment', 'Website Enhancement Experiment'), ('website_enhancement', 'Website Enhancement'), ('doctors', 'Doctors Process')]),
),
migrations.AlterField(
model_name='task',
name=' | step_slug',
field=models.CharField(max_length=200, choices=[('website_enhancement_experiment', 'Website Enhancement'), ('website_enhancement', 'Website Enhancement'), ('export', 'Export'), ('design', 'Design'), ('content_extraction', ' Content Extraction')]),
),
migrations.AlterField(
... |
Hasimir/pyjs | pyjswidgets/pyjamas/ui/GlassWidget.py | Python | apache-2.0 | 6,537 | 0.000306 | # Copyright 2006 James Tauber and contributors
# Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
# Copyright (C) 2010 Serge Tarkovski <serge.tarkovski@gmail.com>
#
# 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.ap | ache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# lim... |
t3dev/odoo | addons/point_of_sale/tests/test_frontend.py | Python | gpl-3.0 | 13,746 | 0.002182 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.api import Environment
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT
from datetime import date, timedelta
import odoo.tests
class TestUi(odoo.tests.HttpCase):
def test_01_pos_basic_order(self):
... | 0,
'applied_on': '0_product_variant',
'product_id': env.ref('point_of_sale.desk_pad').id,
})],
})
env['product.pricelist'].create({
'name': 'min_quantity ordering',
'item_ids': [(0, 0, {
'compute_ | price': 'fixed',
'fixed_price': 1,
'applied_on': '0_product_variant',
'min_quantity': 2,
'product_id': env.ref('point_of_sale.wall_shelf').id,
}), (0, 0, {
'compute_price': 'fixed',
'fixed_price': 2,
... |
jschaub30/tidy | sparkread.py | Python | apache-2.0 | 3,370 | 0.00089 | #!/usr/bin/python
'''
Input: file
Output: stdout
Tidy output of spark stderr file CSV format
Jeremy Schaub
$ ./sparkread.py [time_output_file]
'''
import sys
class Measurement:
'''
Data structure for /usr/bin/time measurement
'''
def __init__(self):
self.stage_times = ['0']
self.s... | nished in ')[1:])
stage_times = ['' for i in range(num_stages)]
i = 0
total_time = 0
for a in blob.split('finished in ')[1:]:
st | age_times[i] = a.split(' s\n')[0]
total_time += float(stage_times[i])
i += 1
stage_times.append(str(total_time))
self.stage_times = stage_times
self.spill_count = str(blob.lower().count('spill'))
if not self.is_valid():
sys.... |
obi-two/Rebelion | data/scripts/templates/object/tangible/deed/city_deed/shared_theater_corellia_deed.py | Python | mit | 465 | 0.047312 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPL | ES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/deed/city_deed/shared_theater_corellia_deed.iff"
result.attribute_ | template_id = 2
result.stfName("deed","corellia_theater_deed")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
toboso-team/toledo | toledo/graphics/screen.py | Python | mit | 7,808 | 0.001671 | import pygame
import math
class Screen:
'''
Se encarga de controlar lo que ve el jugador en la pantalla.
Parameters
----------
size : List[int]
Tamaño de la pantalla, ``[w, h]``.
Notes
-----
Primero se debe crear una instancia de este objeto, luego, en cada loop del
juego ... | osición en la pantalla en donde dibujar. Se respeta el tamaño dado.
angle : :obj:`float`, optional
Ángulo de rotación en grados, sentido contrario | a las agujas del
reloj.
smooth : :obj:`bool`, optional
Si usar o no antialiasing.
anchor : :obj:`int`, optional
Tipo de anclaje a usar, (por ej. si centrado o esquinado). Usar las
constantes definidas. Ej: ``Screen.ANCHOR_CENTER`` o
``Screen.A... |
SuminAndrew/lxml-asserts | setup.py | Python | apache-2.0 | 1,329 | 0.001505 | # coding=utf-8
from setuptoo | ls import setup
from setuptools.command.test import test
class TestHook(test):
def run_tests(self):
import nose
nose.main(argv=['nosetests', 'tests/', '-v', '--logging-clear-handlers'])
setup(
name='lxml-asserts',
version='0.1.2',
description='Handy functions for testing lxml etree o... | lxml-asserts',
author='Andrew Sumin',
author_email='sumin.andrew@gmail.com',
classifiers=[
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Pro... |
endlessm/chromium-browser | third_party/depot_tools/bootstrap/bootstrap.py | Python | bsd-3-clause | 12,038 | 0.00947 | # Copyright 2016 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 argparse
import collections
import contextlib
import fnmatch
import hashlib
import logging
import os
import platform
import posixpath
import shutil
im... | stamp version.
fn (callable): A callable to invoke if the current stamp version doesn't
match |stamp_version|.
Returns (bool): True if an update occurred.
"""
stamp_version = stamp_version.strip()
if os.path.isfile(stamp_path):
with open(stamp_path, 'r', e | ncoding='utf-8') as fd:
current_version = fd.read().strip()
if current_version == stamp_version:
return False
fn()
with open(stamp_path, 'w', encoding='utf-8') as fd:
fd.write(stamp_version)
return True
def _in_use(path):
"""Checks if a Windows file is in use.
When Windows is using an... |
beagles/sosreport-neutron | sos/plugins/mysql.py | Python | gpl-2.0 | 1,718 | 0.006985 | ### 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 in the hope that it will be useful,... | tions
"""
packages = ('mysql-server', 'mysql-common')
def setup(self):
self.mysql_cnf = "/etc/mysql/my.cnf"
super(DebianMysql, self).set | up()
self.add_copy_spec("/etc/mysql/conf.d/mysql*")
|
Bargetor/chestnut | bargetor/common/HTMLUtil.py | Python | gpl-2.0 | 1,310 | 0.010687 | import html5lib
import traceback
def build_html_dom_from_str(html_str):
return html5lib.parse(html_str, 'dom')
def find_html_element_list_for_tag(element, tag, class_style = None):
elements = element.getElementsByTagName(tag)
if not class_style: return elements
result = []
for e in elements:
... | Exception, e:
exstr = traceback.format_exc()
| print exstr
|
cydenix/OpenGLCffi | OpenGLCffi/GLES3/EXT/NV/conservative_raster_pre_snap_triangles.py | Python | mit | 142 | 0.021127 | from OpenGLCffi.GLES3 import params
@params(api='gles3', prms=['pname', 'par | am'])
def glConservativeRasterParameteriNV(pname, p | aram):
pass
|
apehua/pilas | pilas/ejemplos/ejemplos/minijuegos/memorice/escena_menu.py | Python | lgpl-3.0 | 3,498 | 0.004574 | # -*- encoding: utf-8 -*-
# For pilas engine - a video game framework.
#
# copyright 2011 - Pablo Garrido
# license: lgplv3 (see http://www.gnu.org/licenses/lgpl.html)
#
# website - http://www.pilas-engine.com.ar
import pilas
class EscenaMenu(pilas.escena.Base):
"Escena de presentacion del juego."
def __init... | r_normal)
self.boton_ayuda.x = [-160]
# boton salir
def presionamos_boton_salir():
self.salir_del_juego()
def sobre_boton_salir():
self.boton_salir.pintar_sobre()
opcion.x = 21
opcion.y = -119
self.boton_salir = pilas.actores.Bo... | conectar_sobre(sobre_boton_salir)
self.boton_salir.conectar_normal(self.boton_salir.pintar_normal)
self.boton_salir.x = [-190]
def desactivar_botones(self):
self.boton_inicio.desactivar()
self.boton_ayuda.desactivar()
self.boton_salir.desactivar()
def iniciar_juego(s... |
dcjohnson/Project-Euler | 221/221.py | Python | mit | 554 | 0.001805 | #!/usr/bin/env python
def get_yz_vals(x):
| b = -1
yVals = []
while x ** 2 + 1 > b * x and b != x:
a = (x ** 2) - (b * x) + 1
if a % b == 0:
yVals.append((b - x, a / b))
b -= 1
return yVals
if __name__ == '__main__':
count = 0
x = -1
answers = []
while count < 1000000:
for y, z in get_yz_v... | += 1
answers.append(x * y * z)
x -= 1
# remove duplicates
answers = list(set(answers))
answers.sort()
print answers[149999]
|
liuyepiaoxiang/es6-learning | 032-python/chap2/4.9.py | Python | mit | 369 | 0.02168 | # usr/bin/sh
# -*- coding:utf8 -*-
# @function listDeal
# @parma {list} list
def listDeal(list):
listString = ''
for i in range(0,len(list)):
print(i)
if i!=(len(list)-1):
| listString += list[i]+',';
else:
listString += 'and '+list[i]
print(listString)
spam = ['apples','bananas','tofu','c | ats']
listDeal(spam) |
Favidavid/graphwars | graphwars/test_map.py | Python | mit | 420 | 0.002381 | from map | import Map
import networkx as nx
import matplotlib.pyplot as plt
import random
import numpy as np
from scipy.spatial import Delaunay
pts = np.array([[random.random(), random.random()] for i in range(10)])
delTri = Delaunay(pts)
print(delTri.vertices)
G = Map(40, 3, 2, 10, 10, 5, 0)
#pos_dict = {G.map.nodes()[i]: G.ma... | show()
|
JonnaStalring/AZOrange | azorange/AZutilities/getBBRCDesc.py | Python | lgpl-3.0 | 12,011 | 0.012822 | import logging
import os,string,sys
from AZutilities import dataUtilities
import random
import bbrc
import orange
from cinfony import rdk
logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
class BBRC(object):
def __init__(self, verbose = 0):
self.iniDir = os.getcwd()
... | g. export FMINER_LAZAR=1).
#FMINER_PVALUES : Produce p-values instead of chi-square values (e.g. export FMINER_PVALUES=1).
#FMINER_NO_AROMATIC_WC: Disallow aromatic wildcard bonds on aliphatic bonds, when aromatic perception was switched off (
# '-a') (e.g. export FMINER_NO... | ER_NR_HITS : Display (in the occurrence lists) the number of times each fragment occurs in a molecule.
try:
# lazar smarts pvalue no_aromatic_wc silent fminer_nr_hits
self.MyFminer = bbrc.Bbrc( True, True, False, False, 0, ... |
emersonsoftware/ansiblefork | lib/ansible/plugins/connection/ssh.py | Python | gpl-3.0 | 36,337 | 0.003357 | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright 2015 Abhijit Menon-Sen <ams@2ndQuadrant.com>
# Copyright 2017 Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Lice... | []
#
# First, the command to invoke
#
# If we want to use password authentication, we | have to set up a pipe to
# write the password to sshpass.
if self._play_context.password:
if not self._sshpass_available():
raise AnsibleError("to use the 'ssh' connection type with passwords, you must install the sshpass program")
self.sshpass_pipe = os.pipe()
... |
zibawa/zibawa | devices/views.py | Python | gpl-3.0 | 7,956 | 0.018854 | from builtins import str
from builtins import range
from django.http import HttpResponse,HttpResponseNotFound
from django.template import loader
from django.shortcuts import get_list_or_404
from django.shortcuts import render
from .forms import TestMessageForm
from .models import Device
from django.conf import settings... | ttChecksList=processMessages(testMsg)
myTopic=TopicData(form.cleaned_data['topic'])
lastInflux= getLastInflux(request.user,myTopic.device,myTopic.channel)
context = {
'h | as_permission':request.user.is_authenticated,
'is_popup':False,
'form':form,
'mqttChecksList':mqttChecksList,
'title':'Send test message',
'site_title':'zibawa',
'status_list':status_list,
'site_url':settings... |
pacharrin/karel.js | libkarel/libkarel_test.py | Python | mit | 3,511 | 0.000856 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Pruebas unitarias de libkarel."""
import unittest
import libkarel
class TestLibKarelInput(unittest.TestCase):
"""Prueba libkarel.KarelInput."""
# pylint: disable=R0904
def test_basic(self):
"""Prueba básica."""
karel_in = libkarel.KarelInput... | >
</ejecucion>
''') |
# Dimensiones del mundo
self.assertEqual(karel_in.w, 100)
self.assertEqual(karel_in.h, 100)
# Estado inicial de Karel
self.assertEqual(karel_in.x, 1)
self.assertEqual(karel_in.y, 1)
self.assertEqual(karel_in.mochila, 0)
self.assertEqual(karel_in.direccio... |
googleapis/python-compute | tests/unit/gapic/compute_v1/test_global_network_endpoint_groups.py | Python | apache-2.0 | 122,865 | 0.0014 | # -*- 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... | unt_info(info, transport=transport_name)
assert client.transport._credentials == creds
assert isinstance(client, client_class)
assert client.transport._host == (
"compute.googl | eapis.com{}".format(":443")
if transport_name in ["grpc", "grpc_asyncio"]
else "https://{}".format("compute.googleapis.com")
)
@pytest.mark.parametrize(
"transport_class,transport_name",
[(transports.GlobalNetworkEndpointGroupsRestTransport, "rest"),],
)
def test_global_network... |
pstrinkle/drf-coupons | coupons/tests/test_coupon_list.py | Python | apache-2.0 | 4,596 | 0.000218 | from django.contrib.auth import get_user_model
from rest_framework import status
from datetime import datetime, timedelta
from coupons.tests.base import BasicTest
class CouponListTests(BasicTest):
def setUp(self):
u = get_user_model()
u.objects.create_superuser('admin', 'john@snow.com', self.PW)... | username='admin')
response = self.client.post('/coupon', coupon, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
coupon['code_l'] = coupon['code'].lower()
coupon['repeat'] = 0
coupon['bound'] = False
self.verify_bu... | n, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
coupon['code_l'] = coupon['code'].lower()
self.verify_built(coupon, response.data)
response = self.client.get('/coupon', format='json')
self.assertEqual(response.status_code, ... |
nprapps/graeae | scrapers/seamus/models.py | Python | mit | 2,968 | 0.000674 | from collections import OrderedDict
from dateutil import parser
from itertools import groupby
from pytz import timezone
from pyquery import PyQuery
from scrapers.homepage.models import ApiEntry
import os
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class Sto... | e('UTC')).replace(tzinfo=None)
return adjusted
except ValueError:
logger.warning('Datetime for %s was naive' % | self.story_id)
return parsed
@property
def story_id(self):
"""
Get the story ID
"""
return self.element.attr('id')
@property
def title(self):
"""
Get the title
"""
return self.element.children('title').text()
@property
... |
fgaudin/aemanager | autoentrepreneur/migrations/0003_sales_limit_init.py | Python | agpl-3.0 | 6,763 | 0.007689 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
# moved to initial data
pass
def backwards(self, orm):
pass
models = {
'auth.group': {
... | efault': "''", 'max_length': '255', 'blank': 'True'}),
'creation_date': ('django.db.models.fields.DateField', [], {'null': 'True' | , 'blank': 'True'}),
'creation_help': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'freeing_tax_payment': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'... |
nfxosp/platform_external_skia | PRESUBMIT.py | Python | bsd-3-clause | 19,070 | 0.010068 | # Copyright (c) 2013 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.
"""Top-level presubmit script for Skia.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmi... | sing class name in super.
'W0613', # Unused argument.
)
# Run Pylint on only the modified python files. Unfortunately it still runs
# Pylint on the whole file instead of just the modified lines.
affected_python_files = []
for affected_file in input_api.AffectedSourceFiles(None):
affected_file_path ... | ected_file_path)
return input_api.canned_checks.RunPylint(
input_api, output_api,
disabled_warnings=pylint_disabled_warnings,
white_list=affected_python_files)
def _IfDefChecks(input_api, output_api):
"""Ensures if/ifdef are not before includes. See skbug/3362 for details."""
comment_block_sta... |
zearom32/SmartBooks | books/migrations/0013_auto_20150418_1551.py | Python | mit | 658 | 0.00304 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('books', '0012_auto_20150414_1231'),
]
operations = [
migrations.AlterField(
mod... | =models.ForeignKey(related_name=b'goods', to='books.BookInfo'),
),
migrations.AlterField(
model_name='goodsinfo',
name='seller',
| field=models.ForeignKey(related_name=b'goods', to=settings.AUTH_USER_MODEL),
),
]
|
jamfang/Agora-WebRTC-Live-Broadcasting-Demo | node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py | Python | mit | 17,013 | 0.009757 | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""GYP backend that generates Eclipse CDT settings files.
This backend DOES NOT generate Eclipse CDT projects. Instead, it generates XML
files that can be importe... | GetCompilerPath(target_list, data, options):
"""Dete | rmine a command that can be used to invoke the compiler.
Returns:
If this is a gyp project that has explicit make settings, try to determine
the compiler from that. Otherwise, see if a compiler was specified via the
CC_target environment variable.
"""
# First, see if the compiler is configured in ma... |
2mf/moto | moto/dynamodb2/models.py | Python | apache-2.0 | 15,127 | 0.001917 | from __future__ import unicode_literals
from collections import defaultdict
import datetime
import json
from moto.compat import OrderedDict
from moto.core import BaseBackend
from .comparisons import get_comparison_func
from .utils import unix_time
class DynamoJsonEncoder(json.JSONEncoder):
def default(self, obj)... | return obj.to_json()
def dynamo_json_dump(dynamo_object):
return json.dumps(dynamo_object, cls=DynamoJsonEncoder)
class DynamoType(object):
"""
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModelDataTypes
"""
def __init__(self, type_as_dict):
... | ct.values())[0]
def __hash__(self):
return hash((self.type, self.value))
def __eq__(self, other):
return (
self.type == other.type and
self.value == other.value
)
def __lt__(self, other):
return self.value < other.value
def __le__(self, other):... |
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGL/EGL/KHR/stream_producer_eglsurface.py | Python | lgpl-3.0 | 831 | 0.008424 | '''OpenGL extension KHR.stream_producer_eglsurface
This module customises the behaviour of the
OpenGL.raw.EGL.KHR.stream_ | producer_eglsurface to provide a more
Python-friendly API
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/KHR/stream_producer_eglsurface.txt
'''
from OpenGL import platform, constant, arrays
from OpenGL import extensions, wrapper
import ctypes
from OpenGL | .raw.EGL import _types, _glgets
from OpenGL.raw.EGL.KHR.stream_producer_eglsurface import *
from OpenGL.raw.EGL.KHR.stream_producer_eglsurface import _EXTENSION_NAME
def glInitStreamProducerEglsurfaceKHR():
'''Return boolean indicating whether this extension is available'''
from OpenGL import extensions
re... |
alexrudy/Cauldron | Cauldron/ext/declarative/descriptor.py | Python | bsd-3-clause | 15,071 | 0.008559 | # -*- coding: utf-8 -*-
"""
Implement the declarative descriptor.
"""
from __future__ import absolute_import
import warnings
import weakref
from .events import _DescriptorEvent, _KeywordEvent
from .utils import descriptor__get__, hybridmethod
from ...utils import ReferenceError
from ...exc import CauldronException, Ca... | self.callback = _DescriptorEvent("_propogate", r | eplace_method=False)
self._events.append(self.callback)
self._initial = initial
self._orig_initial = initial
self._initial_keyword_values = {}
self._bound = False
@property
def name(self):
"""Keyword name"""
return self._name
@name.se... |
aYukiSekiguchi/ACCESS-Chromium | native_client_sdk/src/build_tools/make_sdk_tools.py | Python | bsd-3-clause | 4,613 | 0.008454 | #!/usr/bin/env python
# Copyright (c) 2012 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.
"""Create the base (auto)updater for the Native Client SDK"""
import py_compile
import optparse
import os
import shutil
import sys... | he contents of a given directory.
The path of the resulting contents in the zipfile will match that of the
last directory name in dirpath.
Args:
dirpath: Path to directory to add to zipfile
zippath: filename of resulting zipfile
'''
zip = None
try:
zip = zipfile.ZipFile(zippath, 'w', zipfile.Z... | P_DEFLATED)
basedir = '%s%s' % (os.path.dirname(dirpath), os.sep)
for root, dirs, files in os.walk(dirpath):
if os.path.basename(root)[0] == '.':
continue # skip hidden directories
dirname = root.replace(basedir, '')
for file in files:
zip.write(os.path.join(root, file), os.pat... |
a2ohm/lagos | lagos.py | Python | mit | 2,116 | 0.003308 | #! /usr/bin/python3
# -*- coding:utf-8 -*-
# lagos
# by antoine@2ohm.fr
"""
Play a little with imap.
"""
import imaplib
import smtplib
from lib.remail import remail
from lib.redoc import redoc
import yaml
import sys
import os
import logging
# Config the log machine
logging.basicConfig(
format='\033[90m[%(lev... | except IOError:
logging.error( "Please use lagos.conf.default to set a " \
"valid lagos.conf file.")
sys.exit()
def sendMail(fromadd | r, toaddr, mss, config):
"""Send a mail.
"""
S = smtplib.SMTP(config.get('smtp_server', ''))
S.login(config.get('smtp_user', ''),
config.get('smtp_password', ''))
S.sendmail(fromaddr, toaddr, mss)
S.quit()
# Define aliases
pool = config.get('pool', '/tmp/pool/')
# Init the conne... |
scheib/chromium | third_party/wpt_tools/wpt/tools/wpt/run.py | Python | bsd-3-clause | 32,866 | 0.001826 | import argparse
import os
import platform
import sys
from distutils.spawn import find_executable
from typing import ClassVar, Type
wpt_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
sys.path.insert(0, os.path.abspath(os.path.join(wpt_root, "tools")))
from . import browser, insta... |
option_strings,
dest=argparse.SUPPRESS,
default=argparse.SUPPRESS,
help=None):
super(WptrunnerHelpAction, s | elf).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
from wptrunner import wptcommandline
wptparser = wptcommandline.create_parser(... |
MartinPyka/Parametric-Anatomical-Modeling | pam/export/to_csv.py | Python | gpl-2.0 | 4,220 | 0.001422 | """Export Module"""
import csv
import io
import logging
import zipfile
import bpy
import bpy_extras
from .. import model
from .. import pam
logger = logging.getLogger(__package__)
def getUVs(object, particle_system):
""" returns a numpy-array of uv - coordinates for a given particle-system
on a given obj... | ance matrices
* nglist: list of neural groups
* connection_list: list | of layer-based connections
"""
cmatrices = []
dmatrices = []
for c in model.CONNECTION_RESULTS:
cmatrices.append(c['c'])
dmatrices.append(c['d'])
mapping_names = get_mapping_names()
with zipfile.ZipFile(filepath, 'w', zipfile.ZIP_DEFLATED) as file:
csv_write_matrices(f... |
jdavidrcamacho/Tests_GP | 02 - Programs being tested/05 - opt initial tests/Tests1_Kernel_opt.py | Python | mit | 8,509 | 0.032554 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 14 14:49:00 2017
@author: camacho
"""
import Kernel;reload(Kernel);kl=Kernel
import Kernel_likelihood;reload(Kernel_likelihood);lk=Kernel_likelihood
import Kernel_optimization;reload(Kernel_optimization);opt=Kernel_optimization
import RV_function;reload(RV_function);RVf... | ##'
print ''
kernel_ESS7=kl.ExpSineSquared(1.7, 0.1, 7.5)
likelihood_ESS7=lk.likelihood(kernel_ESS7,x,x,y,yerr)
print 'Kernel ESS7 ->', kernel_ESS7
pri | nt 'likelihood ESS7 ->', likelihood_ESS7
optimization7=opt.committed_optimization(kernel_ESS7,x,x,y,yerr)
print 'kernel ESS7 final ->',optimization7[1]
print 'likelihood ESS7 final ->', optimization7[0]
print ''
kernel_ESS8=kl.ExpSineSquared(2.0, 0.1, 10.0)
likelihood_ESS8=lk.likelihood(kernel_ESS8,x,x,y,yerr)
print '... |
gogetdata/ggd-cli | tests/test_make_meta_recipe.py | Python | mit | 47,025 | 0.013759 | from __future__ import print_function
import os
import sys
import subprocess as sp
import pyte | st
import yaml
import tempfile
import requests
import argparse
import json
import re
from argparse import Namespace
from argparse import ArgumentParser
import glob
import contextlib
import tarfi | le
from helpers import CreateRecipe
from ggd import utils
from ggd import make_meta_recipe
import oyaml
if sys.version_info[0] == 3:
from io import StringIO
elif sys.version_info[0] == 2:
from StringIO import StringIO
#------------------------------------------------------------------------------------------... |
agripo/website | core/tests/views/test_partners.py | Python | gpl-2.0 | 3,228 | 0.001859 | from django.core.urlresolvers import reverse
from core.tests.views.base import ViewsBaseTestCase
from core.models.partners import Partner
class PartnersBaseTestCase(ViewsBaseTestCase):
def _insert_random_partners(self, quantity):
created_partners = []
for i in range(quantity):
partne... | ers_page_displays_message_if_no_partners(self):
self._assert_p | artners_page_contains('id="no_partner_to_show_message', 1)
class PartnersRightModuleTest(PartnersBaseTestCase):
def test_display_block_if_there_are_partners(self):
self._insert_random_partners(5)
response = self.client.get(reverse('home_page'))
self.assertContains(response, '"partnersCaro... |
colloquium/spacewalk | client/solaris/smartpm/smart/channel.py | Python | gpl-2.0 | 12,171 | 0.002218 | #
# Copyright (c) 2004 Conectiva, Inc.
#
# Written by Gustavo Niemeyer <niemeyer@conectiva.com>
#
# This file is part of Smart Package Manager.
#
# Smart Package Manager 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 Fou... | elif value in ("n", "no", "false", "0",
| _("n"), _("no"), _("false")):
value = Fals |
JshWright/home-assistant | homeassistant/components/switch/dlink.py | Python | apache-2.0 | 4,666 | 0 | """
Support for D-link W215 smart switch.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.dlink/
"""
import logging
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const impo... | ON: current_consumption,
ATTR_TOTAL_CONSUMPTION: total_consumption,
ATTR_TEMPERATURE: temperature
}
return attrs
@property
def current_power_watt(self):
"""Return the current power usage in Watt."""
try:
| return float(self.data.current_consumption)
except ValueError:
return None
@property
def is_on(self):
"""Return true if switch is on."""
return self.data.state == 'ON'
def turn_on(self, **kwargs):
"""Turn the switch on."""
self.data.smartplug.state = ... |
juju/python-libjuju | examples/status.py | Python | apache-2.0 | 1,149 | 0 | """
This example demonstrate how status works
"""
from juju import jasyncio
from juju import loop
import logging
| import sys
from logging import getLogger
from juju.model import Model
from juju.status import formatted_status
LOG = getLogger(__name__)
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
async def main():
model = Model()
await model.connect_current()
application = await model.deploy(
'c... | he status to observe the evolution
# during a minute
for i in range(12):
try:
# By setting raw to True, the returned
# entry contains a FullStatus object with
# all the available status data.
# status = await model.status(raw=True)
status = awa... |
marduk191/plugin.video.movie25 | resources/libs/adventure/nationalgeo.py | Python | gpl-3.0 | 11,061 | 0.027574 | import urllib,urllib2,re,cookielib,os,sys
import xbmc, xbmcgui, xbmcaddon, xbmcplugin
from resources.libs import main
#Mash Up - by Mash2k3 2012.
from t0mm0.common.addon import Addon
from resources.universal import playbackengine, watchhistory
addon_id = 'plugin.video.movie25'
selfAddon = xbmcaddon.Addon(id=addon_id)... | 72,art+'/nga2.png')
main.addDir('Reptiles','http://video.nationalgeograph | ic.com/video/animals/reptiles-animals/',72,art+'/nga2.png')
main.GA("NationalGeo","NGA")
elif murl =='ngk':
main.addDir('Animals & Pets','http://video.nationalgeographic.com/video/kids/animals-pets-kids/',72,art+'/ngk.png')
main.addDir('Cartoons & Shows','http://video.nationalgeographic.com... |
rahulnadella/Sort_Algorithms | countingsort/countingsort.py | Python | bsd-2-clause | 1,805 | 0.004432 | """
Counting sort is applicable when each input is known to belong to a particular
set, S, of possibilities. The algorithm runs in O(|S| + n) time and O(|S|)
memory where n is the length of the input. It works by creating an integer array
of size |S| and using the ith bin to count the occurrences of the ith member of
S... | Each bucket's key represents a value in the
array. So for each bucket, from smallest key to largest,
add the index of the bucket to the input array and
decrease the counter in said bucket by one; until the
counter is zero.
"""
def sort(array):
maximum = max(array)
minimum = min(array)
count_arra... | al - minimum] += 1
sorted_array = []
for i in range(minimum, maximum + 1):
if count_array[i - minimum] > 0:
for j in range(0, count_array[i - minimum]):
sorted_array.append(i)
return sorted_array
|
Snifer/BurpSuite-Plugins | faraday/plugins/repo/burp/plugin.py | Python | gpl-2.0 | 8,375 | 0.01397 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Faraday Penetration Test IDE - Community Version
Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
See the file 'doc/LICENSE' for the license information
'''
from __future__ import with_statement
from plugins import core
from model import api
import re
im... | t__(self)
self.id = "Burp"
self.name = "Burp XML Output Plugin"
self.plugin_version = "0.0.1"
self.version = "1.5.18 BurpPro"
self.framework_version = "1.0.0"
self.options = None
self._current_output = None
self.t... | current_path
self._output_file_path = os.path.join(self.data_path,
"burp_output-%s.xml" % self._rid)
def parseOutputString(self, output, debug = False):
parser = BurpXmlParser(output)
for item in parse... |
deepmind/sonnet | sonnet/src/conv_transpose.py | Python | apache-2.0 | 16,137 | 0.002727 | # Copyright 2019 The Sonnet 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 applicable l... | or) or isinstance(v2, tf.Tensor):
return func(v1, v2)
else:
return [func(x, y) for (x, y) in zip(v1, v2)]
class ConvNDTranspose(base.Module):
"""An N-dimensional transpose convolut | ional module.
Attributes:
w: Weight variable. Note is `None` until module is connected.
b: Biases variable. Note is `None` until module is connected.
input_shape: The input shape of the first set of inputs. Note is `None`
until module is connected.
"""
def __init__(self,
num... |
JoeHsiao/bioformats | components/xsd-fu/python/generateDS/generateDS.py | Python | gpl-2.0 | 169,830 | 0.003645 | #!/usr/bin/env python
"""
Synopsis:
Generate Python classes from XML Schema definition.
Input is read from in_xsd_file or, if "-" (dash) arg, from stdin.
Output is written to files named in "-o" and "-s" options.
Usage:
python generateDS.py [ options ] <xsd_file>
python generateDS.py [ options ] -
O... | NOT LIMITED TO THE WARRANTIES OF
## MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
## IN NO EVENT SHALL THE AUTHO | RS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
## CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
## TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
## SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#from __future__ import generators # only needed for Python 2.2
import sy... |
Hack4Eugene/Hack4Cause2016 | src/bobby-drop-tables/15thnight/db_create.py | Python | mit | 64 | 0.03125 | from __init__ import db
db.create_all()
|
db.session.commi | t() |
sangwook236/general-development-and-testing | sw_dev/python/rnd/test/probabilistic_graphical_model/gpflow/gpflow_multiclass_classification.py | Python | gpl-2.0 | 4,520 | 0.029867 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys, csv
import numpy as np
from scipy.cluster.vq import kmeans
import tensorflow as tf
from matplotlib import pyplot as plt
import matplotlib
import gpflow
def plot(m):
f = plt.figure(figsize=(12, 6))
a1 = f.add_axes([0.05, 0.05, 0.9, 0.6])
a2 = f.add_axes([0.0... | ead_value().flatten() == i]
points, = a3.plot(x, x * 0, '.')
color = points.get_color()
a1.plot(xx, mu[:,i], color=color, lw=2)
a1.plot(xx, mu[:,i] + 2 * np.sqrt(var[:,i]), '--', color=color)
a1.plot(xx, mu[:,i] - 2 * np.sqrt(var[:,i]), '--', co | lor=color)
a2.plot(xx, p[:,i], '-', color=color, lw=2)
a2.set_ylim(-0.1, 1.1)
a2.set_yticks([0, 1])
a2.set_xticks([])
# REF [site] >> https://gpflow.readthedocs.io/en/latest/notebooks/multiclass.html
def sparse_variational_gaussian_approximation_example():
#%matplotlib inline
plt.style.use('ggplot')
np.rando... |
sdague/home-assistant | homeassistant/auth/providers/homeassistant.py | Python | apache-2.0 | 10,935 | 0.000823 | """Home Assistant auth provider."""
import asyncio
import base64
from collections import OrderedDict
import logging
from typing import Any, Dict, List, Optional, Set, cast
import bcrypt
import voluptuous as vol
from homeassistant.const import CONF_ID
from homeassistant.core import HomeAssistant, callback
from homeass... | 4encode(hashed)
return hashed
def add_auth(self, username: str, password: str) -> None:
"""Add a new authenticated use | r/pass."""
username = self.normalize_username(username)
if any(
self.normalize_username(user["username"]) == username for user in self.users
):
raise InvalidUser
self.users.append(
{
"username": username,
"password": s... |
alirizakeles/tendenci | tendenci/apps/versions/models.py | Python | gpl-3.0 | 2,293 | 0.001744 | # models.py
from dateutil.parser import parse
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.fields import GenericForeignKey
import json
from te... | me + "_id"] = data[field_name]
elif unicode(f.get_internal_type()) == 'DateTimeField':
obj_data[field_name] = parse(data[f | ield_name])
else:
obj_data[field_name] = data[field_name]
obj = self.get_object().__class__(**obj_data)
return obj
def get_object_version_url(self):
try:
return self.get_version_object().get_version_url(self.hash)
except:
... |
jawilson/Flexget | flexget/tests/test_content_size.py | Python | mit | 4,349 | 0.00092 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import pytest
@pytest.mark.usefixtures('tmpdir')
class TestTorrentSize(object):
config = """
tasks:
test_min:
mock:
- {tit... | k:
# content_size should not be read for this directly, as it is a torrent file
- {title: 'test', location: 'test.torrent'}
"""
@pytest.mark.filecopy('test.torrent', '__tmp__/test.file')
def test_min(self, execute_task):
"""Content Size: torrent with min size"""
... | in')
entry = task.find_entry('rejected', title='test')
assert entry, 'should have rejected, minimum size'
assert entry['content_size'] == 0, \
'content_size was not detected'
@pytest.mark.filecopy('test.torrent', '__tmp__/test.file')
def test_max(self, execute_task):
... |
SrNetoChan/QGIS | tests/src/python/test_qgslayoutmanager.py | Python | gpl-2.0 | 10,513 | 0.000951 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsLayoutManager.
.. note:: 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.
"""
... | project = QgsProject()
manager = QgsLayoutManager(project)
| # add a bunch of layouts
layout = QgsPrintLayout(project)
layout.setName('test layout')
layout2 = QgsPrintLayout(project)
layout2.setName('test layout2')
layout3 = QgsPrintLayout(project)
layout3.setName('test layout3')
manager.addLayout(layout)
manager.... |
williballenthin/python-sdb | scripts/sdb_dump_patch.py | Python | apache-2.0 | 3,397 | 0.000589 | import sys
import logging
import hexdump
import vstruct
import vivisect
import envi
import envi.archs.i386 as x86
import envi.archs.amd64 as x64
import sdb
from sdb import SDB_TAGS
from sdb_dump_common import SdbIndex
from sdb_dump_common import item_get_child
from sdb_dump_common import item_get_children
logging.b... | atch = item_get_child(shim_ref, SDB_TAGS.TAG_PATCH)
name_ref = item_get_child(patch, SDB_TAGS.TAG_NAME)
name = index.get_string(name_ref.value.reference)
if name != patch_name:
continue
bits = item_get_child(patch, SDB_TAGS.TAG_PATCH_BITS)
dum... | t_child(patch, SDB_TAGS.TAG_NAME)
name = index.get_string(name_ref.value.reference)
if name == patch_name:
bits = item_get_child(patch, SDB_TAGS.TAG_PATCH_BITS)
dump_patch(bits, arch=ARCH_32)
def main():
import sys
return sys.exit(_main(*sys.argv[1:]))
if __name__ ==... |
nttks/edx-platform | cms/djangoapps/contentstore/views/course.py | Python | agpl-3.0 | 75,601 | 0.00328 | """
Views related to operations on course objects
"""
import copy
import json
import logging
import random
import string # pylint: disable=deprecated-module
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.core.u... | oth be set; else a HttpBadResponseRequest is returned.
For each of these operations, the requesting user must have access to the course;
else a PermissionDenied error is returned.
GET
json: return json representing information about the notification (action, state, etc)
DELETE
json: re... | ication
PUT
Raises a NotImplementedError.
POST
Raises a NotImplementedError.
"""
# ensure that we have a course and an action state
if not course_key_string or not action_state_id:
return HttpResponseBadRequest()
response_format = request.REQUEST.get('format', 'html')
... |
JTarball/tetherbox | docker/app/app/backend/manage.py | Python | isc | 255 | 0 | #!/usr/bin/env | python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.base")
from django.core.management import execute_from_command_line
|
execute_from_command_line(sys.argv)
|
ral99/whodat | tests/unit_tests/wsgi_test.py | Python | bsd-3-clause | 5,007 | 0.002796 | import unittest
from os.path import dirname, join, realpath
from whodat.extension import *
from whodat.handler import *
from whodat.http import *
from whodat.wsgi import *
### Extensions ###
class ExtensionA(Extension):
def __call__(self, app):
setattr(app, 'one', 1)
def process_request(self, reques... | us, '404 Not Found')
def test_internal_server_error(self):
request = HTTPRequest.get(path_info='/error/')
response = self.app.handle_request(request)
self.assertEqual(response.text, '5xx')
self.assertEqual(response.st | atus, '500 Internal Server Error')
def test_method_not_allowed(self):
request = HTTPRequest.put(path_info='/')
response = self.app.handle_request(request)
self.assertEqual(response.text, 'Error 405')
self.assertEqual(response.status, '405 Method Not Allowed')
def test_static_fi... |
paulfitz/sheetsite | sheetsite/destination/install_local_soup.py | Python | mit | 666 | 0.003003 | import subprocess
# Hey this is embarrassing I'll remove it soon I promise.
# I mean, maybe. Or I'll leave it malingering for years.
def apply(params, state):
subprocess.check_output(["cp",
state['sqlite_file'],
"/srv/git/datacommons_manitoba/production.... | process.check_output(["/srv/git/datacommons_manitoba/rebuild.sh"])
ok = True
break
except subprocess.CalledProcessError:
pass
| if not ok:
raise subprocess.CalledProcessError("rebuild sadness")
return True
|
BlackstoneEngineering/yotta | yotta/test/cli/owners.py | Python | apache-2.0 | 2,645 | 0.002268 | #!/usr/bin/env python
# Copyright 2014 ARM Limited
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
# standard library modules, , ,
import unittest
import os
import tempfile
# internal modules:
from yotta.lib.fsutils import rmRf
from . import cli
Test_Module_JSON = '''{
"name": ... | nd@example.com'], cwd=self.test_dir)
if statuscode != 0:
self.assertTrue((stdout+stderr).find('login required' | ) != -1)
def test_rmOwner(self):
stdout, stderr, statuscode = cli.run(['-n', 'owners', 'rm', 'friend@example.com'], cwd=self.test_dir)
if statuscode != 0:
self.assertTrue((stdout+stderr).find('login required') != -1)
if __name__ == '__main__':
unittest.main()
|
marcoantoniooliveira/labweb | tests/config.py | Python | bsd-3-clause | 5,326 | 0.001314 | #!/usr/bin/env python
import os
import django
from django.conf import settings, global_settings
import oscar
def configure():
if not settings.configured:
from oscar.defaults import OSCAR_SETTINGS
# Helper function to extract absolute path
location = lambda x: os.path.join(
os... | },
},
'INSTALLED_APPS': [
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessi | ons',
'django.contrib.sites',
'django.contrib.flatpages',
'django.contrib.staticfiles',
'compressor',
'tests._site.model_tests_app', # contains models we need for testing
'tests._site.myauth',
# Use a custo... |
xpclove/autofp | diffpy/pyfullprof/runfullprof.py | Python | gpl-3.0 | 15,164 | 0.004616 | #!/usr/bin/env python
##############################################################################
#
# diffpy.pyfullprof by DANSE Diffraction group
# Simon J. L. Billinge
# (c) 2010 Trustees of the Columbia University
# in the City of New York. All rights reserve... |
""" read the output of FullProf output file
1. Last line contains "=> END"
- check Chi2: is last Chi2 = "NaN"? "Chi2:-NaN,
- refined output
2. otherwise to 1
a) "Error During Opening File" + file_name : terminate the program
b) "NO REFLECTI... | OUND": as Chi2 = NaN
algorithm:
(1) split Chi2 line with ":"
return 1: good refinement
0 not refined
-1: setup error
-2: excessive peak overlap
-3: singular matrix
"""
result = 0
# 1. Exception!
... |
commaai/openpilot | selfdrive/loggerd/tests/test_uploader.py | Python | mit | 5,365 | 0.010438 | #!/usr/bin/env python3
import os
import time
import threading
import unittest
import logging
import json
from selfdrive.swaglog import cloudlog
import selfdrive.loggerd.uploader as uploader
from common.xattr import getxattr
from selfdrive.loggerd.tests.loggerd_tests_common import UploaderTestCase
class TestLogHand... | seg2_nums = [5, 50, 51]
for i in seg2_nums:
self.seg_dir = self.seg_format2.format(i)
self.gen_files(boot=False)
exp_order = self.gen_order(seg1_nums, seg2_nums, boot=False)
self.start_thread()
# allow enough time that files could upload twice if there is a bug in the logic
time.sle... | (5)
self.join_thread()
self.assertTrue(len(log_handler.upload_ignored) == 0, "Some files were ignored")
self.assertFalse(len(log_handler.upload_order) < len(exp_order), "Some files failed to upload")
self.assertFalse(len(log_handler.upload_order) > len(exp_order), "Some files were uploaded twice")
... |
rbtying/Companion-Cube | neato_node/nodes/neato.py | Python | gpl-3.0 | 6,453 | 0.006974 | #!/usr/bin/env python
# ROS node for the Neato Robot Vacuum
# Copyright (c) 2010 University at Albany. All right 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 ret... | vel[1])))
# ask for the next scan while we finish processing stuff
self.robot.requestScan()
# now update position in | formation
dt = (scan.header.stamp - then).to_sec()
then = scan.header.stamp
d_left = (left - encoders[0])/1000.0
d_right = (right - encoders[1])/1000.0
encoders = [left, right]
dx = (d_left+d_right)/2
dth = (d_right-d_left... |
timstaley/pysovo | integration_tests/readmail_test.py | Python | bsd-2-clause | 1,781 | 0.005053 | #!/usr/bin/env python
import time
import sys
from pysovo.comms import email
from pysovo.comms.email import keys as acc_keys
from pysovo.local import contacts
import base64
from imbox import Imbox
def make_imbox(account):
imbox = Imbox('imap.gmail.com',
account[acc_keys.username],
... | nt[acc_keys.username],
unread=True)
print "Will they remain marked? Got new list of length:", len(match_uids)
print "Now mark as seen..."
for uid in match_uids:
imbox.mark_seen(uid)
match_uids = imbox.query_uids(sent_fro | m=account[acc_keys.username],
unread=True)
print "Remaining unseen:", len(match_uids)
imbox.logout()
if __name__ == "__main__":
main()
|
tridc/django_local_library | catalog/migrations/0002_bookinstance_borrower.py | Python | gpl-3.0 | 661 | 0.001513 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-10 09:46
from __future__ import unicode_literals
from django.conf imp | ort settings
from django.db import migrations, models
import django.db.models.deleti | on
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('catalog', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='bookinstance',
name='borrower',
field=models.Fo... |
TissueMAPS/TmLibrary | tmlib/workflow/imextract/cli.py | Python | agpl-3.0 | 1,460 | 0.000685 | # TmLibrary - TissueMAPS library for distibuted image analysis routines.
# Copyright (C) 2016 Markus D. Herrmann, University of Zurich and Robin Hafen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Softwa... | of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from tmlib.utils import notimplemented
from tmlib.utils import assert_type
from tmlib.workflow.cli import WorkflowStepCLI
logger = logging.getLogger(__name__)
class Imextra | ct(WorkflowStepCLI):
@assert_type(api_instance='tmlib.workflow.imextract.api.ImageExtractor')
def __init__(self, api_instance, verbosity):
'''
Parameters
----------
api_instance: tmlib.workflow.metaextract.api.ImageExtractor
instance of API class to which processing ... |
eduNEXT/edunext-platform | import_shims/studio/contentstore/views/checklists.py | Python | agpl-3.0 | 410 | 0.009756 | """Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
# pylint: disable=redefined-builtin,wrong-import-position,wi | ldcard-import,useless-suppression,line-too-long
from import_shims.warn import warn_deprecated_import
warn_deprecated_import('contentstore.views.checklists', 'cms.djangoapps.contentstore.views.checklists')
from cms.djangoapps.contentstore.views.checklists | import *
|
mmnelemane/nova | nova/tests/unit/scheduler/test_scheduler_options.py | Python | apache-2.0 | 5,307 | 0.001131 | # Copyright 2011 OpenStack Foundation
# 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 requ... | old_data | , jdata)
self.assertEqual(data, fake.get_configuration('foo.json'))
self.assertTrue(fake.file_was_loaded)
|
brianrock/brianrock-ringo | main.py | Python | apache-2.0 | 1,353 | 0.011086 | #!/usr/bin/env python
#
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | cense.
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), 'third_party'))
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import handlers.intro
import handlers.oauth
import handlers.play
import handlers.leaderboard
import handlers.poll
def main():
app... | ('/', handlers.intro.IntroHandler),
('/oauth/init/', handlers.oauth.OAuthInitHandler),
('/oauth/callback/', handlers.oauth.OAuthCallbackHandler),
('/worker/poll/', handlers.poll.PollHandler),
('/play/', handlers.play.PlayHandler),
('/leaderboard/', handlers.leaderboard.LeaderboardHandler)
], de... |
FedeMPouzols/Savu | savu/test/travis/plugin_tests/filter_tests/monitor_correction_test.py | Python | gpl-3.0 | 1,328 | 0.000753 | # Copyright 2014 Diamond Light Source Ltd.
#
# 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 t... | are
# 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.
"""
.. module:: monitor_correction_test
:platform: Unix
:synops... | tu
from savu.test.travis.framework_tests.plugin_runner_test import \
run_protected_plugin_runner
class MonitorCorrectionTest(unittest.TestCase):
def test_monitor_correction(self):
data_file = tu.get_test_data_path('mm.nxs')
process_file = tu.get_test_process_path('monitor_correction_test.nxs... |
sdague/home-assistant | homeassistant/components/nest/sensor_legacy.py | Python | apache-2.0 | 6,398 | 0.000781 | """Support for Nest Thermostat sensors for the legacy API."""
import logging
from homeassistant.const import (
CONF_MONITORED_CONDITIONS,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
PERCENTAGE,
STATE_OFF,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from . import CONF_SENSORS, DATA_NEST, DATA_NES... | ]
for structure, device in nest.smoke_co_alarms():
all_sensors += [
NestBasicSensor(structure, device, variable)
for variable in conditions
| if variable in PROTECT_SENSOR_TYPES
]
structures_has_camera = {}
for structure, device in nest.cameras():
structures_has_camera[structure] = True
for structure in structures_has_camera:
all_sensors += [
NestBasicSensor(structure, None, variabl... |
SpectralAngel/django-select2-forms | select2/models/descriptors.py | Python | bsd-2-clause | 8,496 | 0.005767 | import django
from django.db import router
from django.db.models import signals
try:
from django.db.models.fields.related import ReverseManyRelatedObjectsDescriptor
except ImportError:
from django.db.models.fields.related import ManyToManyDescriptor as ReverseManyRelatedObjectsDescriptor
from ..utils import cached... | else:
new_ids.add(obj)
db = router.db_for_write(self.through, instance=self.instance)
vals = self.through._default_manager.using(db).values_ | list(target_field_name, flat=True)
vals = vals.filter(**{
source_field_name: getattr(self, '_pk_val', getattr(self, '_fk_val', self.instance.pk)),
'%s__in' % target_field_name: new_ids,
})
new_ids = new_ids - set... |
pbmanis/acq4 | acq4/modules/Console/__init__.py | Python | mit | 60 | 0.016667 | from __future__ import print_ | fun | ction
from .Console import * |
Vdragon/git-cola | cola/ordered_dict.py | Python | gpl-2.0 | 8,796 | 0.001478 | """Backport of OrderedDict() class
Runs on Python 2.4, 2.5, 2.6, 2.7, 3.x and pypy.
Passes Python2.7's test suite and incorporates all the latest updates.
Copyright 2009 Raymond Hettinger, released under the MIT License.
http://code.activestate.com/recipes/576693/
"""
from __future__ import absolute_import, division... | key]
elif hasattr(other, 'keys'):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
| self[key] = value
__update = update # let subclasses override update without breaking __init__
__marker = object()
def pop(self, key, default=__marker):
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, oth... |
tomato42/tlsfuzzer | scripts/test-sig-algs-renegotiation-resumption.py | Python | gpl-2.0 | 43,213 | 0.000787 | # Author: Hubert Kario, (c) 2021
# Released under Gnu GPL v2.0, see LICENSE file for details
from __future__ import print_function
import traceback
import sys
import getopt
from itertools import chain
from random import sample
from tlsfuzzer.runner import Runner
from tlsfuzzer.messages import Co | nnect, ClientHelloGenerator, \
ClientKeyExchangeGenerator, ChangeCipherSpecGenerator, \
FinishedGenerator, ApplicationDataGenerator, AlertGenerator, \
ResetHandshakeHashes, Close
from tlsfuzzer.expect import ExpectServerHello, ExpectCertificate, \
ExpectServerHelloDone, ExpectChangeCiphe... | uite, AlertLevel, AlertDescription, \
GroupName, ExtensionType
from tlslite.extensions import SupportedGroupsExtension, \
SignatureAlgorithmsExtension, SignatureAlgorithmsCertExtension
from tlsfuzzer.utils.lists import natural_sort_keys
from tlsfuzzer.helpers import SIG_ALL
version = 2
def help_msg(... |
URXtech/pex | tests/test_package.py | Python | apache-2.0 | 1,829 | 0.013669 | # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import pytest
from pkg_resources import Requirement, parse_version
from pex.pa | ckage import EggPackage, SourcePackage
def test_source_packages():
for ext in ('.tar.gz', '.tar', '.tgz', '.zip', '.tar.bz2'):
sl = SourcePackage('a_p_r-3.1.3' + ext)
assert sl._name == 'a_p_r'
assert sl.name == 'a-p-r'
a | ssert sl.raw_version == '3.1.3'
assert sl.version == parse_version(sl.raw_version)
for req in ('a_p_r', 'a_p_r>2', 'a_p_r>3', 'a_p_r>=3.1.3', 'a_p_r==3.1.3', 'a_p_r>3,<3.5'):
assert sl.satisfies(req)
assert sl.satisfies(Requirement.parse(req))
for req in ('foo', 'a_p_r==4.0.0', 'a_p_r>4.0.0', 'a... |
vanam/clustering | clustering_system/corpus/MetaMmCorpusWrapper.py | Python | mit | 406 | 0 | from gensim.corpora import MmCorpus
from gensim.utils import unpickle
class MetaMmCorpusWrapper:
"""Wrapper which l | oads MM corpus with metadata."""
def __init__(self, filename):
se | lf.corpus = MmCorpus(filename)
self.metadata = unpickle(filename + ".metadata.cpickle")
def __iter__(self):
for i, doc in enumerate(self.corpus):
yield doc, self.metadata[i]
|
amitdhiman000/dais | politics/models.py | Python | apache-2.0 | 2,210 | 0.026697 | from django.db import models
from user.models import State
from django.utils.translation import ugettext as _
## debug
from pprint import pprint
# Create your models here.
class Party(models.Model):
short_name = models.CharField(max_length=10, default='***')
full_name = models.CharField(max_length=50, default='****... | ader, on_delete=models.CASCADE)
constituency = models.ForeignKey(LegislativeConstituency, on_delete=mo | dels.CASCADE)
class Meta:
verbose_name = _('MemberLegislative')
verbose_name_plural= _('MemberLegislatives')
|
volpino/Yeps-EURAC | scripts/scramble/scripts/DRMAA_python-macosx.py | Python | mit | 1,938 | 0.028896 | import os, sys, shutil
if "SGE_ROOT" not in os.environ:
print "scramble(): Please set SGE_ROOT to the path of your SGE installation"
print "scramble(): before scrambling DRMAA_python"
sys.exit(1)
# change back to the build dir
if os.path.dirname( sys.argv[0] ) != "":
os.chdir( os.path.dirname( sys.arg... | removing dir:", dir
shutil.rmtree( dir )
# patch
file = "setup.py"
print "scramble(): Patching", file
if not os.access( "%s.orig" %file, os.F_OK ):
shutil.copyfile( file, "%s.orig" %file )
i = open( "%s.orig" %file, "r" )
o = open( file, | "w" )
for line in i.readlines():
if line == 'SGE6_ROOT="/scratch_test02/SGE6"\n':
line = 'SGE6_ROOT="%s"\n' % os.environ["SGE_ROOT"]
if line.startswith('link_args ='):
line = 'link_args = [ "-L%s" % os.path.join(SGE6_ROOT, "lib", SGE6_ARCH), "-ldrmaa" ]\n'
print >>o, line,
i.close()
o.close... |
grv87/thesis-code | table_count_of_transactions.py | Python | gpl-3.0 | 1,922 | 0.017942 | #!/usr/bin/env python3
# -*- coding, utf-8 -*-
# TODO
# TODO
# Copyright © 2014 Василий Горохов-Апельсинов
# This file is part of code for my bachelor's thesis.
#
# Code for my bachelor's thesis is free software: you can redistribute
# it and/or modify it under the terms of the GNU General Public License
# as publi... | y,
hour,
COUNT(id) AS "'''+tableName+'''"
FROM
(
SELECT
day::date,
hour
FROM
generate_series((SELECT min(date_trunc('day', moment)) FROM "MICEX_SBER"), (SELECT max(date_trunc('day', moment)) FROM "MICEX_SBER"), '1 day'::interval) AS days(day),
generate_series(0, 23) AS hours(hour)
) AS in... | ment)
GROUP BY
day, hour
ORDER BY
day, hour
''', conn)
df = df.pivot(index = 'hour', columns = 'day', values = tableName)
print('Writing output to `{:s}`...'.format(outFileName))
df.to_csv(outFileName, sep = ';')
print('Done.')
del conn
|
emailweixu/Paddle | paddle/capi/examples/model_inference/sequence/trainer_config.py | Python | apache-2.0 | 420 | 0 | from paddle.trainer_ | config_helpers import *
WORD_DIM = 3000
sentence = data_layer(name='sentence', size=WORD_DIM)
sentence_embedding = embedding_layer(
input=sentence,
size=64,
param_attr=ParameterAttribute(
initial_max=1.0, initial_min=0.5))
| lstm = simple_lstm(input=sentence_embedding, size=64)
lstm_last = last_seq(input=lstm)
outputs(fc_layer(input=lstm_last, size=2, act=SoftmaxActivation()))
|
dstenb/pylaunchr-netflix | netflix/data/__init__.py | Python | mit | 1,529 | 0.000654 | from .genre import NetflixGenres
from .search import NetflixSearchStore
from ..utils import netflix_url
class NetflixTitle(object):
def __init__(self, title, title_id, year, maturity, duration, description,
background_url):
self.title = title
self.title_id = title_id
self.year... | ar = year
self.duration = duration
self.boxart_url = boxart_url
self.url = self.watch_url()
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
def __repr__(self):
return "Net | flixTitleLink(%s)" % str(self.title)
def title_url(self):
return netflix_url("title/" + str(self.title_id))
def watch_url(self):
return netflix_url("watch/" + str(self.title_id))
class NetflixData(object):
def __init__(self, handler):
self.search = NetflixSearchStore(handler)
... |
babyliynfg/cross | tools/project-creator/Python2.6.6/Lib/lib2to3/fixes/fix_exec.py | Python | mit | 1,016 | 0 | # Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Fixer for exec.
This converts usages of the exec statement into calls to a built-in
exec() function.
exec code in ns1, ns2 -> exec(code, ns1, ns2)
"""
# Local imports
from .. import pytree
from .. imp... | s = [a.clone()]
args[0].prefix = ""
if b is not None:
args.extend([Comma(), b.clone()])
if c is not None:
args.extend([Comma(), c.clone()])
return Call(Name(u"exec | "), args, prefix=node.prefix)
|
tensorflow/tensorflow | tensorflow/python/distribute/v1/input_lib.py | Python | apache-2.0 | 16,205 | 0.007097 | # Copyright 2021 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... | ributedIteratorV1(self._input_workers, iterators,
self._strategy, cardinality, |
self._enable_get_next_as_optional)
iterator._element_spec = self._element_spec # pylint: disable=protected-access
# When async eager is enabled, sometimes the iterator may not finish
# initialization before passing to a multi device function, add a sync point
# he... |
schalkneethling/snippets-service | snippets/base/tests/test_simple_dict_cache.py | Python | mpl-2.0 | 27,353 | 0.000585 | # -*- coding: utf-8 -*-
# FROM https://github.com/mozilla/bedrock/blob/master/bedrock/base/tests/test_simple_dict_cache.py
# Tests for our custom local memory cache backend that does not use pickle
# and instead uses a simple dict for in-memory storage. These were adapted
# from the cache backend tests in Django itse... | mport compress, decompress
value = 'value_to_be_compressed'
compressed_value = compress(value.encode())
# Test set
cache.set('binary1', compressed_value)
compressed_res | ult = cache.get('binary1')
self.assertEqual(compressed_value, compressed_result)
self.assertEqual(value, decompress(compressed_result).decode())
# Test add
cache.add('binary1-add', compressed_value)
compressed_result = cache.get('binary1-add')
self.assertEqual(compressed... |
akintolga/superdesk-aap | server/aap/publish/formatters/aap_newscentre_formatter_test.py | Python | agpl-3.0 | 9,537 | 0.002621 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014, 2015 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import ... | key',
'unique_id': '1',
'type': 'text',
'body_html': '<p>The story body line 1<br>Line 2</p>'
'<p>abcdefghi abcdefghi abcdefghi abcdefghi abcdefghi abcdefghi abcde | fghi abcdefghi more</p>',
'word_count': '1',
'priority': 1
}
subscriber = self.app.data.find('subscribers', None, None)[0]
f = AAPNewscentreFormatter()
seq, item = f.format(article, subscriber)[0]
item = json.loads(item)
expected = ' By joe\r\... |
TeamLab/Gachon_CS50_Python_KMOOC | code/11/finally_exception.py | Python | mit | 209 | 0 | for i in range(0, 10):
try:
result = 10 // i
print(i, "------", result)
except ZeroDivisi | onError:
print("Not divided by 0")
finally:
| print("종료되었습니다.")
|
bospetersen/h2o-3 | h2o-py/tests/testdir_algos/glm/pyunit_NOFEATURE_getLambdaModel_mediumGLM.py | Python | apache-2.0 | 1,335 | 0.040449 | import sys
sys.path.insert(1, "../../../")
import h2o, tests
import random
def getLambdaModel(ip,port):
print("Read data")
prostate = h2o.import_file(path=h2o.locate("smalldata/logreg/prostate.csv"))
myX = ["AGE","RACE","DPROS","DCAPS","PSA","VOL","GLEASON"]
myY = "CAPSULE"
family = random.choice(["gaussian... | print("this model should be same as the one above:")
m2 = h2o.getGLMLambdaModel(model.models(random.randint(0,len(model.models()-1)),Lambda=Lam | bda))
m2.show()
assert m1==m2, "expected models to be equal"
if __name__ == "__main__":
tests.run_test(sys.argv, getLambdaModel)
|
dokato/connectivipy | connectivipy/mvar/fitting.py | Python | bsd-2-clause | 9,963 | 0.001305 | # -*- coding: utf-8 -*-
#! /usr/bin/env python
from __future__ import absolute_import
import numpy as np
from six.moves import range
def mvar_gen(Acf, npoints, omit=500):
"""
Generating data point from MVAR coefficiencs matrix *Acf*.
Args:
*Acf* : numpy.array
array in shape of (p,k,k) whe... | shape[1]-r)
zy = y.take(idxs, axis=1, mode='wrap')
cov[:, :, r] = np.dot(x[:, :N-r], zy[:, :N-r].T)
if norm:
kv = cov/(N-1)
else:
kv = cov
if p == 0:
kv = np.squeeze(kv)
return kv
def vieiramorf(y, pmax=1):
"""
Compute multichannel autoregresive ... | tr) for multitrial
k - nr of channels, n -data points, tr - nr of trials
*pmax*: int >0
model order
Returns:
*Ar* : np.array
matrix with parameters matrix (p, k, k) where p - model order,
k - nr of channels
*Vr* : np.array
prediction error matrix ... |
feltnerm/blog | publishconf.py | Python | mit | 620 | 0.004839 | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
DEVELOP = False
SITEURL = 'http://blog.feltnerm.com'
FE... | L
FEED_ATOM = 'feeds/atom.xml'
FEED_RSS = 'feeds/rss.xml'
FEED_ALL_ATOM = 'feeds/all.atom.xml'
FEED_ALL_ | RSS = 'feeds/all.rss.xml'
RELATIVE_URLS = False
DELETE_OUTPUT_DIRECTORY = True
# Following items are often useful when publishing
#DISQUS_SITENAME = ""
#GOOGLE_ANALYTICS = ""
|
adrienpacifico/openfisca-france-data | openfisca_france_data/debugger.py | Python | agpl-3.0 | 20,788 | 0.009958 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redist... | onsumers).union(set(column.consumers)))
# column_names = list(set(parameters).union(set(consumers)))
# self.columns_to_fetch = column_names
# self.variable_consumers = list(set(consumers))
self.variable_parameters = list(set(parameters))
self.column | s_to_fetch = list(set(parameters))
def build_openfisca_data_frames(self):
column_names = self.columns_to_fetch
for column in column_names:
assert column in survey_scenario.tax_benefit_system.column_by_name.keys()
data_frame_by_entity_key_plural = survey_scenario.create_data_fram... |
Gabotero/GNURadioNext | gr-digital/python/ofdm_receiver.py | Python | gpl-3.0 | 7,942 | 0.009192 | #!/usr/bin/env python
#
# Copyright 2006-2008 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your opt... | 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 GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
import math
from numpy import fft
from gnuradio import gr
from gnuradio import analog
from gnuradio import blocks
from gnuradio import filter... |
ctmyers/sign | plugins/time/time.py | Python | mit | 380 | 0.002632 | from yapsy.IPlugin import IPlugin
from manager.message impor | t Message
import protocol.control as control
import schedule
class Time(IPl | ugin, Message):
def __init__(self):
IPlugin.__init__(self)
Message.__init__(self)
self.text = control.SPEED_1 + '\x0B9 \x0B8' + control.NEW_LINE + control.CALL_TIME
self.schedule = schedule.every(3).hours
|
lotharwissler/bioinformatics | python/generic/flat-split-by-lines.py | Python | mit | 3,166 | 0.02969 | #!/usr/bin/python
import os, sys # low level handling, such as command line stuff
import string # string methods available
import getopt # comand line argument handling
from low import *
# =============================================================================
def show_help( ):
""" displays th... | fies the presence of all necessary arguments and returns the data dir """
if len ( sys.argv ) == 1:
print >> sys.stderr, "no | arguments provided."
show_help()
try: # check for the right arguments
keys, values = getopt.getopt( sys.argv[1:], "hf:i:l:" )
except getopt.GetoptError:
print >> sys.stderr, "invalid arguments provided."
show_help()
args = {}
for key, value in keys:
if key == '-f': args['file'] = valu... |
hopr/hopr | hopr/tool/test_run.py | Python | gpl-3.0 | 5,871 | 0.003407 | # -*- coding: utf-8 -*-
#
# This file is part of hopr: https://github.com/hopr/hopr.
#
# Hopr 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 ve... | 'log_file': 'log.txt',
'config_dir': '',
'print_keymap': False,
}, vars(x))
class TestRun(ut.TestCase):
def setUp(self):
params = dict(event_parser=MagicMock(name='parser'),
event_wrapper=Ma | gicMock(name='event_wrapper'),
find_keyboards=MagicMock(name='find_keyboards'),
read_events=MagicMock(name='read_events'),
grab_keyboards=MagicMock(name='grab_keyboards'))
for k,v in list(params.items()):
setattr(self, k, v)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.