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 |
|---|---|---|---|---|---|---|---|---|
dannyperry571/theapprentice | script.module.pydevd/lib/interpreterInfo.py | Python | gpl-2.0 | 8,047 | 0.006462 | '''
This module was created to get information available in the interpreter, such as libraries,
paths, etc.
what is what:
sys.builtin_module_names: contains the builtin modules embeeded in python (rigth now, we specify all manually).
sys.prefix: A string giving the site-specific directory prefix where the platform ind... | return 'mbcs'
return 'utf-8'
def getfilesystemencoding():
try:
ret = __getfilesystemencoding()
#Check i | f the encoding is actually there to be used!
if hasattr('', 'encode'):
''.encode(ret)
if hasattr('', 'decode'):
''.decode(ret)
return ret
except:
return 'utf-8'
file_system_encoding = getfilesystemencoding()
if IS_PYTHON_3K:
unicode_type... |
Daniel-CA/odoo-addons | account_invoice_manual_analytic/__openerp__.py | Python | agpl-3.0 | 669 | 0 | # -*- coding: utf-8 -*-
# Copyright 2017 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Account Invoice Manual Analytic",
"version": "8.0.1.0.0",
"category": "Accounting & Finance",
"license": "AGPL-3",
"author": "AvanzOSC",
"website"... | "views/account_analytic_line_view.xml",
],
"installable": Tr | ue,
}
|
edofic/ggrc-core | src/ggrc/models/access_group.py | Python | apache-2.0 | 777 | 0.002574 | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from ggrc import db
from ggrc.models.mixins import BusinessObject, Timeboxed, CustomAttributable
from ggrc.models.object_document import Documentable
from ggrc.models.object_owner import Ownable
from ggrc.mo... | tate,
CustomAttributable, Personable, Documentable, Relatab | le,
Timeboxed, Ownable, BusinessObject, db.Model):
__tablename__ = 'access_groups'
_aliases = {"url": "Access Group URL"}
track_state_for_class(AccessGroup)
|
MPTCP-smartphone-thesis/pcap-measurement | example_graph.py | Python | gpl-3.0 | 2,787 | 0.005023 | #! /usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2015 Quentin De Coninck
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any... | ture__ import print_function
import argparse
import common as co
import common_graph as cog
import matplotlib
# Do not use any X11 backend
matplotlib.use('Agg')
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib. | rcParams['ps.fonttype'] = 42
import matplotlib.pyplot as plt
import mptcp
import numpy as np
import os
import tcp
##################################################
## ARGUMENTS ##
##################################################
parser = argparse.ArgumentParser(
description="... |
IV-GII/SocialCookies | ENV1/webcookies/socialcookies/forms.py | Python | gpl-2.0 | 1,986 | 0.019153 | #encoding:utf-8
# Copyright (C) 2014 SocialCookies @IV/GII
# @anaprados @oskyar @torresj @josemlp91
# @franciscomanuel @rogegg @pedroag @melero90
# Aplicacion web, para gestionar pedidos de galletas,
# con fotos de Instagram y Twitter.
# This program is free software; you can redistribute it and/or
# modify it ... | ass':'form | -control'}))
direccion = forms.CharField(label='Direccion', widget=forms.TextInput(attrs={'class':'form-control'}))
telefono = forms.IntegerField(label='Telefono de contacto', widget=forms.TextInput(attrs={'class':'form-control'}))
correo = forms.EmailField(label='Correo electrónico',widget=forms.TextInput(attrs={'... |
jgmanzanas/CMNT_004_15 | project-addons/sale_display_stock/__openerp__.py | Python | agpl-3.0 | 1,737 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2004-2014 Pexego Sistemas Informáticos All Rights Reserved
# $Marta Vázquez Rodríguez$ <marta@pexego.es>
#
# This program is free software: you can redistribute it and/or modify
# it unde... | ock
========================================
* Displays the real stock of product at each sale order line.
""",
"depends": ["base", "sale", "stock", "account",
"product_virtual_stock_conservative",
"stock_reserve"],
"data": [
"sale_view.xml",
"product_view.xm... | rity/sale_display_stock_security.xml"
],
"demo": [],
'auto_install': False,
"installable": True,
'images': [],
}
|
timvideos/flumotion | flumotion/test/test_icalbouncer.py | Python | lgpl-2.1 | 17,170 | 0.002446 | # -*- Mode: Python; -*-
# vi:si:et:sw=4:sts=4:ts=4
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L.
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# All rights reserved.
#
# This file may be distributed and/or modified under the te | rms of
# the GNU Lesser General Public License version 2.1 as published by
# the Free Software Foundation.
# This file is distributed without any warranty; without even the implied
# warranty of merchantability or fitness for a particular purpose.
# See "LICENSE.LGPL" in the source distribution for more information.
#
... | from icalendar import vDatetime
HAS_MODULES = True
except ImportError:
pass
import os
import tempfile
import time
from datetime import datetime, timedelta
from flumotion.common import testsuite
from twisted.trial import unittest
from twisted.internet import defer
from flumotion.common import keycards
from fl... |
scorphus/politicos | tests/unit/handlers/test_political_party.py | Python | agpl-3.0 | 4,973 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Marcelo Jorge Vieira <metal@alucinados.com>
#
# 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 Software Foundation, either version 3 of the
# License, or (at... | political_parties.append(party.to_dict())
response = yield self | .anonymous_fetch(
'/political-parties/',
method='GET'
)
expect(response.code).to_equal(200)
political_parties_loaded = loads(response.body)
expect(political_parties_loaded).to_length(5)
expect(political_parties_loaded).to_be_like(political_parties)
@... |
lmmentel/ase-espresso | espresso/worldstub.py | Python | gpl-3.0 | 616 | 0 | # -*- coding: utf-8 -*-
# ****************************************************************************
# Original work Copyright (C) 2013-2015 SUNCAT
# Modified work Copyright 2015-2017 Lukasz Mentel
#
# This file is distributed un | der the terms of the
# GNU General Public License. See the file 'COPYING'
# in the root directory of the present di | stribution,
# or http://www.gnu.org/copyleft/gpl.txt .
# ****************************************************************************
# mpi stub for object having number of nodes as "size" attribute
class world:
def __init__(self, size):
self.size = size
|
joaduo/rel_imp | rel_imp.py | Python | mit | 8,202 | 0.000488 | '''
Copyright (c) 2014 Joaquin Duo - File under MIT License
Import this module to enable explicit relative importing on a submodule or
sub-package running it as a main module. Doing so is useful for running smoke
tests or small scripts within the module.
Usage:
------
To enable explicit relative importing in __main_... | Use PYTHON_DISABLE_REL_IMP environment variable to disable the initialization
'''
global _initialized
if _initialized:
_log_debug('Initialized. Doing nothing')
return
elif 'PYTHON_DISABLE_REL_IMP' in os.environ:
_log_debug('PYTHON_DISABLE_REL_IMP environment variable present. ... | _main__':
frame = frame.f_back
_init(frame, log_level)
def _init(frame, log_level=ERROR):
'''
Enables explicit relative import in sub-modules when ran as __main__
:param log_level: module's inner logger level (equivalent to logging pkg)
'''
global _log_level
_log_level = log_level
... |
jacksonllee/lxa5 | linguistica/datasets/__init__.py | Python | mit | 179 | 0 | # -*- encoding: utf8 -*-
import os
brown = os.path.join(os.path. | dirname(__file__), 'english-brown.txt')
cmudict = os.path.join(os.path.dirname(__file__), | 'english-cmudict.dx1')
|
USGSDenverPychron/pychron | docs/user_guide/operation/scripts/examples/argus/extraction/apis/PrepareForApis.py | Python | apache-2.0 | 702 | 0.014245 | def main():
info('Evacuate Microbone')
close(description='Jan Inlet')
open(description='Jan Io | n Pump')
#close(description='Minibone to Bone')
open(description='Minibone to Bone')
#close(description='Microbone to Minibone')
open(description='Microbone to Minibone')
open('C')
close('P')
close(description='Microbone to CO2 Laser')
open(description='Microbone to Turbo')
... | ne to Inlet Pipette')
open(description='Microbone to Getter NP-10C')
#evacuate apis section
#info('evacuate apis')
open(description='Microbone to Getter NP-10H')
#sleep(15)
#close(description='Microbone to Getter NP-10H') |
satanas/libturpial | tests/models/test_media.py | Python | gpl-3.0 | 1,767 | 0.007923 | import pytest
import __builtin__
from libturpial.api.models.media import Media
from tests.helpers import DummyFileHandler
class TestMedia:
@classmethod
@pytest.fixture(autouse=True)
def setup_class(self, monkeypatch):
monkeypatch.setattr(__builtin__, 'open', lambda x, y: DummyFileHandler())
... | sert isinstance(media, Media)
def test_save_content(self, monkeypatch):
media = Media(Media.IMAGE, 'foo', 'binary', path='/path/to/ble/', info='lorem ipsum')
# TODO: How test that this works?
assert media.save_content() == None
def raise_ex():
| raise KeyError
monkeypatch.setattr(__builtin__, 'open', lambda x, y: raise_ex())
media = Media(Media.IMAGE, 'foo', 'binary', path='/path/to/ble/', info='lorem ipsum')
assert media.save_content() == None
def test_type(self):
media = Media(Media.VIDEO, 'foo', 'binary', path='... |
donaldinou/nuked-gamer | make.py | Python | gpl-2.0 | 988 | 0.004049 | #!/usr/bin/python
import os
import shutil
import zipfile
import zlib
import os.path
def _ignore(src, name ):
if src == './UPLOAD/':
print name
return ['RESTDIR', 'conf.inc.php', 'Nuked-Klan.zip', '.hg', 'make.py']
else:
return []
def _RecImport(src, dst, zip | ):
elements = os.listdir(src)
ignored = _ignore('.' + dst, elements)
for delete in ignored:
try:
elements.remove(delete)
except ValueError:
pass
for ele in elements:
if os.path.isfile(src + ele):
zip.write(src + ele, dst + ele)
pri... | + ele + '/', dst + ele + '/', zip)
try:
shutil.rmtree('tmp')
except OSError:
pass
file = 'Nuked-Klan.zip'
try:
os.remove(file)
except OSError:
pass
zip = zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED, False)
_RecImport('RESTDIR/', '/', zip)
_RecImport('./', '/UPLOAD/', zip)
|
stachenov/PyLeetCode | problems/integer_replacement.py | Python | unlicense | 421 | 0 | class Solution(object):
def integerReplacement(self, n):
"""
:type n: int
:rtype: int
| """
if n < 4:
return [0, 0, 1, 2][n]
elif (n & 0b01) == 0b00:
return self.integerReplacement(n / 2) + 1
elif (n & 0b11) == | 0b01:
return self.integerReplacement(n - 1) + 1
else:
return self.integerReplacement(n + 1) + 1
|
synsun/robotframework | utest/running/test_userhandlers.py | Python | apache-2.0 | 6,437 | 0.001243 | import unittest
from robot.errors import DataError
from robot.model import Keywords
from robot.running.userkeyword import (EmbeddedArgs, EmbeddedArgsTemplate,
UserKeywordHandler)
from robot.running.arguments import EmbeddedArguments, UserKeywordArgumentParser
from robot.utils.ass... | sing" % attr)
class TestGetArgSpec(unittest.TestCase):
def test_no_args(self):
self._verify('')
def test_one_arg(self):
self._verify('${arg1}', ['arg1',])
def test_one_vararg(self):
self._verify('@{varargs}', exp_varargs='varargs')
def test_one_default(self):
self._... | _one_empty_default(self):
self._verify('${arg1} ${arg2}= @{varargs}',
['arg1', 'arg2'], [''], 'varargs')
def test_many_defaults(self):
self._verify('${arg1}=default1 ${arg2}=default2 ${arg3}=default3',
['arg1', 'arg2', 'arg3'],
['defaul... |
google-research/remixmatch | ablation/ab_cta_remixmatch_noweak.py | Python | apache-2.0 | 3,534 | 0.001698 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | ss AugmentPoolCTANoWeak(AugmentPoolCTA):
@staticmethod
def numpy_apply_policies(arglist):
x, cta, probe = arglist
if x.ndim == 3:
assert probe
policy = cta.policy(probe=True)
return dict(policy=policy,
probe=ctaugment.apply(x, policy),
... | robe=False)))
assert not probe
return dict(image=np.stack([ctaugment.apply(y, cta.policy(probe=False)) for y in x]).astype('f'))
class ABCTAReMixMatchNoWeak(ABCTAReMixMatch):
AUGMENT_POOL_CLASS = AugmentPoolCTANoWeak
def main(argv):
utils.setup_main()
del argv # Unused.
dataset = da... |
Azure/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/azure/mgmt/sql/operations/_operations.py | Python | mit | 5,294 | 0.004156 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | (self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list(
self,
**kwargs: Any
) -> Iterable["_models.OperationListResult"]:
... | ed the direct response
:return: An iterator like instance of either OperationListResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.sql.models.OperationListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', No... |
jeryfast/piflyer | piflyer/servo_handler.py | Python | apache-2.0 | 5,739 | 0.002265 | from __future__ import division
import number_range as n
import time
import Adafruit_PCA9685
import delays
MIN = 0
MAX = 180
# RPi code
# !/usr/bin/python
# Initialise the PWM device using the default address
pwm = Adafruit_PCA9685.PCA9685(0x41)
# Note if you'd like more debug output you can instead run:
# pwm = PWM... | arduino_map(down, 0, 100, MIN, MAX)
if (u):
self.setPosition(self.up)
print("Servo position: %d" % (self.up))
u | = False
elif (d):
self.setPosition(self.down)
print("Servo position: %d" % (self.down))
d = False
elif (self.upAdd == 1):
self.up = n.arduino_map(up, 0, 100, MAX, MIN)
self.down = n.arduino_map(down, 0, 100, MAX, MIN)
... |
kaday/cylc | lib/parsec/example/cfgspec.py | Python | gpl-3.0 | 1,963 | 0.037188 | #!/usr/bin/env python
# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2015 NIWA
#
# 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 yo... | ems and validators for the parsec test config file.
"""
SPEC = {
'title' : vdr( vtype="string" ),
| 'single values' :
{
'integers' : { '__MANY__' : vdr( vtype="integer" ) },
'booleans' : { '__MANY__' : vdr( vtype="boolean" ) },
'floats' : { '__MANY__' : vdr( vtype="float" ) },
'strings' : { '__MANY__' : vdr( vtype="string" ) },
'strings with i... |
ocefpaf/biggus | biggus/tests/test_adapter.py | Python | gpl-3.0 | 8,309 | 0 | # (C) British Crown Copyright 2012 - 2013, Met Office
#
# This file is part of Biggus.
#
# Biggus 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 3 of the License, or
# (at your option) a... | type=bool))],
(3, 4)],
[(3, 4), [(slice(None), np.array([0, 0, 0, 0], dtype=bool))],
(3, 0)],
# Boolean indexing (too few indices - zero pad)
[(3, 4), [np.array([1, 1], dtype=bool)], (2, 4)],
[(3, 4), [(slice(None), np.array([1, 1, 1], dtype=bool... | lice(None), np.array([1, 1, 1, 1, 0], dtype=bool))],
IndexError],
# Boolean testing, repeated slicing
[(3, 4), [(slice(None), slice(None)),
np.array([0, 1, 0], dtype=bool)], (1, 4)],
[(3, 4), [(slice(None), slice(None)),
(slice... |
saschpe/pycadf | pycadf/audit/api.py | Python | apache-2.0 | 9,375 | 0 | # -*- encoding: utf-8 -*-
#
# Copyright 2013 IBM Corp.
#
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
try:
self._BODY_ACTIONS = dict(audit_map.items('body_actions'))
except ConfigParser.NoSectionError:
pass
try:
self._SERVICE_ENDPOINTS = \
dict(audit_map.items('service_endpoints'))
... | ApiConfigError(
'Error parsing audit map file: %s' % err)
def _get_action(self, req):
"""Take a given Request, parse url path to calculate action type.
Depending on req.method:
if POST: path ends with action, read the body and get action from map;
reque... |
s1mbi0se/s1ipc | s1ipc/sharedcache/tests/memoize_tests.py | Python | apache-2.0 | 1,191 | 0.002519 | # codi | ng=utf-8
from multiprocessing import Process
import unittest
from unittest import TestCase
from .. import SharedCacheServer, SharedCache, Memoize
import time
__author__ = 'matheus2740'
class Memo | izeTests(TestCase):
def setUp(self):
pass
def tearDown(self):
fun.remove_local_namespaces()
def test_simple_call(self):
server = SharedCacheServer()
i1 = fun()
i2 = fun()
i2 = fun()
i2 = fun()
i2 = fun()
assert i1 == i2
ass... |
blitzmann/Pyfa | eos/db/migrations/__init__.py | Python | gpl-3.0 | 1,545 | 0.000647 | """
The migration module includes migration logic to update database scheme and/or
data for the user database.
To create a migration, simply create a file upgrade<migration number>.py and
define an upgrade() function with the logic. Please note that there must be as
many upgrade files as there are database versions (v... | or m in pkgutil.iter_modules(__path__, prefix)]
# special handling for PyInstaller
importers = map(pkgutil.get_importer, __path__)
toc = set()
for i in importers:
if hasattr(i, 'toc'):
toc |= i.toc
for elm in toc:
if elm.startswith(prefix):
module_names.append(elm)
for modname in module_names... | name.rsplit('.', 1)[-1]
module = __import__(modname, fromlist=True)
m = re.match("^upgrade(?P<index>\d+)$", modname_tail)
if not m:
continue
index = int(m.group("index"))
appVersion = max(appVersion, index)
upgrade = getattr(module, "upgrade", False)
if upgrade:
updates[index... |
PaddlePaddle/Paddle | python/paddle/fluid/tests/unittests/ipu/test_lookuptable_op_ipu.py | Python | apache-2.0 | 4,745 | 0.000211 | # Copyright (c) 2021 PaddlePaddle 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 appli... | IPU")
class TestBase(IPUOpTest):
def setUp(self):
self.set_atol()
self.set_training()
self.set_data_feed()
self.set_feed_attr()
self.set_op_attrs()
@property
def fp16_enabled(self):
return True
def set_data_feed(self):
data = np.a | rray([[[1], [3]], [[2], [4]], [[4], [127]]])
self.feed_cpu = {"x": data.astype(np.int64)}
self.feed_ipu = {"x": data.astype(np.int32)}
def set_feed_attr(self):
self.feed_shape = [x.shape for x in self.feed_cpu.values()]
self.feed_list = list(self.feed_cpu.keys())
self.feed_d... |
kabrapratik28/DeepVideos | model/model_GAN_8.py | Python | apache-2.0 | 38,127 | 0.011278 | import os
import sys
import shutil
import numpy as np
import tensorflow as tf
from tensorflow.python.ops import init_ops
from tensorflow.contrib.layers.python.layers import regularizers
module_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "..")
if module_path not in sys.path:
sys.path.append(mod... | tf.to_float(shape[1] * shape[ | 2] * shape[3])
square_diff = tf.square(gt_frames - gen_frames)
batch_errors = 10 * log10(1 / ((1 / num_pixels) * tf.reduce_sum(square_diff, [1, 2, 3])))
return tf.reduce_mean(batch_errors)
def sharp_diff_error(gen_frames, gt_frames):
"""
Computes the Sharpness Difference error between the generate... |
vincentadam87/gatsby-hackathon-seizure | code/python/seizures/examples/cross_validation_test.py | Python | bsd-2-clause | 5,173 | 0.011212 | '''
Created on 10 August 2014
@author: vincent
'''
# Loading necessary packages
import numpy as np
import sys
from seizures.data.DataLoader_v2 import DataLoader
from seizures.evaluation.XValidation import XValidation
from seizures.evaluation.performance_measures import accuracy, auc
from seizures.features.FeatureExt... | :"PLVFeatures",'args':{}},{'name':'SEFeatures','args':{}}])
#feature_extractor = SEFeatures()
#f | eature_extractor = LyapunovFeatures()
#feature_extractor = StatsFeatures()
preprocess = True
predictor = SVMPredictor
#predictor = XtraTreesPredictor
if preprocess==True:
print 'Preprocessing ON'
else:
print 'Preprocessing OFF'
print 'predictor: ',predictor
Xval_on_pa... |
01org/fMBT | pythonshare/pythonshare/server.py | Python | lgpl-2.1 | 30,835 | 0.002594 | # fMBT, free Model Based Testing tool
# Copyright (c) 2013-2019, Intel Corporation.
#
# Author: antti.kervinen@intel.com
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU Lesser General Public License,
# version 2.1, as published by the Free Software... | ote
def __del__(self):
python | share._close(self.conn, self.to_remote, self.from_remote)
_g_local_namespaces = {}
# client-id -> set of namespaces
_g_namespace_users = {}
_g_executing_pythonshare_conn_id = None
# _g_remote_namespaces: namespace -> Connection to origin
_g_remote_namespaces = {}
# _g_namespace_exports: namespace -> list of Connect... |
Serveza/Server | serveza/scripts/resetdb.py | Python | gpl-2.0 | 3,940 | 0.003807 | import csv
import getpass
import io
import sqlite3
import json
import requests
import re
import urllib.request
import os
from geopy.geocoders import GoogleV3
from serveza.app import app
from serveza.db import db
from serveza.settings import PROJECT_ROOT, DB_PATH
from pprint import pprint
from bs4 import BeautifulSoup
... | mgur.com/5h2fDdT.jpg')
db.session.add(aang)
print('Superuser token:', admin.api_token)
def reset_db():
| # Reset all data
reset_data()
reset_users()
db.session.commit()
def main():
app.config['SQLALCHEMY_ECHO'] = True
app.test_request_context().push()
reset_db()
|
sj26/webapp | build/lib/webapp/session.py | Python | gpl-3.0 | 1,477 | 0.007448 | from paste.session import make_session_middleware
from webapp.app import *
from webapp.check import Check, environ_has
Request.session = property(lambda self: self.environ['paste.session.factory']())
def session_has(*args, **kwargs):
"""
Check for the presense and, optionally, value of a session variable.
... | e) in kwarg | s.iteritems()))
class Sessioned(object):
def __middleware_factory__(self, app):
return super(Sessioned, self).__middleware_factory__(make_session_middleware(app, {}))
|
josephsl/wintenApps | addon/appModules/cortana.py | Python | gpl-2.0 | 2,658 | 0.020316 | # Cortana Conversations
# Part of Windows App Essentials collection
# Copyright 2019-2022 Joseph Lee, released under GPL
# Various workarounds for Cortana Conversations (in build 18922 and later)
import appModuleHandler
import api
import ui
import UIAHandler
from NVDAObjects.UIA import UIA
class AppModule(appModule... | dule):
# Sometimes, Cortan | a's textual response is announced twice.
_cortanaResponse: str = ""
def event_UIA_notification(self, obj, nextHandler, displayString=None, **kwargs):
# For some reason Cortana fires this event whenever user types and an answer is received.
# Results are displayed inside a list.
# Thus respond to both and see w... |
remarkablerocket/django-vend | django_vend/stores/tests.py | Python | bsd-3-clause | 7,713 | 0.000648 | from datetime import datetime
from uuid import UUID
from django.utils.timezone import make_aware, now, FixedOffset
from django.test import TestCase
from django_vend.auth.models import VendRetailer
from .models import VendOutlet, VendRegister
from .forms import VendOutletForm, VendRegisterForm
class VendOutletFormTe... | rieved = now()
self.assertTrue(form.is_valid())
if form.is_valid():
instance = | form.save()
del_time = make_aware(datetime(2014, 7, 1, 20, 22, 58), FixedOffset(0))
self.assertEqual(instance.uid, UUID(uid))
self.assertEqual(instance.name, "London Outlet")
self.assertEqual(instance.time_zone, tz)
self.assertEqual(instance.currency, currency)
self.ass... |
qiuminxu/tensorboard | tensorboard/plugins/hparams/metadata.py | Python | apache-2.0 | 3,935 | 0.004574 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | =PLUGIN_NAME,
content=content.SerializeToString()))
def parse_experiment_plugin_data(content):
"""Parses a given HParam's SummaryMetadata.plugin_data.content and
returns the 'experiment'.
Raises:
HParamsError if the content doesn't have 'experiment' set or
this file is incompatible with the v... |
return _parse_plugin_data_as(content, 'experiment')
def parse_session_start_info_plugin_data(content):
"""Parses a given HParam's SummaryMetadata.plugin_data.content and
returns the 'session_start_info' field.
Raises:
HParamsError if the content doesn't have 'session_start_info' set or
this file is ... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.1/Lib/test/test_xmllib.py | Python | mit | 532 | 0.00188 | '''Test module to thest the xmllib module.
Sjoerd | Mullender
'''
from test_support import verbose
testdoc = """\
<?xml version="1.0" encoding="UTF-8" standalone='yes' ?>
<!-- comments aren't allowed before the <?xml?> tag,
but they are allowed before the <!DOCTYPE> tag -->
<!DOCTYPE greeting [
<!ELEMENT greeting (#PCDATA)>
]>
<greeting>Hello, world!</greeting>... | MLParser()
else:
parser = xmllib.XMLParser()
for c in testdoc:
parser.feed(c)
parser.close()
|
FrozenPigs/Taigabot | plugins/_disabled/pyexec.py | Python | gpl-3.0 | 200 | 0.005 | import re
|
from util import hook, http
from util.execute import eval_py
@hook.command(adminonly=True)
def python(inp):
"python <prog> -- Executes <prog> as Python code."
return eval_py(i | np)
|
lucidmotifs/newtopia | newtopia/ntgame/admin.py | Python | gpl-3.0 | 2,300 | 0.001304 | from django.contrib import admin
from django.utils.safestring import mark_safe
from django.urls import reverse
from .models import Kingdom, Province, Military, Race
from .models import Infrastructure, InfrastructureItem, Building
from .models import Effect, Instance
from .models import Spell
# Register your models he... | = ('explored','built',)
verbose_name_plural = "Infrastructure"
fieldsets = (
| (None, {
'fields': (
'land',
)
}),
('Details', {
'fields': (
'built',
'explored',
)
}),
)
class MilitaryInline(admin.StackedInline):
model = Military
show_change_link = True
can_delete = False
... |
tensorflow/tensorflow | tensorflow/python/data/kernel_tests/interleave_test.py | Python | apache-2.0 | 17,486 | 0.005319 | # Copyright 2017 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... | as a queue of iterators over each element of `lists`.
al | l_iterators = [iter(l) for l in lists]
# `open_iterators` are the iterators whose elements are currently being
# interleaved.
open_iterators = []
if cycle_length is None:
# The logic here needs to match interleave C++ kernels.
if num_parallel_calls is None:
cycle_length = multiprocessing.cpu_coun... |
silentfuzzle/calibre | src/calibre/gui2/library/models.py | Python | gpl-3.0 | 67,194 | 0.003423 | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import functools, re, os, traceback, errno, time
from collections import defaultdict, namedtuple
from itertools import gro... | er import ParseException
from calibre.ebooks.metadata import fmt_sidx, authors_to_string, string_to_authors
from calibre.ebooks.metadat | a.book.formatter import SafeFormat
from calibre.ptempfile import PersistentTemporaryFile
from calibre.utils.config import tweaks, device_prefs, prefs
from calibre.utils.date import dt_factory, qt_to_dt, as_local_time, UNDEFINED_DATE
from calibre.utils.icu import sort_key
from calibre.utils.search_query_parser import Se... |
daviddrysdale/python-phonenumbers | python/phonenumbers/shortdata/region_NO.py | Python | apache-2.0 | 772 | 0.007772 | """Auto-generated file, do not edit by hand. NO metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_NO = PhoneMetadata(id='NO', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='1\\d\\d(?:\\d(?:\\d{2})?)?' | , possible_length=(3, 4, 6)),
toll_free=PhoneNumberDesc(national_number_pattern='11(?:[023]|6\\d{3})', example_number='110', possible_length=(3, 6)),
emergency=PhoneNumberDesc(national_number_pattern='11[023]', example_number='110', possible_length=(3,)),
short_code=PhoneNumberDesc(national_number_pattern='... | ?:12|[59])|7[57]|8[5-9]\\d|90)', example_number='110', possible_length=(3, 4, 6)),
short_data=True)
|
NiJeLorg/CDADMap | cdad/cdadmap/migrations/0037_auto_20151106_1149.py | Python | mit | 1,088 | 0.003676 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cdadmap', '0036_auto_20151105_1350'),
]
operations = [
migrations.AddField(
model_name='locationpanel',
... |
migrations.AddField(
model_name='surveypanel',
name='Service_Population_Other',
field=models.CharField(default=b'', max_length=255, null=True, | blank=True),
),
migrations.AlterField(
model_name='surveypanel',
name='CDAD_Services_Other',
field=models.CharField(default=b'', max_length=255, null=True, blank=True),
),
]
|
carsongee/edx-platform | cms/djangoapps/contentstore/views/tests/test_course_index.py | Python | agpl-3.0 | 8,877 | 0.002816 | """
Unit tests for getting the list of courses and the course outline.
"""
import json
import lxml
from contentstore.tests.utils import CourseTestCase
from contentstore.utils import reverse_course_url, add_instructor
from contentstore.views.access import has_course_access
from course_action_state.models import CourseR... | staff_client, course_staff = self.create_non_ | staff_authed_user_client()
for course in [self.course, self.odd_course]:
permission_url = reverse_course_url('course_team_handler', course.id, kwargs={'email': course_staff.email})
self.client.post(
permission_url,
data=json.dumps({"role": "staff"}),
... |
JakubPetriska/poker-cfr | test/cfr_tests.py | Python | mit | 1,756 | 0.001708 | import unittest
import acpc_python_client as acpc
from cfr.main import Cfr
KUHN_POKER_GAME_FILE_PATH = 'games/kuhn.limit.2p.game'
KUHN_BIG_DECK_POKER_GAME_FILE_PATH = 'games/kuhn.bigdeck.limit.2p.game'
KUHN_BIG_DECK_2ROUND_POKER_GAME_FILE_PATH = 'games/kuhn.bigdeck.2round.limit.2p.game'
LEDUC_POKER_GAME_FILE_PATH = ... | e)
cfr.train(5, weight_delay=2)
def test_kuhn_bigdeck_cfr_works(self):
game = acpc.read_game_file(KUHN_BIG_DECK_POKER_GAME_FILE_PATH)
cfr = Cfr(game, show_progress=False)
cfr.train(5, weight_delay=2)
def test_kuhn_bigdeck_2round_cfr_works(self):
game = acpc.read_game_fi... | AME_FILE_PATH)
cfr = Cfr(game, show_progress=False)
cfr.train(5, weight_delay=2)
def test_leduc_cfr_works(self):
game = acpc.read_game_file(LEDUC_POKER_GAME_FILE_PATH)
cfr = Cfr(game, show_progress=False)
cfr.train(5, weight_delay=2)
def test_kuhn_cfr_checkpointing(self... |
tinloaf/home-assistant | homeassistant/components/lovelace/__init__.py | Python | apache-2.0 | 5,109 | 0 | """
Support for the Lovelace UI.
For more details about this component, please refer to the documentation
at https://www.home-assistant.io/lovelace/
"""
from functools import wraps
import logging
import os
import time
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.exce... | return con | fig
async def async_save(self, config):
"""Save config."""
self._data['config'] = config
await self._store.async_save(self._data)
class LovelaceYAML:
"""Class to handle YAML-based Lovelace config."""
def __init__(self, hass):
"""Initialize the YAML config."""
self... |
MarllonSoares/PYTHON-ESTUDO | lista-de-atividades/01-estrutura-sequencial/02-atividade/algoritmo-atv2.py | Python | mit | 360 | 0 | # -*- coding | : utf-8 -*-
"""
Created on Mon Mar 20 00:30:34 2017
@author: Marllon Soares
@site: www.marllonsoares.com. | br
@linguagem: Python 3
@assunto: Estrutura sequencial
@problema:
Faça um Programa que peça um número e então mostre
a mensagem O número informado foi [número].
"""
numero = int(input())
print("O número informado foi ", numero)
|
kaushik94/tardis | tardis/tests/integration_tests/report.py | Python | bsd-3-clause | 8,984 | 0.000779 | """
A helper class which works as a plugin to generate the test report and upload it
to the group server's dokuwiki. It inheirts from the class `HTMLReport` of
the `pytest-html` plugin. The test report contains the following details:
* The git commit hash on which test run was executed.
* The time of generation of tes... | tardis_githash
)
)
gh_commit_data = json.lo | ads(gh_request.content)
# Pick only first line of commit message
gh_commit_message = gh_commit_data["message"].split("\n")[0]
# Truncate long commit messages
if len(gh_commit_message) > 60:
gh_commit_message = "{0}...".format(gh_commit_message[:57])
row = "| "
... |
akilism/moving_violation_scraper | scraper.py | Python | mit | 1,500 | 0.002667 | __author__ = 'akilharris'
import httplib
from bs4 import BeautifulSoup
import os
#Load http://www.nyc.gov/html/nypd/html/traffic_reports/traffic_summons_reports.shtml
#grab all pdfs and save to a folder
path = "raw_data/pdf/"
def scrape(url):
conn = httplib.HTTPConnection("www.nyc.gov")
conn.request("GET", ... | nsion) != -1:
links.append(href)
return links
def save_links(links):
if not os.path.exists(path):
parts = path.split("/")
for part in parts:
if len(part) > 0:
os.mkdir(part)
os.chdir(part)
else:
os.chdir(path)
# print(os.... | me.strip("sum.pdf")
print("Saving: " + precinct + " - " + os.getcwd() + "/" + file_name)
file_data = scrape(link)
with open(file_name, "wb") as f:
f.write(file_data)
def getPDFs():
raw_data = scrape("/html/nypd/html/traffic_reports/traffic_summons_reports.shtml")
links = pa... |
karlp/pyOCD | pyOCD/transport/__init__.py | Python | apache-2.0 | 687 | 0.002911 | """
mbed CMSIS-DAP debugger
Copy | right (c) 2006-2013 ARM Limited
Licensed und | er the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distribu... |
jwg4/flask-autodoc | setup.py | Python | mit | 1,280 | 0 | """
Flask-Selfdoc
-------------
Flask selfdoc automatically creates an online documentation for your flask app.
"""
from setuptools import setup
def readme():
with open('README.md') as f:
return f.read()
setup(
name='Flask-Selfdoc',
version='1.1.0',
url='http://github.com/jwg4/flask-selfdoc... | 'Arnaud Coomans',
maintainer='Jack Grahl',
maintainer_email='jack.grahl@gmail.com',
description='Documentation generator for flask',
long_description=readme(),
# py_modules=['flask_autodoc'],
# if you would be using a package instead use packages instead
# of py_modules:
packages=['flask... | ates/autodoc_default.html']},
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'Flask'
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating ... |
octocoin-project/octocoin | qa/rpc-tests/bip65-cltv-p2p.py | Python | mit | 6,411 | 0.003588 | #!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, N... | 'Modify the signature in vin 0 of the tx to fail CLTV
Prepends -1 CLTV DROP in th | e scriptSig itself.
'''
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
'''
This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY)
Connect to a single node.
Mine 2 (version 3) blocks (save the coinbases for later).
Generat... |
madebydaniz/django1-11 | src/menus/models.py | Python | mit | 1,040 | 0.009615 | from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
from restaurants.models import RestaurantLocation
class Item(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
restaurant = models.ForeignKey(RestaurantLocation)
name ... | e)
timestamp = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('menus:detail', kwargs={'pk': self.pk})
class Meta:
ordering = ['-updated', '-timestamp... | |
CPonty/jrxml2sql | docs/scope.py | Python | gpl-2.0 | 3,584 | 0.000279 | """
jrxml2sql v0
- parameter extractor only; don't attempt full parser (yet?)
- query2workbench.py: "dumb" conversion
- jrxml2sql.py: extract query & parameter types from tags
- usage:
> if no arguments provided, open as CLI:
-- splash screen with name/purpose of script
-- paste text to terminal
-- ... | ostges.sql, query_sqlserver.sql"
-- prompt for next query
-- ctrl-c / ctrl-d / q / exit / quit exits
> drag-n-drop is the same as providing one argument
> -d flag: debug mode, detailed progress printed to terminal
- components:
> mappings_[language].py files
//-- map parameter to default type, per lang... | eter to $X{} default value, per language
-- map parameter to $P{} default value (+ type), per language
-- map java type to sql type, per language
> classes
-- parameter, incl. java type & converted type per language
-- $X statement - original string, value, parameter
- jrxml2sql steps:
> load and ver... |
leszektarkowski/PAR273 | server/server.py | Python | gpl-2.0 | 2,220 | 0.011712 | import gpib
class PARWriteError(Exception):
pass
class PARReadError(Exception):
pass
class PARCellWorking(Exception):
| pass
class Poll:
COMMAND_DONE = 1
COMMAND_ERROR = 2
CURVE_DONE = 4
OVERLOAD = 16
SWEEP_DONE = 32
SRQ = 64
OUTPUT_READY = 128
class PAR(object):
def __init__(self, addres | ):
self.dev = gpib.dev(*addres)
self.write('DD 13')
self.write('TYPE Succesfull init"')
def write(self, cmd):
while True:
status = ord(gpib.serial_poll(self.dev))
#print '.',
if status & Poll.COMMAND_DONE != 0:
break
... |
JakeFountain/H3DAPIwithOculusSupport | examples/bumpmap/bumpmap.py | Python | gpl-2.0 | 571 | 0.042032 | from H3DInterface import *
class SFVec3f | ToColor( TypedField( MFColor, ( SFVec3f, SFMatrix4f, MFVec3f ) ) ):
def update( self, event ):
inputs = self.getRoutesIn()
light_pos_global = inputs[0].getValue()
acc_inverse_matrix = inputs[1].getValue()
points = inputs[2].getValue()
light_pos = acc_inverse_matrix * lig | ht_pos_global
res = []
for p in points:
v = light_pos - p
v.normalize()
v.y = -v.y
v = v * 0.5 + Vec3f( 0.5, 0.5, 0.5 )
res.append( RGB( v.x, v.y, v.z ) )
return res
toColor = SFVec3fToColor()
|
googleads/google-ads-python | google/ads/googleads/v9/errors/types/header_error.py | Python | apache-2.0 | 1,153 | 0.000867 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2 | .0
#
# Unless required by applicable law or 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
# limitations under the License.
#
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v9.errors",
marshal="google.ads.googleads.v9",
manifest={"HeaderErrorEnum",}... |
702nADOS/sumo | tools/route/routeDiffStats.py | Python | gpl-3.0 | 3,296 | 0.001517 | #!/usr/bin/env python
"""
@file routeStats.py
@author Jakob Erdmann
@date 2014-12-18
@version $Id: routeDiffStats.py 19649 2015-12-17 21:05:20Z behrisch $
compute statistics for two sets of routes (for the same set of vehicles)
SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
Copyright (C) 2014-2014... | ption("-v", "--verbose", action="store_true",
default=False, help="Gi | ve more output")
optParser.add_option("--binwidth", type="float",
default=100, help="binning width of route length difference histogram")
optParser.add_option("--hist-output", type="string",
default=None, help="output file for histogram (gnuplot compatible)")
... |
masayoota/upPIR | uppirlib.py | Python | mit | 26,413 | 0.016393 | """
<Author> Justin Cappos
(inspired from a previous version by Geremy Condra)
<Start Date>
May 16th, 2011
<Description>
Lots of helper code for upPIR. Much of this code will be used multiple
places, but some many not. Anything that is at least somewhat general will
live here.
"""
import sys
# u... | idx:]
# verify the manifest with the digital signature of the vendor
if _verify_ | manifest(signature, rawmanifest):
return rawmanifest
return ''
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from base64 import b64decode
def _verify_manifest(signature, data):
# private function that verifies data using the digital signature
... |
RobotTurtles/mid-level-routines | test_RobotMenu.py | Python | apache-2.0 | 659 | 0.003035 | from RobotMenu import RobotMenu
import unittest
import logging
class TestSequenceFunctions(unittest.TestCase):
"""Tests for basic movement, currently write to/from a file"""
def setUp(self):
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
self.__targetFile = 'testR... | ess(qrCode)
| #Assert
self.assertTrue(True, 'some message')
if __name__ == '__main__':
unittest.main() |
felliott/waterbutler | waterbutler/providers/osfstorage/metadata.py | Python | apache-2.0 | 4,099 | 0.002196 | import pytz
import dateutil.parser
from waterbutler.core import metadata
class BaseOsfStorageMetadata:
@property
def provider(self):
return 'osfstorage'
class BaseOsfStorageItemMetadata(BaseOsfStorageMetadata):
def __init__(self, raw, materialized):
super().__init__(raw)
self._... | @pr | operty
def path(self):
return self.raw['path']
@property
def materialized_path(self):
return self._materialized
class OsfStorageFileMetadata(BaseOsfStorageItemMetadata, metadata.BaseFileMetadata):
@property
def modified(self):
return self.raw['modified']
@property
... |
dweinstein/mitmproxy | libmproxy/protocol/base.py | Python | mit | 6,663 | 0.003152 | from __future__ import (absolute_import, print_function, division)
import sys
import six
from netlib import tcp
from ..models import ServerConnection
from ..exceptions import ProtocolException
from netlib.exceptions import TcpException
class _LayerCodeCompletion(object):
"""
Dummy class that provides type h... | self).__init__(**mixin_args)
def | __call__(self):
"""Logic of the layer.
Returns:
Once the protocol has finished without exceptions.
Raises:
~libmproxy.exceptions.ProtocolException: if an exception occurs. No other exceptions must be raised.
"""
raise NotImplementedError()
def __get... |
jthurst3/newspeeches | get_words.py | Python | mit | 836 | 0.026316 | # get_words.py
# returns a list of words from the relevant lines of a speech
# J. Hassler Thurston
# RocHack Hackathon December 7, 2013
import csv
import nltk
def | get_words(line_list):
sentences = parse_to_sentences(line_list)
#print sentences
words = [nltk.word_tokenize(sent) for sent in sentences]
return sentences
# returns a list of sentences from the list of lines
def parse_to_sentences(line_list) | :
#print line_list
sentence_list = []
for line in line_list:
# insert the sentences into the list
sentence_list.extend(line.split('.'))
return sentence_list
# exports the list of words to a CSV file (currently only exports sentences)
def export_to_csv(word_list, filename):
out = open(filename, 'w')
#wr = csv... |
Aloomaio/python-sdk | setup.py | Python | apache-2.0 | 645 | 0 | #!/usr/bin/env python
from setuptools import setup
sdk_package_name = 'alooma_pysdk'
packages = [sdk_package_name]
setup(
name=sdk_package_name,
packages=packages,
package_data={sdk_package | _name: ['alooma_ca']},
version='2.1',
description='An easy-to-integrate SDK for your Python apps to report '
'events to Alooma',
url='https://github.com/Aloomaio/python-sdk',
author='Alooma',
author_email='integrations@alooma.com',
keywords=['python', 'sdk', 'alooma', 'pysdk'],
... | require=open("requirements-tests.txt").readlines()
)
|
lukas-krecan/tensorflow | tensorflow/python/ops/control_flow_ops.py | Python | apache-2.0 | 71,570 | 0.006721 | # 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... | urn gen_control_flow_ops._ref_merge(values, name)
else:
return gen_co | ntrol_flow_ops._merge(values, name)
def _Enter(data, frame_name, is_constant=False, parallel_iterations=10,
use_ref=True, name=None):
"""Creates or finds a child frame, and makes `data` available to it.
The unique `frame_name` is used by the `Executor` to identify frames. If
`is_constant` is true, `... |
mfwarren/FreeCoding | 2015/01/fc_2015_01_30.py | Python | mit | 367 | 0 | #!/usr/bin/env python3
# imports go here
#
# Free Coding session for 2015-01-30
# Written by Matt Warren
#
def main():
print("writing code for someone else")
print("and not getting paid for it")
print("with no chance that it benfits me - even indirectly")
print("on a friday nigh | t")
print("this sucks! | ")
if __name__ == '__main__':
main()
|
prheenan/BioModel | BellZhurkov/Python/TestExamples/TestUtil/Bell_Test_Data.py | Python | gpl-2.0 | 2,506 | 0.01237 | # force floating point division. Can still use integer with //
from __future__ import division
# This file is used for importing the common utilities classes.
import numpy as np
import matplotlib.pyplot as plt
import sys
class BellData:
def __init__(self,forces,RatesFold,RatesUnfold=None):
self.Forces = fo... | ces)
# write down the folding and unfolding rates as decaying/increasing
# exponentials, based on their starting val | ue in the graph
ForceDiff = max(Forces)-min(Forces)
# we have
# y ~ exp(+/- t/tau)
# so y_f/y_i = exp(+/- (t_f-t_i)/tau)
# so tau = +/- np.log(yf/y_i)/(tf-t_i). aparently the signs work themselves
# out the way I use tau below
yf = 300
yi = 8
# get the 'taus' for the exponential deca... |
sahiljain/catapult | telemetry/telemetry/story/story.py | Python | bsd-3-clause | 4,429 | 0.00858 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
from telemetry.story import shared_state as shared_state_module
_next_story_id = 0
class Story(object):
"""A class styled on unittest.TestCas... | elif isinstance(tags, list):
tags = set(tags)
else:
assert isinstance(tags, set)
self._tags = tags
self._is_local = is_local
self._make_javascript_deterministic = make_javascript_deterministic
if grouping_keys is None:
grouping_keys = {}
else:
assert isinstance(grouping... | self._grouping_keys = grouping_keys
def Run(self, shared_state):
"""Execute the interactions with the applications and/or platforms."""
raise NotImplementedError
@property
def tags(self):
return self._tags
@property
def shared_state_class(self):
return self._shared_state_class
@proper... |
lindemann09/pytrak | pytrak/plotter.py | Python | gpl-3.0 | 10,237 | 0.001661 | __version__ = "0.1"
import threading
import numpy as np
import pygame
from expyriment.stimuli import Canvas
from expyriment.stimuli._visual import Visual
lock_expyriment = threading.Lock()
Numpy_array_type = type(np.array([ | ]))
def inherit_docs(cls):
for name, func in vars(cls).items():
if not func.__doc__:
for parent in cls.__bases__:
parfunc = getattr( | parent, name)
if parfunc and getattr(parfunc, '__doc__', None):
func.__doc__ = parfunc.__doc__
break
return cls
@inherit_docs
class PGSurface(Canvas):
"""PyGame Surface: Expyriment Stimulus for direct Pygame operations and
PixelArrays
In contras... |
Pikecillo/digi-dark | digidark/parser.py | Python | gpl-3.0 | 3,699 | 0.001352 | import re
from simpleparse.parser import Parser
from simpleparse.dispatchprocessor import *
grammar = """
root := transformation
transformation := ( name, index, assign, expr )
assign := '='
expr := ( trinary )
/ ( term )
trinary := ( term, '?', term, ':', term )
term := ( factor, binaryop, term )
... | / ( expr )
opar := '('
cpar := ')'
name := [_a-zA-Z], [_a-zA-Z0-9]*
number := ( float )
/ ( integer )
integer := [0-9]+
float := ( in | teger, '.', integer )
index := ( '[', expr, ',', expr, ']' )
/ ( '[', function, ']' )
"""
class SyntaxTreeProcessor(DispatchProcessor):
def transformation(self, info, buffer):
(tag, left, right, children) = info
res = dispatchList(self, children, buffer)
return " ".join(res)
... |
antoinecarme/pyaf | tests/model_control/detailed/transf_Quantization/model_control_one_enabled_Quantization_MovingMedian_Seasonal_DayOfWeek_LSTM.py | Python | bsd-3-clause | 168 | 0.047619 | import t | ests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Quantization'] , ['MovingMedian'] , ['Se | asonal_DayOfWeek'] , ['LSTM'] ); |
b1quint/samfp | other/pyadhoc.py | Python | bsd-3-clause | 8,475 | 0.006608 | import numpy as np
from scipy import constants as cst
import pyfits as pf
from pyfits import Column
from time import sleep
import matplotlib as mpl
from matplotlib import pyplot as plt
#import codecs
#verifier l'organisation des cubes fits si on les ouvre en python
#faire un programme readad qui voit l'extension pour ... | ) then begin
#; On regarde si plutot le fichier est .ad3.gz...
#if (testgz ne 'gz') then begin
#realfilename = filename + '.gz'
#info = file_info(realfilename)
#endif else begin
#realfilename = filename
#endelse
#if (info.exists eq 0) or (info.read eq 0) then return, -1
#if (!versio... | #size = ulong64(output[1])
#if testgz eq 'gz' then begin
#trailer.was_compressed = 1
#endif
def readad3(filename, xyz=True):
"""Parameters
----------
filename: string
Name of the input file
xyz=True: boolean (optional)
False to return data in standard zxy adhoc format
... |
Droriel/python_training | data/groups.py | Python | apache-2.0 | 216 | 0.004651 | # -*- coding: utf-8 -*-
from model | .group import Group
# Stałe dane testowe
testData = [
Group(name='name1', header='header1', footer='footer1'),
Group(name='name2', he | ader='header2', footer='footer2')
]
|
atuljain/odoo | addons/project/project.py | Python | agpl-3.0 | 68,455 | 0.006121 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | }
def _get_default_project_ids(self, cr, uid, ctx={}):
project_id = self.pool['project.task']._get_default_project | _id(cr, uid, context=ctx)
if project_id:
return [project_id]
return None
_defaults = {
'sequence': 1,
'project_ids': _get_default_project_ids,
}
_order = 'sequence'
class project(osv.osv):
_name = "project.project"
_description = "Project"
_inherits... |
recoded-co/geonition_aliases | setup.py | Python | lgpl-2.1 | 781 | 0.002561 | from setuptools import setup
from setuptools import find_packages
setup(
name='geonition_aliases',
version='0.0.1',
author='Dariusz Walczak',
url='',
packages=find_packages(),
include_package_data=True,
package_data = {
"geoforms": [
| "templates/*.html",
"templates/*.api.js",
"templates/jstranslations.txt",
"templates/help/*.html",
"templates/admin/geoforms/geoformelement/*.html",
"locale/*/LC_MESSAGES/*.po",
"locale/*/LC_MESSAGES/*.mo",
"static/js/*",
"... | ltranslation'],
)
|
veroc/Bika-LIMS | bika/lims/browser/widgets/addresswidget.py | Python | agpl-3.0 | 2,605 | 0.005374 | from AccessControl import ClassSecurityInfo
from Products.Archetypes.utils import DisplayList
from Products.Archetypes.Registry import registerWidget
from Products.Archetypes.Widget import TypesWidget
from Products.CMFPlone.i18nl10n import ulocalized_time
from Products.CMFCore.utils import getToolByName
from bika.lims.... | ties.copy()
_properties.update({
'macro': "bika_widgets/addresswidget",
'helper_js': ("bika_widgets/addresswidget.js",),
'helper_css': ("bika_widgets/addresswidget.css",),
'showLegend': True,
'showDistrict' | : True,
'showCopyFrom': True,
'showCity': True,
'showPostalCode': True,
'showAddress': True,
})
security = ClassSecurityInfo()
# The values in the form/field are always
# Country Name, State Name, District Name.
def getCountries(self):
items = []
it... |
huaweiswitch/neutron | neutron/tests/unit/cisco/n1kv/test_n1kv_plugin.py | Python | apache-2.0 | 59,556 | 0.000487 | # Copyright 2013 Cisco Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | nt_range}
if segment_type == c_const.NETWORK_TYPE_OVERLAY:
profile['sub_type'] = 'unicast'
profile['multicast_ip_range'] = '0.0.0.0'
net_p = n1kv_db_v2.create_network_profile(db_session, profile | )
n1kv_db_v2.sync_vxlan_allocations(db_session, net_p)
elif segment_type == c_const.NETWORK_TYPE_VLAN:
profile['physical_network'] = PHYS_NET
net_p = n1kv_db_v2.create_network_profile(db_session, profile)
n1kv_db_v2.sync_vlan_allocations(db_session, net_p)
... |
milad-soufastai/ansible-modules-extras | cloud/openstack/os_user_role.py | Python | gpl-3.0 | 6,078 | 0.000987 | #!/usr/bin/python
# Copyright (c) 2016 IBM
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distrib... | module.check_mode:
module.exit_json(changed=_system_state_change(state, assignment))
changed = False
if state == 'present':
if not assignment:
kwargs = _build_kwargs(user, group, project, domain)
cloud.grant_role(role, **kwargs)
... | roup, project, domain)
cloud.revoke_role(role, **kwargs)
changed=True
module.exit_json(changed=changed)
except shade.OpenStackCloudException as e:
module.fail_json(msg=str(e))
from ansible.module_utils.basic import *
from ansible.module_utils.openstack import *
i... |
KrisKennaway/pyapple2disk | src/apple2disk/process.py | Python | bsd-2-clause | 1,497 | 0.002672 | import disk
import dos33disk
import os
import sys
def main():
disks = {}
for root, dirs, files in os.walk(sys.argv[1]):
for f in files:
if not f.lower().endswith('.dsk') and not f.lower().endswith('.do'):
continue
print f
b = bytearray(open(os.path.... | xcept AssertionError:
pass
disks[f] = img
for ts, data in sorted(img.sectors.iteritems()):
print data
# Group disks by hash of boot1 sector
boot1_hashes = {}
for f, d in d | isks.iteritems():
boot1_hash = d.Boot1.hash
boot1_hashes.setdefault(boot1_hash, []).append(f)
for h, disks in boot1_hashes.iteritems():
print h
for d in sorted(disks):
print " %s" % d
if __name__ == "__main__":
main()
|
trabacus-softapps/docker-magicecommerce | additional_addons/product_pricelist_fixed_price/model/__init__.py | Python | agpl-3.0 | 909 | 0.0011 | # -*- coding: utf-8 -*-
##############################################################################
#
# 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 Software Foundation, either version 3 of the L... | 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 Affero General Public License for more details.
#
# You should have received a c | opy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import product_pricelist_item
|
yourlabs/django-autocomplete-light | test_project/select2_djhacker_formfield/urls.py | Python | mit | 446 | 0.004484 | from dal import autocomplete
from django.conf.urls import url
from .models import TModel
urlpatterns = [ |
url(
'test-autocomplete/$',
autocomplete.Select2QuerySetView.as_view(model=TModel),
name='select2_djhacker_formfield',
),
]
import djhacker
from django import forms
djhacker.formfield(
TModel.test,
forms.ModelChoiceField,
widget=autocomplete.ModelSelect2(url='select2 | _djhacker_formfield')
)
|
naelstrof/PugBot-Discord-Django | sample_secret_key.py | Python | mit | 64 | 0 | SECRET_KEY = 'KEY GENERATED BY KEY GEN FUNCTION IN sett | ings.p | y'
|
muffinresearch/solitude | lib/bango/client.py | Python | bsd-3-clause | 7,873 | 0.000127 | from datetime import datetime
import functools
import os
import uuid
from time import time
from django.conf import settings
from django_statsd.clients import statsd
from mock import Mock
from requests import post
from suds import client as sudsclient
from suds.transport import Reply
from suds.transport.http import Ht... | for ints, mean that tests work and so do requests from the
# command line using mock. As long as you don't do them too fast.
ltime = | lambda: str(int(time() * 1000000))[8:]
mock_data = {
'CreateBangoNumber': {
'bango': 'some-bango-number',
},
'CreatePackage': {
'packageId': ltime,
'adminPersonId': ltime,
'supportPersonId': ltime,
'financePersonId': ltime
},
'UpdateSupportEmailAddress': {
... |
facebookresearch/ParlAI | parlai/crowdsourcing/utils/worlds.py | Python | mit | 3,648 | 0.001919 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from parlai.core.worlds import World
class CrowdDataWorld(World):
def prep_save_data(self, workers):
"""
... | world for Crowd tasks.
"""
def __init__(self, opt, agent):
"""
Init should set up resources for running the task world.
"""
| self.agent = agent
self.episodeDone = False
def parley(self):
"""
A parley should represent one turn of your task.
"""
self.episodeDone = True
def episode_done(self):
"""
A ParlAI-Mephisto task ends and allows workers to be marked complete when t... |
LighthouseHPC/lighthouse | sandbox/lily/django_orthg/orthg/database/writeUrl.py | Python | mit | 396 | 0.035354 | import csv
with open('guided_least.csv', 'rb') as csvfile:
spamreader = csv.rea | der(csvfile)
url = open('url.csv','w')
for row in spamreader:
url.write(row[0]+',')
url.write(row[1]+',')
url.write(row[2]+',')
url.write("/"+row[1]+row[2]+',')
url.write('\n')
print "/"+row[1]+row[2]+'.f'+', | '
|
EventGhost/EventGhost | plugins/TheaterTek/__init__.py | Python | gpl-2.0 | 31,794 | 0.008178 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Ralph Eisenbach
#
# This plugin is based on the plugin for ZoomPlayer
# by Lars-Peter Voss <bitmonster@eventghost.net>
#
# This file is a plugin for EventGhost.
# Copyright © 2005-2020 EventGhost Project <http://www.eventghost.net/>
#
# EventGhost is free software: you can... | ISTCOUNT 3050 // AP->TT Current list count
#define IP_GETLIST 3060 // AP->TT Get playlist (name|name)
#define IP_DELATINDEX 3070 // AP->TT Delete file at index
#define IP_SETPRIVATE 4000 // AP->TT Private app | string
#define IP_GETPRIVATE 4010 // AP->TT Private app string
#define IP_WM_COMMAND 5000 // AP->TT Internal command
#define IP_KEYPRESS 5010 // AP->TT Key code
#define IP_SENDMSG 5020 // AP->TT Send message
#define IP_POSTMSG 5030 // AP->TT Post message
Auto Killer Commands
--------------------
#define IP_... |
dims/nova | nova/cells/state.py | Python | apache-2.0 | 18,615 | 0.000269 | # Copyright (c) 2012 Rackspace Hosting
# 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 req... | _cells_from_dict(self, db_cells_dict):
"""Make our cell info map match the db."""
# Update current cells. Delete ones that disappeared
for cells_dict in (self.parent_cells, self.child_cells):
for cell_name, cell_info in cells_dict.items():
| is_parent = cell_info.db_info['is_parent']
db_dict = db_cells_dict.get(cell_name)
if db_dict and is_parent == db_dict['is_parent']:
cell_info.update_db_info(db_dict)
else:
del cells_dict[cell_name]
# Add new cells
... |
tchellomello/home-assistant | homeassistant/components/heos/media_player.py | Python | apache-2.0 | 12,782 | 0.000469 | """Denon HEOS Media Player."""
from functools import reduce, wraps
import logging
from operator import ior
from typing import Sequence
from pyheos import HeosError, const as heos_const
from homeassistant.components.media_player import MediaPlayerEntity
from homeassistant.components.media_player.const import (
ATT... | er.set_volume(int(volume * 1 | 00))
async def async_update(self):
"""Update supported features of the player."""
controls = self._player.now_playing_media.supported_controls
current_support = [CONTROL_TO_SUPPORT[control] for control in controls]
self._supported_features = reduce(ior, current_support, BASE_SUPPORT... |
KaiRo-at/socorro | alembic/versions/32b54dec3fc0_fixes_bug_970406_add_raw_adi_logs_table.py | Python | mpl-2.0 | 1,194 | 0.008375 | """Fixes bug 970406 - add raw_adi_logs table
Revision ID: 32b54dec3fc0
Revises: 1ab8d5514ce2
Create Date: 2014-06-12 11:47:19.398882
"""
# revision identifiers, used by Alembic.
revision = '32b54dec3fc0'
down_revision = '1ef041dfc3d5'
from alembic import op
from socorrolib.lib import citexttype, jsontype, buildtype... | .create_table('raw_adi_logs',
sa.Column('report_date', sa.DATE(), nullable=True),
sa.Column('product_name', sa.TEXT(), nullable=True),
sa.Column('product_os_platform', sa.TEXT(), nullable=True),
sa.Column('product_os_version', sa.TEXT(), nullable=True),
sa.Column('product_version... | llable=True),
sa.Column('build_channel', sa.TEXT(), nullable=True),
sa.Column('product_guid', sa.TEXT(), nullable=True),
sa.Column('count', sa.INTEGER(), nullable=True)
)
def downgrade():
op.drop_table('raw_adi_logs')
|
simongibbons/numpy | numpy/core/_type_aliases.py | Python | bsd-3-clause | 7,272 | 0.002338 | """
Due to compatibility, numpy has a very large number of different naming
conventions for the scalar types (those subclassing from `numpy.generic`).
This file produces a convoluted set of dictionaries mapping names to types,
and sometimes other mappings too.
.. data:: allTypes
A dictionary of names to types that... | dx += 1
sctypes['int'].insert(indx, _gi.type)
sctypes['uint'].insert(indx, dtype('P').type)
_set_array_types()
# Add additional strings to the sctypeDict
_toadd = ['int', 'float', 'complex', 'bool', 'object',
'str', 'bytes', ('a', 'bytes_')]
for name in _t | oadd:
if isinstance(name, tuple):
sctypeDict[name[0]] = allTypes[name[1]]
else:
sctypeDict[name] = allTypes['%s_' % name]
del _toadd, name
|
StructuralNeurobiologyLab/SyConn | syconn/proc/graphs.py | Python | gpl-2.0 | 26,039 | 0.001613 | # -*- coding: utf-8 -*-
# SyConn - Synaptic connectivity inference toolkit
#
# Copyright (c) 2016 - now
# Max Planck Institute of Neurobiology, Martinsried, Germany
# Authors: Philipp Schubert, Joergen Kornfeld
import itertools
from typing import List, Any, Optional, TYPE_CHECKING
import networkx as nx
import numpy as... | a majority vote on a
BFS subset of nodes for every node in the graph
Parameters
Args:
vertices: np.array
N, 3
vertex_labels: np.array
N, 1
max_edge_length: float
maximum distance between vertices to consider them connected in the
graph... | """
G = create_graph_from_coords(vertices, max_dist=max_edge_length, mst=False,
force_single_cc=False)
# create BFS subset
bfs_nn = split_subcc(G, max_nb=n_voting, verbose=False)
new_vertex_labels = np.zeros_like(vertex_labels)
for ii in range(len(vertex_labels)):
... |
starlure/google_python_class | babynames/babynames.py | Python | apache-2.0 | 2,697 | 0.021505 | #!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
"""Baby Names exercise
Define the extract_names() function below and c... | order.
['2006', 'Aaliyah 91', Aaron 57', 'Abagail 895', ' ...]
"""
# +++your code here+++
dict = {}
printlist = []
f = open(filename, 'rU')
totalstr = f.read()
matchyear = re.search('<h\d.*>Popularity\sin\s(\d\d\d\d)</h\d>',totalstr)
printlist.append(matchyear.group(1))
#return matchyear.group(1)
... | t.keys().extend(tuples[1])
dict[tuples[1]] = tuples[0]
if not tuples[2] in dict.keys():
dict.keys().extend(tuples[2])
dict[tuples[2]] = tuples[0]
#return sorted(dict.items())
for pairs in sorted(dict.items()):
printlist.append(pairs[0] + ' ' + pairs[1])
return printlist
def main():
# ... |
alan-mnix/MLFinalProject | pynlpl/formats/timbl.py | Python | gpl-2.0 | 4,614 | 0.014088 | ###############################################################
# PyNLPl - Timbl Classifier Output Library
# by Maarten van Gompel (proycon)
# http://ilk.uvt.nl/~mvgompel
# Induction for Linguistic Knowledge Research Group
# Universiteit van Tilburg
#
# Derived from code by Sander ... | 1
self.ignorevalues = ignorevalues #Ignore columns with the following values
de | f __iter__(self):
# Note: distance parsing (+v+di) works only if distributions (+v+db) are also enabled!
for line in self.stream:
endfvec = None
line = line.strip()
if line and line[0] != '#': #ignore empty lines and comments
segments... |
Zenohm/mafiademonstration | tests/test_stage.py | Python | mit | 336 | 0 | from unittest import TestCase
class TestStage(TestCase):
def tes | t_add_players(self):
self.fail()
def test_initialize_settings(self):
self.fail()
def test_initialize_players(self):
self.fail()
| def test_on_enter(self):
self.fail()
def test_on_pre_leave(self):
self.fail()
|
sebrandon1/tempest | tempest/api/orchestration/stacks/test_soft_conf.py | Python | apache-2.0 | 7,882 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | all fields were created
self.assert_fields_in_dict(
self.deployment['software_deployment'], 'action', 'config_id',
'id', 'input_values', 'output_values', 'server_id', 'status',
'status_reason')
# Testing get for this deployment and verifying parameters
self._... | d('2ac43ab3-34f2-415d-be2e-eabb4d14ee32')
def test_software_deployment_update_no_metadata_change(self):
"""Testing software deployment update without metadata change."""
metadata = self.client.show_software_deployment_metadata(
self.server_id)
# Updating values without changing t... |
yspanchal/storm-example | petrel/petrel/generated/storm/Nimbus.py | Python | bsd-3-clause | 98,735 | 0.016104 | #
# Autogenerated by Thrift Compiler (0.9.1)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from ttypes import *
from thrift.Thrift import TProcessor
from thrift.transport import TTransport
... | plicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = activate_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.e is not None:
raise result.e
return
def deactivate(self, name):
"""
Parameters:
- name
... | _deactivate(name)
self.recv_deactivate()
def send_deactivate(self, name):
self._oprot.writeMessageBegin('deactivate', TMessageType.CALL, self._seqid)
args = deactivate_args()
args.name = name
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_deact... |
OpenUpSA/contact-mps | manage.py | Python | mit | 253 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
| os.environ.setdefault("DJANGO_SETTINGS | _MODULE", "contactmps.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
SchrodingersGat/kicad-footprint-generator | scripts/Connector/Connector_Harwin/conn_harwin_m20-781xx45_smd_top_dual_row.py | Python | gpl-3.0 | 9,793 | 0.008475 | #!/usr/bin/env python3
'''
kicad-footprint-generator is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
kicad-footprint-generator is distributed... | ######################## CrtYd Layer ###########################
CrtYd_offset = configuration['courtyard_offset']['connector']
CrtYd_grid = configuration['courtyard_grid']
poly_yd = [
{'x': -3.8 - | CrtYd_offset, 'y': body_edge['top'] - CrtYd_offset},
{'x': 3.8 + CrtYd_offset, 'y': body_edge['top'] - CrtYd_offset},
{'x': 3.8 + CrtYd_offset, 'y': body_edge['bottom'] + CrtYd_offset},
{'x': -3.8 - CrtYd_offset, 'y': body_edge['bottom'] + CrtYd_offset},
{'x': -3.8 - CrtYd_offset, 'y': ... |
SHS-ComputerScience/A-Level_2016-18 | 2. Exemplars/Factorial_Finder/factorial.py | Python | gpl-3.0 | 853 | 0.007034 | """ Factorial Finder
Name: Mr Gorman
Date: 01/12/2016
"""
def find_factorial_loop(n):
""" Function to find factorial using iteration.
For more info on range:
https://docs.python.org/3/library/stdtypes.html#range
"""
factorial = 1
for i in range(n, 0, -1): # alternatively... | e(1, n + 1):
factorial *= i
return factorial
def find_factorial_recursive(n):
""" Function to find factorial using recursion.
For more info on recursion limit:
https://docs.python.org/3/library/sys.html#sys.getrecursionlimit
"""
if n == 0:
return 1
else:
... | main() |
ESOedX/edx-platform | openedx/core/djangoapps/site_configuration/context_processors.py | Python | agpl-3.0 | 626 | 0.003195 | """
Django template context processors.
"""
from __future__ import absolute_import
from | django.conf import settings
from django.utils.http import urlquote_plus
from openedx.core.djangoapps.site_configuratio | n import helpers as configuration_helpers
def configuration_context(request):
"""
Configuration context for django templates.
"""
return {
'platform_name': configuration_helpers.get_value('platform_name', settings.PLATFORM_NAME),
'current_url': urlquote_plus(request.build_absolute_uri(... |
hfaran/slack-export-viewer | slackviewer/user.py | Python | mit | 2,188 | 0.002285 | # User info wrapper object
import logging
class User(object):
"""
Wrapper o | bject around an entry in users.json. Behaves like a read-only dictionary if
asked, but adds some useful logic to decouple the front end from the JSON structure.
"""
_NAME_KEYS = ["display_name", "real_name"]
_DEFAULT_IMAGE_KEY = "image_512"
def __init_ | _(self, raw_data):
self._raw = raw_data
def __getitem__(self, key):
return self._raw[key]
@property
def display_name(self):
"""
Find the most appropriate display name for a user: look for a "display_name", then
a "real_name", and finally fall back to the always-pres... |
yippeecw/sfa | sfa/managers/slice_manager.py | Python | mit | 23,958 | 0.008598 | import sys
import time
import traceback
from StringIO import StringIO
from copy import copy
from lxml import etree
from sfa.trust.sfaticket import SfaTicket
from sfa.trust.credential import Credential
from sfa.util.sfalogging import logger
from sfa.util.xrn import Xrn, urn_to_hrn
from sfa.util.version import version_... | "elapsed": time.time()-tStart, "status": "success"}
except Exception, e:
api.logger.log_exc("ListResources failed at %s" %(server.url))
return {"aggregate": aggregate, "elapsed": time.time()-tStart, "status": "exception", "exc_info": sys.exc_info()}
# get slice's... | (hrn, type) = urn_to_hrn(xrn)
if 'geni_compressed' in options:
del(options['geni_compressed'])
# get the rspec's return format from options
rspec_version = version_manager.get_version(options.get('geni_rspec_version'))
version_string = "rspec_%s" % (rspec_version)
... |
VirusTotal/content | Packs/CortexXDR/Integrations/XDR_iocs/XDR_iocs.py | Python | mit | 17,908 | 0.00201 | import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
import hashlib
import secrets
import string
import tempfile
from datetime import timezone
from typing import Dict, Optional, List, Tuple, Union
from dateparser import parse
from urllib3 import disable_warnings
from math ... | endors
def demisto_types_to_xdr(_type: str) -> str:
xdr_type = _type.upper()
if xdr_type.startswith('FILE'):
return 'HASH'
elif xdr_type == 'DOMAIN':
return 'DOMAIN_NAME'
else:
return xdr_type
def demisto_ioc_to_xdr(ioc: Dict) -> Dict:
try:
xdr_ioc: Dict = {
... | to_types_to_xdr(str(ioc['indicator_type'])),
'reputation': demisto_score_to_xdr.get(ioc.get('score', 0), 'UNKNOWN'),
'expiration_date': demisto_expiration_to_xdr(ioc.get('expiration'))
}
# get last 'IndicatorCommentRegular'
comment: Dict = next(filter(lambda x: x.get('typ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.