repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
ldesousa/PyWPS | pywps/inout/outputs.py | ##################################################################
# Copyright 2016 OSGeo Foundation, #
# represented by PyWPS Project Steering Committee, #
# licensed under MIT, Please consult LICENSE.txt for details #
####################################################... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_07_01/operations/_available_endpoint_services_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 ... |
merriam/dectools | docs/sphinx/conf.py | # -*- coding: utf-8 -*-
#
# dectools documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 4 16:11:14 2010.
#
# 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.
#
# Al... |
rafafigueroa/amrws | src/amrpkg/scripts/scan_control.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
import numpy as np
pub = rospy.Publisher('/mobile_base/commands/velocity', Twist, queue_size=10)
def sc_callback(robot_sc):
scan_ranges = robot_s... |
simpleai-team/simpleai | simpleai/search/web_viewer_server.py | # coding: utf-8
from __future__ import print_function
import json
from os import path, _exit
from time import sleep
from flask import Flask, Response, send_file
def run_server(viewer):
resources = path.join(path.dirname(path.realpath(__file__)),
'web_viewer_resources')
app = Flask... |
Blitzman/udacity-730 | l1/softmax.py | """Softmax."""
scores = [3.0, 1.0, 0.2]
import numpy as np
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
return (np.exp(x) / np.sum(np.exp(x), axis=0))
print(softmax(scores))
# Plot softmax curves
import matplotlib.pyplot as plt
x = np.arange(-2.0, 6.0, 0.1)
scores = np.vstack(... |
mtharp/laureline-firmware | util/resize_ld.py | #!/usr/bin/env python2
#
# Copyright (c) Michael Tharp <gxti@partiallystapled.com>
#
# This file is distributed under the terms of the MIT License.
# See the LICENSE file at the top of this tree, or if it is missing a copy can
# be found at http://opensource.org/licenses/MIT
#
import os
import re
import subprocess
im... |
slerch/ppnn | data_retrieval/forecasts/retrieve_ecmwf_fc_data.py | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 24 10:44:53 2017
@author: sebastian
"""
## retrieve ECMWF forecast data, based on example from
## https://software.ecmwf.int/wiki/display/WEBAPI/TIGGE+retrieval+efficiency
# ECMWF forecasts from TIGGE data set:
# T2M fields
# all available full years, 2007-2016
# ... |
LabD/django-postcode-lookup | src/django_postcode_lookup/backends/base.py | import attr
from django.core.cache import cache
@attr.s
class PostcodeLookupResult(object):
postcode = attr.ib()
number = attr.ib()
street = attr.ib()
city = attr.ib()
def json(self):
return attr.asdict(self)
class PostcodeLookupException(IOError):
pass
class _none(object):
pa... |
johnstonskj/PyDL7 | tests/test_files.py | import pytest
import divelog.files
def test_formats_dict():
for key in divelog.files.formats:
assert divelog.files.formats[key].FORMAT_NAME == key
def test_formats_dict_error():
with pytest.raises(KeyError):
divelog.files.formats['NO_TYPE']
def test_extensions_dict():
assert divelog.fi... |
MadeInHaus/django-social | social/admin/__init__.py | from django.contrib import admin
from ..models import (FacebookAccount, FacebookMessage, FacebookSearch,
TwitterAccount, TwitterMessage, TwitterSearch,
RSSAccount, RSSMessage, Message,
InstagramAccount, InstagramSearch, InstagramMessage,
... |
hearsaycorp/normalize | tests/test_mfs_diff.py | #
# This file is a part of the normalize python library
#
# normalize is free software: you can redistribute it and/or modify
# it under the terms of the MIT License.
#
# normalize is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FI... |
jorik041/txrudp | tests/benchmark.py | #! /usr/bin/env python
import collections
import random
import time
from txrudp import rudp, constants, connection
class StubHandler(connection.Handler):
def __init__(self):
self.shutdown = False
self.received_count = 0
self.last_message = None
def receive_message(self, message):
... |
WoodNeck/tataru | cogs/sound.py | import os
import asyncio
import logging
from discord import opus, ClientException
from discord.ext import commands
from discord.opus import OpusNotLoaded
from cogs.utils.music import Music
from cogs.utils.music_type import MusicType
from cogs.utils.music_player import MusicPlayer
OPUS_LIBS = ['libopus-0.x86.dll', 'lib... |
arcticfoxnv/slackminion | setup.py | from setuptools import setup, find_packages
from slackminion.plugins.core import version
setup(
name='slackminion',
version=version,
packages=find_packages(exclude=['test_plugins']),
url='https://github.com/arcticfoxnv/slackminion',
license='MIT',
author='Nick King',
... |
WheatonCS/Lexos | lexos/views/k_means.py | from flask import session, Blueprint
from lexos.helpers import constants as constants
from lexos.managers import session_manager as session_manager
from lexos.models.k_means_model import KMeansModel
from lexos.views.base import render
k_means_blueprint = Blueprint("k-means", __name__)
@k_means_blueprint.route("/k-me... |
nicodv/kmodes | kmodes/util/dissim.py | """
Dissimilarity measures for clustering
"""
import numpy as np
def matching_dissim(a, b, **_):
"""Simple matching dissimilarity function"""
return np.sum(a != b, axis=1)
def jaccard_dissim_binary(a, b, **__):
"""Jaccard dissimilarity function for binary encoded variables"""
if ((a == 0) | (a == 1... |
Pretagonist/Flexget | flexget/plugins/filter/exists_movie.py | from __future__ import unicode_literals, division, absolute_import
import logging
import re
from path import Path
from flexget import plugin
from flexget.config_schema import one_or_more
from flexget.event import event
from flexget.plugin import get_plugin_by_name
from flexget.utils.tools import TimedDict
log = log... |
BenjiLee/PoloniexAnalyzer | poloniex_apis/api_models/balances.py | from poloniex_apis import trading_api
class Balances:
def __init__(self):
self.all_balances = trading_api.return_complete_balances()
def get_btc_total(self):
total_btc = 0
for stock, balances in self._get_active_balances().items():
total_btc += float(balances['btcValue'])
... |
vhaupert/mitmproxy | test/mitmproxy/addons/test_export.py | import os
import shlex
import pytest
import pyperclip
from mitmproxy import exceptions
from mitmproxy.addons import export # heh
from mitmproxy.test import tflow
from mitmproxy.test import tutils
from mitmproxy.test import taddons
from unittest import mock
@pytest.fixture
def get_request():
return tflow.tflow(... |
migafgarcia/programming-challenges | hackerrank/cracking_the_coding_interview/davis_staircase.py | #!/bin/python
table = dict()
def climb(n):
if table.has_key(n):
return table[n]
if n == 0:
return 1
if n < 0:
return 0
total = 0
total += climb(n - 1)
total += climb(n - 2)
total += climb(n - 3)
table[n] = total
return total
... |
Timtam/cards-against-humanity | accessible_output/speech/outputs/nvda.py | from ctypes import windll
from accessible_output import paths
from main import OutputError, ScreenreaderSpeechOutput
class NVDA (ScreenreaderSpeechOutput):
"""Supports The NVDA screen reader"""
name = 'NVDA'
def __init__(self, *args, **kwargs):
super(NVDA, self).__init__(*args, **kwargs)
try:
self.dll = w... |
tegg89/SRCNN-Tensorflow | main.py | from model import SRCNN
from utils import input_setup
import numpy as np
import tensorflow as tf
import pprint
import os
flags = tf.app.flags
flags.DEFINE_integer("epoch", 15000, "Number of epoch [15000]")
flags.DEFINE_integer("batch_size", 128, "The size of batch images [128]")
flags.DEFINE_integer("image_size", 33... |
m0re4u/SmartLight | client/modules/face_recognizer/recognize.py | #! /usr/bin/python
#
# Example to run classifier on webcam stream.
# Brandon Amos & Vijayenthiran
# 2016/06/21
#
# Copyright 2015-2016 Carnegie Mellon University
#
# 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... |
ArthurFortes/CaseRecommender | examples/rating_prediction_knn.py | """
Running KNN Recommenders [Rating Prediction]
- Cross Validation
- Simple
"""
from caserec.recommenders.rating_prediction.user_attribute_knn import UserAttributeKNN
from caserec.recommenders.rating_prediction.item_attribute_knn import ItemAttributeKNN
from caserec.recommenders.rating_prediction.itemkn... |
dutradda/swaggerit | swaggerit/utils.py | # MIT License
# Copyright (c) 2016 Diogo Dutra <dutradda@gmail.com>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, co... |
tomwphillips/oscpo | oscpo.py | from glob import glob
import csv
from peewee import *
database = SqliteDatabase(None)
class BaseModel(Model):
class Meta:
database = database
class Location(BaseModel):
postcode = CharField(unique=True, max_length=8)
positional_quality_indicator = IntegerField()
eastings = IntegerField()
... |
ajtag/TrinRoofPlayer | Constants.py | __author__ = 'ajtag'
from pygame import Rect
import collections
import csv
import os.path
MADRIX_X = 132
MADRIX_Y = 70
MADRIX_SIZE = (MADRIX_X, MADRIX_Y)
white = 255, 255, 255, 0xff
black = 0, 0, 0, 0xff
red = 255, 0, 0, 0xff
green = 0, 255, 0, 0xff
blue = 0, 0, 255, 0xff
dark_grey = 0x30, 0x30, 0x30, 0xff
transpar... |
Tarrasch/problemtools | ProblemPlasTeX/__init__.py | import re
import os
import shutil
import plasTeX.Renderers
from plasTeX.Renderers.PageTemplate import Renderer
from plasTeX.Filenames import Filenames
from plasTeX.dictutils import ordereddict
from plasTeX.Imagers import Image
class ImageConverter(object):
fileExtension = '.png'
imageAttrs = ''
imageUnits ... |
matham/kivy | kivy/core/window/window_sdl2.py | # found a way to include it more easily.
'''
SDL2 Window
===========
Windowing provider directly based on our own wrapped version of SDL.
TODO:
- fix keys
- support scrolling
- clean code
- manage correctly all sdl events
'''
__all__ = ('WindowSDL', )
from os.path import join
import sys
from typing... |
jeremiedecock/snippets | python/matplotlib/save_without_borders.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Remove borders on saved figures
"""
import matplotlib.pyplot as plt
import numpy as np
fig, ax1 = plt.subplots(nrows=1, ncols=1, figsize=(8, 6))
x = np.arange(-10, 10, 0.1)
y = np.power(x, 2.)
ax1.plot(x, y)
# Save file and plot ########
output_file = "save_with... |
t-g-williams/seattle_hackathon | code/query/euclidean.py | '''
Calculate the Euclidean distance between all points to inform the querying
'''
import time
import sqlite3
from math import radians, cos, sin, asin, sqrt
import os
import logging
logger = logging.getLogger(__name__)
def calculate(mode, db_fn, db_temp_fn):
'''
Generate the euclidean distance for each orig, ... |
AngelinNjakasoa/Range-analysis-experiments | data_structure.py | #!/usr/bin/python
# coding: utf8
"""
Contains range related data structures
List of data structures:
- VariableRangeValue
"""
class VariableRangeValue(object):
"""
Contains the range [lower_bound, 0, upper_bound]
Initialize the range to [-inf, 0, +inf]
"""
identifier = ""
bit_vector... |
AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_10_01/models/virtual_network_gateway_sku.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 ... |
uzh-ethz-ini/uzh-cd-sphinx-theme | setup.py | #!/usr/bin/env python
# -*- Mode: Python; py-indent-offset: 4; coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
## Copyright (C) 2014, University of Zurich and ETH Zurich
## Copyright (C) 2014, Claudio Luck <cluck@ini.uzh.ch>
## Licensed under the terms of the MIT License, see LICENSE file.
import os
from ... |
qiubit/luminis | backend/tests/test_websocket_request_processing.py | #
# Copyright (C) 2017 Dominik Murzynowski
#
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
#
import unittest
from unittest.mock import MagicMock
from websocket.request_processor import RequestProcessor
class TestWebSocketRequestProcessing(uni... |
airanmehr/bio | Scripts/Miscellaneous/Tutorials/SimPop.py | '''
Copyleft Nov 24, 2015 Arya Iranmehr, PhD Student, Bafna's Lab, UC San Diego, Email: airanmehr@gmail.com
'''
# import simuPOP as sim
import numpy as np
import pandas as pd
import sys,os
home=os.path.expanduser('~') +'/'
"""
alleleFrea is a dictionary {site:{0:AF0, 1:1-AF0}}
"""
def simuLDDecay(popSize=1000, gen=1... |
codepotpl/codepot-backend | codepot/views/auth/auth_json_schema.py | sign_in_req_schema = {
'$schema': 'http://json-schema.org/draft-04/schema',
'type': 'object',
'properties': {
'email': {
'type': 'string',
'minLength': 1,
'format': 'email',
},
'password': {
'type': 'string',
'minLength': 1,... |
dcf21/4most-4gp-scripts | src/scripts/synthesize_samples/synthesize_demo_stars_2.py | #!../../../../virtualenv/bin/python3
# -*- coding: utf-8 -*-
# NB: The shebang line above assumes you've installed a python virtual environment alongside your working copy of the
# <4most-4gp-scripts> git repository. It also only works if you invoke this python script from the directory where it
# is located. If these... |
bgporter/mp3utilities | meta.py | #! /usr/bin/env python
import codecs
import csv
import os.path
from mutagen.easyid3 import EasyID3
from mutagen.mp3 import MP3
import mutagen
kMetadataFields = ["artist", "title", "album", "tracknumber", "genre", "date", "bitrate", "length", "filename"]
def MsToMinSec(ms):
''' given a duration value in millisec... |
mitchellcash/ion | qa/rpc-tests/rpcbind_test.py | #!/usr/bin/env python2
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Copyright (c) 2015-2018 The PIVX developers
# Copyright (c) 2018 The Ion developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Test for -rpcbind... |
BigQueryManager/bigquerymgr | guery_manager/guery_manager/settings.py | """
Django settings for guery_manager project.
Generated by 'django-admin startproject' using Django 1.11.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
imp... |
andersjel/boxes | src/symmath/format.py | def join_terms(terms):
if len(terms) == 0:
return "0"
rval = ""
first = True
for sign, factors in terms:
if first:
if sign != '+':
rval += sign
first = False
else:
rval += " {} ".format(sign)
if not factors:
rval += "1"
else:
rval += " ".join(factors)
... |
CS326-important/space-deer | contentdensity/textifai/views.py | from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.db.models import Q, Co... |
doylew/practice | python/linked_list.py | import sys
# Linked list class
class Linked_List:
'''
List_Node is an inner class of the Linked_List class.
It stores a value, and a pointer to the next List_Node.
Note the __repr__ method, which shows the addresses in
the next pointers, so you can compare several nodes and
verify that they ar... |
ALenfant/django-push-notifications | setup.py | #!/usr/bin/env python
import os.path
from distutils.core import setup
README = open(os.path.join(os.path.dirname(__file__), "README.rst")).read()
CLASSIFIERS = [
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License ::... |
lijiali1226/Code | leetcode/python/P226InvertBinaryTree.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Definition for a binary tree node.
class CNode:
left, right, val = None, None, 0
def __init__(self, val):
# initializes the val members
self.left = None
self.right = None
self.val = val
class CBOrdTree:
def... |
rjschwei/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/models/container_service_ssh_configuration.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 ... |
gto76/standard-aliases | scripts/update-readme.py | #!/usr/bin/env python3
#
# Usage: update-readme.py
# Prints updated README.md. It substitutes tables of commands
# with newly generated ones.
import sys
import re
import util
import const
import generate_table_of_functions
TARGET_LINE = "There are currently "
TABLES_TARGET_LINE_START = "Below is a list of most usef... |
abacuspix/NFV_project | Build_Web_With_Flask/Building web applications with Flask_Code/chapter06/ex02.py | # coding:utf-8
from flask import Flask, jsonify, request, abort, render_template, url_for
from flask_sqlalchemy import SQLAlchemy
from marshmallow import Schema, fields
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///articles.sqlite'
app.config['SQLALCHEMY... |
jf248/scrape-the-plate | recipes/migrations/0003_auto_20180713_1354.py | # Generated by Django 2.0.6 on 2018-07-13 20:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0002_auto_20180710_0956'),
]
operations = [
migrations.AlterField(
model_name='recipe',
name='slug',
... |
helewonder/knightgame | wargame/hut.py | import random
from functions import print_bold
from knight import Knight
from orcrider import OrcRider
class Hut():
"""Class to create hut object in the game Attack of the Orcs.
:arg int number: Hut number to be assigned.
:arg `AbstractRider` occupant: The new occupant of the Hut.
:ivar int number:... |
AdiVarma27/Kmeans2D | Kmeans SKlearn/KmeansSKlearn.py | import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")
from sklearn.cluster import KMeans
from scipy import sparse
x = [2,3,1,3,1.5]
y = [2,2,1,1,0.5]
plt.scatter(x,y)
plt.show()
X = np.array([[2,2],[3,2],[1,1],[3,1],[1.5,0.5]])
kmeans = KMeans(n_clusters=2)
kmeans.fit(X... |
wulfebw/LittlePlaNet-Models | scripts/extract_features.py | import caffe
import numpy as np
import os
import sys
model_prototxt = '../features/deploy.prototxt'
model_trained = '../models/best_citynet/_iter_100000.caffemodel'
mean_path = '../data/mean_image.binaryproto'
layer_name = 'pool5/7x7_s1'
image_list_filepath = '../data/train.txt'
features_filepath = '../features/featur... |
allthedata/objectexplorer | objectexplorer/objectexplorer.py | # -*- coding: utf-8 -*-
'''
Object explorer in PySide/PyQt4
Created on May 07 2013
@author: Christopher Liman
Features:
represents the following categories of objects in globals() or a root object as a tree:
- sequence-like objects (e.g. lists, numpy arrays)
- mapping-like objects (e.g. dicts, pandas objects)
- classe... |
ghing/python-peewee_ckansql | setup.py | from distutils.core import setup
setup(
name='peewee_ckansql',
version='0.1.0dev',
author='Geoffrey Hing',
author_email='geoffhing@gmail.com',
packages=['peewee_ckansql',],
license='LICENSE.txt',
description='Python Database API',
long_description=open('README.rst').read(),
install_... |
Swimlane/sw-python-client | tests/adapters/test_usergroup_adapters.py | import mock
import pytest
from swimlane.core.resources.usergroup import Group, User
def test_group_list(mock_group, mock_swimlane):
mock_response = mock.MagicMock()
mock_response.json.return_value = {'groups': [mock_group._raw for _ in range(3)]}
with mock.patch.object(mock_swimlane, 'request', return_v... |
despawnerer/theatrics | api/theatrics/utils/fields.py | from marshmallow import fields
__all__ = ['CommaSeparatedList']
class CommaSeparatedList(fields.List):
def _serialize(self, value, attr, obj):
result = super()._serialize(value, attr, obj)
return ','.join(result) if result is not None else None
def _deserialize(self, value, attr, data):
... |
reciprep/reciprep-server | flask-api/tests/test_recipe.py | import time
import json
import unittest
import uuid
from api import db
from api.models.user import User
from api.models.recipe import Recipe
from api.models.ingredient import Ingredient, PantryIngredient, RecipeIngredient
from tests.base_test_case import BaseTestCase
from helpers import json_to_ingredient, json_to_us... |
christianreimer/treescore | treescore/judge/draw.py | """
Functionality to draw using OpenCV functionality.
"""
from collections import namedtuple
import itertools
import numpy as np
import cv2
from . import utils
from . import colors
def blank_canvas(shape, color):
"""Return a blank canvas of the specified shape and color"""
blank = np.array([color] * shape[0]... |
themattrix/python-pollute | pollute/test/test_modified_environ.py | import os
from functools import partial
from nose.tools import with_setup, eq_
from pollute import modified_environ
#
# Tests
#
def test_no_changes():
old_env = os.environ.copy()
def ensure_no_changes():
eq_(dict(os.environ), old_env)
test_scenarios = partial(
__ensure_usage,
kw... |
LevinJ/Supply-demand-forecasting | utility/datafilepath.py |
class DataFilePath:
def __init__(self):
self.dataDir = '../data/citydata/season_1/'
return
def getOrderDir_Train(self):
return self.dataDir + 'training_data/order_data/'
def getOrderDir_Test1(self):
return self.dataDir + 'test_set_1/order_data/'
def getTest1Dir(self)... |
bzz-framework/bzz | tests/test_auth_hive.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of bzz.
# https://github.com/heynemann/bzz
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT-license
# Copyright (c) 2014 Bernardo Heynemann heynemann@gmail.com
from mock import Mock, patch
import cow.server as server
import torn... |
UrQA/URQA-Server | soma3/soma3/wsgi.py | """
WSGI config for soma3 project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` se... |
facebookresearch/ParlAI | tests/nightly/cpu/test_urls.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# Download and build the data if it does not exist.
import unittest
import importlib
from parlai.tasks.task_list import ... |
Debian/debile | debile/master/orm.py | # Copyright (c) 2012-2013 Paul Tagliamonte <paultag@debian.org>
# Copyright (c) 2014-2015 Clement Schreiner <clement@mux.me>
#
# 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 restrict... |
ganwell/rbtree | old_dev/src/test_stack.py |
# SPDX-FileCopyrightText: 2019 Jean-Louis Fuchs <ganwell@fangorn.ch>
#
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Test if the stack stays consistent."""
from build._rbtree_tests import lib, ffi
from hypothesis.stateful import GenericStateMachine
from hypothesis.strategies import tuples, just, integers
class I... |
CorverDevelopment/Avenue | tests/test_processors.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from avenue import Avenue
from avenue import MatchError
from avenue import MethodProcessor
from avenue import PathProcessor
from avenue import Processor
from avenue.processors import Match
from pytest import raises
class TestPro... |
csdms/wmt-metadata | metadata/InfilRichards1D/hooks/pre-stage.py | import os
import shutil
from wmt.config import site
from wmt.models.submissions import prepend_to_path
from wmt.utils.hook import find_simulation_input_file
from topoflow_utils.hook import (assign_parameters, lowercase_choice,
scalar_to_rtg_file)
file_list = []
def execute(env):
... |
slremy/testingpubsub | myBallPlate/sweep.py | import time
import timeit
import signal
from sys import exit, exc_info, argv
from math import sin, cos, sqrt, asin, isnan, isinf, pi
from collections import deque
from references import *
#http://www.forkosh.com/mimetex.cgi?P(s)=\frac{\alpha_2z^2+\alpha_1z+\alpha_0}{\beta_2z^2+\beta_1z+\beta_0}
#http://www.forkosh.com/... |
fopina/pyfispip | fispip/__main__.py | import argparse
from . import __description__, __program__
from . import PIP
def build_parser():
parser = argparse.ArgumentParser(
prog=__program__,
description=__description__
)
parser.add_argument(
'-u', '--user',
dest='user', action='store',
metavar='USER', defau... |
eb-intl/eb-intl.com | webapp/webapp/urls.py | from django.conf.urls import url, include
from django.conf.urls.static import static
from django.views.generic import TemplateView
from django.contrib import admin
from django.conf import settings
from apps import urls
urlpatterns = [
url(r'', include(urls, namespace='apps')),
#url(r'^jet/', include('jet.ur... |
mic4ael/indico | indico/modules/events/persons/forms.py | # This file is part of Indico.
# Copyright (C) 2002 - 2020 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.
from __future__ import unicode_literals
from flask import request
from wtforms.fields import BooleanField... |
amdegroot/ssd.pytorch | data/coco.py | from .config import HOME
import os
import os.path as osp
import sys
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
import cv2
import numpy as np
COCO_ROOT = osp.join(HOME, 'data/coco/')
IMAGES = 'images'
ANNOTATIONS = 'annotations'
COCO_API = 'PythonAPI'
INSTANCES_SET = 'insta... |
untergrunt/untergrunt | outdated/objects.py | v_letters=('a','e','i','o','u','y')
class Thing:
p={} #properties
name=''
def __init__(self,name,properties):
self.name=name
self.p=properties
def description(self):
adj=''
has_n=['','n'][self.name[0].lower() in v_letters]
if '_adjective' in self.p.keys():
adj=self.p['_ad... |
EclipseXuLu/DataHouse | DataHouse/test/pymongo_test.py | from pymongo import MongoClient
def insert_item(item):
client = MongoClient()
db = client.douban.movie
result = db.insert_one(item)
def query_document():
client = MongoClient()
db = client.douban.movie
cursor = db.find()
for document in cursor:
print(document)
def delete_item()... |
Lanceolata/code-problems | python/leetcode_medium/Question_156_Additive_Number.py | #!/usr/bin/python
# coding: utf-8
class Solution(object):
def isAdditiveNumber(self, num):
"""
:type num: str
:rtype: bool
"""
length = len(num)
for i in range(1, length):
for j in range(i + 1, length):
s1, s2 = num[0 : i], num[i : j]
... |
avuori/intracmd | intra.py | import httplib, urllib, sys, re
from datetime import datetime
from BeautifulSoup import BeautifulSoup
def error(s):
sys.stderr.write(s + "\n")
sys.exit(-1)
HOST = "intra.fast.sh"
passwd = open(".passwd", "r").read().split("\n")
try:
USER = passwd[0]
PASSWORD = passwd[1]
except IndexError:
error("Invalid .passw... |
ActiveState/code | recipes/Python/577978_Text_Model/recipe-577978.py | def hash_style(style):
return tuple(sorted(style.items()))
style_pool = {}
defaultstyle = {}
def create_style(**kwds):
style = defaultstyle.copy()
style.update(kwds)
key = hash_style(style)
try:
return style_pool[key]
except KeyError:
style_pool[key] = style
return s... |
mitsei/dlkit | tests/functional/test_authz/grading/test_grade_system_authz.py | """TestAuthZ implementations of grading.GradeSystem"""
import datetime
import pytest
from tests.utilities.general import is_never_authz, is_no_authz, uses_cataloging
from dlkit.abstract_osid.authorization import objects as ABCObjects
from dlkit.abstract_osid.authorization import queries as ABCQueries
from dlkit.abstra... |
maduma/hpany | record.py | import requests, json
"""
Get single record
"""
tokenFile = 'token.txt'
hpsaServer = 'mslon001pngx.saas.hp.com'
tenantId = 725867830
entityType = 'Person'
accountId = 80585
layout = 'Name'
def getRecord(server, token, tenantId, entityType, entityId, layout):
rest = 'rest/{0}/ems/Person/{1}'.format(tenantId, acco... |
applecool/Practice | Python/LinkedLists/IsLinkedListLengthEven.py | #find if the length of the linked list is even or not?
class Node:
def __init__(self, data):
self.data = data
self.next = None
def setData(self, data):
self.data = data
def getData(self):
return self.data
def setNext(self, next):
self.next =... |
peterhoward42/qt-layout-gen | src/qtlayoutbuilder/lib/builder.py | from qtlayoutbuilder.api.layouterror import LayoutError
from qtlayoutbuilder.lib.builderassertions import BuilderAssertions
from qtlayoutbuilder.lib.childadder import ChildAdder
from qtlayoutbuilder.lib.layoutscreated import LayoutsCreated
from qtlayoutbuilder.lib.line_parser import LineParser
from qtlayoutbuilder.lib.... |
rbharath/deepchem | deepchem/molnet/load_function/kaggle_datasets.py | """
KAGGLE dataset loader.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import time
import numpy as np
import deepchem
from deepchem.molnet.load_function.kaggle_features import merck_descriptors
def remove_missing_entries(dataset):
"""... |
pebbie/BIBINT | scripts/scrape.py | import os
import sys
import glob
import mechanize
from mechanize._beautifulsoup import BeautifulSoup, Tag
import json
import math
from urlparse import urlparse
from collections import deque
from time import sleep
from random import randint
import httplib
base_url = u"http://ieeexplore.ieee.org"
conn = None
def fetch... |
joshmarlow/crowdpact | crowdpact/apps/pact/migrations/0003_auto_20150411_2325.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('pact', '0002_auto_20150411_1952'),
]
operations = [
migrations.AddField(
model_name='pact',
name='go... |
mbodenhamer/syn | syn/python/b/base.py | import ast
from copy import deepcopy
from operator import itemgetter
from functools import partial, wraps
from syn.base_utils import get_typename, ReflexiveDict, assign
from syn.util.log.b import StringEvent
from syn.tree.b import Node, Tree
from syn.base.b import create_hook, Attr, init_hook, Base, Counter
from syn.ty... |
onlytiancai/warning-agent | src/counters/default.py | # -*- coding: utf-8 -*-
import psutil
def get_sysinfo():
result = {}
result['cpu_utilization'] = psutil.cpu_percent()
result['mem_utilization'] = psutil.virtual_memory().percent
result['swap_utilization'] = psutil.swap_memory().percent
for part in psutil.disk_partitions(all=False):
r = psu... |
morevnaproject/scripts | blender/io_import_lipSync_Importer.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
yaukwankiu/armor | start4_taipei_taichung_tainan.py | #################
# codes for testing armor.patternMatching.pipeline and armor.patternMatching.algorithms
import time
import shutil
import os
time0 = time.time()
startTime =time.asctime()
from armor import defaultParameters as dp
from armor import misc
from armor import pattern, pattern2
p2 = pattern2
from ar... |
funnyplan/Pager | pager/libs/facebook_.py | import base64
import hashlib
import hmac
import json
from datetime import datetime, timedelta
from flask import request
from timezone import KST, now
def base64_url_decode(inp):
padding_factor = (4 - len(inp) % 4) % 4
inp += "="*padding_factor
return base64.b64decode(unicode(inp).translate(dict(zip(map(or... |
shtarbanov/MAS.500 | HW3/startServer.py | import ConfigParser, logging, datetime, os
import mediacloud
from flask import Flask, render_template, request
CONFIG_FILE = 'settings.config'
basedir = os.path.dirname(os.path.realpath(__file__))
# load the settings file
config = ConfigParser.ConfigParser()
config.read(os.path.join(basedir, 'settings.config'))
# se... |
e2t/cli-tools | src/sort_drawings.py | """Модуль для сортировки чертежей по каталогам."""
import re
import os
import sys
import shutil
DESIGNATION = r'[a-zA-Zа-яА-Я].*\d'
TYPE = r'СБ|МЧ|ВО|УЧ'
NAME = r'[a-zA-Zа-яА-Я].*?\S'
CHANGES = r'\(изм\.\d{2}\))'
EXTENSION = r'\.[^.]+'
SEP = r'[\s_]'
DRAWING = re.compile(
f'^({DESIGNATION})' # обозначение ... |
cmusatyalab/opendiamond | opendiamond/blaster/__init__.py | #
# The OpenDiamond Platform for Interactive Search
#
# Copyright (c) 2012 Carnegie Mellon University
# All rights reserved.
#
# This software is distributed under the terms of the Eclipse Public
# License, Version 1.0 which can be found in the file named LICENSE.
# ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS S... |
OxPython/python_control_flow_if_or_operator | src/control_flow_if_or.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Jul 22, 2014
@author: anroco
How to use the or operator in an if statement of Python?
¿Cómo usar el operador or en una sentencia if de Python?
'''
#if expression1 or expression2 or expressionN:
# statements
#create two boolean objects
a = False
b = Fa... |
shadow-robot/sr_common | sr_description/mujoco_models/meshes/arm_and_hand_meshes/conversion.py | # Copyright 2019 Shadow Robot Company Ltd.
#
# 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 version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITH... |
ClaudiaEsp/inet | Fiji/curved_distances_.py | """
curved_distances.py
Jose Guzman, sjm.guzman@gmail.com
Claudia Espinoza, claudia.espinoza@ist.ac.at
Created: Mon Nov 20 18:13:47 CET 2017
This is an ImageJ-pluging writen in Jython. Jython is the Python
implementation to run the Java platform in ImageJ. Check
https://imagej.net/Jython_Scripting
It calculates... |
euclides5414/kaggle-allstate-purchase | conv.py |
states = {
'FL':36,
'NY':35,
'PA':34,
'OH':33,
'MD':32,
'IN':31,
'WA':30,
'CO':29,
'AL':28,
'CT':27,
'TN':26,
'KY':25,
'NV':24,
'MO':23,
'OR':22,
'UT':21,
'OK':20,
'MS':19,
'AR':18,
'WI':17,
'GA':16,
'NH':15,
'ME':14,
'NM':13,
'ID':12,
'RI':11,
'KS':10,
'WV':9,
'IA':8,
'DE':7,
'DC':6,
... |
morrillo/sale_taxes_report | __init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
Dr762/PythonExamples3.4 | Python2/indexer.py | from Queue import Queue
from threading import Thread
from test import pystone
import time
from cmd_profile import *
import subprocess
import logging
import os
import sys
__author__ = "alex"
__date__ = "$May 14, 2015 12:22:46 AM$"
# run python indexer.py zc.buildout-2.3.1-py.2.7.egg 1
# file indexer
dirname = os.path.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.