repo_name
stringlengths
5
104
path
stringlengths
4
248
content
stringlengths
102
99.9k
ithinksw/philo
philo/models/fields/__init__.py
from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields im...
nficano/python-lambda
aws_lambda/aws_lambda.py
import hashlib import json import logging import os import subprocess import sys import time from collections import defaultdict from shutil import copy from shutil import copyfile from shutil import copystat from shutil import copytree from tempfile import mkdtemp import boto3 import botocore import yaml import sys ...
mfil/getebook
getebook/epub.py
# Copyright (c) 2015, Max Fillinger <max@max-fillinger.net> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND...
banacer/door-wiz
src/identification/Identifier.py
import numpy as np import pandas as pd from pandas import Series, DataFrame from scipy.spatial import distance import matplotlib.pyplot as plt from sklearn.cluster import DBSCAN from sklearn import metrics from sklearn.datasets.samples_generator import make_blobs from sklearn.preprocessing import StandardScaler from s...
wanghuafeng/spider_tools
decorator.py
#!-*- coding:utf-8 -*- import time def retries(times=3, timeout=1): """对未捕获异常进行重试""" def decorator(func): def _wrapper(*args, **kw): att, retry = 0, 0 while retry < times: retry += 1 try: return func(*args, **kw) ...
poliastro/poliastro
contrib/CR3BP/test_run_CR3BP.py
""" ******************************************************************** Test file for implementation check of CR3BP library. ******************************************************************** Last update: 21/01/2022 Description ----------- Contains a few sample orbit propagations to test the CR3BP l...
tzpBingo/github-trending
codespace/python/tencentcloud/scf/v20180416/errorcodes.py
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses...
bohdan7/python_koans
python3/koans/about_iteration.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self):...
2Checkout/2checkout-python
twocheckout/sale.py
from api_request import Api from util import Util from twocheckout import Twocheckout class Sale(Twocheckout): def __init__(self, dict_): super(self.__class__, self).__init__(dict_) @classmethod def find(cls, params=None): if params is None: params = dict() response = ...
CenterForOpenScience/scinet
scinet/views.py
import json import os from flask import request, g, render_template, make_response, jsonify, Response from helpers.raw_endpoint import get_id, store_json_to_file from helpers.groups import get_groups from json_controller import JSONController from main import app from pymongo import MongoClient, errors HERE = os.pat...
DanceCats/CoreCat
corecat/models/project.py
from corecat.constants import OBJECT_CODES, MODEL_VERSION from ._sqlalchemy import Base, CoreCatBaseMixin from ._sqlalchemy import Column, \ Integer, \ String, Text class Project(CoreCatBaseMixin, Base): """Project Model class represent for the 'projects' table which is used to store project's basic i...
TerryHowe/ansible-modules-hashivault
ansible/modules/hashivault/hashivault_approle_role_get.py
#!/usr/bin/env python from ansible.module_utils.hashivault import hashivault_argspec from ansible.module_utils.hashivault import hashivault_auth_client from ansible.module_utils.hashivault import hashivault_init from ansible.module_utils.hashivault import hashiwrapper ANSIBLE_METADATA = {'status': ['stableinterface'],...
HashirZahir/FIFA-Player-Ratings
FIFAscrape/spiders/fifa_spider.py
from scrapy.spiders import Spider from scrapy.selector import Selector from scrapy.http import HtmlResponse from FIFAscrape.items import PlayerItem from urlparse import urlparse, urljoin from scrapy.http.request import Request from scrapy.conf import settings import random import time class fifaSpider(Spider...
Azure/azure-sdk-for-python
sdk/sql/azure-mgmt-sqlvirtualmachine/azure/mgmt/sqlvirtualmachine/aio/_sql_virtual_machine_management_client.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 ...
griimick/feature-mlsite
app/liner/views.py
from flask import Blueprint, request, render_template from ..load import processing_results from ..abbr import get_abbr_map abbr_map = get_abbr_map() liner_mod = Blueprint('liner', __name__, template_folder='templates', static_folder='static') @liner_mod.route('/liner', methods=['GET', 'POST']) def liner(): if r...
lmazuel/azure-sdk-for-python
azure-mgmt-web/azure/mgmt/web/models/dimension.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 ...
TheMasterGhost/CorpBot
Cogs/Time.py
import asyncio import discord import datetime import pytz from discord.ext import commands from Cogs import FuzzySearch from Cogs import Settings from Cogs import DisplayName from Cogs import Message from Cogs import Nullify class Time: # Init with the bot reference, and a reference to the s...
the-zebulan/CodeWars
tests/beta_tests/test_what_color_is_your_name.py
import unittest from katas.beta.what_color_is_your_name import string_color class StringColorTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(string_color('Jack'), '79CAE5') def test_equal_2(self): self.assertEqual(string_color('Joshua'), '6A10D6') def test_equal_3(...
michaelBenin/sqlalchemy
test/engine/test_execute.py
# coding: utf-8 from sqlalchemy.testing import eq_, assert_raises, assert_raises_message, \ config, is_ import re from sqlalchemy.testing.util import picklers from sqlalchemy.interfaces import ConnectionProxy from sqlalchemy import MetaData, Integer, String, INT, VARCHAR, func, \ bindparam, select, event, Type...
wiki-ai/editquality
editquality/utilities/generate_make.py
""" ``editquality generate_make -h`` :: Code-generate Makefile from template and configuration :Usage: generate_make -h | --help generate_make [--config=<path>] [--main=<filename>] [--output=<path>] [--template...
vulcansteel/autorest
AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/auto_rest_swagger_bat_array_service/models/product.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 ...
guori12321/todo
todo/parser.py
# coding=utf8 """ Parser for todo format string. from todo.parser import parser parser.parse(string) # return an Todo instance """ from models import Task from models import Todo from ply import lex from ply import yacc class TodoLexer(object): """ Lexer for Todo format string. Tokens ID ...
alisaifee/limits
tests/storage/test_memcached.py
import time import pymemcache.client import pytest from limits import RateLimitItemPerMinute, RateLimitItemPerSecond from limits.storage import MemcachedStorage, storage_from_string from limits.strategies import ( FixedWindowElasticExpiryRateLimiter, FixedWindowRateLimiter, ) from tests.utils import fixed_sta...
ff0000/red-fab-deploy
fab_deploy/joyent/postgres.py
import os import sys import tempfile from fabric.api import run, sudo, env, local, hide, settings from fabric.contrib.files import append, sed, exists, contains from fabric.context_managers import prefix from fabric.operations import get, put from fabric.context_managers import cd from fabric.tasks import Task from ...
chriso/gauged
gauged/drivers/__init__.py
""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <cohara87@gmail.com> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): ...
ibtokin/ibtokin
manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ibtokin.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the ...
laterpay/rubberjack-cli
tests/test_cli.py
import boto import mock import moto import tempfile import unittest from click.testing import CliRunner from rubberjackcli.click import rubberjack class CLITests(unittest.TestCase): @moto.mock_s3_deprecated @mock.patch('boto.beanstalk.layer1.Layer1.create_application_version') @mock.patch('boto.beansta...
tareqalayan/pytest
testing/test_capture.py
from __future__ import absolute_import, division, print_function # note: py.io capture tests where copied from # pylib 1.4.20.dev2 (rev 13d9af95547e) from __future__ import with_statement import pickle import os import sys from io import UnsupportedOperation import _pytest._code import py import pytest import contextl...
greencoder/hopefullysunny-django
registrations/management/commands/registration_worker.py
import zmq import datetime import pytz from django.core.management.base import BaseCommand, CommandError from django.conf import settings from registrations.models import Registration from registrations import handlers from registrations import tasks class Command(BaseCommand): def log(self, message): f...
dcorney/text-generation
core/dialogue.py
import numpy as np from numpy import cumsum, sum, searchsorted from numpy.random import rand import math import utils import core.sentence as sentence import core.markovchain as mc import logging logger = logging.getLogger(__name__) # Dialogue making class. Need to review where to return a string, where to return a l...
executablebooks/mdformat
src/mdformat/renderer/_context.py
from __future__ import annotations from collections import defaultdict from collections.abc import Generator, Iterable, Mapping, MutableMapping from contextlib import contextmanager import logging import re import textwrap from types import MappingProxyType from typing import TYPE_CHECKING, Any, NamedTuple from markd...
alfateam123/Teca
tests/test_utils.py
import teca.utils as tecautils import teca.ConfigHandler as tecaconf import unittest class TestFileFilter(unittest.TestCase): def setUp(self): self.conf = tecaconf.ConfigHandler( "tests/test_data/configuration.json", {"starting_path": "tests/test_data/images"} ) self...
DayGitH/Python-Challenges
DailyProgrammer/DP20150713A.py
""" [2015-07-13] Challenge #223 [Easy] Garland words https://www.reddit.com/r/dailyprogrammer/comments/3d4fwj/20150713_challenge_223_easy_garland_words/ # Description A [_garland word_](http://blog.vivekhaldar.com/post/89763722591/garland-words) is one that starts and ends with the same N letters in the same order, f...
redsolution/django-generic-ratings
ratings/forms/widgets.py
from decimal import Decimal from django import forms from django.template.loader import render_to_string from django.template.defaultfilters import slugify class BaseWidget(forms.TextInput): """ Base widget. Do not use this directly. """ template = None instance = None def get_parent_id(self,...
NESCent/phylocommons
tools/treebase_scraper/annotate_trees.py
#!/usr/bin/env python import sys import os from treestore import Treestore try: taxonomy = sys.argv[1] except: taxonomy = None t = Treestore() treebase_uri = 'http://purl.org/phylo/treebase/phylows/tree/%s' tree_files = [x for x in os.listdir('trees') if x.endswith('.nex')] base_uri = 'http://www.phylocommons.org/...
IQSS/miniverse
dv_apps/metrics/stats_views_dataverses.py
from .stats_view_base import StatsViewSwagger, StatsViewSwaggerKeyRequired from .stats_util_dataverses import StatsMakerDataverses class DataverseCountByMonthView(StatsViewSwaggerKeyRequired): """API View - Dataverse counts by Month.""" # Define the swagger attributes # Note: api_path must match the path...
masschallenge/django-accelerator
simpleuser/models.py
import uuid from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import BaseUserManager from django.utils import timezone from accelerator_abstract.models import BaseUserRole from accelerator_abstract.models.base_base_profile...
keithhamilton/transposer
setup.py
from setuptools import setup, find_packages from codecs import open import os def read(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as f: return f.read() setup( name='transposer', version='0.0.3', description='Transposes column...
RobSpectre/garfield
garfield/phone_numbers/migrations/0002_phonenumber_related_sim.py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-11-01 20:02 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('phone_numbers', '0001_initial'), ...
DestructHub/bcs-contest
2016/Main/L/Python/solution_1_wrong.py
def calc(): h, l = input().split(' ') mapa = [] for i_row in range(int(h)): mapa.append(input().split(' ')) maior_num = 0 for row in mapa: for col in row: n = int(col) if (n > maior_num): maior_num = n qtd = [0 for i in range(maior_num + 1)] for row in mapa: for col in row: n ...
jonasrauber/c2s
c2s/experiment.py
#!/usr/bin/env python """ Manage and display experimental results. """ __license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>' __author__ = 'Lucas Theis <lucas@theis.io>' __docformat__ = 'epytext' __version__ = '0.4.3' import sys import os import numpy import random import scipy import socke...
mikhtonyuk/rxpython
concurrent/futures/cooperative/ensure_exception_handled.py
import traceback class EnsureExceptionHandledGuard: """Helper for ensuring that Future's exceptions were handled. This solves a nasty problem with Futures and Tasks that have an exception set: if nobody asks for the exception, the exception is never logged. This violates the Zen of Python: 'Errors s...
KevinJMcGrath/Symphony-Ares
modules/plugins/PABot/logging.py
import logging.handlers import os _pabotlog = logging.getLogger('PABot') _pabotlog.setLevel(logging.DEBUG) _logPath = os.path.abspath("./logging/pabot.log") _formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s') _consoleStreamHandler = logging.StreamHandler() _consoleStreamHandler.s...
vdods/heisenberg
heisenberg/plot/__main__.py
import ast import heisenberg.library.heisenberg_dynamics_context import heisenberg.library.orbit_plot import heisenberg.option_parser import heisenberg.plot import heisenberg.util import matplotlib import numpy as np import sys # https://github.com/matplotlib/matplotlib/issues/5907 says this should fix "Exceeded cell ...
nhatbui/LebronCoin
lebroncoin/key_loader.py
def load_keys(filepath): """ Loads the Twitter API keys into a dict. :param filepath: file path to config file with Twitter API keys. :return: keys_dict :raise: IOError """ try: keys_file = open(filepath, 'rb') keys = {} for line in keys_file: key, value =...
snfactory/cubefit
cubefit/main.py
"""Main entry points for scripts.""" from __future__ import print_function, division from argparse import ArgumentParser from collections import OrderedDict from copy import copy from datetime import datetime import glob import json import logging import math import os import scipy.stats import numpy as np from .ve...
vicenteneto/online-judge-solutions
URI/1-Beginner/1021.py
# -*- coding: utf-8 -*- def calc_note(count, value): qnt = 0 if count >= value: qnt = int(count) / value print '%d nota(s) de R$ %d.00' % (qnt, value) return count - qnt * value n = float(raw_input()) print 'NOTAS:' n = calc_note(n, 100) n = calc_note(n, 50) n = calc_note(n, 20) n = calc_no...
slava-sh/NewsBlur
apps/reader/views.py
import datetime import time import boto import redis import requests import random import zlib from django.shortcuts import get_object_or_404 from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.template.loader import render_to_string from django.db import IntegrityE...
kif/freesas
freesas/average.py
__author__ = "Guillaume" __license__ = "MIT" __copyright__ = "2015, ESRF" import numpy from freesas.model import SASModel class Grid: """ This class is used to create a grid which include all the input models """ def __init__(self, inputfiles): """ :param inputfiles: list of pdb files...
18F/quotable
app_config.py
#!/usr/bin/env python """ Project-wide application configuration. DO NOT STORE SECRETS, PASSWORDS, ETC. IN THIS FILE. They will be exposed to users. Use environment variables instead. See get_secrets() below for a fast way to access them. """ import os """ NAMES """ # Project name used for display PROJECT_NAME = 'q...
swcarpentry/amy
amy/workshops/management/commands/instructors_activity.py
import os import logging from django.core.management.base import BaseCommand from django.core.mail import send_mail from django.template.loader import get_template from workshops.models import Badge, Person, Role logger = logging.getLogger() class Command(BaseCommand): help = 'Report instructors activity.' ...
Azure/azure-sdk-for-python
sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/v2016_12_01/operations/_policy_assignments_operations.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 ...
loretoparisi/docker
theano/rsc15/preprocess.py
# -*- coding: utf-8 -*- """ Created on Fri Jun 25 16:20:12 2015 @author: Balázs Hidasi @lastmodified: Loreto Parisi (loretoparisi at gmail dot com) """ import sys import os import numpy as np import pandas as pd import datetime as dt # To redirect output to file class Logger(object): def __init__(self, filename=...
JensTimmerman/radical.pilot
docs/architecture/api_draft/unit_manager.py
from attributes import * from constants import * # ------------------------------------------------------------------------------ # class UnitManager (Attributes) : """ UnitManager class -- manages a pool """ # -------------------------------------------------------------------------- # ...
EssaAlshammri/django-by-example
bookmarks/bookmarks/actions/utils.py
import datetime from django.contrib.contenttypes.models import ContentType from django.utils import timezone from .models import Action def create_action(user, verb, target=None): now = timezone.now() last_minute = now - datetime.timedelta(seconds=60) similar_actions = Action.objects.filter(user_id=user...
72squared/redpipe
docs/conf.py
# -*- coding: utf-8 -*- # # RedPipe documentation build configuration file, created by # sphinx-quickstart on Wed Apr 19 13:22:45 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 # autogenerated file. # # A...
juanchodepisa/sbtk
SBTK_League_Helper/src/interfacing/servers.py
from src.tools.dictionaries import PostLoadedDict # Utility class ################################################ class ServerImplementationDict(PostLoadedDict): def __missing__(self, key): try: return super().__missing__(key) except KeyError: return NotImplemented ########...
arnavd96/Cinemiezer
myvenv/lib/python3.4/site-packages/music21/ext/jsonpickle/__init__.py
# -*- coding: utf-8 -*- # # Copyright (C) 2008 John Paulett (john -at- paulett.org) # Copyright (C) 2009, 2011, 2013 David Aguilar (davvid -at- gmail.com) # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. """Python libr...
marcus-nystrom/share-gaze
sync_clocks/test_clock_resolution.py
# -*- coding: utf-8 -*- """ Created on Wed Sep 09 13:04:53 2015 * If TimerTool.exe is running, kill the process. * If input parameter is given, start TimerTool and set clock resolution Starts TimerTool.exe and sets the clock resolution to argv[0] ms Ex: python set_clock_resolution 0.5 @author: marcus """ ...
ValorNaram/isl
inputchangers/002.py
blocklevel = ["blockquote", "div", "form", "p", "table", "video", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "details", "article", "header", "main"] def normalizeEnter(src): #Deletes all user defined for readability reason existing line breaks that are issues for the HTML output for elem in blocklevel: while src.fin...
mrmrwat/pylsner
pylsner/gui.py
import cairo from gi.repository import Gtk from gi.repository import Gdk from pylsner import plugin class Window(Gtk.Window): def __init__(self): super(Window, self).__init__(skip_pager_hint=True, skip_taskbar_hint=True, ) ...
mrwsr/monotone
test/test_monotone.py
""" Tests for L{monotone}. """ from hypothesis import given, strategies as st import errno from monotone import get_clock_info, monotonic from monotone import _api, _bindings import os import platform import pytest needs_posix = pytest.mark.skipif( os.name == "posix" and platform.system() == "Darwin", reas...
Nic30/HWToolkit
hwt/synthesizer/dummyPlatform.py
from hwt.synthesizer.rtlLevel.extract_part_drivers import extract_part_drivers from hwt.synthesizer.rtlLevel.remove_unconnected_signals import removeUnconnectedSignals from hwt.synthesizer.rtlLevel.mark_visibility_of_signals_and_check_drivers import markVisibilityOfSignalsAndCheckDrivers class DummyPlatform(): ""...
Bengt/AL-FanControl
python/fancontrol/ui/cli_util.py
from __future__ import (absolute_import, division, print_function, unicode_literals) RJUST = 12 def format_fans(fans): return format_line(prefix='fans'.rjust(RJUST), values=fans) def format_rpms(rpms): return format_line(prefix='rpms'.rjust(RJUST), values=rpms) def format_pwms(pwm...
toranb/django-bower-registry
api/migrations/0001_initial.py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Package' db.create_table(u'api_package', ( (u'id', self.gf('django.db.models.fie...
ee-in/python-api
plotly/tests/test_optional/test_matplotlylib/test_annotations.py
from __future__ import absolute_import import matplotlib # Force matplotlib to not use any Xwindows backend. matplotlib.use('Agg') import matplotlib.pyplot as plt from plotly.tests.utils import compare_dict from plotly.tests.test_optional.optional_utils import run_fig from plotly.tests.test_optional.test_matplotlylib...
aldialimucaj/Streaker
setup.py
from distutils.core import setup setup( # Application name: name="streaker", # Version number (initial): version="0.0.1", # Application author details: author="Aldi Alimucaj", author_email="aldi.alimucaj@gmail.com", # Packages packages=["streaker"], scripts=['bin/streaker'],...
smarkets/smk_python_sdk
smarkets/statsd.py
from __future__ import absolute_import, division, print_function, unicode_literals # Statsd client. Loosely based on the version by Steve Ivy <steveivy@gmail.com> import logging import random import socket import time from contextlib import contextmanager log = logging.getLogger(__name__) class StatsD(object): ...
kjchalup/dtit
setup.py
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='fcit', # Versions...
PythonProgramming/Support-Vector-Machines---Basics-and-Fundamental-Investing-Project
p10.py
import pandas as pd import os import time from datetime import datetime import re from time import mktime import matplotlib import matplotlib.pyplot as plt from matplotlib import style style.use("dark_background") # path = "X:/Backups/intraQuarter" # for Windows with X files :) # if git clone'ed then use relative path...
arvinddoraiswamy/LearnPython
17.py
import struct ''' Refer to docs for all the exact formats. There are many so check them out before converting things yourself ''' ''' If there's a specific offset you want to do things from, use pack_into and unack_into from the docs ''' #Integer to string i1= 1234 print "Int to string as 8 byte little endian", repr(...
jeremiedecock/tictactoe-py
jdhp/tictactoe/player/greedy.py
# -*- coding: utf-8 -*- # Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org) # 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 right...
KeserOner/puissance4
bestaplayer.py
__author__ = 'besta' class BestaPlayer: def __init__(self, fichier, player): self.fichier = fichier self.grille = self.getFirstGrid() self.best_hit = 0 self.players = player def getFirstGrid(self): """ Implements function to get the first grid. :retur...
hfaran/slack-export-viewer
slackviewer/user.py
# User info wrapper object import logging class User(object): """ Wrapper object around an entry in users.json. Behaves like a read-only dictionary if asked, but adds some useful logic to decouple the front end from the JSON structure. """ _NAME_KEYS = ["display_name", "real_name"] _DEFAULT_IM...
naumenko-sa/cre
cre.locate_sample.py
#!/hpf/largeprojects/ccmbio/naumenko/tools/bcbio/anaconda/bin/python """ Looks for a specific sample """ import re import sys import os import os.path sample = sys.argv[1] family,sample_only = sample.split("_") match = re.match('\d*',family) if match: prefix=str(int(match.group(0))/100) report_path = pref...
SatoshiNakamotoGeoscripting/SatoshiNakamotoGeoscripting
Final_assignment/main.py
# -*- coding: utf-8 -*- """ Date: 2/2/2017 Team: Satoshi Nakamoto @Authors: Alex Levering and Hector Muro Non-standard dependencies: * Twython * NLTK * Folium * Geocoder * psycopg2 TO DO BEFOREHAND: The following steps are non-automatable and have to be performed manually. * Have the NLTK vader lexicon locally (nltk...
xairy/mipt-schedule-parser
msp/test/schedule_tests.py
#!/usr/bin/python #coding: utf-8 from __future__ import unicode_literals import os import unittest import xlrd import msp.schedule_parser as schedule_parser __author__ = "Andrey Konovalov" __copyright__ = "Copyright (C) 2014 Andrey Konovalov" __license__ = "MIT" __version__ = "0.1" this_dir, this_filename = os.pat...
vervacity/ggr-project
scripts/data_qc/summarize_chipseq_qc.py
import gzip import glob import numpy as np import pandas as pd from scipy.stats import pearsonr from scipy.stats import spearmanr def get_num_lines_gz(filename): num_lines = 0 with gzip.open(filename, "r") as fp: for line in fp: num_lines += 1 return num_lines def main(): ...
ajitghz582/PythonLearning
DAY_1_ASSIGNMENTS/1_name_phone_number.py
student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's p...
stevearc/dynamo3
tests/__init__.py
""" Tests for Dynamo3 """ import sys import unittest from decimal import Decimal from pickle import dumps, loads from urllib.parse import urlparse from botocore.exceptions import ClientError from mock import ANY, MagicMock, patch from dynamo3 import ( Binary, Dynamizer, DynamoDBConnection, DynamoDBEr...
zdvresearch/fast15-paper-extras
ecfs_user_sessions/src/analyze_user_sessions.py
#!/usr/bin/env python3 """ Categorize and analyze user sessions. Read in ecfs_obfuscated_filtered.gz file, output some fancy results. """ from collections import defaultdict from collections import Counter import sys import time import os import resource import json import fnmatch from pipes import Pipes impo...
reiths/ros_spinnaker_interface
examples/example_ros_spinnaker_interface.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author Stephan Reith @date 31.08.2016 This is a simple example to demonstrate how the ROS Spinnaker Interface can be used. You will also need a ROS Listener and a ROS Talker to send and receive data. Make sure they communicate over the same ROS topics and std_msgs....
VulcanTechnologies/oauth2lib
oauth2lib/utils.py
from __future__ import absolute_import, division, print_function, unicode_literals import string import urllib try: from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse from urllib.request import urlopen, Request from urllib.error import HTTPError except ImportError: from urlpars...
ksmit799/Toontown-Source
toontown/classicchars/DistributedGoofySpeedwayAI.py
from otp.ai.AIBaseGlobal import * import DistributedCCharBaseAI from direct.directnotify import DirectNotifyGlobal from direct.fsm import ClassicFSM, State from direct.fsm import State from direct.task import Task import random from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer impo...
dcondrey/scrapy-spiders
dist/spiders/newenglandfilm.py
#!/usr/bin/python # -*- coding: utf-8 -*- from scrapy.spider import Spider from scrapy.selector import Selector from my_settings import name_file, test_mode, difference_days from datetime import datetime, timedelta print "Run spider NewenglandFilm" file_output = open(name_file, 'a') email_current_sessio...
isaac-philip/loolu
common/django/contrib/admin/views/decorators.py
import base64 try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.3, 2.4 fallback. from django import http, template from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from djang...
coders-creed/botathon
src/info/fetch_info.py
# -*- coding: utf-8 -*- # @Author: karthik # @Date: 2016-12-10 21:40:07 # @Last Modified by: chandan # @Last Modified time: 2016-12-11 12:55:27 from models.portfolio import Portfolio from models.company import Company from models.position import Position import tenjin from tenjin.helpers import * import wikipedia...
pisskidney/leetcode
medium/16.py
#!/usr/bin/python from typing import List, Optional """ 16. 3Sum Closest https://leetcode.com/problems/3sum-closest/ """ def bsearch(nums, left, right, res, i, j, target): while left <= right: middle = (left + right) // 2 candidate = nums[i] + nums[j] + nums[middle] if res is None or ab...
Jayin/practice_on_py
Process&Thread/PoolTest.py
from multiprocessing import Pool import os, time, random def long_time_task(name): print 'Run task %s (%s)...' % (name, os.getpid()) start = time.time() time.sleep(random.random() * 3) end = time.time() print 'Task %s runs %0.2f seconds.' % (name, (end - start)) if __name__ == '__main__': p...
Azure/azure-sdk-for-python
sdk/storage/azure-storage-blob/tests/test_large_block_blob.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. # --------------------------------------------------------------------...
ThiefMaster/indico
bin/maintenance/update_header.py
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os import re import subprocess import sys from datetime import date import click import yaml from...
spezifanta/Paste-It
api/v01/views.py
from django.shortcuts import redirect from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from paste.models import Paste, Language @csrf_exempt def add(request): print "jojo" if request.method == 'POST': language = request.POST['language'] content = r...
kantel/processingpy
sketches/Apple_Invaders/sprites.py
class Sprite(object): def __init__(self, xPos, yPos): self.x = xPos self.y = yPos self.th = 32 self.tw = 32 def checkCollision(self, otherSprite): if (self.x < otherSprite.x + otherSprite.tw and otherSprite.x < self.x + self.tw and self.y < otherSpri...
ssut/py-hanspell
tests.py
# -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def setUp(self): pass def test_basic_check(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인...
algorhythms/LeetCode
282 Expression Add Operators.py
""" Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. Examples: "123", 6 -> ["1+2+3", "1*2*3"] "232", 8 -> ["2*3+2", "2+3*2"] "105", 5 -> ["1*0+5","10-5"] "00", 0 -> ["0+0", "...
uber-common/opentracing-python-instrumentation
tests/opentracing_instrumentation/test_mysqldb.py
import sys import pytest from opentracing.ext import tags from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from opentracing_instrumentation.client_hooks import mysqldb as mysqldb_hooks from opentracing_instrumentation.request_context import span_in_context from .sql_common import metadata...
Mathew/psychoanalysis
psychoanalysis/apps/pa/migrations/0002_auto__del_participant.py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting model 'Participant' db.delete_table(u'pa_participant') # Removing M2M table for field us...
JDSWalker/AdventOfCode
2015/Day05/advent_of_code_2015_day_05.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Advent of Code 2015 from http://adventofcode.com/2015/day/5 Author: James Walker Copyrighted 2017 under the MIT license: http://www.opensource.org/licenses/mit-license.php Execution: python advent_of_code_2015_day_05.py --- Day 5: Doesn't He Have Intern-Elves For ...
peepall/FancyLogger
FancyLogger/__init__.py
#!/bin/env/python # coding: utf-8 import logging import os import time import uuid from logging import Formatter from logging.handlers import RotatingFileHandler from multiprocessing import Queue from time import strftime import dill from .commands import * from .processing import MultiprocessingLogger class TaskP...
mlund/pyha
pyha/openmm.py
from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system....