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 |
|---|---|---|---|---|---|---|---|---|
waseem18/oh-mainline | vendor/packages/scrapy/scrapy/telnet.py | Python | agpl-3.0 | 2,808 | 0.002137 | """
Scrapy Telnet Console extension
See documentation in docs/topics/telnetconsole.rst
"""
import pprint
from twisted.conch import manhole, telnet
from twisted.conch.insults import insults
from twisted.internet import protocol
from scrapy.xlib.pydispatch import dispatcher
from scrapy.exceptions import NotConfigured... | t_engine_status(self.crawler.engine),
'p': pprint.pprint,
'prefs': print_live_refs,
'hpy': hpy,
'help': "This is Scrapy telnet console. For more info see: " \
"http://doc.scrapy.org/topics/telnetconsole.html", # see #284
| }
send_catch_log(update_telnet_vars, telnet_vars=telnet_vars)
return telnet_vars
|
jokerYellow/TranslateFiles | test/conversion_test.py | Python | mit | 4,082 | 0.003791 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import unittest
class OpenCCTest(unittest.TestCase):
def setUp(self):
self.openCC = OpenCC()
def test_hk2s(self):
self.openCC.set_conversion('hk2s')
words = '香煙(英語:Cigarette),為煙草製品的一種。滑鼠是一種很常見及常用的電腦輸入設備。'
sel... | self.openCC.set_conversion('s2tw')
words = '香烟(英语:Cigarette),为烟草制品的一种。鼠标是一种很常见及常用的电脑输入设备。'
self.assertEqual(self.openCC.convert(words), '香菸(英語:Cigarette),為菸草製品的一種。鼠標是一種很常見及常用的電腦輸入設備。')
def test_s2twp(self):
self.openCC.set_conversion('s2twp')
words = '香烟(英语:Cigarette),为烟草制品的一种。... | 常用的電腦輸入裝置。')
def test_t2hk(self):
self.openCC.set_conversion('t2hk')
words = '香菸(英語:Cigarette),爲菸草製品的一種。滑鼠是一種很常見及常用的電腦輸入裝置。'
self.assertEqual(self.openCC.convert(words), '香煙(英語:Cigarette),為煙草製品的一種。滑鼠是一種很常見及常用的電腦輸入裝置。')
def test_t2s(self):
self.openCC.set_conversion('t2s')
... |
cas4ey/behavior-studio | source/remote_debugger/debugger_mode.py | Python | gpl-3.0 | 2,171 | 0.003224 | # coding=utf-8
# -----------------
# file : debugger_mode.py
# date : 2014/11/18
# author : Victor | Zarubkin
# contact : [email protected]
# copyright : Copyright (C) 2014 Victor Zarubkin
# license : This file is part of BehaviorStudio.
# :
# : BehaviorStudio is free software: you can redistribute it and/or modify
# : it under the terms of the GNU General Public Licen... | : (at your option) any later version.
# :
# : BehaviorStudio 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 General Pub... |
lidavidm/mathics-heroku | venv/lib/python2.7/site-packages/sympy/strategies/tree.py | Python | gpl-3.0 | 3,710 | 0.001348 | from functools import partial
from sympy.strategies import chain, minimize
import sympy.strategies.branch as branch
from sympy.strategies.branch import yieldify
identity = lambda x: x
def treeapply(tree, join, leaf=identity):
""" Apply functions onto recursive containers (tree)
join - a dictionary mapping co... | his is an exhaustive algorithm. In the example
([a, b], [c, d])
All of the results from
(a, c), (b, c), (a, d), (b, d)
are returned. This can lead to combinatorial blowup.
See sympy.strategies.greedy for details on input
"""
return treeapply(tree, {list: branch.multiplex, tupl... | ty, **kwargs):
return lambda expr: min(tuple(allresults(tree, **kwargs)(expr)),
key=objective)
|
venicegeo/eventkit-cloud | eventkit_cloud/utils/services/errors.py | Python | bsd-3-clause | 454 | 0.002203 | class ServiceError(Exception):
"""Base class for exceptions in this module."""
pass
class UnsupportedFormatError(ServiceError):
"""Used to raise exceptions when a response doesn't match expected semantics or for failed version checks."""
pass
clas | s MissingLayerError(ServiceError):
"""Used if expected layer could not be found in the service."""
def __init__(self, message):
| self.message = message
|
fedora-infra/tahrir-api | alembic/versions/3c7fd5b4e2c2_add_two_new_columns_.py | Python | gpl-3.0 | 1,034 | 0.003868 | """Add two new columns for Person.
Revision ID: 3c7fd5b4e2c2
Revises: | 24282792d72a
Create Date: 2013-06-26 14:46:28.361709
"""
# revision identifiers, used by Alembic.
revision = "3c7fd5b4e2c2"
down_revision = "16943d9088cf"
import tahrir_api
from alembic import op
import sqlalchemy as sa
import datetime
def upgrade():
op.add_column("persons", sa.Column("created_on", sa.DateTime... | sa.Boolean()))
# We have to do this manually because I can't figure out how to make
# alembic apply defaults to sqlite.
engine = op.get_bind().engine
session_maker = sa.orm.sessionmaker(bind=engine)
session = sa.orm.scoped_session(session_maker)
persons = session.query(tahrir_api.model.Person)... |
booi/aracna | pypose-old/aracna-python/driver.py | Python | gpl-3.0 | 5,702 | 0.003858 | #!/usr/bin/env python
"""
PyPose: Serial driver for connection to arbotiX board or USBDynamixel.
Copyright (c) 2008,2009 Michael E. Ferguson. All right reserved.
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 Fr... |
vals = self.execute(index, AX_READ_DATA, [regstart, rlength])
if vals == None:
print "Read Failed: Servo ID = " + str(index)
return -1
if rlength == 1:
return vals[0]
return vals
def syncWrite(self, regstart, vals):
""" Set the va... | d1, val1, val2), (id2, val1, val2))) """
self.ser.flushInput()
length = 4
valsum = 0
for i in vals:
length = length + len(i)
valsum = valsum + sum(i)
checksum = 255 - ((254 + length + AX_SYNC_WRITE + regstart + len(vals[0]) - 1 + valsum)%256)
... |
CrowdSpot/shareabouts | src/sa_web/views.py | Python | gpl-3.0 | 15,185 | 0.001317 | import requests
import yaml
import ujson as json
import logging
import os
import time
import hashlib
import httpagentparser
import urllib2
from .config import get_shareabouts_config
from django.shortcuts import render
from django.conf import settings
from django.core.cache import cache
from django.core.mail import Emai... | get('CONFIG'))
config.update(settings.SHAREABOUTS.get('CONTEXT', {}))
# Before we start, check whether we're | configured to send at all on new
# place.
should_send = config.get('notifications', {}).get('on_new_place', False)
if not should_send:
return
# First, check that we have all the settings and data we need. Do not bail
# after each error, so that we can report on all the validation problems
... |
ubuntu-touch-apps/filemanager-app | tests/autopilot/filemanager/fixture_setup.py | Python | gpl-3.0 | 2,725 | 0 | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
#
# Copyright (C) 2013, 2014 Canonical Ltd.
#
# 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; version 3.
#
# Thi... | file, self.path)
@autopilot.logging.log_action(logger.info | )
def delete_file(self, path):
"""Delete a file, if it exists."""
if os.path.exists(path):
logger.debug('Deleting file.')
os.remove(path)
else:
logger.debug('File does not exist.')
class TemporaryDirectoryInDirectory(fixtures.Fixture):
"""Create a te... |
titasakgm/brc-stock | openerp/addons/bangkok_rubber/__openerp__.py | Python | agpl-3.0 | 1,546 | 0.003234 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | date_xml': [
'security.xml',
'stock_view.xml',
'adempier_view.xml',
],
'images': [],
'installable': True,
'a | pplication': True,
'auto_install': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
backmari/moose | python/peacock/Execute/TerminalTextEdit.py | Python | lgpl-2.1 | 1,846 | 0.00325 | #!/usr/bin/env python
from PyQt5.QtWidgets import QTextEdit, QMenu, QFileDialog, QSizePolicy
import mooseutils
class TerminalTextEdit(QTextEdit):
"""
A readonly text edit that replaces terminal codes with appropiate html codes.
Also uses fixed font.
"""
def __init__(self, **kwds):
super(Ter... | import sys
qapp = QApplication(sys.argv)
w = TerminalTextEdit()
w.append('<span style="color:red;">foo</s | pan>')
w.show()
w.setEnabled(True)
sys.exit(qapp.exec_())
|
madoodia/codeLab | nuke_sdk/CompoTool/menu.py | Python | mit | 630 | 0.004762 | # [email protected]
# This to | ol created for using in composite, for Hossein Bayat
import os
import nuke
# add our paths to the plugins path of nuke
current_dir = os.path.dirname(os.path.abspath(__file__))
icons_path = current_dir + r"\icons"
nuke.pluginAddPath(icons_path)
gizmos_path = current_dir + r"\gizmos"
nuke.pluginAddPath(g | izmos_path)
scripts_path = current_dir + r"\scripts"
nuke.pluginAddPath(scripts_path)
import app
# adding HB menu
nuke.menu('Nuke').addCommand('--HB--/CompoTool', 'app.show()', 'ctrl+alt+n', icon='target_d.png')
nuke.menu('Nuke').addCommand('--HB--/About', 'app.aboutUs()', 'ctrl+alt+m')
|
google-code/billreminder | src/gui/adddialog.py | Python | mit | 20,237 | 0.004101 | # -*- coding: utf-8 -*-
__all__ = ['AddDialog']
import pygtk
pygtk.require('2.0')
import gtk
import gconf
import datetime
import locale
import gobject
from lib import utils
from lib import common
from lib import scheduler
from lib.bill import Bill
from lib.actions import Actions
from lib.utils import create_pixbuf
f... | :
gtk.Dialog. | __init__(self, title=title, parent=parent,
flags=gtk.DIALOG_MODAL|gtk.DIALOG_NO_SEPARATOR,
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
gtk.STOCK_SAVE, gtk.RESPONSE_ACCEPT))
self.set_icon_from_file(common.APP_ICON)
... |
realraum/ari | test/overlay-test.py | Python | gpl-3.0 | 6,283 | 0.006844 | #!/usr/bin/env python
##
## ari
##
## the realraum audience response indicator
##
##
## Copyright (C) 2015 Christian Pointner <[email protected]>
##
## This file is part of ari.
##
## ari is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as publi... | _spacing_, box_y + self.meter_spacing_, self.meter_width_*l, self.meter_height_)
svg += " <line x1='%i' y1='%i' x | 2='%i' y2='%i' style='stroke:rgb(255,0,0);stroke-width:3' />\n" %(
box_x + self.meter_width_*lp, box_y + self.meter_spacing_, box_x + self.meter_width_*lp, box_y + self.meter_spacing_ + self.meter_height_)
svg += " <rect x='%i' y='%i' width='%i' height='%i' style='fill:url(#vumeter);opacity:0.9' /... |
jinzekid/codehub | python/day9/ssh.py | Python | gpl-3.0 | 310 | 0 | # Author: Jason Lu
import paramiko
ssh = p | aramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='10.0.031', port=52113, username='root', password='123')
stdin, stdout, stderr = ssh.exec_command('df')
result = stdout.read()
print(result.deco | de())
ssh.close()
|
PandaWei/tp-libvirt | libvirt/tests/src/virsh_cmd/domain/virsh_setmaxmem.py | Python | gpl-2.0 | 7,485 | 0 | import logging
from autotest.client.shared import utils, error
from virttest import virsh, virt_vm
from virttest.libvirt_xml import vm_xml
def run(test, params, env):
"""
Test command: virsh setmaxmem.
1) Prepare vm environment.
2) Handle params
3) Run test command and get vm started then get max... | etail)
# Actual results
test_vmxml_mem = vmxml_max_mem(vm_name)
test_dominfo_mem = vm.get_max_mem()
# Expected results for both vmxml and dominfo
if sizearg == "yes":
expected_mem = int(dargs["sizearg"])
else:
| expected_mem = int(dargs["size"])
print_debug_stats(original_vmxml_mem, original_dominfo_mem,
expected_mem, test_vmxml_mem, test_dominfo_mem)
else:
if vm.state() == "paused":
vm.resume()
finally:
original_vmxml.s... |
gbrmachado/treeherder | tests/etl/test_buildapi.py | Python | mpl-2.0 | 10,999 | 0.001 | import json
import os
import pytest
import responses
from django.conf import settings
from django.core.cache import cache
from treeherder.etl.buildapi import (CACHE_KEYS,
Builds4hJobsProcess,
PendingJobsProcess,
... | se
stored_obj = jm.get_dhub().execute(proc="jobs_test.selects.jobs")
jm.disconnect()
assert len(stored_obj) == 1
def test_ingest_builds4h_jobs(jm, initial_data,
mock_buildapi_builds | 4h_url,
mock_post_json,
mock_log_parser,
mock_get_resultset,
mock_get_remote_content):
"""
a new buildapi completed job creates a new obj in the job table
"""
etl_process = Builds4hJob... |
NervanaSystems/coach | rl_coach/presets/CartPole_Dueling_DDQN.py | Python | apache-2.0 | 2,384 | 0.002936 | import math
from rl_coach.agents.ddqn_agent import DDQNAgentParameters
from rl_coach.architectures.head_parameters import DuelingQHeadParameters
from rl_coach.base_parameters import VisualizationParameters, PresetValidationParameters
from rl_coach.core_types import TrainingSteps, EnvironmentEpisodes, EnvironmentSteps
... |
graph_manager = BasicRLGraphManager(agent_params=agent_params, env_params=env_params,
schedule_params=schedule_params, vis_params=VisualizationParameters(),
| preset_validation_params=preset_validation_params)
|
ForensicTools/GRREAT-475_2141-Chaigon-Failey-Siebert | parsers/ie_history.py | Python | apache-2.0 | 5,573 | 0.00646 | #!/usr/bin/env python
# Copyright 2011 Google Inc. All Rights Reserved.
"""Parser for IE index.dat files.
Note that this is a very naive and incomplete implementation and should be
replaced with a more intelligent one. Do not implement anything based on this
code, it is a placeholder for something real.
For anyone w... | ry record.
"""
record_header = "<4sLQQL"
get4 = lambda x: struct.unpack("<L", self.input_dat[x:x+4])[0]
url_offset = struct.unpack("B", self.input_dat[offset+52:offset+53])[0]
if url_offset in [0xFF, 0xFE]:
return None
data_offset = get4( | offset + 68)
data_size = get4(offset + 72)
start_pos = offset + data_offset
data = struct.unpack("{0}s".format(data_size),
self.input_dat[start_pos:start_pos + data_size])[0]
fmt = record_header
unknown_size = url_offset - struct.calcsize(fmt)
fmt += "{0}s".format(unknow... |
caseyching/incubator-airflow | airflow/contrib/operators/bigquery_operator.py | Python | apache-2.0 | 3,249 | 0.002155 | # -*- coding: utf-8 -*-
#
# 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
... | ks.bigquery_hook import BigQueryHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class BigQueryOperator(BaseOperator):
"""
Executes BigQuery SQL queries in a specific BigQuery database
"""
template_fields = ('bql', 'destination_dataset_table')
templa... | bql,
destination_dataset_table = False,
write_disposition='WRITE_EMPTY',
allow_large_results=False,
bigquery_conn_id='bigquery_default',
delegate_to=None,
udf_config=False,
*args,
... |
vladiibine/trust-network | src/python/trust_network_backend/tnb/apps/core/views.py | Python | mit | 954 | 0.002096 | import os
from tornado import gen
import tornado.web
class DocsHandler(tornado.web.RequestHandler):
| @gen.coroutine
def get(self):
version = "{}://{}/docs/version/v1.yml".format(
self.request.protocol, self.request.host)
self.render("swagger/index.html", version=version)
class HomeHandler(tornado.web.StaticFileHandler):
@gen.coroutine
def get(self, path, include_body=True):
... | r(tornado.web.StaticFileHandler):
"""If a file exists in the root folder, serve it, otherwise serve index.html
"""
@gen.coroutine
def get(self, path, include_body=True):
absolute_path = self.get_absolute_path(self.root, path)
is_file = os.path.isfile(absolute_path)
if is_file:... |
egbertbouman/tribler-g | Tribler/UPnP/common/objectconsole.py | Python | lgpl-2.1 | 2,734 | 0.006584 | # Written by Ingar Arntzen
# see LICENSE.txt for license information
"""
This module implements a generic console interface that can
be attached to any runnable python object.
"""
import code
import __builtin__
import threading
import exceptions
##############################################
# OBJECT CONSOLE
#######... | _run = getattr(object_, run)
self._object_stop = getattr(object_, stop)
self._thread = threading.Thread(group=None,
target=self._object_run,
name="ObjectT | hread")
# Configure Console Namespace
self._name_space = {}
self._name_space['__builtiname_space__'] = __builtin__
self._name_space['__name__'] = __name__
self._name_space['__doc__'] = __doc__
self._name_space['help'] = self._usage
if name_space and isinstance(n... |
bbtfr/MarkdownLight | tests/test_markdown_light.py | Python | mit | 22,066 | 0.005121 | import syntax_test
class TestMarkdownLight(syntax_test.SyntaxTestCase):
def setUp(self):
super().setUp()
self.set_syntax_file("Packages/MarkdownLight/MarkdownLight.tmLanguage")
def check_default(self, patterns):
self.check_in_single_scope(patterns, 'text')
def test_simple_text(sel... |
```
''')
self.check_eq_scope([ 'int', 'def' ], 'storage.type')
self.check_eq_scope([ | '123', '567' ], 'constant.numeric')
self.check_eq_scope('g', 'entity.name')
self.check_eq_scope('return', 'keyword.control')
def test_indented_raw_blocks(self):
self.set_text('''
A
B
C
''')
self.check_eq_scope(r' B\n', 'markup.raw.block')
self.check_default([ r'\nA\... |
TianpeiLuke/GPy | GPy/util/linalg_gpu.py | Python | bsd-3-clause | 3,189 | 0.011602 | # Copyright (c) 2012, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
#
# The utility functions for GPU computation
#
import numpy as np
from ..util import gpu_init
try:
from pycuda.reduction import ReductionKernel
from pycuda.elementwise import ElementwiseKernel
... | np.einsum('na,nb->nab',m1,m2) a=dim1, b=dim2 )
join_prod = ElementwiseKernel("double *out, double *m1, double *m2, int dim1, int dim2", "out[i] = m1[(i%dim1)*dim1+(i%(dim1*dim2))/dim1]*m2[(i%dim1)*dim1+i/(dim1*dim2)]", "join_prod")
except:
pass
try:
import scikits.cuda.linalg as culinalg
from scikits.... | |
stevegt/isconf4 | lib/python/isconf/Cache.py | Python | gpl-2.0 | 23,037 | 0.007727 | from __future__ import generators
import ConfigParser
import copy
import email.Message
import email.Parser
import email.Utils
import errno
import hmac
import inspect
import md5
import os
import popen2
import random
import re
import select
import sha
import shutil
import socket
import sys
import tempfile
import time
imp... | debug("sendq overflow")
return
self.sendq.append((msg,addr,self.udpport))
def sender(self):
while True:
yield None
yield kernel.sigsleep, 1
while len( | self.sendq):
msg,addr,udpport = self.sendq.pop(0)
try:
debug("sendto", addr, msg)
self.sock.sendto(msg,0,(addr,udpport))
except:
info("sendto failed: %s" % addr)
self.sendq.append((msg,addr,ud... |
BorisJeremic/Real-ESSI-Examples | analytic_solution/test_cases/Contact/Stress_Based_Contact_Verification/SoftContact_NonLinHardSoftShear/Area/Normalized_Shear_Stress_Plot.py | Python | cc0-1.0 | 6,112 | 0.017507 | #!/usr/bin/python
import h5py
import matplotlib.pylab as plt
import matplotlib as mpl
import sys
import numpy as np;
plt.rcParams.update({'font.size': 28})
# set tick width
mpl.rcParams['xtick.major.size'] = 10
mpl.rcParams['xtick.major.width'] = 5
mpl.rcParams['xtick.minor.size'] = 10
mpl.rcParams['xtick.minor.width... | ar_stress = np.sqrt(shear_stress_x*shear_stress_x + shear_stress_y*shear_stress_y );
shear_stress = shear_stress_x;
shear_strain = shear_strain_x;
# Configure the figure filename, according to the input filename.
outfig=thefile.replace("_","-")
outfigname=outfig.replace("h5.feioutput","pdf")
# Plot the figure. Add la... | [mm]$")
plt.ylabel(r"Normalized Shear Stress $\tau/\sigma_n$")
###############################################################
## Area = 1e^-4 m^2
###############################################################
# Go over each feioutput and plot each one.
thefile = "A_1e-4/Analytical_Solution_Shear.feioutput";
fin... |
ceeblet/OST_PythonCertificationTrack | Python2/MoreGuiLayout_homework/src/moreframesandbuttons2.py | Python | mit | 3,128 | 0.003836 | import os
from tkinter import *
ALL = N+S+E+W
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master.rowconfigure(0, weight=1)
self.master.columnconfigure(0, weight=1)
self.grid(sticky=ALL)
root.bind("<Return>", self.file_op... | l=BOTH, expand=True)
self.rowconfigure(0, weight=1)
self.rowconfig | ure(1, weight=1)
self.label1 = Label(self.f1, bg="red", text="Frame 1")
self.label1.grid(row=0, sticky=ALL)
self.label2 = Label(self.f2, bg="green", text="Frame 2")
self.label2.grid(row=1, sticky=ALL)
# self.label3 = Label(self.f3, bg="blue", text="Frame 3")
... |
danielgavrilov/schools | db/insert_schools.py | Python | mit | 1,894 | 0.00264 | from pymongo import MongoClient
from helpers import db_url, db_database, pa | rse_csv, to_int, to_float
mongo = MongoClient(db_url)
db = mongo[db_database]
print("Updating school information from 2015 data...")
for school in parse_csv("../data/2015/ks5_attainment.csv"):
# All schools are RECTYPE=1. Other RECTYPEs are used for local averages. |
# Closed schools are ICLOSE=1. We skip them too.
if (school["RECTYPE"] != "1") or (school["ICLOSE"] == "1"):
continue
db.schools.update(
{ "_id": school["URN"] },
{ "$set": {
"lea": to_int(school["LEA"]),
"name": school["SCHNAME"],
"a... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_08_01/operations/_express_route_service_providers_operations.py | Python | mit | 5,203 | 0.004421 | # 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._serialize = serializer
self._deserialize = deserializer
self._config = config
def list(
self,
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.ExpressRouteServiceProviderListResult"]
"""Gets all the available express route service providers... | A custom type or function that will be passed the direct response
:return: An iterator like instance of either ExpressRouteServiceProviderListResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2019_08_01.models.ExpressRouteServiceProviderListResult]
:... |
liamneath1/SUMOWaferBackend | PythonBackend/EmailObject.py | Python | mit | 1,333 | 0.009002 | import hashlib
import sys
import datetime
class EmailObject:
def __init__(self, sender, date, subject, body):
self.sender = sender
self.date = datetime.datetime.strptime(date[5:25], '%d %b %Y %H:%M:%S') #TODO: FIX THIS CODE TO BE MORE ROBUST
self.body = body
self.subject = subject
... | hasher = hashlib.md5()
hasher.update(self.sender.encode() + self.date.strftime('%Y-%m-%d %H:%M:%S').encode() + self.subject.encode())
hasher.upda | te(self.body.encode())
result = int(hasher.hexdigest(), 16) % sys.maxsize
return result
def fetchEmailMain(self):
sqlLine = "('" + self.sender + "','" + self.date.strftime('%Y-%m-%d %H:%M:%S') + "','" + self.subject + "'," + str(self.emailId) + ")"
return sqlLine
def fetchEmail... |
anhstudios/swganh | data/scripts/templates/object/static/structure/tatooine/shared_planter_hanging_style_01.py | Python | mit | 463 | 0.047516 | #### NOTICE: THIS FILE IS A | UTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Static()
result.template = "object/static/structure/tatooine/shared_planter_hanging_style_01.iff"
result.attribute_template_id = -1
result.... | t")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
JulienLeonard/PVG | tests/test_geoquad.py | Python | gpl-2.0 | 502 | 0.031873 | from utils import *
from geoutils import *
from polygon import *
from circle import *
from geoquad import *
import unittest
class GeoQuad | Test(unittest.TestCase):
def test_init(self):
geoquad = GeoQuad.square(Point(1.0,1.0),2.0)
self.assertEqual(geoquad.xpoint(Point(0.5,0.5)).coords(),(1.0,1.0))
def test_split(self):
geoquad = GeoQuad.square(Point(1.0,1.0),2.0)
sel | f.assertEqual(len(geoquad.xsplit(0.5)),2)
|
dmacvicar/spacewalk | client/solaris/rhnclient/compile.py | Python | gpl-2.0 | 3,533 | 0.001698 | #!/usr/bin/python
#
# Copyright (c) 2008 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have ... | long(os.stat(file | )[8])
codestring = f.read()
f.close()
if codestring and codestring[-1] != '\n':
codestring = codestring + '\n'
try:
codeobject = __builtin__.compile(codestring, dfile or file, 'exec')
except SyntaxError, detail:
lines = traceback.format_exception_only(SyntaxError, detail)
... |
xlhtc007/blaze | blaze/compute/csv.py | Python | bsd-3-clause | 2,667 | 0.00075 | from __future__ import absolute_import, division, print_function
import pandas
import os
from toolz import curry, concat
import pandas as pd
import numpy as np
from collections import Iterator, Iterable
from odo import into
from odo.chunks import chunks
from odo.backends.csv import CSV
from multipledispatch import MDN... | ne, chunksize=2**18, **kwargs):
comfortable_memory = comfortable_memory or min(1e9, available_memory() / 4)
kwargs = dict()
# Chunk if the file is large
if os.path.getsize(data.path) > comfortable_memory:
kwargs['chunksize'] | = chunksize
else:
chunksize = None
# Insert projection into read_csv
oexpr = optimize(expr, data)
leaf = oexpr._leaves()[0]
pth = list(path(oexpr, leaf))
if len(pth) >= 2 and isinstance(pth[-2], (Projection, Field)):
kwargs['usecols'] = pth[-2].fields
if chunksize:
... |
mishbahr/django-fwdform | setup.py | Python | bsd-3-clause | 1,751 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import fwdform
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
version = fwdform.__version__
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload | ')
sys.exit()
if sys.argv[- | 1] == 'tag':
print("Tagging the version on github:")
os.system("git tag -a %s -m 'version %s'" % (version, version))
os.system("git push --tags")
sys.exit()
long_description = open('README.rst').read()
setup(
name='django-fwdform',
version=version,
description="""Simple and painless form p... |
letter113/android-build-system | android_build_system/pre_checks/env_check.py | Python | apache-2.0 | 851 | 0.001175 | import os
import shutil
from android_build_system.pre_checks.base import BaseCheck
from android_build_system.config import AAPT, ZIPALIGN
class EnvCheck(BaseCheck):
def __init__(self):
super().__init__ | ("Env check")
def _check(self):
return os.environ.get("ANDROID_HOME", None) is not None
class AAPTCheck(BaseCheck):
def __init__(self):
super().__init__("Binary 'aapt' found")
def _check(self):
return AAPT is not None
class ZIPALIGNCheck(BaseCheck):
def __init__(self):
... | def __init__(self, cmd):
self.cmd = cmd
self.message = "Command '{}' found".format(cmd)
def _check(self):
return shutil.which(self.cmd) is not None |
srimalik/pynfs | nfs4.1/block.py | Python | gpl-2.0 | 10,274 | 0.002531 | from __future__ import with_statement
from xdrdef.pnfs_block_pack import PNFS_BLOCKPacker as Packer
from xdrdef.pnfs_block_pack import PNFS_BLOCKUnpacker as Unpacker
from xdrdef.pnfs_block_type import *
from xdrdef.pnfs_block_const import *
import fs_base
from threading import Lock
import struct
# draft 8
# All size... | out.append(self)
return out
def get_xdr(self, mapping):
"""Returns filled (and unpacked) pnfs_block_volume4 structure.
Nee | d mapping from device:to top-level array index to do the conversion.
"""
raise NotImplementedError
def resolve(self, i):
"""Map a byte offset to the corresponding Simple volume and byte offset.
"""
return NotImplementedError
def extent(self, i, limit):
"""Same a... |
liushuaikobe/GitArchiveUtils | daily-task/util.py | Python | gpl-2.0 | 3,053 | 0.004751 | # -*- coding: utf-8 -*-
import glob
import os
import csv
import smtplib
from email.mime.text import MIMEText
from whoosh import index
from whoosh.fields import Schema, TEXT
import config
from database import get_redis_pipeline
mail_config = config.mail_config
def sendmail(sbj, content,
fromwhom=mail_config['f... | (WhooshUtil, self).__init__()
self.ix_path = ix_path
self.schema = | Schema(location=TEXT(stored=True), rlocation=TEXT(stored=True))
def build_whoosh_index(self):
"""建立location的Whoosh搜索索引"""
if not os.path.exists(self.ix_path):
os.mkdir(self.ix_path)
ix = index.create_in(self.ix_path, self.schema)
else:
ix = index.... |
Dinoshauer/pryvate | pryvate/blueprints/pypi/pypi.py | Python | mit | 1,874 | 0 | """PyPi blueprint."""
import os
from flask import Blueprint, current_app, g, request
blueprint = Blueprint('pypi', __name__, url_prefix='/pypi')
def register_package(localproxy):
"""Register a new package.
Creates a folder on the filesystem so a new package can be uploaded.
Arguments:
localprox... | est']
file_path = os.path.join(current_app.config['BASEDIR'],
localproxy.form['name'].lower(),
contents.filename.lower())
contents.save(file_path)
with open('{}.md5'.format(file_path), 'w') as md5_digest:
md5_digest.write(digest)
return ... | route('', methods=['POST'])
def post_pypi():
"""Find a package and return the contents of it.
Upon calling this endpoint the ``PRIVATE_EGGS`` set will be updated,
and proper action will be taken based on the request.
"""
actions = {
'submit': register_package,
'file_upload': upload_... |
PPCDroid/external-lirc | tools/pronto2lirc.py | Python | gpl-2.0 | 4,612 | 0.019514 | #
# A tool for converting Pronto format hex codes to lircd.conf format
#
# Copyright by Olavi Akerman <[email protected]>
#
# pronto2lirc 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 ... | # EOF?
break
[sCodeName,sHexCodes]=sLine.split(':')
seq=CodeSequence()
finalgap=seq.AnalyzeCode(sCodeName,sHexCodes)
if finalgap>self.lGap:
self.lGap=finalgap
self.sCodes.append(seq)
f.close()
def Wr... | Conf(self,sOutFileName):
f=open(sOutFileName,'w')
f.write('begin remote\n')
f.write('\tname\t'+self.sRemoteName+'\n')
f.write('\tflags\tRAW_CODES\n')
f.write('\teps\t30\n')
f.write('\taeps\t100\n')
f.write('\tgap\t%d\n' % self.lGap )
f.write('\t\tbegin ra... |
gsathya/dsalgo | run_tests.py | Python | mit | 834 | 0.004796 | import unittest
import test.bst
import test.sorted_array_to_bst
import test.edit_distance
import test.binary_search
import test.print_level_order_test
import test.binary_add_test
impor | t test.linked_list_test
suite = unittest.TestLoader()
suite | = suite.loadTestsFromModule(test.bst)
suite.addTest(unittest.TestLoader().loadTestsFromModule(test.sorted_array_to_bst))
suite.addTest(unittest.TestLoader().loadTestsFromModule(test.edit_distance))
suite.addTest(unittest.TestLoader().loadTestsFromModule(test.binary_search))
#suite.addTest(unittest.TestLoader().loadTes... |
rgayon/plaso | tests/parsers/setupapi.py | Python | apache-2.0 | 5,214 | 0.000959 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Windows Setupapi log parser."""
from __future__ import unicode_literals
import unittest
from plaso.parsers import setupapi
from tests.parsers import test_lib
class SetupapiLogUnitTest(test_lib.ParserTestCase):
"""Tests for the Windows Setupapi log ... | ed_short_message)
def testParseSetupLog(self):
"""Tests the Parse function on setupapi.setup.log."""
parser = setupapi.SetupapiLogParser()
storage_writer = self._ParseFile(['setupapi.setup.log'], parser)
self.assertEqual(storage_writer.number_of_warnings, 0)
self.assertEqual(storage_writer.numbe... | event = events[2]
self.CheckTimestamp(event.timestamp, '2015-11-22 17:53:28.973000')
event = events[4]
event_data = self._GetEventDataOfEvent(storage_writer, event)
self.CheckTimestamp(event.timestamp, '2015-11-22 17:53:29.305000')
expected_message = 'Setup Plug and Play Device Install'
ex... |
o2gy84/libproperty | src/clang_compilation_database.py | Python | gpl-3.0 | 3,027 | 0.002973 | #!/usr/bin/env python
# encoding: utf-8
# Christoph Koke, 2013
"""
Writes the c and cpp compile commands into build/compile_commands.json
see http://clang.llvm.org/docs/JSONCompilationDatabase.html
Usage:
def configure(conf):
conf.load('compiler_cxx')
...
conf.load('clang_compilation_databa... | f runnable_status(self):
def exec_co | mmand(cmd, **kw):
pass
run_status = self.old_runnable_status()
if run_status == Task.SKIP_ME:
setattr(self, 'old_exec_command', getattr(self, 'exec_command', None))
setattr(self, 'exec_command', exec_command)
self.run()
setattr(self, 'exec_com... |
stevelittlefish/easyforms | easyforms/form.py | Python | apache-2.0 | 35,700 | 0.004566 |
"""
Base classes for forms and fields
"""
import logging
from collections import OrderedDict
from flask import Markup, request
from . import validate
from . import exceptions
from . import formtype
from . import styles
from .env import env
__author__ = 'Stephen Brown (Little Fish Solutions LTD)'
log = logging.get... | e.replace('-', ' ').title()
def set_default_form_type(form_type):
global _default_form_type
if form_type not in formtype.ALL_FORM_TYPES:
raise ValueError('Invalid form type: {}'.format(form_type) | )
_default_form_type = form_type
class Field(object):
def __init__(self, name, label=None, value=None, id=None, optional=False, css_class='',
readonly=False, help_text=None, strip_value=True, convert_empty_to_none=True,
validators=[], required=False, render_after_sections=Fa... |
braghiere/JULESv4.6_clump | examples/us-me2/output/plot_limiting_vertical_bl.py | Python | gpl-2.0 | 10,209 | 0.029484 | # June 2015
# read and plot the co2 runs on jules
import os
import matplotlib.pyplot as plt
import numpy as np
import sys
from matplotlib.font_manager import FontProperties
from matplotlib.ticker import MultipleLocator
import matplotlib.patches as mpatches # for | mask legend
from matplotlib.font_manager import FontProperties
from matplotlib import cm
import pandas as pd
from matplotlib import dates as d
import datetime as dt
import scipy.stats as st
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy | as np
from scipy.ndimage.filters import gaussian_filter
import scipy.ndimage
#from colormap_viridis import test_cm as viridis # viridis colormap from
#from colormaps_reference.py import *
# https://github.com/BIDS/colormap/blob/master/option_d.py
fontP = FontProperties()
#fontP.set_size('small')
fontP.set_... |
kervi/kervi | ukervi/ukervi/platforms/upython/i2c_driver.py | Python | mit | 1,355 | 0.00369 | #Copyright 2018 Tim Wentlau.
#Distributed under the MIT License. See LICENSE in root of project.
from kervi.hal.i2c import II2CDeviceDriver
class I2CDeviceDriver(II2CDeviceDriver):
"""
Class for communicating with an I2C devices.
"""
def __init__(self, address, busnum):
raise NotImplementedE... | read_raw8(self):
raise NotImplementedError
def read_U8(self, register):
raise NotImplementedError
def read_S8(self, register):
raise NotImplementedError
def read_U16(self, register, little_endian=True):
raise NotImplementedError
def read_S16(self, register, littl | e_endian=True):
raise NotImplementedError
def read_U16LE(self, register):
raise NotImplementedError
def read_U16BE(self, register):
raise NotImplementedError
def read_S16LE(self, register):
raise NotImplementedError
def read_S16BE(self, register):
raise NotImp... |
zwegner/pythonc | tests/import/submodule.py | Python | gpl-3.0 | 30 | 0 | print('In sub | module | .')
x = 3
|
rven/odoo | addons/hr/wizard/hr_plan_wizard.py | Python | agpl-3.0 | 1,529 | 0.001962 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, mod | els
class HrPlanWizard(models.TransientModel):
_name = 'hr.plan.wizard'
_description = 'Plan Wizard'
plan_id = fields.Many2one('hr.plan', default=lambda self: self.env['hr.plan'].search([], limit=1))
employee_id = fields.Many2one(
'hr.employee', string='Employee', required=True,
defau... | ch(self):
for activity_type in self.plan_id.plan_activity_type_ids:
responsible = activity_type.get_responsible_id(self.employee_id)
if self.env['hr.employee'].with_user(responsible).check_access_rights('read', raise_exception=False):
date_deadline = self.env['mail.activ... |
ExCiteS/geokey-wegovnow | geokey_wegovnow/tests/test_templatetags.py | Python | mit | 2,388 | 0 | """Test all template tags."""
from django.test import TestCase
from allauth.socialaccount.models import SocialApp, SocialAccount
from geokey.users.tests.model_factories import UserFactory
from geokey.users.templatetags.social import get_social_apps
from geokey_wegovnow.templatetags import wegovnow
class TemplateT... | n socialapps)
self.assertTrue(socialapp_2 in socialapps)
self.assertFalse(socialapp_3 i | n socialapps)
def test_exclude_uwum_accounts(self):
"""Test excluding UWUM accounts."""
user = UserFactory.create()
socialaccount_1 = SocialAccount.objects.create(
user=user,
provider='facebook',
uid='5454'
)
socialaccount_2 = SocialAccoun... |
StrellaGroup/erpnext | erpnext/hr/doctype/payroll_entry/payroll_entry.py | Python | gpl-3.0 | 21,415 | 0.027411 | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from dateutil.relativedelta import relativedelta
from frappe.utils import cint,... | elf.create_salary_slips()
def before_submit(self):
if self.validate_attendance:
if self.validate_employee_atten | dance():
frappe.throw(_("Cannot Submit, Employees left to mark attendance"))
def on_cancel(self):
frappe.delete_doc("Salary Slip", frappe.db.sql_list("""select name from `tabSalary Slip`
where payroll_entry=%s """, (self.name)))
def get_emp_list(self):
"""
Returns list of active employees based on sel... |
saisankargochhayat/algo_quest | graph/dijkstra.py | Python | apache-2.0 | 4,465 | 0.006943 | import sys
class Vertex:
def __init__(self, node):
self.id = node
self.adjacent = {}
# Set distance to infinity for all nodes
self.distance = sys.maxint
# Mark all nodes unvisited
self.visited = False
# Predecessor
self.previous = None
... |
g.add_edge('a', 'b', 7)
g.add_edge('a', 'c', 9)
g.add_edge('a', 'f', 14)
g.add_edge('b', 'c', 10)
g.add_edge('b', 'd', 15)
g.add_edge('c', 'd', 11)
g.add_edge('c', 'f', 2)
g.add_edge('d', 'e', 6)
g.add_edge('e', 'f', 9)
print('Graph data:')
for v in g:
for w in v.... | w.get_id()
print('( %s , %s, %3d)' % ( vid, wid, v.get_weight(w)))
dijkstra(g, g.get_vertex('a'))
target = g.get_vertex('e')
path = [target.get_id()]
shortest(target, path)
print('The shortest path : %s' %(path[::-1]))
|
pyro-ppl/numpyro | numpyro/version.py | Python | apache-2.0 | 107 | 0 | # Copyright Contributors to the Pyro project.
# SPDX-Licens | e-Identifie | r: Apache-2.0
__version__ = "0.9.0"
|
jorisv/RBDynUrdf | binding/python/generate.py | Python | gpl-3.0 | 3,124 | 0.010243 | # This file is part of Tasks.
#
# Tasks 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) any later version.
#
# Tasks is distributed in the hope tha... | attribute('tl', 'std::map<int, double>')
limits.add_instance_attribute('tu', 'std::map<int, double>')
urdf = rbdyn_urdf.add_struct('Urdf')
urdf.add_instance_attribute('mbg', 'rbd::MultiBodyGraph')
urdf.add_instance_attribute('limits', 'rbdyn_urdf::Limits')
# build function
rbdyn_urdf.add_function('readUrd... | readUrdfFile', retval('rbdyn_urdf::Urdf'),
[param('const std::string&', 'fileName')],
throw=[run_ex])
rbdyn_urdf.add_function('writeUrdf', None,
[param('const std::string&', 'filename'),
param('const std::string&... |
cjaymes/pyscap | src/scap/model/ocil_2_0/ChoiceGroupType.py | Python | gpl-3.0 | 1,043 | 0.001918 | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP 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.
#
# PySCAP is ... | r = logging.getLogger(__name__)
class ChoiceGroupType(Model):
MODEL_MAP = {
'elements': [
{'tag_name': 'choice', 'list': 'choices', 'class': 'ChoiceType', 'min': 1},
],
'attributes': {
| 'id': {'type': 'ChoiceGroupIDPattern', 'required': True},
},
}
|
theo-l/django_common | models/__init__.py | Python | mit | 182 | 0 | # -*- coding: utf-8 -*-
# @Author: theo-l
# @Date: 2017-06-28 20:38:33
# @Last Modified by: theo-l
# @Last Modified time: 2017-07-08 20:50:07
fr | om .base_models | import BaseModel
|
Rademade/taiga-back | taiga/base/api/renderers.py | Python | agpl-3.0 | 24,541 | 0.000897 | # Copyright (C) 2014-2016 Andrey Antukh <[email protected]>
# Copyright (C) 2014-2016 Jesús Espino <[email protected]>
# Copyright (C) 2014-2016 David Barragán <[email protected]>
# Copyright (C) 2014-2016 Alejandro Alonso <[email protected]>
# This program is free software: you can redistribute it and/or mo... | ranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# The code is partially taken (a | nd modified) from django rest framework
# that is licensed under the following terms:
#
# Copyright (c) 2011-2014, Tom Christie
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions ... |
nophead/Skeinforge50plus | skeinforge_application/skeinforge_plugins/craft_plugins/home.py | Python | agpl-3.0 | 8,025 | 0.023427 | """
This page is in the table of contents.
Plugin to home the tool at beginning of each layer.
The home manual page is at:
http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Home
==Operation==
The default 'Activate Home' checkbox is on. When it is on, the functions described below will work, when it is off, not... | ocationUp = Vector3( location.x, location.y, self.highestZ )
self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRateMinut | e, locationUp.dropAxis(), locationUp.z ) )
def getCraftedGcode( self, gcodeText, repository ):
"Parse gcode text and store the home gcode."
self.repository = repository
self.homeLines = settings.getAlterationFileLines(repository.nameOfHomeFile.value)
if len(self.homeLines) < 1:
return gcodeText
self.line... |
auready/django | tests/admin_views/models.py | Python | bsd-3-clause | 24,291 | 0.000618 | import datetime
import os
import tempfile
import uuid
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.core.fil... | dels.CharField(max_length=100)
gender = models.IntegerField(choices=GENDER_CHOICES)
age = models.IntegerField(default=21)
alive = models.BooleanField(default=True)
def __str__(self):
return self.name
class Persona(models.Model):
"""
A simple pers | ona associated with accounts, to test inlining of related
accounts which inherit from a common accounts class.
"""
name = models.CharField(blank=False, max_length=80)
def __str__(self):
return self.name
class Account(models.Model):
"""
A simple, generic account encapsulating the infor... |
bluesliverx/smartthings-src | apps/wifi-104-ssdp-server/lib/ssdp.py | Python | apache-2.0 | 8,142 | 0.001105 | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2005, Tim Potter <[email protected]>
# Copyright 2006 John-Mark Gurney <[email protected]>
# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006,2007,2008,2009 Frank Scholz <[email protected]>
# Co... | mport time
import socket
import logging
from email.utils import formatdate
from errno import | ENOPROTOOPT
SSDP_PORT = 1900
SSDP_ADDR = '239.255.255.250'
SERVER_ID = 'Wifi 104 SSDP Server'
logger = logging.getLogger('ssdp')
logger.setLevel('WARNING')
class SSDPServer:
"""A class implementing a SSDP server. The notify_received and
searchReceived methods are called when the appropriate type of
d... |
tudennis/LeetCode---kamyu104-11-24-2015 | Python/move-zeroes.py | Python | mit | 1,485 | 0 | from __future__ import print_function
# Time: O(n)
# Space: O(1)
# Given an array nums, write a function to move all 0's
# to the end of it while maintaining the relative order
# of the non-zero elements.
#
# For example, given nums = [0, 1, 0, 3, 12], after
# calling your function, nums should be [1, 3, 12, 0, 0].
#... | """
:type nums: List[int]
:rtype: void Do not return an | ything, modify nums in-place instead.
"""
pos = 0
for i in xrange(len(nums)):
if nums[i]:
nums[pos] = nums[i]
pos += 1
for i in xrange(pos, len(nums)):
nums[i] = 0
if __name__ == '__main__':
s = Solution()
r = s.moveZeroe... |
tempbottle/ironpython3 | Tests/compat/sbs_exceptions/try_except3.py | Python | apache-2.0 | 904 | 0.009956 | #####################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of t... | ail to
# [email protected]. By using this source code in any fashion, you are agreeing to be bound
# by the terms of the Apache License, Version 2.0.
#
# You must not remove this notice, or any other, from this software.
#
#
################################################################################### | ##
from common import runtests
from .shared import try_except_maker3
from .shared import setGenerator, test_exceptions
setGenerator(try_except_maker3)
runtests(test_exceptions)
|
wernersa/Streprogen_web | app/__init__.py | Python | gpl-3.0 | 1,393 | 0.007179 | # -*- coding: utf-8 -*-
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from os import listdir
from os.path import isfile, join
import random
import datetime
def files_in_dir(directory):
"""
:param directory: The directory
:return: List of all files in directory
"""
re... | ig['SQLALCHEMY_DATABASE_URI'] = 'sqlite:/ | //' + os.path.join(basedir, 'database.db')
db = SQLAlchemy(app)
app.jinja_env.globals.update(enumerate=enumerate, is_christmas=is_christmas)
from . import views, models
# Create database if it's not there
for file in files_in_dir(basedir):
if 'database.db' in file:
break
else:
db.create_all()
pr... |
jemromerol/apasvo | bin/apasvo-generator.py | Python | gpl-3.0 | 21,718 | 0.001105 | #!/usr/bin/python2.7
# encoding: utf-8
'''Earthquake Generator
A tool that generates synthetic seismic signals.
@author: Jose Emilio Romero Lopez
@copyright: Copyright 2013-2014, Jose Emilio Romero Lopez.
@license: GPL
@contact: [email protected]
This file is part of APASVO.
This program is free... | beginning of the signal.
If FILEIN is None, this parameter has no effect.
output: Output file name (absolute path).
If no input file is provided and n_events is greater than 1, the
| name of each generated file will be followed by its ordinal number.
E.g. given FILEIN = None, output = 'example.out' and n_events = 5,
the function will generate 5 synthetic files named:
'example00.out', 'example01.out', 'example02.out', 'example03.out'
and 'examp... |
psykokwak4/ydk-gen | sdk/python/core/tests/test_sanity_type_mismatch_errors.py | Python | apache-2.0 | 7,229 | 0.005948 | # ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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/LICENS... | etrizedTestCase.parametrize(
SanityYang,
de | vice=device,
non_demand=non_demand,
common_cache=common_cache,
timeout=timeout))
ret = not unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful()
sys.exit(ret)
|
sadig/DC2 | components/dc2-lib/dc2/lib/logging/__init__.py | Python | gpl-2.0 | 890 | 0.001125 | # -*- coding: utf-8 -*-
#
# (DC)² - DataC | enter Deployment Control
# Copyright (C) 2010, 2011, 2012, 2013, 2014 Stephan Adig <[email protected]>
# 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 yo... | ANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
f... |
nadrees/PyEuler | 0004.py | Python | unlicense | 416 | 0.00241 | '''
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
'''
nums = range(9 | 99, 99, -1)
allProducts = [x * y for x in nums for y in nums]
palindromeProducts = [p for p in | allProducts if str(p) == str(p)[::-1]]
answer = max(palindromeProducts)
print(answer)
|
ChainsAutomation/chains | lib/chains/common/addict.py | Python | gpl-2.0 | 7,719 | 0.000259 | from inspect import isgenerator
import re
import copy
# version: 0.4.0
# author: Mats Julian Olsen
# license: MIT
# https://github.com/mewwts/addict/
class Dict(dict):
"""
Dict is a subclass of dict, which allows you to get AND SET(!!)
items in the dict using the attribute syntax!
When you previous... | elf[key]
else:
if isins | tance(val, tuple):
new_iter = tuple(new_iter)
self[key] = new_iter
@classmethod
def _prune_iter(cls, some_iter, prune_zero=False, prune_empty_list=True):
new_iter = []
for item in some_iter:
if item == 0 and prune_zero:
co... |
matejm/advent-of-code-2016 | day19.py | Python | mit | 829 | 0.001206 | number = [i for i in range(1, 3001330+1)]
# number = [i for i in range(1, 10)]
number2 = number[:]
last = len(number) % 2 != 0
while len(number) > 1:
next_last = len(number) % 2 != last
number = [j for i, j in enumerate(number) if i % 2 != last]
last = next_last
print('#1', number[0])
number = number2
... | ange(start, len(number)):
pop.add(number[(i + (len(number) + i - start) // 2) % len(number)])
num | ber = [i for i in number if i not in pop]
print('#2', number[0])
|
cydenix/OpenGLCffi | OpenGLCffi/GL/EXT/KHR/debug.py | Python | mit | 2,870 | 0.010453 | from OpenGLCffi.GL import params
@params(api='gl', prms=['source', 'type', 'severity', 'count', 'ids', 'enabled'])
def glDebugMessageControl(source, type, severity, count, ids, enabled):
pass
@params(api='gl', prms=['source', 'type', 'id', 'severity', 'length', 'buf'])
def glDebugMessageInsert(source, type, id, seve... | urce, type, severity, count, ids, enabled):
pass
@params(api='gl', prms=['source', 'type', 'id', 'severity', 'length', 'buf'])
def glDebugMessageInsertKHR(source, type, id, severity, length, buf):
pass
@params(api='gl', prms=['callback', 'userParam'])
def glDebugMessageCallbackKHR(callback, user | Param):
pass
@params(api='gl', prms=['count', 'bufSize', 'sources', 'types', 'ids', 'severities', 'lengths', 'messageLog'])
def glGetDebugMessageLogKHR(count, bufSize, sources, types, ids, severities, lengths, messageLog):
pass
@params(api='gl', prms=['source', 'id', 'length', 'message'])
def glPushDebugGroupKHR(... |
jthorniley/pyusb2ax | example.py | Python | gpl-2.0 | 1,401 | 0.009993 | import | usb2ax
import time
import math
import sys
with usb2ax.Controller(fix_sync_read_delay = True) as dxl:
servo_list = dxl.servo_list
if len(servo_list) == 0:
raise "Nothing connected..."
sys.exit()
print "Servo: \t" + "\t".join( [str(x) for x in servo_list] ) + "\tRead rate (Hz)\tNumber of e... | i = 0
pos_data = [0]*len(servo_list)
n_read_errors = 0
try:
t0 = time.time()
while True:
pos = math.sin(t0*math.pi)*50.0
pos = int(512+pos)
dxl.sync_write(servo_list,"goal_position",[pos]*len(servo_list))
done = False
while not ... |
mumuwoyou/vnpy | vn.trader/vtFunction.py | Python | mit | 1,565 | 0.008578 | # encoding: UTF-8
"""
包含一些开放中常用的函数
"""
import decimal
import json
import os
from datetime import datetime
MAX_NUMBER = 10000000000000
MAX_DECIMAL = 4
#----------------------------------------------------------------------
def safeUnicode(value):
"""检查接口数据潜在的错误,保证转化为的字符串正确"""
# 检查是数字接近0时会出现的浮点数上限
if type... | ging = setting['mongoLogging']
except:
host = 'localhost'
port = 27017
logging = False
|
return host, port, logging
#----------------------------------------------------------------------
def todayDate():
"""获取当前本机电脑时间的日期"""
return datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
|
nchaparr/Geospatial-Analysis-with-Python | 1138_08_01-ndvi.py | Python | cc0-1.0 | 3,886 | 0.013124 | """
Output a normalized vegetative index
"""
import gdal, gdalnumeric, ogr
import Image, ImageDraw
def imageToArray(i):
"""
Converts a Python Imaging Library
array to a gdalnumeric image.
"""
a=gdalnumeric.numpy.fromstring(i.tostring(),'b')
a.shape=i.im.size[1], i.im.size[0]
return a
... | ionErrors
ndvi = 1.0 * (irClip - rClip) / irClip + rClip + 1.0
# Remove any NaN values from the final product
ndvi = gdalnumeric.numpy.nan_to_num(ndvi)
# Save ndvi as tiff
gdalnumeric.SaveArray(ndvi, target, \
format="GTiff | ", prototype=source)
|
damonchen/chan | chan/core/templates/uwsgi_handler.py | Python | bsd-2-clause | 429 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import click
from {{project}} import app as application
|
@click.com | mand()
@click.option('--debug/--no-debug', default=True,
envvar='REPO_DEBUG')
@click.option('--host', default='0.0.0.0')
@click.option('--port', default=5000)
def main(debug, host, port):
application.debug = debug
application.run(host=host, port=port)
if __name__ == '__main__':
main()
|
renzon/gae-continuous-delivery | test/testloader.py | Python | mit | 635 | 0.001575 | #!/usr/bin/env python
# c | oding: utf-8
import unittest
import sys
import os
PROJECT_PATH = os.path.sep.join(os.path.abspath(__file__).split(os.path.sep)[:-2])
ROOT_PATH = os.path.dirname(__file__)
if __name__ == '__main__':
if 'GAE_SDK' in os.environ:
SDK_PATH = os.environ['GAE_SDK']
sys.path.insert(0, SDK_PATH)
... | rver.fix_sys_path()
sys.path.append(os.path.join(PROJECT_PATH, 'src'))
tests = unittest.TestLoader().discover(ROOT_PATH, "*tests.py")
result = unittest.TextTestRunner().run(tests)
if not result.wasSuccessful():
sys.exit(1)
|
rickyHong/dqn-repl | sandbox/old/imageTest.py | Python | gpl-3.0 | 1,421 | 0.009148 | f = open("pixels.dat", "r")
pixs = f.readline()
f.close()
print len(pixs)
from PIL import Image
import numpy as np
img = Image.new('RGB', (160, 210), "black") # create a new black image
pixels = img.load() # create the pixel map
# Load the hardcoded grayscale array
from grayscale import getGrayscaleArray
colMat =... | , 45, img.copy(), 'thisdoesntmatter', img.copy(), 'this neither'] #,deepcopy(img),'thisdoesntmatter',deepcopy(img),deepcopy(img)]
sequence = preprocessSequenceWithActions(sequence)
# Example 3: take a sequence that DOES contain actions and preprocess the images in-place
from preprocessing import preprocessSequenceNoAc... | img.copy(), img.copy(), img.copy()]
sequence = preprocessSequenceNoActions(sequence)
|
tsaoyu/D3HRE | D3HRE/core/battery_models.py | Python | gpl-3.0 | 18,409 | 0.002988 | import numpy as np
def min_max_model(power, use, battery_capacity):
"""
Minimal maximum battery model, obsoleted
:param power: Pandas TimeSeries, total power from renewable system
:param use: float, unit W fixed load of the power system
:param battery_capacity: float, unit Wh battery capacity
... | energy = energy_new # battery energy got update
waste_history.append(0)
else:
waste_history.append(p - use)
energy = energy
elif p < use:
energy_new = energy * (1 - discharge_rate) + (p - use) / discharge_eff
if e... | waste_history.append(0)
use_history.append(use)
elif energy * (1 - discharge_rate) + p * battery_eff < battery_capacity:
energy = energy * (1 - discharge_rate) + p * battery_eff
unmet_history.append(use - p)
use_history.append(0)
... |
CatoTH/OpenSlides | server/openslides/global_settings.py | Python | mit | 3,385 | 0.000296 | import os
from openslides.utils.plugins import collect_plugins
MODULE_DIR = os.path.realpath(os.path.dirname(os.path.abspath(__file__)))
# This is not set to the docker environment
OPENSLIDES_USER_DATA_DIR = "/app/personal_data/var"
# Application definition
INSTALLED_APPS = [
"openslides.core",
"openslide... | USER_DATA_DIR, "collected-static")
# Files
# https://docs.djangoproject.com/en/2.2/topics/files/
MEDIA_ROOT = os.path.join(OPENSLIDES_USER_DATA_DIR, "media", "")
MEDIA_URL = "/media/"
# Sessions and user authentication
# https://docs.djangoproject.com/en/2.2/topics/http/sess | ions/
# https://docs.djangoproject.com/en/2.2/topics/auth/
AUTH_USER_MODEL = "users.User"
AUTH_GROUP_MODEL = "users.Group"
AUTHENTICATION_BACKENDS = ["openslides.utils.auth_backend.ModelBackend"]
SESSION_COOKIE_NAME = "OpenSlidesSessionID"
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
CSRF_COOKIE_NAME = "OpenSlidesCsrfT... |
rodrigozn/CW-Shop | tests/test_checkout.py | Python | bsd-3-clause | 7,657 | 0.00222 | import pytest
from django.conf import settings
from django.contrib.auth.models import AnonymousUser |
from mock import MagicMock, Mock
from prices import Price
from saleor.checkout import views
from saleor.checkout.core import STORAGE_SESSION_KEY, Checkout
from saleor.shipp | ing.models import ShippingMethodCountry
from saleor.userprofile.models import Address
def test_checkout_version():
checkout = Checkout(Mock(), AnonymousUser(), 'tracking_code')
storage = checkout.for_storage()
assert storage['version'] == Checkout.VERSION
@pytest.mark.parametrize('storage_data, expected... |
odoocn/odoomrp-wip | mrp_product_variants/__openerp__.py | Python | agpl-3.0 | 1,735 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# 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 Licens... | "AvanzOSC,"
"Serv. Tecnol. Avanzados - Pedro M. Baeza",
"contributors": [
| "Oihane Crucelaegui <[email protected]>",
"Pedro M. Baeza <[email protected]>",
"Ana Juaristi <[email protected]>",
],
"category": "Manufacturing",
"website": "http://www.odoomrp.com",
"summary": "Customized product in manufacturing",
"data": [
... |
yishenggudou/Alistar | Alistar/app.py | Python | bsd-2-clause | 674 | 0.007418 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# [email protected]
# @timger http://weibo.com/zhanghaibo
__author__ = 'timgerk'
from flask imp | ort Flask, send | _from_directory, redirect
import os
DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
app = Flask(__name__, static_url_path=DIR_PATH)
@app.route("/")
def index():
return redirect('app/index.html')
@app.route('/app/bower_components/<path:path>')
def send_app(path):
return send_from_direct... |
kottoson/cs3240-labdemo | helper.py | Python | mit | 103 | 0.009709 | # h | elper.py
# K. Ottoson
# February 20, 2017
__author__ = "kjo9fq"
def greeting(msg | ):
print(msg) |
samdroid-apps/sugar | extensions/cpsection/modemconfiguration/__init__.py | Python | gpl-2.0 | 885 | 0 | # Copyright (C) 2009 Paraguay Educa, Martin Abente
#
# This program is free software; you can redistribu | te it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied wa... | received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 US
from gettext import gettext as _
CLASS = 'ModemConfiguration'
ICON = 'module-modemconfiguration'
TITLE = _('Modem Configuration')
|
seibert/numba | numba/tests/test_typeguard.py | Python | bsd-2-clause | 765 | 0 | """
Tests to ensure that typeguard is working as expected.
This mostly contains negative tests as proof that typeguard can catch errors.
"""
import unittest
from numba.tests.support import TestCa | se, skip_unless_typeguard
def guard_args(val: int):
return
def guard_ret(val) -> int:
return val
@skip_unless_typeguard
class TestTypeGuard(TestCase):
def test_check_args(self):
with self.assertRaises(TypeError):
guard_args(float(1.2))
def test_check_ret(self):
with se... | urn
guard(float(1.2))
if __name__ == '__main__':
unittest.main()
|
bdfoster/blumate | blumate/components/switch/command_line.py | Python | mit | 4,275 | 0 | """
Support for custom shell commands to turn a switch on/off.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.command_line/
"""
import logging
import subprocess
from blumate.components.switch import SwitchDevice
from blumate.const import CONF_VAL... | es.get('statecmd', False),
properties.get(CONF_VALUE_TEMPLATE, False)))
add_devices_callback(devices)
# pylint: disable=too-many-instance-attributes
class CommandSwitch(SwitchDevice):
"""Representation a switch that can be toggled using shell commands."""
# pylint: disable=too-many-argum... | hass, name, command_on, command_off,
command_state, value_template):
"""Initialize the switch."""
self._hass = hass
self._name = name
self._state = False
self._command_on = command_on
self._command_off = command_off
self._command_state = command_... |
deepcharles/ruptures | src/ruptures/datasets/pw_constant.py | Python | bsd-2-clause | 1,465 | 0.000683 | """Piecewise constant signal (with noise)"""
import numpy as np
from ruptures.utils import draw_bkps
def pw_constant(
n_samples=200, n_features=1, n_bkps=3, noise_std=None, delta=(1, 10), seed=None
):
"""Return a piecewise constant signal and the associated changepoints.
Args:
n_samples (int): ... | onal): number of changepoints
noise_std (float, optional): noise std. If None, no noise is added
delta (tuple, optional): (delta_min, delta_max) max and m | in jump values
seed (int): random seed
Returns:
tuple: signal of shape (n_samples, n_features), list of breakpoints
"""
# breakpoints
bkps = draw_bkps(n_samples, n_bkps, seed=seed)
# we create the signal
signal = np.empty((n_samples, n_features), dtype=float)
tt_ = np.arange... |
spchal/Pwn-Write-ups | protostar/ex_heap1.py | Python | gpl-2.0 | 395 | 0.005063 | from pwn | import *
#change the host IP to your IP
sh = ssh(host='192.168.1.104', user='root',
password='godmode', port=22)
cmd = sh.set_working_directory('/opt/protostar/bin')
e = ELF("./heap1")
puts_add = p32(e.got["puts"])
winner = pack(0x8048494)
print "puts: ", puts_add
arg1 = "A"*20
arg | 1 += puts_add
arg2 = winner
print sh.run(['./heap1', arg1, arg2]).recvall().strip()
|
ActiveState/code | recipes/Python/523034_emulate_collectionsdefaultdict/recipe-523034.py | Python | mit | 1,492 | 0.006032 | try:
from collections import defaultdict
except:
class defaultdict(dict):
def __init__(self, default_factory=None, *a, **kw):
if (default_factory is not None and
not hasattr(default_factory, '__call__')):
raise TypeError('first argument must be callable')
... | sing__(key)
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
self[key] = value = self.default_factory()
return value
def __reduce__(self):
if self.default_factory | is None:
args = tuple()
else:
args = self.default_factory,
return type(self), args, None, None, self.items()
def copy(self):
return self.__copy__()
def __copy__(self):
return type(self)(self.default_factory, self)
de... |
HoverHell/pyimapsmtpt | pyimapsmtpt/xmpptransport.py | Python | gpl-2.0 | 8,036 | 0.003116 | #!/usr/bin/env python
# coding: utf8
import logging
import signal
import time
import xmpp
from xmpp.browser import (
ERR_ITEM_NOT_FOUND,
ERR_JID_MALFORMED,
NS_COMMANDS,
NS_VERSION,
Browser,
Error,
Message,
NodeProcessed,
Presence,
)
from .common import jid_to_data
_log = logging.... |
name=self.config.xmpp_disco_name)],
features=[NS_VERSION, NS_COMMANDS])
if ev_type == 'items':
return []
else:
self.send_message(Error(event, ERR_ITEM_NOT_FOUND))
| raise NodeProcessed
else:
self.send_message(Error(event, ERR_JID_MALFORMED))
raise NodeProcessed
def xmpp_presence(self, con, event):
# Add ACL support
fromjid = event.getFrom()
ev_type = event.getType()
to = event.getTo()
if ev... |
Azure/azure-sdk-for-python | sdk/eventgrid/azure-eventgrid/azure/eventgrid/_generated/_event_grid_publisher_client.py | Python | mit | 3,272 | 0.003667 | # 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 ... | blisherClient(object):
"""EventGrid Python Publisher Client.
"""
def __init__(
self,
**kwargs # type: Any
):
# type: (...) -> None
base_url = 'https://{topicHostname}'
self._config = EventGridPublisherClientConfiguration(**kwargs)
self._client = Pipelin... | Any]
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
def send_request(
self,
request, # type: HttpRequest
**kwargs # type: Any
):
# type: (...) -> HttpResponse
... |
anhstudios/swganh | data/scripts/templates/object/tangible/ship/crafted/reactor/shared_reactor_limiter_mk5.py | Python | mit | 479 | 0.045929 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/crafted/reactor/shared_reactor_limiter_mk5.iff"
result.attribu... | TIONS ####
#### END MODIFICATIONS #### |
return result |
brentp/goleft | depth/test/cmp.py | Python | mit | 562 | 0.005338 | import subprocess | as sp
import sys
goleft_bed = sys.argv[1]
bam = sys.argv[2]
for toks in (l.rstrip().split("\t") for l in open(goleft_bed)):
cmd = "samtools depth -a -Q 1 -r '%s:%d-%s' %s | awk '{s+=$3}END{if(NR==0){print 0}else{print s/%d}}'" % (toks[0], int(toks[1]) + 1, toks[2], bam, int(toks[2]) - int(toks[1]))
out = sp.... | rip())) > 0.5:
print("ERROR")
print(float(out.strip()), expected)
print(cmd)
sys.exit(1)
|
citrix-openstack-build/pycadf | pycadf/identifier.py | Python | apache-2.0 | 1,525 | 0 | # -*- encoding: utf-8 -*-
#
# Copyright 2013 IBM Corp.
#
# Author: Matt Rutkowski <[email protected]>
#
# 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/LICE... | tions
# under the License.
import six
import uuid
from oslo.config import cfg
CONF = cfg.CONF
opts = [
cfg.StrOpt('namespace',
default='openstack',
help='namespace prefix for generated id'),
]
CONF.register_opts(opts, group='audit')
# TODO(mrutkows): make the namespace prefix conf... | k.org\")...
def generate_uuid():
return norm_ns(str(uuid.uuid4()))
def norm_ns(str_id):
prefix = CONF.audit.namespace + ':' if CONF.audit.namespace else ''
return prefix + str_id
# TODO(mrutkows): validate any cadf:Identifier (type) record against
# CADF schema. This would include schema validation as ... |
hipnusleo/laserjet | lib/core/loggers.py | Python | apache-2.0 | 1,506 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: yyg
@Create: 2016MMDD
@LastUpdate: 2016-12-15 HH:MM:SS
@Version: 0.0
"""
from json import load
from logging import (Formatter, _defaultFormatter, exception,
getLogger, FileHandler, basicCon... | = LOG_DAT_FMT
self._start()
def _start(self):
logger = getLogger(LOGGER_NAME)
log_handler = ConcurrentRotatingFileHandler(LOG_FILE)
log_formatter = Formatter(self.fmt, self.datefmt)
log_handler.setFormatter(log_formatter)
console_handler = StreamHandler()
... |
logger.info("Logger activated")
def print_func(anything_str):
log = getLogger(LOGGER_NAME)
log.info(anything_str)
if __name__ == "__main__":
logger = LaserjetLogger()
test_pool = Pool()
for i in range(5):
test_pool.apply_async(print_func, args=(i,))
test_pool.c... |
bossiernesto/melta | test/fixture/class_repositories.py | Python | bsd-3-clause | 637 | 0.00157 | from melta.dynamic.propertyMaker import PropertyMaker
property_maker = PropertyMaker()
class Person:
pass
person1 = Person()
property_maker.buildProperty(person1, "edad", 20) \
.buildProperty(person1, "altura", 180) \
.buildProperty(pe | rson1, "sexo", "male")
class House:
pass
house1 = House()
property_maker.buildProperty(house1, "antiguedad", 32) \
.buildProperty(house1, "tipo_casa", "bungalow") \
.buildProperty(house1, "mt2", 360)
house2 = House()
property_maker.buildProperty(house2, "building_age", 34) \
| .buildProperty(house2, "material", "brick") \
.buildProperty(house2, "sq2mts", 453) |
wattlebird/Chi | www/app/data.py | Python | mit | 3,269 | 0.033344 | from app import db, cache
from model import UserInfo
import pickle
from random import seed, randint
from heapq import nlargest
seed()
cache.clear()
fr = open('dat/a.dat','rb')
U = pickle.load(fr) # a user_num x 100 mat
unorm = pickle.load(fr)
fr.close()
#for i in xrange(len(unorm)):
# unorm[i]+=1
class DUser:
... | dex]*unorm[i])))
slist=nlargest(11,qlist)
rlist=[]
for i in xrange(1,11):
q=UserInfo.query.filter_by(index=slist[i].id).first()
rlist.append((q.name,round(_normalize(slist[i].sim),4)))
return rlist
@cache.memoize(timeout=600)
def getsim(db, username, candidate):
q=UserInfo.query.f | ilter_by(name=username).first()
u=U[q.index,:]
p=UserInfo.query.filter_by(name=candidate).first()
v=U[p.index,:]
return round(_normalize(u.dot(v.T).toarray()[0][0]/(unorm[q.index]*unorm[p.index])),4)
@cache.memoize(timeout=600)
def getrank(db, username, candidate):
q=UserInfo.query.filter_by(name=u... |
deepmind/interval-bound-propagation | examples/train.py | Python | apache-2.0 | 10,867 | 0.005521 | # coding=utf-8
# Copyright 2019 The Interval Bound Propagation Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | ata_test = tf.keras.datasets.cifar10.load_data()
data_train = (data_train[0], data_train[1].flatten())
data_test = (data_tes | t[0], data_test[1].flatten())
data = ibp.build_dataset(data_train, batch_size=FLAGS.batch_size,
sequential=False)
if FLAGS.dataset == 'cifar10':
data = data._replace(image=ibp.randomize(
data.image, (32, 32, 3), expand_shape=(40, 40, 3),
crop_shape=(32, 32, 3), vertica... |
drhagen/parsita | examples/positioned.py | Python | mit | 3,313 | 0.000906 | """User-defined positioned parser example.
This shows how a new parser can be defined outside Parsita and used in tandem
with the built-in parsers. The ``positioned`` parser updates the value
returned from an arbitrary parser with the position in the input that was
consumed by that parser.
"""
from abc import abstrac... | econd: Variable
class PlusParsers(TextParsers):
variable = positioned(reg("[A-Za-z][A-Za-z0-9_]*") > UnfinishedVariable)
plus = variable & "+" >> variable > splat(Pl | us)
if __name__ == "__main__":
print(PlusParsers.plus.parse("abc + xyz").or_die())
|
lxp/apt2d8 | src/apt2d8/rpc/rpcexception.py | Python | gpl-3.0 | 774 | 0.005168 | #
# This fi | le is part of apt2d8.
#
# Copyright (C) 2013 David Gnedt
#
# apt2d8 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.
#
# apt2d8 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... |
PermutaTriangle/PermStruct | examples/classical_5x4/1234_1243_2134_2431_4213.py | Python | bsd-3-clause | 693 | 0.010101 | from __future__ import print_function
from permuta import *
import permstruct
import permstruct.dag
from permstruct import *
from permstruct.dag import taylor_dag
import sys
# -- Example from Kuszmaul paper -- #
# STATUS ================================================ >
task = '1234_1243_2134_2431_4213'
p | atts = [ Permutation([ int(c) for c in p ]) for p in task.split('_') ]
# patts | = [Permutation([5,2,3,4,1]), Permutation([5,3,2,4,1]), Permutation([5,2,4,3,1]), Permutation([3,5,1,4,2]), Permutation([4,2,5,1,3]), Permutation([3,5,1,6,2,4])]
struct(patts, size=6, perm_bound = 8, subpatts_len=4, subpatts_num=3)
# struct(patts, size = 4, verify_bound = 10, ask_verify_higher = True)
|
gasman/pyrecoil | setup.py | Python | gpl-2.0 | 1,164 | 0.003436 | from setuptools import setup, find_packages, Extension
recoil_module = Extension('_recoil', sources=['recoil_interface.c', 'recoil.c'])
def readme():
with open('README.rst') as f:
return f.read()
setup(
name="pyrecoil",
version="0.3.1",
packages=find_packages(),
ext_modules=[recoil_module... | rs=[
"Development Status :: 5 - Production/Stable",
"Topic :: Multimedia :: Graphics",
"Topic :: Multim | edia :: Graphics :: Graphics Conversion",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Pyth... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.