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 |
|---|---|---|---|---|---|
__author__ = 'janos'
"""
Generate queries against DE-SYNPUF database or another claim's database were
the coding is flat for understanding relationships between first time of diagnosis.
"""
import sqlalchemy as sa
import re
import csv
def find_columns_that_match(table_columns, regex_field_match):
columns_that_m... | jhajagos/DeSYNPUFAnalysis | scripts/generate_de_synpuf_queries.py | Python | mit | 6,815 |
class EventQueue(object):
"""
A simple container for events.
Can only store events.
"""
def __init__(self):
self._events = []
def pop(self):
"""Gets the next event in the queue"""
return self._events.pop(0)
def get(self):
"""Gets all the events in the queue, subsequently clearing the queue"""
events... | jrburga/VGEngine | cbd/event.py | Python | mit | 1,338 |
# ext/horizontal_shard.py
# Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""Horizontal sharding support.
Defines a rudimental 'horizontal sharding'... | sqlalchemy/sqlalchemy | lib/sqlalchemy/ext/horizontal_shard.py | Python | mit | 8,926 |
# download LSL and pylsl from https://code.google.com/p/labstreaminglayer/
# Eg: ftp://sccn.ucsd.edu/pub/software/LSL/SDK/liblsl-Python-1.10.2.zip
# put in "lib" folder (same level as user.py)
from __future__ import print_function
import plugin_interface as plugintypes
from pylsl import StreamInfo, StreamOutlet
import ... | OpenBCI/OpenBCI_Python | openbci/plugins/streamer_lsl.py | Python | mit | 3,320 |
from utilities import ParameterException, get_table_ref
import os
import boto3
import json
from datetime import datetime
from uuid import uuid4 as uuid
from boto3.dynamodb.conditions import Key
#Actions
def get_parameter(paramID, deviceID):
print("Getting Parameter.")
parameter = load_parameter(paramID,deviceID)... | crslade/HomeAPI | parameters.py | Python | mit | 3,569 |
from cupy import _core
from cupy._math import ufunc
from cupy_backends.cuda.api import runtime
signbit = _core.create_ufunc(
'cupy_signbit',
('e->?', 'f->?', 'd->?'),
'out0 = signbit(in0)',
doc='''Tests elementwise if the sign bit is set (i.e. less than zero).
.. seealso:: :data:`numpy.signbit`
... | cupy/cupy | cupy/_math/floating.py | Python | mit | 1,617 |
#!/usr/bin/python
# The MIT License (MIT)
#
# Copyright (c) 2015 Christian Zielinski
#
# 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 r... | royshan/portfolioopt | example.py | Python | mit | 3,337 |
# (c) Copyright IBM Corp. 2021
# (c) Copyright Instana Inc. 2021
from instana.collector.helpers.process import ProcessHelper
from instana.log import logger
class FargateProcessHelper(ProcessHelper):
""" Helper class to extend the generic process helper class with the corresponding fargate attributes """
def... | instana/python-sensor | instana/collector/helpers/fargate/process.py | Python | mit | 1,056 |
from psy.irt import grm
| inuyasha2012/pypsy | psy/irt/__init__.py | Python | mit | 24 |
from django.core.exceptions import ValidationError
def validate_quantity(value):
if not value < 5:
raise ValidationError("Campomenor que 5.") | CoutinhoElias/danibraz | danibraz/checkout/validate_error_invoice.py | Python | mit | 154 |
from datetime import date
import math
import atomium
from unittest import TestCase
class DeNovoStructureTests(TestCase):
def test_structure_processing(self):
# Create five atoms of a residue
atom1 = atomium.Atom("N", 0, 0, 0, 1, "N", 0.5, 0.5, [0] * 6)
atom2 = atomium.Atom("C", 1.5, 0, 0, ... | samirelanduk/molecupy | tests/integration/test_file_structure_reading.py | Python | mit | 33,544 |
"""
CSS colors.
A simple name to hex and hex to name map of CSS3 colors.
http://www.w3.org/TR/SVG/types.html#ColorKeywords
"""
from typing import Optional
name2hex_map = {
'aliceblue': '#f0f8ff',
'antiquewhite': '#faebd7',
'aqua': '#00ffff',
'aquamarine': '#7fffd4',
'azure': '#f0ffff',
'beige... | facelessuser/ColorHelper | lib/coloraide/spaces/srgb/color_names.py | Python | mit | 4,701 |
import random
import string
import datetime
import math
import re
from django.conf import settings
from django.utils.text import slugify
from django.utils.html import strip_tags
from itsdangerous import URLSafeTimedSerializer
from rest_framework.views import exception_handler
def unique_string_generator(size=10, ch... | aminhp93/learning_python | src/learning_python/utils.py | Python | mit | 2,516 |
'''
This module provides some tests of mgtm/mean_dens against analytic f_coll.
As such, it is the best test of all calculations after sigma.
'''
import numpy as np
import inspect
import os
LOCATION = "/".join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))).split("/")[:-1])
# from nose.tools ... | tbs1980/hmf | tests/test_fcoll.py | Python | mit | 3,489 |
# -*- coding: utf-8 -*-
import contextlib
import oauth2 as oauth
import urllib2
import urlparse
from urllib import urlencode
class OAuthHelper(object):
'''
classdocs
'''
request_token_url = 'https://chpp.hattrick.org/oauth/request_token.ashx'
authorize_path = 'https://chpp.hattrick.org/o... | diego-plan9/hattrick-oauth | oauthhelper.py | Python | mit | 4,919 |
from parameter_domain import ParameterDomain
from vector_calculus.containers import Vector, Tensor
from vector_calculus.operators import dot, cross
from sympy import Number, symbols, diff, Matrix, sqrt, Rational
from numpy import array, ndarray
from numpy.linalg import det
# Symbols in terms of which the mapping is d... | MiroK/vector_calculus | vector_calculus/measures/parametrized_set.py | Python | mit | 8,991 |
#urls
from django.conf.urls.defaults import *
import settings
urlpatterns = patterns('swcomments.views',
url(r'^post-comment/$', 'post_comment', name='swcomments_post_comment'),
)
| socialwireinc/swcomments | swcomments/urls.py | Python | mit | 184 |
from discord.ext import commands
from discord.utils import find
from .utils import checks
class Tutoring(commands.Cog):
def __init__(self, bot):
"""
init for cog class
"""
super().__init__()
self.bot = bot
self.studying_timers = []
@commands.command()
asyn... | dashwav/nano-chan | cogs/tutoring.py | Python | mit | 4,576 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('emailApp', '0002_email_textcleaned'),
]
operations = [
migrations.AddField(
model_name='email',
name... | abhipec/pec | emailApp/emailApp/migrations/0003_email_removedcontent.py | Python | mit | 438 |
#! /usr/bin/env python
#***********************************************************
#* Software License Agreement (BSD License)
#*
#* Copyright (c) 2011, A.M.Howard, S.Williams
#* All rights reserved.
#*
#* Redistribution and use in source and binary forms, with or without
#* modification, are permitted provided that... | gt-ros-pkg/humans | src/actuator_array/actuator_array_gui/src/actuator_array_gui/actuator_array_gui_frame.py | Python | mit | 11,586 |
'''
simple-MC: Test module.
Meant for use with py.test.
Write each test as a function named test_<something>.
Read more here: http://pytest.org/
Copyright 2014, Dan Schien
Licensed under MIT
'''
def test_example():
assert True
| dschien/simple-MC | tests/basic_test.py | Python | mit | 234 |
import os
import oss2
# Specify access information, such as AccessKeyId, AccessKeySecret, and Endpoint.
# You can obtain access information from evironment variables or replace sample values in the code, such as <your AccessKeyId> with actual values.
#
# For example, if your bucket is located in the China (Hangzhou) ... | aliyun/aliyun-oss-python-sdk | examples/bucket_worm.py | Python | mit | 2,004 |
import math
from scipy.integrate import ode
import argparse
def derivatives(t, y, p):
"""
Defines the differential equations for the full system.
t : Time
y : Vector of the state variables:
y = [n_0, n_1, n_2, ..., n_N, n]
p : Dictionary of parameters:
... | spa-networks/spa | utilities/integrator.py | Python | mit | 3,285 |
"""
indico Test Suite
Routes - Utils
"""
import unittest, json
from indico.tests.mocks.request_mock import RequestHandler
from indico.error import InvalidJSON, MissingField, WrongFieldType
import indico.utils as utils
# Mock request handler
req_handler = RequestHandler()
# Mongo Callback Tests
@utils.mongo_callback(... | sihrc/tornado-boilerplate | indico/tests/utils/test_routes_utils.py | Python | mit | 2,293 |
"""
{"diameter": 1, "coarse": 0.25, "fine": 0.2},
{"diameter": 1.2, "coarse": 0.25, "fine": 0.2},
{"diameter": 1.4, "coarse": 0.3, "fine": 0.2},
{"diameter": 1.6, "coarse": 0.35, "fine": 0.2},
{"diameter": 1.8, "coarse": 0.35, "fine": 0.2},
{"diameter": 2, "coarse": 0.4, "fine": 0.25},
{"diameter": 2.5, "coarse": 0.45,... | vishnubob/pyscad | src/screw.py | Python | mit | 1,149 |
import logging
import asyncio
import os
from hbmqtt.broker import Broker
logger = logging.getLogger(__name__)
config = {
'listeners': {
'default': {
'type': 'tcp',
'bind': '0.0.0.0:1883',
},
'ws-mqtt': {
'bind': '127.0.0.1:8080',
'type': 'ws'... | beerfactory/hbmqtt | samples/broker_taboo.py | Python | mit | 1,096 |
from typing import Optional
from fastapi import APIRouter, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, HttpUrl
app = FastAPI()
class Invoice(BaseModel):
id: str
title: Optional[str] = None
customer: str
total: float
class InvoiceEvent(BaseModel):
descripti... | tiangolo/fastapi | tests/test_sub_callbacks.py | Python | mit | 11,010 |
#!/usr/bin/python3
# -*- coding: utf8 -*-
# -*- Mode: Python; py-indent-offset: 4 -*-
"""
Django settings for timevortex project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and ... | timevortexproject/timevortex | timevortex/settings/base.py | Python | mit | 6,969 |
import time
import warnings
from collections import deque
from contextlib import contextmanager
from django.conf import settings
from django.db import DEFAULT_DB_ALIAS
from django.db.backends import utils
from django.db.backends.signals import connection_created
from django.db.transaction import TransactionMa... | diego-d5000/MisValesMd | env/lib/python2.7/site-packages/django/db/backends/base/base.py | Python | mit | 18,465 |
from flask_restplus import fields
class PriceRangeResponse(object):
@staticmethod
def get_model(api, name):
return api.model(
name,
{
"min": fields.Float(required=True, example=10.0),
"max": fields.Float(required=True, example=20.0)
}... | willrp/willbuyer | backend/util/response/store/models/price_range/price_range_response.py | Python | mit | 331 |
"""Auto-generated file, do not edit by hand. ZM metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_ZM = PhoneMetadata(id='ZM', country_code=260, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[289]\\d{8}', possible_length=(9,)),
... | samdowd/drumm-farm | drumm_env/lib/python2.7/site-packages/phonenumbers/data/region_ZM.py | Python | mit | 1,055 |
'''
This script runs the full-data run of the ftrl-proximal model using
data from gl_features.features2(). This only runs one epoch (~200M rows).
It differs a little from run2.py in that the features2 data contains fields
that have to be removed (SearchID and SearchDate).
author: David Thaler
date: July 2015
'''
impo... | davidthaler/Kaggle_Avito-2015 | val_run3.py | Python | mit | 3,052 |
from astrofunc.LensingProfiles.p_jaffe import PJaffe
import numpy as np
class PJaffe_Ellipse(object):
"""
this class contains functions concerning the NFW profile
relation are: R_200 = c * Rs
"""
def __init__(self):
self.spherical = PJaffe()
self._diff = 0.000001
def function... | sibirrer/astrofunc | astrofunc/LensingProfiles/p_jaffe_ellipse.py | Python | mit | 2,605 |
from direct.directnotify import DirectNotifyGlobal
import HoodDataAI
from toontown.toonbase import ToontownGlobals
from toontown.coghq import DistributedFactoryElevatorExtAI
from toontown.coghq import DistributedCogHQDoorAI
from toontown.building import DoorTypes
from toontown.coghq import LobbyManagerAI
from toontown.... | ksmit799/Toontown-Source | toontown/hood/CSHoodDataAI.py | Python | mit | 4,185 |
from collections import defaultdict
from datetime import datetime
from dateutil.relativedelta import relativedelta
import random
ACCEPTABLE_MONTH_TIMEFRAME = 3
def add_team_vote(*args, **kwargs):
today = kwargs.pop('today', datetime.now().strftime('%x'))
entry = today
with open('LunchSpotData.txt', 'a'... | stroy1/localFoodLearner | src/learner.py | Python | mit | 4,248 |
ORIGINAL_TRAIN_DIRECTORY = "../data/original_train/"
TRAIN_DIRECTORY = "../data/train/"
VALID_DIRECTORY = "../data/valid/"
TEST_DIRECTORY = "../data/test/"
CLASSES = ['cat', 'dog']
VALIDATION_SIZE = 0.2 # size of the validation we want to use
TEST_SIZE = 0.1
import glob
import os
import shutil
import numpy as np
#... | gabrielrezzonico/dogsandcats | notebooks/create_data.py | Python | mit | 2,866 |
from motioncapture.app import Managers
class ScrapCap:
def __init__(self):
self.cameras = []
self.trackers = []
scrapcap = ScrapCap() | g-rauhoeft/scrap-cap | motioncapture/app/__init__.py | Python | mit | 163 |
from .base import BaseCommand
class SnapshotStatusCommand(BaseCommand):
command_name = "elasticsearch:snapshot-status"
def is_enabled(self):
return True
def run_request(self, repository=None, snapshot=None, **kwargs):
if not repository:
self.show_repository_list_panel(self.ru... | KunihikoKido/sublime-elasticsearch-client | commands/snapshot_status.py | Python | mit | 606 |
#!/usr/bin/env python
#########################################################################################
#
# Extract spinal levels
#
#
# ---------------------------------------------------------------------------------------
# Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca>
# Author: Karun Raju... | 3324fr/spinalcordtoolbox | dev/spinal_level/sct_extract_spinal_levels.py | Python | mit | 12,611 |
from glad.lang.common.loader import BaseLoader
from glad.lang.c.loader import LOAD_OPENGL_DLL, LOAD_OPENGL_DLL_H, LOAD_OPENGL_GLAPI_H
_WGL_LOADER = \
LOAD_OPENGL_DLL % {'pre':'static', 'init':'open_gl',
'proc':'get_proc', 'terminate':'close_gl'} + '''
int gladLoadWGL(HDC hdc) {
int statu... | valeriog-crytek/glad | glad/lang/c/loader/wgl.py | Python | mit | 3,025 |
"""Config flow for Keenetic NDMS2."""
from __future__ import annotations
from typing import Any
from urllib.parse import urlparse
from ndms2_client import Client, ConnectionException, InterfaceInfo, TelnetConnection
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components impor... | rohitranjan1991/home-assistant | homeassistant/components/keenetic_ndms2/config_flow.py | Python | mit | 6,614 |
from setuptools import setup
setup(
name='unroll',
version=open('VERSION').read().strip(),
author='Oakland John Peters',
author_email='oakland.peters@gmail.com',
description='Tool for multi-line and advanced list/dict/generator comprehensions.',
long_description=open('README.rst').read(),
... | OaklandPeters/unroll | setup.py | Python | mit | 1,038 |
from PIL import Image
import collections
import glob
import os
import yaml
import copy
import json
import argparse
jsonPath = '../assets/gallery.json'
SIZES = [300, 1000, 2000]
def ensure_folder(folder):
if not os.path.exists(folder):
os.mkdir(folder)
def resize_image(file, size, savePath):
with I... | itko/itko.github.io | scripts/sizes.py | Python | mit | 3,491 |
#!/usr/bin/env python
#
# The MIT License ( MIT )
#
# Copyright ( c ) 2016 Davit Samvelyan
#
# 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 limitatio... | davits/DyeVim | python/dye/buffer.py | Python | mit | 6,566 |
#coding=utf-8
'''
Created on 2016年3月3日
'''
from zmqf.core.base import ZmqfHandler, ZmqfApplication, ZmqfServer, ZmqfPattern
__author__ = 'chenjian'
class MainHanlder(ZmqfHandler):
'''
'''
def __init__(self, *args, **kwargs):
ZmqfHandler.__init__(self, *args, **kwargs)
def handle(s... | TataStar/zmqf | zmqf/examples/mrer/server.py | Python | mit | 1,000 |
import unittest
from psychic_disco import util
import os
import shutil
class TestUtil(unittest.TestCase):
def test_shell(self):
util.shell(["touch", "poop.txt"])
self.assertTrue(os.path.exists("poop.txt"))
os.remove("poop.txt")
def test_cp(self):
with open("poop_src.txt", "w")... | robertdfrench/psychic-disco | psychic_disco/tests/util/test_util.py | Python | mit | 2,050 |
import sqlite3
#outsourcing the database operations.
class db:
def __init__(self):
# create/connnect to database and table
self.db = sqlite3.connect('settings.db')
self.db.row_factory = sqlite3.Row
self.db.execute('''CREATE TABLE IF NOT EXISTS settings
(n... | metzbernhard/eu4_settings_selector | settings_db.py | Python | mit | 2,782 |
import pymel.core as pm
import logging
import os
log = logging.getLogger("mtapLogger")
class BinaryMesh(object):
def __init__(self, meshList = None):
self.meshList = meshList
self.path = pm.optionVar.get('mtap_binMeshExportPath', pm.workspace.path + "/geo/export.binarymesh")
self.prefix = ... | haggi/OpenMaya | src/mayaToAppleseed/mtap_devmodule/scripts/Appleseed/appleseedMenu.py | Python | mit | 9,336 |
from ._base import FunctionBase
class Function(FunctionBase):
name = 'help'
doc = 'Returns help text'
methods_subclass = {}
def handle_input(self, term_system, term_globals, exec_locals, text):
fname, method, args = self.get_method_args(text)
if method:
ret = '%s function d... | Bakterija/mmplayer | mmplayer/kivy_soil/terminal_widget/functions/help.py | Python | mit | 1,053 |
#!/usr/bin/python
"""
This script parses the stderr output of doxygen and looks for undocumented
stuff. By default, it just counts the undocumented things per file. But with
the -A option, it rewrites the files to stick in /*DOCDOC*/ comments
to highlight the undocumented stuff.
"""
import os
import re
impo... | hexxcointakeover/hexxcoin | src/tor/scripts/maint/locatemissingdoxygen.py | Python | mit | 1,940 |
#!/usr/bin/env python
"""
Validate SVGs using the W3C nu validator.
The following arguments are supported:
-always Don't prompt to save changes.
¶ms;
"""
from functools import lru_cache
from typing import Any, FrozenSet, List
import mwparserfromhell
import pywikibot
import requests
from mwparserfromhe... | JJMC89/JJMC89_bot | enwiki/svg_validator.py | Python | mit | 8,126 |
# 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/loganalytics/azure-mgmt-loganalytics/azure/mgmt/loganalytics/aio/__init__.py | Python | mit | 816 |
"""Admin classes for the active_users app."""
from django.contrib import admin
from . import models
class ActivityAdmin(admin.ModelAdmin):
list_display = ['day', 'count', 'user', 'user__email', 'last_active']
search_fields = ['user__email']
raw_id_fields = ['user']
def user__email(self, obj):
... | TheArtling/django-active-users-stats | active_users/admin.py | Python | mit | 398 |
# TODO: add "removable_property" we use in tygs
# TODO: add reify, based on removable property
from past.builtins import basestring
def ensure_tuple(val):
if not isinstance(val, basestring):
try:
return tuple(val)
except TypeError:
return (val,)
return (val,)
def nop(... | LucienD/ww | src/ww/utils.py | Python | mit | 341 |
#!/usr/bin/env python
"""
Control Qualcomm based phone via QMSL lib
This file is part of RF_Tuning_Tool.
:copyright: (c) 2013 by the A-mao Chang (maomaoto@gmail.com)
:license: MIT, see COPYING for more details.
"""
import time
from ctypes import *
from WCDMA_attributes import *
truth_dict = {True:"Yes",False:... | tmc9031/RF_Tuning_Tool | QCOM.py | Python | mit | 18,137 |
# -*- coding: utf-8 -*-
"""Installer for the lcm.sitetheme package."""
from setuptools import find_packages
from setuptools import setup
import os
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
long_description = \
read('README.rst') + \
read('docs', 'HISTORY.tx... | a25kk/lcm | src/lcm.sitetheme/setup.py | Python | mit | 1,715 |
"""Admin classes for the aps_bom app."""
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from . import models
class AdditionalTextAdmin(admin.ModelAdmin):
list_display = ['ipn', 'text']
search_fields = ['ipn__code', 'text']
class BOMItemInline(admin.TabularInline):
... | bitmazk/django-aps-bom | aps_bom/admin.py | Python | mit | 3,856 |
from malwareconfig import crypto
from malwareconfig.common import Decoder
from malwareconfig.common import string_printable
class Alina(Decoder):
decoder_name = "Alina"
decoder__version = 1
decoder_author = ["@botnet_hunter, @kevthehermit"]
decoder_description = "Point of sale malware designed to extr... | kevthehermit/RATDecoders | malwareconfig/decoders/alina.py | Python | mit | 725 |
"""Test PortMod message."""
from pyof.v0x01.common.phy_port import PortConfig, PortFeatures
from pyof.v0x01.controller2switch.port_mod import PortMod
from tests.unit.test_struct import TestStruct
class TestPortMod(TestStruct):
"""Test class for PortMod."""
@classmethod
def setUpClass(cls):
"""[Co... | kytos/python-openflow | tests/unit/v0x01/test_controller2switch/test_port_mod.py | Python | mit | 823 |
import json
import logging
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import HttpResponseServerError
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from django.view... | blackholll/loonblog | apps/blog/views.py | Python | mit | 8,792 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import waldur_core.logging.loggers
import model_utils.fields
import waldur_core.core.fields
import waldur_core.core.models
import django.db.models.deletion
import django.utils.timezone
import taggit.managers
import... | opennode/nodeconductor-openstack | src/waldur_openstack/openstack_tenant/migrations/0007_backup_backuprestoration.py | Python | mit | 4,015 |
'''@package tfwriters
contains the objects for writing tensorflow record files'''
from . import tfwriter, numpy_float_array_as_tfrecord_writer, numpy_bool_array_as_tfrecord_writer,\
index_list_as_tfrecord_writer, float_list_as_tfrecord_writer | JeroenZegers/Nabu-MSSS | nabu/processing/tfwriters/__init__.py | Python | mit | 245 |
import json
import langid
placeList = []
placeListFile = open('lists/google_place_long.category', 'r')
for line in placeListFile:
if not line.startswith('#'):
placeList.append(line.strip())
placeListFile.close()
for index, place in enumerate(placeList):
print place
outputFile = open('data/POIHistC... | renhaocui/activityExtractor | cleanHistTweets.py | Python | mit | 967 |
from asyncio import coroutine
class Result(object):
"""
Result,
from Rust.
"""
def __init__(self, target):
"""
>>> Ok(1)
Ok<1>
>>> Err('str')
Err<'str'>
"""
self.target = target
def __repr__(self):
return "{}<{!r}>".format(t... | felixonmars/isperdal | isperdal/utils.py | Python | mit | 2,597 |
import os
DIR = os.path.dirname(__file__)
DICTIONARY = os.path.join(DIR,'data','cities.txt')
| ratpik/py-spellcheck | config.py | Python | mit | 98 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow/contrib/cloud/kernels/bigquery_table_partition.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 _messag... | nubbel/swift-tensorflow | PythonGenerated/tensorflow/contrib/cloud/kernels/bigquery_table_partition_pb2.py | Python | mit | 2,993 |
#!/usr/bin/env python
"""Creates or updates distribution files"""
import subprocess
print "Updates JavaScript and Type Definition files..."
subprocess.call(['rm', 'dist', '-rf'])
subprocess.call(['tsc', '--declaration'])
| soloproyectos-ts/matrix2 | bin/dist.py | Python | mit | 224 |
# coding=utf-8
"""TO-DO: Write a description of what this XBlock is."""
import json
import pkg_resources
import logging
import threading
import math
import sys
from xblock.core import XBlock
from xblock.fields import Scope, Integer, Any, String, Float, Dict, Boolean,List
from xblock.fragment import Fragment
from lxml... | robertlight/worldmapXBlock | worldmap/worldmap/worldmap.py | Python | mit | 71,003 |
import json
with open("samples/troll_scores.json", 'r', encoding='utf-8') as jsonfile:
text = json.load(jsonfile)
for i in range(10):
print (text[i]) | vietzerg/trendy | read_scores.py | Python | mit | 166 |
#!/usr/bin/env python3
def getGenesOfInterest(geneListFile):
file = open(geneListFile, 'r')
geneListLine = file.readline()
geneList = []
while(geneListLine):
geneListLine = geneListLine.strip()
geneList.append(geneListLine)
geneListLine = file.readline()
file.close()
re... | michael-weinstein/UCLA-CPU | fpkMatrixDEG/fpkmatrixDEG.0.1.py | Python | mit | 5,571 |
__author__ = 'JordSti'
import os
class var_file:
def __init__(self, path=None):
self.path = path
self.__vars_order = []
self.__vars = {}
if self.path is not None:
self.read()
def read(self):
if self.path is not None and os.path.exists(self.path):
... | jordsti/stigame | tools/sprite-editor/var_file.py | Python | mit | 1,366 |
from django.shortcuts import render
from django.http import HttpResponse
from .models import tweet, useradd, comment
from django.contrib.auth import authenticate, login
from django.contrib.auth import logout
from .forms import UserForm, TweetForm, CommentForm
# Create your views here.
def index(request):
if reques... | Udayraj123/dashboard_IITG | Binder/Twitter/views.py | Python | mit | 5,579 |
#!/usr/bin/env python
from subprocess import Popen, PIPE
from winrm import Session
from sys import exit, argv
if len(argv) < 2 :
exit('Usage: %s command' % argv[0])
command = " ".join(argv[1:])
mySession = Session(
'jumpbox.monad.net',
auth = (None, None),
kerberos_delegation = True,
... | bielawb/PSConfAsia17-Linux | Scripts/delegatedWinRM.py | Python | mit | 470 |
'''
Python boilerplate template: Smoke test.
Copyright 2014, Konstantin Tretyakov
Licensed under MIT
'''
from subprocess import check_call
import sys, os, shutil
import os.path
def test_smoke():
if os.path.exists('tmp'):
shutil.rmtree('tmp')
os.mkdir('tmp')
os.chdir('tmp')
check_call("paster c... | konstantint/python-boilerplate-template | tests/smoke_test.py | Python | mit | 818 |
"""
WSGI config for homework 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.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SET... | erorrov/university | ex3-django/homework/wsgi.py | Python | mit | 394 |
from twilio.rest import TwilioRestClient
# put your own credentials here
ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
AUTH_TOKEN = "your_auth_token"
client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
# TODO: Confirm passing provide_feedback works
client.messages.create(
to="+15558675309",
from_="+15017... | teoreteetik/api-snippets | rest/messages/feedback-send-sms/feedback-send-sms.5.x.py | Python | mit | 430 |
#!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the avoid_reuse and setwalletflag features."""
from test_framework.test_framework import BitcoinTestFr... | jtimon/bitcoin | test/functional/wallet_avoidreuse.py | Python | mit | 9,952 |
import os
import sys
def populate():
python_cat = add_cat('Python', views=128, likes=64)
add_page(cat=python_cat,
title="Official Python Tutorial",
url="http://docs.python.org/2/tutorial/")
add_page(cat=python_cat,
title="How to Think like a Computer Scientist",
url="http://www.greenteapress.com/thinkpy... | Kentoseth/rangoapp | tango_with_django_project/populate_rango.py | Python | mit | 1,711 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... | frankmaina/django2fa | accounts/migrations/0001_initial.py | Python | mit | 698 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
class Uwhois(object):
def __init__(self, server='127.0.0.1', port=4243):
self.server = server
self.port = port
def query(self, q):
bytes_whois = b''
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
... | Rafiot/uwhoisd | client/uwhois/client.py | Python | mit | 636 |
#!/usr/bin/env python
import json
from twisted.trial import unittest
from twistedpusher.events import Event, load_pusher_event, serialize_pusher_event
from twistedpusher.errors import BadEventNameError
from twistedpusher.test.helpers import TEST_TIMEOUT
class EventTestCase(unittest.TestCase):
timeout = TEST_TIM... | socillion/twistedpusher | test/test_event.py | Python | mit | 5,963 |
from pytest import raises
from crosscompute import __version__
from crosscompute.exceptions import (
CrossComputeConfigurationError,
CrossComputeError)
from crosscompute.routines.configuration import (
validate_automation_identifiers,
validate_protocol,
validate_variables)
class DummyConfiguratio... | crosscompute/crosscompute | tests/test_routines_configuration.py | Python | mit | 2,042 |
from __future__ import print_function
import numpy as np
import sys
from logging import warning
from struct import pack
import matplotlib.pyplot as plt
def display_profiles(gamma, m, pos, u, ax):
r = np.linalg.norm(pos, axis=1)
hist, edges = np.histogram(r, bins='auto')
nbins = len(hist)
rho_c = np.ze... | fgoicovic/gadget-polytrope | libs/Utils.py | Python | mit | 4,570 |
from signals import register
register('app.activate')
register('app.deactivate')
register('app.pre_start')
register('app.start')
register('app.ready')
register('app.close')
register('app.stop')
register('app.chdir')
register('app.command')
register('app.remote')
register('module.loaded')
register( 'command.new' )
... | tommo/gii | lib/gii/core/globalSignals.py | Python | mit | 1,476 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('survey', '0005_auto_20150124_0427'),
]
operations = [
migrations.RemoveField(
model_name='question',
... | Ecotrust/floodplain-restoration | dst/survey/migrations/0006_remove_question_category.py | Python | mit | 355 |
# -*- coding: utf-8 -*-
# Copyright (c) 2014 Rackspace
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | liszd/whyliam.workflows.youdao | urllib3/packages/rfc3986/__init__.py | Python | mit | 1,562 |
#!/usr/bin/env python
import os, time, cPickle
from cogent.util import parallel
__author__ = "Peter Maxwell"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Peter Maxwell"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Peter Maxwell"
__email__ = "pm67nz@gmail.com"
__status__ = "... | sauloal/cnidaria | scripts/venv/lib/python2.7/site-packages/cogent/util/checkpointing.py | Python | mit | 1,561 |
from django.contrib import admin
from .models import KeepInTouchEmail
admin.site.register(KeepInTouchEmail) | nirvaris/nirvaris-comingsoon | comingsoon/admin.py | Python | mit | 109 |
__author__ = 'n3k'
import threading
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
| n3k/SchedulerSimulator | Scheduler/Singleton.py | Python | mit | 278 |
import sys
from concourse_common import common
from concourse_common import jsonutil
from concourse_common import request
import json
from slackclient import SlackClient
import os
import xml.etree.ElementTree
import slack_post
import schemas
def execute(filepath):
valid, payload = jsonutil.load_and_validate_payl... | cosee-concourse/slack-upload-resource | opt/resource/out.py | Python | mit | 2,926 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import GeoIP
def getCountryNameByAddr(ipv4):
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
#ip
name=gi.country_name_by_addr(ipv4)
return name
#gi = GeoIP.new(GeoIP.GEOIP_STANDARD)
#gi = GeoIP.new(GeoIP.GEOIP_MMAP_CACHE)
#gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
#gi = GeoIP.ope... | vtill/SecyrIT | lib/geo.py | Python | mit | 637 |
#!/usr/bin/env python3
"""Project Euler - Problem 49 Module"""
import itertools
import pelib
IGNORE_SEQ_START = 1487
def problem49(nr_of_digits, dist):
"""Problem 49 - Prime permutations"""
limit = 10 ** nr_of_digits
fpc = pelib.FastPrimeChecker()
# Lazy
result = 0
skip_set = set()
for ... | rado0x54/project-euler | python/problem0049.py | Python | mit | 1,037 |
import os
SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
# this is needed to get the absolute path, which django needs for routing
DATABASE_PATH = os.path.join(PROJECT_PATH, 'rango.db')
DATABASES = {
'default': {
... | dannysellers/tangodjango | tango_with_django_project/rango/templates/rango/settings.py | Python | mit | 1,248 |
from flask_wtf import Form
from wtforms import StringField, TextAreaField
from wtforms import SubmitField, validators
class ProductForm(Form):
'''This class creates an ProductForm
object.
'''
# a store has a name and a description
name = StringField('Product',
[validators.Requir... | hanmaslah/bc_8_online_store | app/products/forms.py | Python | mit | 909 |
print("This is a test file")
| clm5uz/cs3240-labdemo | test.py | Python | mit | 29 |
#!/usr/bin/env python
from __future__ import print_function
import re
import subprocess
from fabric.api import task
@task
def release(part='patch'):
""" Automated software release workflow
* (Configurably) bumps the version number
* Tags the release
You can run it like::
$ fab release
... | AWegnerGitHub/stackapi | fabfile.py | Python | mit | 1,536 |
import os
import logging
from twilio.rest import TwilioRestClient
from alerta.app import app
from alerta.plugins import PluginBase
LOG = logging.getLogger('alerta.plugins.twilio')
TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID') or app.config['TWILIO_ACCOUNT_SID']
TWILIO_AUTH_TOKEN = os.environ.get('TWILI... | msupino/alerta-contrib | plugins/twilio/alerta_twilio_sms.py | Python | mit | 1,213 |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def __init__(self):
self.pre = None
self.mistake1 = None
self.mistake2 = None
def recoverTree(self, root):
"""
:type root... | ChuanleiGuo/AlgorithmsPlayground | LeetCodeSolutions/python/99_Recover_Binary_Search_Tree.py | Python | mit | 1,086 |
from copy import deepcopy
class Species(object):
"""docstring for Species"""
def __init__(self, name):
super(Species, self).__init__()
self.name=name
def __repr__(self):
return "<S. "+str(self.name)+">"
def __hash__(self):
return hash(self.__repr__())
def __eq__(self, other):
if isinstance(other, S... | aresio/HERESY | pyRSSIM.py | Python | mit | 7,771 |
"""The tests for Home Assistant frontend."""
# pylint: disable=protected-access,too-many-public-methods
import re
import time
import unittest
import requests
import homeassistant.bootstrap as bootstrap
from homeassistant.components import frontend, http
from homeassistant.const import HTTP_HEADER_HA_AUTH
from tests.... | betrisey/home-assistant | tests/components/test_frontend.py | Python | mit | 2,298 |