repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
ddcatgg/dglib | dglib/codec/keyserial.py | # -*- coding: utf-8 -*-
import wmi
import string
import hashlib
import pywintypes
SERIALCHRS = "".join([string.digits, string.ascii_uppercase])
MD5CHRS = "0123456789ABCDEF"
def md5_to_serial(md5_s):
"""
将md5字符串(32个字符,0-9A-F)转换为序列号字符串(16个字符串,0-9A-Z)
"""
chars = []
for i in range(0, len(md5_s), 2):... |
dwfreed/mitmproxy | test/mitmproxy/test_platform_pf.py | import sys
from mitmproxy.platform import pf
from mitmproxy.test import tutils
class TestLookup:
def test_simple(self):
if sys.platform == "freebsd10":
p = tutils.test_data.path("mitmproxy/data/pf02")
d = open(p, "rb").read()
else:
p = tutils.test_data.path("mi... |
loren138/martaOptimize | summary.py | #n[6]:
import pandas as pd
df = pd.read_csv("train_ridership_one_month.csv")
df.head()
# In[64]:
# Below code removes unwanted passenger activity codes for parking
valid_codes = [1, 9, 10, 11, 12]
df = df[df.use_type != 13 ]
df = df[df.use_type != 14 ]
clean_df = df[df.use_type != 15 ]
cols = ["transit_day", "tra... |
jmtyszka/bidskit | bidskit/translate.py | """
Utility functions for handling protocol series tranlsation and purpose mapping
MIT License
Copyright (c) 2017-2022 Mike Tyszka
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restricti... |
tleonhardt/CodingPlayground | dataquest/SQL_and_Databases/statistics_by_group.py | #!/usr/bin/env python
"""
In many cases, we want to drill down and compute summary statistics per-group. In this mission, we'll
explore how to calculate more granular summary statistics. We'll switch back to writing SQL queries
directly instead of using Python so we can focus more on the SQL syntax.
We'll be working w... |
hxp2k6/https-github.com-stamparm-maltrail | trails/feeds/malwarepatrol.py | #!/usr/bin/env python
"""
Copyright (c) 2014-2015 Miroslav Stampar (@stamparm)
See the file 'LICENSE' for copying permission
"""
import re
from core.common import retrieve_content
__url__ = "https://lists.malwarepatrol.net/cgi/getfile?receipt=f1417692233&product=8&list=dansguardian"
__check__ = "Malware Patrol"
__i... |
vervacity/ggr-project | figs/archive/fig_4.homotypic/analyze.genome.solo_regions.py | #!/usr/bin/env python
import os
import re
import sys
import h5py
import numpy as np
import pandas as pd
from ggr.analyses.bioinformatics import run_gprofiler
from ggr.analyses.linking import regions_to_genes
from tronn.util.utils import DataKeys
from tronn.util.formats import array_to_bed
REMOVE_SUBSTRINGS = [
... |
zooba/pyvsop | setup.py | from setuptools import setup, find_packages
from pathlib import Path
here = Path(__file__).parent
# Get the long description from the relevant file
with open(str(here /'DESCRIPTION.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='pyvsop',
version='0.1',
descriptio... |
EvaErzin/DragonHack | DragonHack/management/commands/databaseCreation.py | import csv
import datetime
import HackApp.models as database
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
def handle(self, *args, **options):
with open("dragon_dump.csv") as file:
data = csv.reader(file, delimiter = ",")
dodanaPodje... |
skylifewww/pangolinland | pangolinland/core/jinja.py | from jinja2 import Environment
from django.conf import settings
from django.contrib.staticfiles.storage import staticfiles_storage
from django.contrib.messages import get_messages
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext
from django.utils.timezone import now
from djang... |
robin-vjc/nsopy | nsopy/methods/subgradient.py | # Classes incorporating the dual subgradient methods implemented in this package.
# New nsopy (and corresponding loggers) can be added by following the templates TemplateMethod, TemplateMethodLogger.
from __future__ import print_function
from __future__ import division
import numpy as np
from nsopy.methods.base impor... |
davidrobles/mlnd-capstone-code | capstone/rl/utils/linear_annealing.py | from .callbacks import Callback
class LinearAnnealing(Callback):
def __init__(self, obj, param, init, final, n_episodes):
self.doing = 'inc' if init < final else 'dec'
self.obj = obj
self.param = param
self.init = init
self.final = final
self.n_episodes = n_episode... |
bsandrow/rogers-usage | rogers_usage/usage.py |
import re
import lxml.html
from collections import namedtuple
DailyBreakdown = namedtuple('DailyBreakdown', ['detail', 'totals'])
# -- URLs --
current_usage_url = 'https://www.rogers.com/web/myrogers/internetUsageBeta?actionTab=CurrentUsageSummary'
monthly_history_url = 'https://www.rogers.com/web/myrogers/internet... |
quietcoolwu/python-playground | imooc/python_advanced/csv_download.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from io import BytesIO
import requests
import unicodecsv as csv
def download(url):
response = requests.get(url, timeout=10)
if response.ok:
return response.content
if __name__ == '__main__':
url = 'http://table.finance.yahoo.com/table.csv?s=000001.... |
pinax/pinax-project-forums | project_name/settings.py | import os
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
# tweaked settings to prevent Django 1.5 detection in Django 1.7
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
"default": {
"ENGINE": "django.db.back... |
sergeii/swat4stats.com | tracker/management/commands/cron_update_positions.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import warnings
from django.core.management.base import BaseCommand, CommandError
from tracker import tasks
class Command(BaseCommand):
"""
Calculate and save positions for each leaderboard withon a selected year.
Usage:
... |
wakiyamap/electrum-mona | electrum_mona/gui/qt/lightning_dialog.py | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2012 thomasv@gitorious
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including witho... |
aurule/npc | tests/character/test_sanitize.py | """Tests the intricacies of the build_header method"""
import re
import npc
from npc.character import *
import pytest
def test_faketype_replaces_type():
c1 = Character(type=['vampire'], faketype=['human'])
c1.sanitize()
assert c1.tags('type').first_value() == 'human'
def test_hidden_tags_are_removed():
... |
cecedille1/PDF_generator | examples/report.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Multipage report with header, footer, and pages numbers
"""
from reportlab.lib import units, colors, enums
from reportlab.platypus import XBox
from pdf_generator import Story, Paragraph
from pdf_generator.page_number import NumberedCanvasFactory
from pdf_generator.t... |
kiyukuta/lencon | code/predict.py |
import argparse
import json
import numpy as np
import sys
import beam_search
import beam_search_fix_len
import beam_search_fix_rng
import greedy_generator
import builder
def get_decoder(decoding_method, model, src_vcb, trg_vcb, beam_width):
if decoding_method == 'bs_normal':
gen = beam_search.BeamSearch... |
michalsapka/basecrm-python | basecrm/configuration.py | import re
from basecrm.version import VERSION
from basecrm.errors import ConfigurationError
class Configuration(object):
"""Base CRM client configuration :class:`Configuration <Configuration>` object.
Used by :class:`HttpClient <HttpClient>` to send requests to Base CRM's servers.
"""
URL_REGEXP = ... |
facebookresearch/ParlAI | parlai/tasks/ubuntu/build.py | #!/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.
# Download and build the data if it does not exist.
import parlai.core.build_data as build_data
import os
from parlai.c... |
tofergregg/IBM-Wheelwriter-Hack | software/GIS_Project/server.py | #!/usr/bin/env python3
import socket
import sys
import os
import json
import time
import serial
import availablePorts
import argparse
DATA_AMOUNT = 1024
MAXLINE = 40
def getArgs():
parser = argparse.ArgumentParser(prog=sys.argv[0])
parser.add_argument('-p','--port',type=int,default=10000,dest='port',help... |
chinmayhegde/retinopathy-detection | tensorFlow_testing/input_data_batching.py | import gzip
import math
import os
import numpy as np
import cv2
import csv
import tempfile
import numpy
from six.moves import urllib
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
class DataSet(object):
def __init__(self, is_necessary, name_label_association, fake_data=Fa... |
knyte/wl_parsers | wl_parsers/ladder_parser.py | # Imports
## parser core - mainly the core parser class
from parser_core import *
# LadderParser class
class LadderParser(WLParser):
"""
class to parse ladders
@PARAMS:
'ladderID': integer ID for ladder to parse
"""
def __init__(self, ladderID):
baseURL = "https://www.warlight.net/Lad... |
thomasrstorey/recipesfordisaster | actions/peel.py | '''
melt.py
Takes a list of input ingredient names. Melts each ingredient, and adds the
resulting model to the current blend or a new blend
Thomas Storey
2016
'''
import sys
import argparse
import bpy
import numpy as np
import os
import bmesh
from math import *
from mathutils import *
import random
def deleteObjec... |
5nizza/party-elli | kid.py | #!/usr/bin/env python3
import argparse
import logging
from LTL_to_atm.translator_via_spot import LTLToAtmViaSpot
from automata.k_reduction import k_reduce
from helpers.main_helper import setup_logging
from interfaces.LTL_to_automaton import LTLToAutomaton
from interfaces.spec import Spec
from module_generation.automa... |
hnawner/musical-forms | models/neuralnets/separate/rnn/utils.py | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
import numpy as np
from os import listdir
def read_mels(folder):
files = listdir(folder)
mels = []
offsets = { "C":0, "C-sharp":1, "D-flat":1, "D":2, "D-sharp":3, "E-flat":3,
"E":4, "E-sharp":5,... |
austinburks/data-science-bowl-2017 | docs/conf.py | # -*- coding: utf-8 -*-
#
# data-science-bowl-2017 documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuratio... |
stygstra/keras-contrib | examples/cifar10_densenet.py | '''
Trains a DenseNet-40-12 model on the CIFAR-10 Dataset.
Gets a 94.84% accuracy score after 100 epochs.
'''
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
from keras import backend as K
from keras.callbacks import ModelCheckpoint, Red... |
wiktorski/ts_analytics | ts_analytics.py | """
This file contains implementation of basic time series analytic methods.
The implementation is based upon many theoretical and prectical sources, including:
"Timeseries Classification: KNN & DTW" by Mark Regan (http://nbviewer.ipython.org/github/markdregan/K-Nearest-Neighbors-with-Dynamic-Time-Warping/blob/master/... |
evereux/flicket | application/flicket/forms/flicket_forms.py | #! usr/bin/python3
# -*- coding: utf-8 -*-
#
# Flicket - copyright Paul Bourne: evereux@gmail.com
from flask import request
from flask import url_for
from flask_babel import lazy_gettext
from flask_pagedown.fields import PageDownField
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, Hidden... |
Vaayne/vaayne.com | app/func/spider/fly.py | # -*- coding:utf-8 -*-
# Created by Vaayne at 2016/07/23 08:17
from gevent.monkey import patch_all
patch_all()
from gevent.pool import Pool
from .spider import Spider
from bs4 import BeautifulSoup
class FlyerTea(Spider):
def __init__(self):
super().__init__()
self.category = '信用卡'
self.spi... |
logpai/logparser | logparser/MoLFI/main/org/core/operators/crossover.py | import random
from ..chromosome.chromosome import Chromosome
def multipoint_cx(ch1: Chromosome, ch2: Chromosome):
""" apply crossover on two Chromosomes at a randomly selected crossover point
:param ch1: first Chromosome
:param ch2: second Chromosome
:return: the two modified chromosomes
... |
zuik/stuff | nearby/nearby.py | from flask import Flask, request, render_template, Response
import json
import time
from bson.json_util import dumps
from pymongo import MongoClient
from flask_cors import CORS, cross_origin
app = Flask(__name__, static_url_path='/static')
CORS(app)
client = MongoClient()
db = client['nearby']
# @app.route("/")
# de... |
flavour/iscram | modules/tests/suite.py | # This script is designed to be run as a Web2Py application:
# python web2py.py -S eden -M -R applications/eden/modules/tests/suite.py
# or
# python web2py.py -S eden -M -R applications/eden/modules/tests/suite.py -A testscript
# Selenium WebDriver
from selenium import webdriver
from gluon import current
from gluon.s... |
managai/cex.io-api-python | cexapi/test.py | # -*- coding: utf-8 -*-
import cexapi
demo = cexapi.api(username, api_key, api_secret)
print("Ticker (GHS/BTC)")
print(demo.ticker()) ## or demo.ticker('GHS/BTC')
print("Ticker (BF1/BTC)")
print(demo.ticker('BF1/BTC'))
print("Order book (GHS/BTC)")
print(demo.order_book()) ## or demo.order_book('GHS/BTC')
print("Order... |
ckuzma/atc_alexa | requests/api.py | # -*- coding: utf-8 -*-
"""
requests.api
~~~~~~~~~~~~
This module implements the Requests API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
"""
from . import sessions
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:para... |
isudox/leetcode-solution | python-algorithm/leetcode/problem_715.py | """715. Range Module
https://leetcode.com/problems/range-module/
A Range Module is a module that tracks ranges of numbers. Your task is to
design and implement the following interfaces in an efficient manner.
addRange(int left, int right) Adds the half-open interval [left, right),
tracking every real number in that ... |
xu6148152/Binea_Python_Project | FluentPython/object_reference_mutability_recycling/deep_shallow_copies.py | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
class Bus:
def __init__(self, passengers=None):
if passengers is None:
self.passengers = []
else:
self.passengers = list(passengers)
def pick(self, name):
self.passengers.append(name)
def drop(self, name):
... |
lilleswing/deepchem | deepchem/models/torch_models/gcn.py | """
DGL-based GCN for graph property prediction.
"""
import torch.nn as nn
import torch.nn.functional as F
from deepchem.models.losses import Loss, L2Loss, SparseSoftmaxCrossEntropy
from deepchem.models.torch_models.torch_model import TorchModel
class GCN(nn.Module):
"""Model for Graph Property Prediction Based on... |
ElessarWebb/dummy | src/dummy/viewer/formatting/plotformatters.py | from dummy.viewer.formatting import ResultFormatter, Formatter
import logging
logger = logging.getLogger( __name__ )
try:
import pylab
import numpy
@Formatter.register( 'plot' )
class PlotFormatter( ResultFormatter ):
def __init__( self, *args, **kwargs ):
super( PlotFormatter, self ).__init__( self, *args... |
voitureblanche/projet-secret | pc_version/font_desc.py | ## Font descriptor
tiny_font = {
"glyph":
[
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '+', '.', '!',
':', ')', '(', ',',
'\0'
],
"x_pos":
[
0, 11, 20, 29, 3... |
gaalcaras/dotfiles | task/hooks/find_hooks.py | #!/usr/bin/env python
"""
Pluggable system for TaskWarrior hooks
Adapted from https://github.com/tbabej/taskpirate
by Gabriel Alcaras
"""
import glob
import importlib.util as lib
import os
def find_hooks(file_prefix):
"""
Find all files in subdirectories whose names start with <file_prefix>
"""
file... |
ernestoalarcon/competitiveprogramming | game-of-thrones.py | #!/bin/python
# Solution for https://www.hackerrank.com/challenges/game-of-thrones
string = raw_input().strip()
def can_be_palindrome(data):
odd_requencies = 0
for l in set(data):
current_frequency = data.count(l)
if current_frequency % 2:
odd_requencies += 1
if... |
stefan-jonasson/home-assistant | homeassistant/components/telegram_bot/polling.py | """
Telegram bot polling implementation.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/telegram_bot.polling/
"""
import asyncio
from asyncio.futures import CancelledError
import logging
import async_timeout
from aiohttp.client_exceptions import ClientE... |
timwienk/mooshell | settings.py | # default settings (usually overwritten in machine_settings.py)
# LAYOUT
MOOSHELL_CROSS_LAYOUT = "Cross"
MOOSHELL_TABS_LAYOUT = "Tabs"
MOOSHELL_SlIDES_LAYOUT = "Slides"
MOOSHELL_DEFAULT_SKIN = 'light'
MOOSHELL_STANDARD_LAYOUT = MOOSHELL_CROSS_LAYOUT
MOOSHELL_EMBEDDED_TITLES = {"js": "JavaScript",
'resources': ... |
ashwyn/eden-message_parser | modules/tests/smoke/broken_links.py | from time import time
try:
from cStringIO import StringIO # Faster, where available
except:
from StringIO import StringIO
import sys
from tests.web2unittest import Web2UnitTest
from gluon import current
try:
from twill import get_browser
from twill import set_output
from twill.browser import *
e... |
danielnyga/dnutils | src/dnutils/tools.py | '''
Created on May 22, 2017
@author: nyga
'''
import re
class UNICODE:
'''
A collection of Unicde symbols.
'''
CROSS = '\u00d7'
WARNING = '\u26a0'
CHECKMARK = '\u2713'
TRIANGLE_UP = '\u25B2 '
TRIANGLE_DOWN = '\u25BC '
def ifnone(if_, else_, transform=None):
'''Returns the cond... |
ecoron/SerpScrap | serpscrap/config.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import datetime
"""
SerpScrap.Config
"""
class Config():
"""
Config
This modul is used to hold and handle the required configuration settings
Attributes:
config: dict of configuration keys and values
apply (dict): method to set a new configur... |
rofolel/AutoTorrent- | database/film/imdb.py | import tools.tools
import requests
import film
import json
def getAllFilms():
strings = tools.tools.get2letterString()
it = len(strings)/100
incr = 0
percent = 0
films = list()
print_s = '\rgetting IMdB database: {0}%'
print print_s.format(0)
for i in strings:
print '\rgetti... |
kingsamchen/Eureka | crack-data-structures-and-algorithms/leetcode/product_of_the_last_k_numbers_q5341.py | # 核心思路
# 使用cache来缓存之前的查询结果,避免TLE
class ProductOfNumbers(object):
def __init__(self):
self._seq = []
self._cache = {}
def add(self, num):
"""
:type num: int
:rtype: None
"""
self._seq.append(num)
self._cache.clear()
def getProduct(self, k):... |
madmatah/lapurge | setup.py | #!/usr/bin/env python
from distutils.core import setup
from lapurge.version import __version__
setup(name='lapurge',
version=__version__,
author='Matthieu Huguet',
author_email='matthieu@huguet.eu',
description='A tool to purge your backup directories according to your retention rules',
... |
Zephor5/zspider | zspider/utils/fields_models.py | # coding=utf-8
import re
import mongoengine.fields as f
from flask_mongoengine import BaseQuerySet
from wtforms import fields
from wtforms import ValidationError
from . import engine
from .pagination import FPagination
__author__ = "zephor"
class BaseValidateField(f.StringField):
def __init__(self, extra_valid... |
newOnahtaN/Genie-GENe-Cataloger | GENe_Windows/GENe.py | import os
import wx
import sys
import time
import __future__
from Bio.Blast import NCBIWWW
from Bio.Blast import NCBIXML
from Bio.Blast.Applications import *
from Bio import SeqIO
from xlrd import open_workbook
from xlwt import Workbook
from threading import Thread
#GENe RNA Cataloger
#Nathan Owen, ncowe... |
dabiid/pitchfork-scraper | pitchfork/spiders/reviews.py | # -*- coding: utf-8 -*-
import scrapy
from pitchfork.items import PitchforkReviewItem
from pitchfork.pipelines import PitchforkReviewsPipeline
from datetime import datetime
from time import strptime
import logging
class ReviewsSpider(scrapy.Spider):
name = "pitchfork"
allowed_domains = ["pitchfork.com"]
s... |
andrewyoung1991/supriya | supriya/tools/ugentools/BPF.py | # -*- encoding: utf-8 -*-
from supriya.tools.ugentools.Filter import Filter
class BPF(Filter):
r'''A 2nd order Butterworth bandpass filter.
::
>>> source = ugentools.In.ar(bus=0)
>>> b_p_f = ugentools.BPF.ar(source=source)
>>> b_p_f
BPF.ar()
'''
### CLASS VARIABLES ... |
SkySchermer/uweclang | django/src/attic/__init__.py | from django.core.cache import cache
import sys
import os
sys.path.append(os.path.dirname(os.path.realpath('..')))
import uweclang
from . import settings
import logging
import pickle
log = logging.getLogger(__name__)
# _CORPUS_LOCATION = os.path.dirname(os.path.realpath('../../test/corpus'),)
_CORPUS_LOCATION = r'/V... |
Hiestaa/miniboard-factorio-manager | tools/utils.py | # -*- coding: utf8 -*-
from __future__ import unicode_literals
import json
import math
import time
from datetime import datetime
import os
"""
This module contains miscelaneous functions that can be useful anywhere in
the project.
"""
def sizeFormat(sizeInBytes):
"""
Format a number of bytes ... |
jml/pyrsistent | tests/vector_test.py | import pickle
import pytest
from pyrsistent._pvector import python_pvector
@pytest.fixture(scope='session', params=['pyrsistent._pvector', 'pvectorc'])
def pvector(request):
m = pytest.importorskip(request.param)
if request.param == 'pyrsistent._pvector':
return m.python_pvector
return m.pvector
... |
robodair/pydocstring | docs/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# pydocstring documentation build configuration file, created by
# sphinx-quickstart on Sat Sep 9 11:45:10 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
... |
Stevearzh/irc-sha | isha/core/factory.py | import csv
from functools import reduce
from isha.model.card import RECIPE as CARD_RECIPE
from isha.dict.card import CARD_SUIT
def card_generator(path, pack_list, recipe=CARD_RECIPE, filters=list(CARD_RECIPE.keys())):
result = []
list(map(lambda pack: result.extend(card_loader(path + pack + '.csv')), pack_lis... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-dns/azure/mgmt/dns/v2016_04_01/models/_models_py3.py | # 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 ... |
Ikusaba-san/Chiaki-Nanami | cogs/games/hangman.py | import asyncio
import contextlib
import functools
import glob
import operator
import os
import random
import string
from collections import namedtuple
import discord
from discord.ext import commands
from ..utils.context_managers import temp_item
from ..utils.formats import escape_markdown, truncate
from ..utils.misc ... |
jennj/BLE-Scripts | scripts-read/scanner.py | import sys
from gattlib import DiscoveryService
service = DiscoveryService("hci0")
possibleTargets = list()
###
# Scan for advertising packets and get AdvAs
###
def doDiscovery():
global possibleTargets
# check 5 times for advertising devices
for x in range(0,10):
# use gattlib to scan for possible target... |
Solar-Computing/solar-app2 | app/models.py | from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
db = SQLAlchemy()
class Unit(db.Model):
table = db.Column(db. String(), primary_key=True)
field = db.Column(db.String(), primary_key=True)
unit = db.Column(db.String())
class Simulation(db.Model):
timestamp = db.Column(db.DateTime(ti... |
tmp6154/torch-rnn | scripts/preprocess.py | # -*- coding: utf-8 -*-
import argparse, json, os
import numpy as np
import h5py
import codecs
import sys
parser = argparse.ArgumentParser()
parser.add_argument('--input_txt', default='data/tiny-shakespeare.txt')
parser.add_argument('--output_h5', default='data/tiny-shakespeare.h5')
parser.add_argument('--output_jso... |
severb/flowy | tests/swf_cases.py | from flowy import SWFWorkflowConfig
from flowy import SWFWorkflowWorker
from workflows import *
no_activity_workflow = SWFWorkflowConfig()
task_activity_workflow = SWFWorkflowConfig()
task_activity_workflow.conf_activity('task', version=1)
task_activity_workflow_rl = SWFWorkflowConfig(rate_limit=3)
task_activity_wo... |
mbeloshitsky/tbf | vm.py | import time
import sched
from expr import *
class RealtimeVM():
def __init__(self, values):
self._dispatcher = sched.scheduler(time.time, time.sleep)
def dispatchProc(callback, timeout):
self._dispatcher.enter(timeout, 1, callback, ())
for val in values.values():... |
edilio/tobeawebproperty | haweb/libs/drf/error_responses.py | from __future__ import unicode_literals
from types import DictType, ListType, StringTypes
from rest_framework import status
from rest_framework.response import Response
class ErrorResponseException(Exception):
pass
class ErrorResponse(Response):
"""
A HttpResponse that indicates an error
"""
de... |
dorellang/MysteryGraphBot | mystery_graph_bot/serializers.py | from marshmallow import Schema, fields
from marshmallow.exceptions import ValidationError
class IntegerOrStrField(fields.Field):
default_error_messages = {
'invalid': 'Not a valid string or integer.'
}
def _serialize(self, value, attr, obj):
if value is None:
return None
... |
aoyono/sicpy | Chapter1/themes/procedure_as_arguments.py | # -*- coding: utf-8 -*-
"""
"""
from operator import add, gt, mul, truediv
from Chapter1.exercises.exercice1_8 import cube
from Chapter1.exercises.exercise1_9 import inc
# Trivial definitions
def sum_ints(a, b):
if gt(a, b):
return 0
return add(
a,
sum_ints(add(a, 1), b)
)
def s... |
mattgibb/visualisation | cxxtest/python/cxxtest/cxxtestgen.py | __all__ = ['main']
import sys
import os.path
from os.path import abspath, dirname
#sys.path.insert(0, dirname(dirname(abspath(__file__))))
import re
import getopt
import glob
import string
from optparse import OptionParser
import cxxtest_parser
try:
import cxxtest_fog
imported_fog=True
except ImportError:
... |
webstack/flask-jwt | flask_jwt/__init__.py | # -*- coding: utf-8 -*-
"""
flask_jwt
~~~~~~~~~
Flask-JWT module
"""
import warnings
from collections import OrderedDict
from datetime import datetime, timedelta
from functools import wraps
import jwt
from flask import current_app, request, jsonify, _request_ctx_stack
from werkzeug.local import LocalPr... |
vortexntnu/rov-control | sensor_interface/scripts/ms5837_interface.py | #!/usr/bin/env python
import rospy
import ms5837
from sensor_msgs.msg import FluidPressure, Temperature
class Ms5837InterfaceNode(object):
def __init__(self):
rospy.init_node('pressure_node')
self.pub_pressure = rospy.Publisher(
'sensors/pressure',
FluidPressure,
... |
jaraco/calendra | calendra/europe/netherlands.py | from datetime import date, timedelta
from ..core import WesternCalendar, SUN, SeriesShiftMixin
from ..registry_tools import iso_register
@iso_register('NL')
class Netherlands(SeriesShiftMixin, WesternCalendar):
'Netherlands'
include_good_friday = True
include_easter_sunday = True
include_easter_monda... |
mdenchev/IDL | src/python/python_parser.py | import os, sys, inspect, types, ast
if len(sys.argv) != 2:
print "Error, invalid number of arguments for python_parser."
sys.exit()
def printFunctions(functions):
print len(functions)
for function in functions:
args = ", ".join(function.args.args[i].id for i in range(len(function.args.args)))... |
suraj/python-django-workshop | python/01_func_gen.py | import random as rand
# Normal python function
def random(count):
"""
Returns 'count' numbers of random integers in the range [0, 100]
"""
ret = []
while count>0:
ret.append(rand.randint(0, 100))
count -= 1
return ret
# generator
def g_random(count):
"""
Returns 'count'... |
duoduo369/django-scaffold | django-scaffold/settings.py | # -*- coding: utf-8 -*-
# Django settings for django-scaffold project.
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = False
TEMPLATE_DEBUG = DEBUG
FEATURES = {
'ENABLE_DJANGO_ADMIN_SITE': True,
'ADMIN... |
Levak/RoleKeeper | lang/russian.py | # The MIT License (MIT)
# Copyright (c) 2017 Levak Borok <levak92@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights t... |
glitchassassin/lackey | lackey/Geometry.py | import time
class Location(object):
""" Basic 2D point object """
def __init__(self, x, y):
self.setLocation(x, y)
def getX(self):
""" Returns the X-component of the location """
return self.x
def getY(self):
""" Returns the Y-component of the location """
retur... |
plotly/python-api | packages/python/plotly/plotly/tests/test_core/test_update_objects/test_update_traces.py | from __future__ import absolute_import
from unittest import TestCase
import inspect
import copy
import plotly.graph_objs as go
from plotly.subplots import make_subplots
class TestSelectForEachUpdateTraces(TestCase):
def setUp(self):
fig = make_subplots(
rows=3,
cols=2,
... |
mixja/eap-sim-lab | lib/pySim/pySim-run-gsm.py | #!/usr/bin/env python
#
# Utility to run the 2G gsm algorithm on the SIM card
# used to generate authentication triplets for EAP-SIM
#
# Copyright (C) 2009 Sylvain Munaut <tnt@246tNt.com>
# Copyright (C) 2010 Harald Welte <laforge@gnumonks.org>
# Copyright (C) 2013 Alexander Chemeris <alexander.chemeris@gmail.com>
... |
mabotech/maboss.py | maboss/functions/label2/certificate_data.py | # -*- coding: utf-8 -*-
import os
import logging
import logging.handlers
import logging.config
#import profile
import time
from time import strftime, localtime
from datetime import datetime
from sqlalchemy import String, Integer
from sqlalchemy.sql.expression import text , bindparam, outparam
from mabolab.common.s... |
mtils/ems | ems/qt4/gui/widgets/row_add_search.py | '''
Created on 23.06.2011
@author: michi
'''
import sys
import time
from PyQt4.QtCore import QObject, QVariant, SIGNAL, SLOT, pyqtSignal, pyqtSlot, \
Qt, QString, QTimer
from PyQt4.QtGui import QWidget, QComboBox, QCheckBox, QLineEdit, QGridLayout, \
QPushButton, QTreeWidgetItem, QStackedWidget, QIcon, QSpinBo... |
jskDr/jamespy_py3 | poodle/linear_model.py | # poodle
# Sung-Jin Kim, April 8, 2016
from sklearn import linear_model
import pandas as pd
import numpy as np
from sklearn import model_selection, cross_validation
def read_csv( *args, index_col=0, header=[0,1], **kwargs):
"""
Emulation for pandas.DataFrame()
Parameters
----------
The parameters of Pandas Da... |
leifos/simiir | simiir/loggers/fixed_cost_goal_logger.py | from loggers import Actions
from loggers.fixed_cost_logger import FixedCostLogger
class FixedCostGoalLogger(FixedCostLogger):
"""
A simple extension to the FixedCostLogger - considers a search goal, and a hard time limit.
"""
def __init__(self,
output_controller,
searc... |
mapbox/rio-mucho | tests/test_mod.py | import riomucho
import rasterio
import numpy
import pytest
from rasterio.errors import RasterioIOError
def read_function_manual(open_files, window, ij, g_args):
"""A user function for testing"""
return numpy.array([f.read(window=window)[0] for f in open_files])
def test_riomucho_manual(tmpdir, test_1_tif, ... |
miRTop/mirtop | mirtop/gff/classgff.py | from mirtop.gff import gff_versions
from collections import OrderedDict
class feature:
""""Class with alignment information."""
def __init__(self, line, sep="="):
# if isinstance(line, basestring) # str in python 3
if isinstance(line, dict):
line = self.create_line(line, sep)
... |
graphql-python/graphene | graphene/types/decimal.py | from __future__ import absolute_import
from decimal import Decimal as _Decimal
from graphql.language.ast import StringValueNode, IntValueNode
from .scalars import Scalar
class Decimal(Scalar):
"""
The `Decimal` scalar type represents a python Decimal.
"""
@staticmethod
def serialize(dec):
... |
pyconll/pyconll | setup.py | from pathlib import Path
from setuptools import setup
from util import parse
def make_relative(fn):
"""
Make the filename relative to the current file.
Args:
fn: The filename to convert.
Returns:
The path relative to the current file.
"""
return Path(__file__).parent / fn
... |
truveris/py-mdstat | mdstat/device_status.py | # Copyright 2015, Truveris Inc. All Rights Reserved.
from __future__ import absolute_import
def parse_device_status_disk_accounting(counts, synced):
disk_counts = counts[1:-1].split("/", 1)
raid_disks, non_degraded_disks = (int(c) for c in disk_counts)
synced = [c == "U" for c in synced[1:-1]]
retu... |
ajar98/todoist_bot | deprecated_client.py | from todoist.api import TodoistAPI
from dateutil.parser import parse
import datetime
from datetime import timedelta
from uuid import uuid4
# implement labels
# create a new project
# create a task in a new project
ID_LENGTH = 20
ADD_TASK_TYPE = 'item_add'
ITEM_COMPLETE_TYPE = 'item_complete'
UPDATE_TASK_TYPE = 'item... |
macobo/python-grader | tasks/task_lister.py | import os
from os.path import join
import json
CURRENT_FOLDER = os.path.abspath(os.path.dirname(__file__))
def process_file(task_file_contents, folder_path):
task_data = json.loads(task_file_contents)
result = []
for task in task_data["tasks"]:
assert all(x in task for x in ("name", "tester", "so... |
sprymix/importkit | importkit/python/__init__.py | ##
# Copyright (c) 2008-2010, 2013 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
import marshal
import sys
try:
from importlib._bootstrap import _SourceFileLoader
except ImportError:
try:
from importlib._bootstrap import SourceFileLoader as _SourceFileLoader
except ImportErro... |
algorhythms/LeetCode | 323 Number of Connected Components in an Undirected Graph.py | """
Premium Question
simple DFS
"""
__author__ = 'Daniel'
class Solution(object):
def countComponents(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
V = [[] for _ in xrange(n)]
for e in edges:
V[e[0]].append(e[1])
... |
drupdates/Slack | __init__.py | """ Send report using Slack. """
from drupdates.settings import Settings
from drupdates.utils import Utils
from drupdates.constructors.reports import Report
import json, os
class Slack(Report):
""" Slack report plugin. """
def __init__(self):
current_dir = os.path.dirname(os.path.realpath(__file__))
... |
ShenggaoZhu/midict | midict/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function #, unicode_literals
import sys
__version__ = '0.1.4'
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
from collections import Hashable, ItemsView, KeysView, Mapping, OrderedDict, ValuesView
NoneType = type(None)... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/connectivity_information.py | # 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 ... |
indirectlylit/kolibri | kolibri/core/auth/management/commands/flushsyncsessions.py | import logging
from datetime import timedelta
from dateutil.parser import isoparse
from django.db.models import Q
from django.utils import timezone
from morango.models import Buffer
from morango.models import RecordMaxCounterBuffer
from morango.models import SyncSession
from morango.models import TransferSession
from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.