code
stringlengths
2
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
import os from datetime import datetime from PIL import Image from demosys import context from demosys.conf import settings class Config: """Container for screenshot target""" target = None alignment = 1 def create(file_format='png', name=None): """ Create a screenshot :param file_format: ...
Contraz/demosys-py
demosys/view/screenshot.py
Python
isc
1,308
#!/usr/bin/env python import json import sys import os from bottle import route, run, get import time import httplib server = "127.0.0.1" statport = "18081" host = "%s:18001" % server staturl = "http://%s:%s/status" % (server,statport) blob = {"id": "bar", "url": staturl} data = json.dumps(blob) connection = httplib...
looprock/Megaphone
sample_service.py
Python
isc
1,823
# -*- coding: utf-8 -*- vim:fileencoding=utf-8: # vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab # Copyright © 2010-2012 Greek Research and Technology Network (GRNET S.A.) # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that th...
apoikos/servermon
hwdoc/management/commands/hwdoc_license.py
Python
isc
1,809
from __future__ import absolute_import import logging from django.shortcuts import render_to_response, render, get_object_or_404, redirect from django.template import RequestContext from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirec...
underlost/Replica
replica/contrib/blip/dashboard/views.py
Python
mit
5,663
from django.db.models import signals from django.db import models from datetime import datetime class FormRenderer(object): def as_p(self): "Returns this form rendered as HTML <p>s." return self._html_output( normal_row='<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>', ...
beratdogan/arguman.org
web/premises/mixins.py
Python
mit
1,086
import json, datetime, decimal from django.http import HttpResponse class EnhancedJSONEncoder(json.JSONEncoder): """ JSONEncoder subclass that knows how to encode date/time and decimal types. """ def default(self, o): if isinstance(o, datetime.datetime): return o.ctime() el...
DeadWisdom/inreach
app/ajax.py
Python
mit
1,366
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # http://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals class OnionCrawlerSpiderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scr...
mheinl/OnionCrawler
OnionCrawler/middlewares.py
Python
mit
1,886
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-28 10:57 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('courses', '0014_course_views'), ] operations = [ migrations.AlterField( ...
sonic182/portfolio3
courses/migrations/0015_auto_20161028_1057.py
Python
mit
445
import json import logging from flask import jsonify def construct_response(message, payload, status): body = {} if status == 500: body['message'] = ( 'Something went wrong constructing response. ' 'Is your payload valid JSON?' ) body['request_payload'] = str(p...
spulec/PyQS
example/api/helpers.py
Python
mit
545
import logging, argparse, os, sys, re import numpy as np from collections import OrderedDict from .utils import getWorkDirs, getEnergy4Key from ..ccsgp.ccsgp import make_panel, make_plot from ..ccsgp.utils import getOpts from ..ccsgp.config import default_colors from decimal import Decimal import uncertainties.umath as...
tschaume/ccsgp_get_started
ccsgp_get_started/examples/gp_ptspec.py
Python
mit
10,339
import traceback from sanic.log import log HOST = '127.0.0.1' PORT = 42101 class SanicTestClient: def __init__(self, app): self.app = app async def _local_request(self, method, uri, cookies=None, *args, **kwargs): import aiohttp if uri.startswith(('http:', 'https:', 'ftp:', 'ftps://...
jrocketfingers/sanic
sanic/testing.py
Python
mit
3,419
# -*- coding: utf-8 -*- """ Module: tie.py Created on Mon Jan 27 17:12:19 2014 @author: gav Description: Utilities for converting to and from ASA's tie polygon format The central common format will be geojson records suitable for the shapely/fiona gis stack. """ ### Imports from __future__ import print_function from ...
gjcoombes/banks
banks/gis/tie.py
Python
mit
5,232
# coding: utf-8 import argparse from pyparsing import OneOrMore, nestedExpr from progressbar import ProgressBar, Percentage, Bar from time import time from collections import defaultdict import platform last_val = -1 checked = False mark_val = "0.1u" class KiCAD_PCB: def __init__(self, filename): self....
apeng2012/apeng-kicad
tools/markcomp/markcomp.py
Python
mit
4,277
from backend.common.models.district import District from backend.common.models.keys import DistrictAbbreviation, Year from backend.common.queries.district_query import DistrictHistoryQuery def preseed_district(year: Year, abbrev: DistrictAbbreviation) -> None: d = District( id=f"{year}{abbrev}", y...
the-blue-alliance/the-blue-alliance
src/backend/common/queries/tests/district_history_query_test.py
Python
mit
1,069
import os,sys from sklearn import svm from sklearn.cluster import KMeans import numpy as np import utils as cu import libLearning as learn import libDetection as det import trainDetector ######################################## ## IMPLEMENTATION OF SINGLE LINEAR DETECTOR ######################################## class ...
jccaicedo/localization-agent
detection/rcnn/subcatDetector.py
Python
mit
4,558
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import re import time from devil.android import device_errors from pylib import flag_changer from pylib.base import base_test_result from pyl...
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/build/android/pylib/local/device/local_device_instrumentation_test_run.py
Python
mit
6,414
''' Created on Feb 3, 2012 @author: marat ''' import string from myvector import Vector class XYZ_file: ''' classdocs ''' def __init__(self,name=None): if name==None: self.FileName = " " self.NumAtom = 0 self.AtomName = [] self.AtomPos = [] ...
rangsimanketkaew/NWChem
contrib/marat/python/XYZ_file.py
Python
mit
2,936
# Python3 def makeArrayConsecutive2(statues): return (max(statues) - min(statues) + 1) - len(statues)
RevansChen/online-judge
Codefights/arcade/intro/level-2/6.Make-Array-Consecutive-2/Python/solution1.py
Python
mit
107
""" This script was used to generate dwt_matlabR2012a_result.npz by storing the outputs from Matlab R2012a. """ from __future__ import division, print_function, absolute_import import numpy as np import pywt try: from pymatbridge import Matlab mlab = Matlab() _matlab_missing = False except ImportError: ...
aaren/pywt
pywt/tests/data/generate_matlab_data.py
Python
mit
2,444
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals # IMPORTANT: only import safe functions as this module will be included in jinja environment import frappe import operator import re, urllib, datetime, math import babel.dates fr...
anandpdoshi/frappe
frappe/utils/data.py
Python
mit
21,230
from wtforms.validators import input_required from wtforms import fields as wtform_fields from ..serializers import serialize_field from ..abstract.controller import AbstractController from wtforms_json import flatten_json class DummyMultiDict(dict): def getlist(self, key): return [self[key]] class WTF...
firemark/zephryos
zephryos/wtform/controller.py
Python
mit
3,101
import argparse import daemon import dateutil.parser import redis_collections import redislite import schedule import subprocess import time from daemon import pidfile from datetime import datetime, timedelta from os import path import sys from helpers import * from log import get_logger MB = 1024.0...
pmarkiewicz/speedtest
speedtest.py
Python
mit
2,637
#Sample command: python pos1.py ds8.txt "/usr/share/red5/webapps/oflaDemo/transcripts" "/var/www/metadata/output/preprocess_audio" enable "Porter-Stemmer" import sys import nltk import os import subprocess import math from operator import itemgetter from time import gmtime, strftime from nltk import stem from nltk.ste...
amudalab/concept-graphs
FastKeyphraseExt/preprocess_audio/pos1.py
Python
mit
3,458
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2019-03-08 16:17 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('studygroups', '0108_auto_20181204_0729'), ] operations = [ migrations.AddFi...
p2pu/learning-circles
studygroups/migrations/0109_auto_20190308_1617.py
Python
mit
1,852
""" It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sniffle.settings") from django.core.wsgi import get_wsgi_application fr...
cesardeazevedo/sniffle
sniffle/wsgi.py
Python
mit
391
"""For the dict-subclass JSobject (defined below), user-defined attribute names may collide with the inherited dict methods (e.g. "keys", "values", "items", etc), overwriting the inherited binding. For these special cases, the built-in dict methods are also bound to corresponding '__'-prefixed attribute names (e.g. "_...
jzitelli/python-gltf-experiments
jsobject.py
Python
mit
1,558
import time import random import highfive # This is the remote worker for the sum example. Here, we define what the # workers do when they get a call from the master. All we need is a single # function which takes the call, does some processing, and returns a response. # An interesting way to play with the workers ...
abau171/highfive
examples/sum_worker.py
Python
mit
1,495
import hashlib from django import template from django.core import urlresolvers register = template.Library() @register.simple_tag(takes_context=True) def gravatar(context, user): email_hash = hashlib.md5(user.email.lower()).hexdigest() return 'https://www.gravatar.com/avatar/{}?s=30&d=retro'.format(email_h...
stackmachine/bearweb
core/templatetags/core_extras.py
Python
mit
1,258
""" Provides XML parsing support. """ from django.conf import settings from rest_framework.exceptions import ParseError from rest_framework.parsers import BaseParser import defusedxml.ElementTree as etree class XMLCompanyParser(BaseParser): """ XML company parser. """ media_type = 'application/xml' ...
bgroff/kala-app
django_kala/api/basecamp_classic/companies/parsers.py
Python
mit
2,236
import inspect import os import re import sys import requests sys.path.append(os.path.join(sys.path[0], '..')) import canvasapi # noqa def validate_method(themethod, quiet=False): # No docstring means no erroneous docstrings if not inspect.getdoc(themethod): return True # Docstrings without A...
ucfopen/canvasapi
scripts/validate_docstrings.py
Python
mit
4,981
#!/usr/bin/env python # # Protein Engineering Analysis Tool DataBase (PEATDB) # Copyright (C) 2010 Damien Farrell & Jens Erik Nielsen # # 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 ver...
dmnfarrell/peat
PEATDB/plugins/biodatabaseplugin.py
Python
mit
4,663
import re from decimal import Decimal import sys import struct from rdbtools.parser import RdbCallback, RdbParser ESCAPE = re.compile(ur'[\x00-\x1f\\"\b\f\n\r\t\u2028\u2029]') ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') HAS_UTF8 = re.compile(r'[\x80-\xff]') ESCAPE_DCT = { '\\': '\\\\', '"': '\\"', '\b': ...
idning/redis-rdb-tools
rdbtools/callbacks.py
Python
mit
7,595
from __future__ import absolute_import, division, print_function import numpy as np import pandas as pd import gsd.hoomd import sklearn import scipy.optimize as opt import os import os.path import pdb from sklearn.neighbors import BallTree from sklearn.neighbors import radius_neighbors_graph from scipy.spatial.distanc...
ramansbach/cluster_analysis
clustering/scripts/old-scripts/clustering_temp.py
Python
mit
73,255
""" WSGI config for imecare project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTI...
andredalton/imecare
imecare/wsgi.py
Python
mit
391
import numpy as np import numpy.ma as ma import rasterio value_raster = "analyses/zonation/priocomp/08_abf_bd/08_abf_bd_out/08_abf_bd.rank.compressed.tif" mask_raster = "analyses/zonation/priocomp/06_abf_es/06_abf_es_out/06_abf_es.rank.compressed.tif" expand_raster = "analyses/zonation/priocomp/08_abf_bd/08_abf_bd_out...
VUEG/priocomp
tests/test_raster_expansion.py
Python
mit
1,814
import sys, os def include( file ): file = os.path.abspath( os.path.join( os.path.dirname( __file__ ), file ) ) sys.path.insert( 0, file ) include( '../libs/StLibsPy' )
webbers/dongle.net
bld/libs/builder/src/setlibspath.py
Python
mit
183
from typing import Optional from fastapi import FastAPI from fastapi.responses import FileResponse from pydantic import BaseModel class Item(BaseModel): id: str value: str responses = { 404: {"description": "Item not found"}, 302: {"description": "The item was moved"}, 403: {"description": "Not...
tiangolo/fastapi
docs_src/additional_responses/tutorial004.py
Python
mit
701
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel, EmailStr app = FastAPI() class UserBase(BaseModel): username: str email: EmailStr full_name: Optional[str] = None class UserIn(UserBase): password: str class UserOut(UserBase): pass class UserInDB(UserB...
tiangolo/fastapi
docs_src/extra_models/tutorial002.py
Python
mit
824
#!/usr/bin/python -tt from graph.node import Node, FileNode def endswith(s, pats): return any(s.endswith(p) for p in pats) def create_graph(files): return Node(None)
shaded-enmity/feaders
feader/utils.py
Python
mit
173
try: import openeye # These can only be imported if openeye tools are available from smarty.atomtyper import * from smarty.sampler import * from smarty.utils import * from smarty.sampler_smirky import * except Exception as e: print(e) print('Warning: Cannot import openeye toolkit; not a...
open-forcefield-group/smarty
smarty/__init__.py
Python
mit
392
# # The weights for this model come from training in a neural network library called CognitoNet which is now retired. # # That training session used images from the Face Scrub data set: # http: http://vintage.winklerbros.net/facescrub.html # H.-W. Ng, S. Winkler. # A data-driven approach to cleaning large fac...
jfrancis71/TensorFlowApps
CZFaceDetection.py
Python
mit
9,947
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: produce_url_resp.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection ...
wonghoifung/learning-python
spider/spider_url_producer/pb/produce_url_resp_pb2.py
Python
mit
1,934
# -*- coding: utf-8 -*- """ Written by Daniel M. Aukes. Email: danaukes<at>seas.harvard.edu. Please see LICENSE.txt for full license. """ import shapely.geometry as sg import popupcad class Layer(object): def __init__(self, geoms): self.geoms = geoms def union(self, layer): return self.binar...
Skylion007/popupcad
popupcad/filetypes/layer.py
Python
mit
2,863
# -*- 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 'Guest' db.create_table('tf_arsfest_guest', ( ('id', self.gf('django.db.models.fi...
Teknologforeningen/tf_arsfest
tf_arsfest/migrations/0001_initial.py
Python
mit
8,064
import base64 from django.conf import settings class SubHubConfig(object): def get_extra_hub_headers(self, feed_url, hub_url): headers = {} if hub_url == settings.SUPERFEEDR_HUB: headers['Authorization'] = \ 'Basic %s' % base64.b64encode('%s:%s' % ( ...
jpadilla/feedleap
feedleap/config.py
Python
mit
527
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Mon Nov 28 23:15:47 2016 @author: jessime """ import sys from PyQt5.QtWidgets import (QMainWindow, QFileDialog, QApplication) class SelectScript(QMainWindow): def __init__(self): super().__init__() self.file = self.initUI() def i...
Jessime/Excision
src/pick_file.py
Python
mit
734
import unittest import matmath import numpy as np import math class TestMatrix(unittest.TestCase): def testRotX(self): mat = matmath.xRotationMatrix(math.radians(90)) pt = np.array([1, 0, 0, 1]) npt = pt.dot(mat) np.testing.assert_almost_equal(npt, [1, 0, 0, 1]) pt = np.ar...
daryllstrauss/tango
test_mat.py
Python
mit
2,661
from datetime import datetime import logging log = logging.getLogger("safecity.tropo.views") from safecity.apps.danger.models import Report from safecity.apps.locate.location_parser import * from safecity.apps.signup.models import Resident from safecity.apps.tropo.tropolib import * from safecity.lib.messages import * ...
onyxfish/safecity
safecity/apps/tropo/views.py
Python
mit
4,268
import os TELEGRAM_TOKEN = os.environ['TELEGRAM_TOKEN'] DATABASE = { 'HOST': os.getenv('DB_PORT_3306_TCP_ADDR', 'localhost'), 'USER': os.getenv('DB_MYSQL_USER', 'root'), 'PASSWORD': os.getenv('DB_MYSQL_PASSWORD', ''), 'NAME': 'aurora', }
synteny/AuroraBot
sessioncontroller/settings.py
Python
mit
256
#!/usr/bin/python3 # -*- coding: utf-8 -*- ################################################################################ # Euler 25 # 1000-digit Fibonacci number # Author: Eugene Kolo - 2014 # Contact: www.eugenekolo.com # The Fibonacci sequence is defined by the recurrence relation: # Fn = Fn−1 + Fn−2, where F1 = ...
eugenekolo/project-euler
euler025.py
Python
mit
856
#!/usr/bin/python ''' Created on Sep 25, 2014 @author: jason ''' import numpy as np import glob import os, sys from scipy.stats import ttest_ind, ttest_1samp from scipy.stats import sem from scipy.stats import norm from sets import Set import matplotlib.pyplot as plt def listofmodels(directory): listOfFiles = glob....
jasonzliang/kick_classifier
summarizeResults.py
Python
mit
6,219
import json import socket class Function(object): def __init__(self, proxy, name): self.proxy = proxy self.name = name def __call__(self, *args): return self.proxy.call(self.name, *args) class RemoteJsonError(RuntimeError): pass class CouldNotConnect(RuntimeError): pass ...
GaretJax/csat
csat/client.py
Python
mit
2,111
from django.http import JsonResponse from django.shortcuts import render from django.urls import reverse def get_swagger_json(request, router): return JsonResponse(router.api.doc) def render_docs(request, router, json_url_name): return render(request, 'lepo_doc/swagger-ui.html', { 'json_url': reques...
akx/lepo
lepo_doc/views.py
Python
mit
373
"""Tail any mongodb collection""" from time import sleep from bson import ObjectId __version__ = "1.1.0" def fetch(collection, filter, last_oid_generation_time=None): if last_oid_generation_time is not None: last_oid = ObjectId.from_datetime(last_oid_generation_time) filter.update({"_id": {"$gt...
Shir0kamii/mongofollow
mongofollow.py
Python
mit
1,092
from App.model import UserAgents async def agent_save(request, user): ua = request.headers['User-Agent'] now = datetime.datetime.now() uas = [await i for i in user.ips] if ua in [i.content for i in contents]: ua_in = [i for i in uas if i.content == content][0] ua_in.utime = now ...
Basic-Components/auth-center
auth-center/App/auth/login_agents.py
Python
mit
533
# -*- coding: utf-8 -*- # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. import install import config import service from fabric.api import env, task env.hosts = ['localhost'] @task def bootstrap(): """Deploy, configure, and start Fridge on hosts""" install.bootstrap() ...
oleiade/Fridge
fabfile/__init__.py
Python
mit
365
import datetime import logging import time import traceback import praw import prawcore _logger = logging.getLogger('reddit') def _preface_each_line(text, preface): lines = text.split('\n') lines = [preface + line for line in lines] return '\n'.join(lines) class Reply(object): body = None child...
c17r/TagTrain
src/tagtrain/reddit/__init__.py
Python
mit
4,844
from nose.tools import eq_, raises from ...errors import DependencyError, DependencyLoop from ..dependent import Dependent from ..functions import dig, draw, expand, normalize_context, solve def test_solve(): # Simple functions eq_(solve(lambda: "foo"), "foo") eq_(list(solve([lambda: "foo", lambda: "bar"...
yafeunteun/wikipedia-spam-classifier
revscoring/revscoring/dependencies/tests/test_functions.py
Python
mit
4,537
import sys from mock import patch from ricecooker import chefs settings = {"generate-missing-thumbnails": True, "compress-videos": True} def test_settings_unset_default(): chef = chefs.SushiChef() for setting in settings: assert chef.get_setting(setting) is None assert chef.get_setting(se...
learningequality/ricecooker
tests/test_settings.py
Python
mit
2,495
import os from sqlalchemy import Column, String, Integer, create_engine from flask_sqlalchemy import SQLAlchemy import json database_name = "trivia" database_path = "postgres://{}:{}@{}/{}".format( 'postgres', 'abc@123', 'localhost:5432', database_name) db = SQLAlchemy() ''' setup_db(app) binds a flask appli...
manishbisht/Udacity
Full Stack Web Developer Nanodegree v2/P2 - Trivia API/backend/models.py
Python
mit
1,781
from ConfigParser import ConfigParser, NoSectionError from os.path import join, exists, realpath, curdir, dirname from shutil import copyfile ### Application constants - these are not exposed to users via config files ### # NOTE: Directories must match Gruntfile.js: jekyll > (serve|build) > options > (src|dest) ROOT ...
GALabs/StaticAid
static_aid/config.py
Python
mit
3,707
# -*coding: utf-8 -*- """Module for creating PosyArray instances. Example ------- >>> x = gpkit.Monomial('x') >>> px = gpkit.PosyArray([1, x, x**2]) """ import numpy as np from .small_classes import Numbers from . import units as ureg from . import DimensionalityError Quantity = ureg.Quantity clas...
galbramc/gpkit
gpkit/posyarray.py
Python
mit
7,110
import random from concurrent import futures import time from collections import defaultdict import grpc import sys from pathlib import Path sys.path.insert(0, '') from quote_service_pb2 import QuoteReply from quote_service_pb2_grpc import (add_QuoterServicer_to_server, QuoterSer...
the-gigi/quote-service
grpc_demo/grpc_quote_server.py
Python
mit
1,420
import os from flask import Flask, request, g from flask_sqlalchemy import SQLAlchemy from .decorators import json db = SQLAlchemy() def create_app(config_name): """ Create the usual Flask application instance.""" app = Flask(__name__) # Apply configuration cfg = os.path.join(os.getcwd(), 'config', ...
andela-akhenda/maisha-goals
app/__init__.py
Python
mit
1,333
from django.db import models class Photo(models.Model): photo_text = models.CharField(max_length=200) image = models.ImageField() pub_date = models.DateTimeField('date published') def __str__(self): return self.photo_text class Comment(models.Model): photo = models.ForeignKey(Photo) co...
louismerlin/merlin-hub
hub/multim/models.py
Python
mit
476
__author__ = 'Caroline Beyne' from PyQt4 import QtGui, QtCore class FrameLayout(QtGui.QWidget): def __init__(self, parent=None, title=None): QtGui.QFrame.__init__(self, parent=parent) self._is_collasped = True self._title_frame = None self._content, self._content_layout = (None, N...
By0ute/pyqt-collapsable-widget
code/FrameLayout.py
Python
mit
3,949
# coding: utf-8 import copy import json from mock import Mock, PropertyMock, patch from tests.helpers import Handler, BaseTestCase, ServerMock, get_free_port, DatabaseMock from core.exceptions import CreationException, ConnectionError, \ SessionException, TimeoutException from core.config import setup_config, co...
2gis/vmmaster
tests/unit/test_commands.py
Python
mit
16,406
import configparser def load_config_file(config_file_path): config = configparser.ConfigParser() config.read(config_file_path) input_folder_path = config['DEFAULT']['InputFolderPath'] too_far_distance = int(config['DEFAULT']['TooFarDistance']) grouping_max_distance = int(config['DEFAULT']['Groupi...
pedroeml/t1-fcg
CrowdDataAnalysis/const.py
Python
mit
686
# Copyright The Plasma Project. # See LICENSE.txt for details. """ Test helpers and classes """ import inspect def dict_for_slots(obj): """ """ slots = [] for cls in inspect.getmro(obj.__class__): if hasattr(cls, '__slots__'): slots += cls.__slots__ return dict(zip(slots, [...
hydralabs/plasma
plasma/test/util.py
Python
mit
354
import lexicon.__main__ import pytest def test_BaseProviderParser(): baseparser = lexicon.__main__.BaseProviderParser() parsed = baseparser.parse_args(['list','capsulecd.com','TXT']) assert parsed.action == 'list' assert parsed.domain == 'capsulecd.com' assert parsed.type == 'TXT' assert parsed...
tnwhitwell/lexicon
tests/test_main.py
Python
mit
1,149
#!/usr/bin/env python import PyQt4.QtCore # <- this line causes the error from multiprocessing import Process class PTask(Process): def __init__(self, func): Process.__init__(self) self._func = func def run(self): self._func() def f(): try: import numpy as np im...
kcii/numpy-pyqt-multiproc-problem
fork.py
Python
mit
868
#!/usr/bin/env python3 import random import numpy as np import sympy mod_space = 29 ''' Generate Encryption Key ''' # In --> size of matrix (n x n) # Out --> List of lists [[1,2,3],[4,5,6],[7,8,9]] def generate_encryption_key(size): determinant = 0 # Need to make sure encryption key is invertible, IE det(k...
jbloom512/Linear_Algebra_Encryption
Generate_Encryption_Key.py
Python
mit
3,446
from django.core.management.base import BaseCommand from django_town.oauth2.models import Client from django_town.core.settings import OAUTH2_SETTINGS class Command(BaseCommand): def handle(self, *args, **options): Client.objects.all().update(available_scope=OAUTH2_SETTINGS.default_scope) print Cl...
uptown/django-town
django_town/oauth2/management/commands/update_default_scope.py
Python
mit
452
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys """ 「石取りゲーム1」(「C言語による最新アルゴリズム事典」6ページより) """ def get_num(message): sys.stdout.write(message) n = '' while (not n.isdigit()): n = raw_input() return int(n) n = get_num(u"石の数?") m = get_num(u"1回に取れる最大の石の数?") if (n < 1 or m < 1): sys.ex...
ryu22e/algorithm1000
ishi/ishi1.py
Python
mit
922
class Solution: def lengthOfLastWord(self, s: str) -> int: if not s: return 0 l = s.split() if not l: return 0 return len(l[-1])
BigEgg/LeetCode
Python/LeetCode/_051_100/_058_LengthOfLastWord.py
Python
mit
190
def import_once(modulenames, silent=1): ## import_once ## Fedmich Last modified: 3:38 PM 5/15/2006 ## version 1.1 ## Usage: ## import_once('os') ## import_once( ["os", 'sys'] ) if type(modulenames) is list: pass elif type(modulenames) is tuple: pass else: mod...
ActiveState/code
recipes/Python/496703_importonce/recipe-496703.py
Python
mit
1,231
# -*- coding: utf-8 -*- # # django-bulbs documentation build configuration file, created by # sphinx-quickstart on Wed Sep 18 16:55:34 2013. # # 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. # ...
pombredanne/django-bulbs
docs/conf.py
Python
mit
8,285
# Written by Bram Cohen # see LICENSE.txt for license information from zurllib import urlopen, quote from btformats import check_peers from bencode import bdecode from threading import Thread, Lock from socket import error, gethostbyname from time import time from random import randrange from binascii import b2a_hex ...
mgp/bittorrent-dissected
Rerequester.py
Python
mit
9,039
#!/usr/bin/env python # encoding: utf-8 # author: www.n0tr00t.com import sys import glob import json import chardet import requests import urlparse import argparse import multiprocessing from common.color import * from common.output import * from collections import OrderedDict def check(plugin, passport, passport_t...
n0tr00t/Sreg
sreg.py
Python
mit
6,889
import unittest from distributed_queue.serializers import BaseSerializer, JsonSerializer class TestSerializers(unittest.TestCase): def test_base_serializer(self): self.assertRaises(NotImplementedError, BaseSerializer.dumps, {}) self.assertRaises(NotImplementedError, BaseSerializer.loads, "{}"...
ProstoKSI/distributed-queue
distributed_queue/tests/test_serializers.py
Python
mit
556
def fact_iter(n): """This function will find the Factorial of the given number by iterative method. This function is coded in Pyhton 3.5.""" # check for integer if not isinstance(n, int): raise TypeError("Please only enter integer") if n <= 0: raise ValueError("Kindly Enter posi...
rvsingh011/NitK_Assignments
Sem1/Algorithm/Factorial_iter.py
Python
mit
1,055
from django.conf.urls.defaults import * from django.contrib import admin from django.conf import settings import os admin.autodiscover() urlpatterns = patterns('', ('^$', 'django.views.generic.simple.redirect_to', {'url': '/admin/'}), (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^admin...
benatkin/tuneage
urls.py
Python
mit
511
from django.apps import AppConfig class DeptConfig(AppConfig): name = 'dept'
shen427/dept
code/DPSite/dept/apps.py
Python
mit
83
def exgcd(a, b): """Uses the extended Euclidean algorithm to return the gcd as well as the solutions to Bézout's identity: coefficients x and y such that ax + by = gcd(a, b).""" x, y = 0, 1 u, v = 1, 0 while a != 0: quo = b // a rem = b % a m = x - (quo * u) n = y...
aelk/loga
math/exgcd.py
Python
mit
429
import subprocess import os from unzip_rename import unzip_rename # 此处需要填写服务器IP,端口,用户名和密码,因上传github,此处隐去这些隐私信息 ip = "xx.xx.xx.xx" user = "xx" port = 22 passwd = 'xx' def download(linux_path, method='.sha1'): win_path = os.path.basename(linux_path) # 下载服务器目标文件 print('Downloading file: ') child1 = subp...
FeitengLab/EmotionMap
0All/CollectData/linux_file_to_win.py
Python
mit
2,591
#!/usr/bin/env python # coding=utf-8 import pprint import csv import click import requests import datetime as datetime from bs4 import BeautifulSoup # from splinter import Browser import time import re import copy import os import json from selenium import webdriver from selenium.webdriver.common.by i...
Fatman13/gta_swarm
hc_pool.py
Python
mit
11,408
class Reverb: pass class ScatterLocation: pass class Chorus: pass class Vocoder: pass class ShuffleSound: pass
ttm/musicLegacy
musicLegacy/effects.py
Python
mit
131
import sys, os, json from pathlib import Path from acmacs_py.mapi_utils import MapiSettings # ====================================================================== class CladeData: sSubtypeToCladePrefix = {"h1pdm": "clades-A(H1N1)2009pdm", "h3": "clades-A(H3N2)", "bvic": "clades-B/Vic", "byam": "clades-B/Yam"} ...
acorg/acmacs-whocc
web/chains-202105/py/directories.py
Python
mit
1,044
import sys from Bio import SeqIO # see corresponding description in the project's wiki inventory = sys.argv[1] db_file = sys.argv[2] seq_format = sys.argv[3] # sanity check is ommited for such a short and simple script # get the files names to be indexed with open(inventory,'r') as fp: fnames = [line.strip() f...
sergpolly/Thermal_adapt_scripts
perform_indexing.py
Python
mit
731
import datetime import os from unittest import mock import pytest from nanogen import models example_post = """\ # Test Post And this is my _markdown_ **content**. Look, it also has: * an * unordered * list """ example_config = """\ [site] author = Example user email = user@example.com description = A test desc...
epochblue/nanogen
tests/test_models.py
Python
mit
10,406
from ems.qt.graphics.storage.interfaces import SceneSerializer from ems.qt.graphics.page_item import PageItem class DictSceneSerializer(SceneSerializer): def serialize(self, scene, tools): saveData = { '@author': 'Michael Tils', '@desciption': 'Graphics Scene Contents', ...
mtils/ems
ems/qt/graphics/storage/dict_scene_serializer.py
Python
mit
921
# Tweepy # Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. import os import mimetypes import urllib from tweepy.binder import bind_api from tweepy.error import TweepError from tweepy.parsers import ModelParser, Parser from tweepy.utils import list_to_csv class API(object): """Twitter API""" ...
svven/tweepy
tweepy/api.py
Python
mit
44,828
"""Jobarchitect agent.""" import os import argparse import subprocess from jobarchitect.utils import ( output_path_from_hash, mkdir_parents ) class Agent(object): """Class to create commands to analyse data.""" def __init__( self, tool_path, dataset_path, output_root...
JIC-CSB/jobarchitect
jobarchitect/agent.py
Python
mit
1,898
# -*- coding: utf-8 -*- # # Nengo documentation build configuration file, created by # sphinx-quickstart on Mon Apr 22 15:42:07 2013. # # 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 c...
jaberg/nengo
docs/conf.py
Python
mit
7,887
#!/usr/bin/env python # Combination of matplotlib sample code to create embedded animations from random import random from time import time import csv import matplotlib matplotlib.use('TkAgg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import matplotlib.animati...
evanprs/openspr
liveplot.py
Python
mit
5,661
# Based on STScI's JWST calibration pipeline. from __future__ import print_function import os import subprocess import sys from setuptools import setup, find_packages, Extension, Command from glob import glob # Open the README as the package long description readme = open('README.rst', 'r') README_TEXT = readme.read...
Nat1405/newer-nifty
setup.py
Python
mit
1,483
# -*- encoding: utf-8 -*- from __future__ import print_function, unicode_literals, division, absolute_import import logging import serial import time from enocean.communicators.communicator import Communicator class SerialCommunicator(Communicator): ''' Serial port communicator class for EnOcean radio ''' lo...
kipe/enocean
enocean/communicators/serialcommunicator.py
Python
mit
1,554
from bvec.carray import carray from bvec.version import __version__ from bcolz import cparams
waylonflinn/bvec
bvec/__init__.py
Python
mit
94
# 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 ...
Azure/azure-sdk-for-python
sdk/notificationhubs/azure-mgmt-notificationhubs/azure/mgmt/notificationhubs/aio/_configuration.py
Python
mit
3,400
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, SMARTX import os from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) setup( name='jira-comment-slack', version='0.1', url='https://github.com/smartxworks/jira-comment-slack', license='MIT', author='SmartXWorks/Kisung', ...
smartxworks/jira-comment-slack
setup.py
Python
mit
1,060