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 |
|---|---|---|---|---|---|
"""
=============================================
Comparison of kernel ridge regression and SVR
=============================================
Both kernel ridge regression (KRR) and SVR learn a non-linear function by
employing the kernel trick, i.e., they learn a linear function in the space
induced by the respective k... | IshankGulati/scikit-learn | examples/plot_kernel_ridge_regression.py | Python | bsd-3-clause | 6,289 |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import (assert_equal, assert_almost_equal,
assert_allclose)
from scipy.special import logit, expit
class TestLogit(object):
def check_logit_out(self, dtype, expected):
a = np.linspace(0,1,10)
... | mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/scipy/special/tests/test_logit.py | Python | mit | 2,911 |
#!/usr/bin/python
# $Id:$
# Play an audio file with DirectShow. Tested ok with MP3, WMA, MID, WAV, AU.
# Caveats:
# - Requires a filename (not from memory or stream yet). Looks like we need
# to manually implement a filter which provides an output IPin. Lot of
# work.
# - Theoretically can traverse the graph to... | sangh/LaserShow | pyglet-hg/experimental/directshow.py | Python | bsd-3-clause | 1,798 |
"""Utility routines depending on the finder,
a combination of code by Jack Jansen and erik@letterror.com.
Most events have been captured from
Lasso Capture AE and than translated to python code.
IMPORTANT
Note that the processes() function returns different values
depending on the OS version it is running on. On MacO... | teeple/pns_server | work/install/Python-2.7.4/Lib/plat-mac/findertools.py | Python | gpl-2.0 | 30,176 |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | unnikrishnankgs/va | venv/lib/python3.5/site-packages/tensorflow/contrib/keras/python/keras/utils/io_utils.py | Python | bsd-2-clause | 3,966 |
#!/usr/bin/env python
"""An zoomed image viewer that demonstrates Surface.scroll
This example shows a scrollable image that has a zoom factor of eight.
It uses the Surface.scroll function to shift the image on the display
surface. A clip rectangle protects a margin area. If called as a function,
the example accepts a... | JulienMcJay/eclock | windows/Python27/Lib/site-packages/pygame/examples/scroll.py | Python | gpl-2.0 | 6,792 |
# -*- coding: utf-8 -*-
#
# Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | endlessm/chromium-browser | tools/swarming_client/third_party/oauth2client/crypt.py | Python | bsd-3-clause | 8,519 |
"""Copyright 2008 Orbitz WorldWide
Copyright 2011 Chris Davis
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 ... | redice/graphite-web | webapp/graphite/render/hashing.py | Python | apache-2.0 | 3,188 |
"""
====================== 8< ============================
This file is an Hachoir parser template. Make a copy
of it, and adapt it to your needs.
You have to replace all "TODO" with you code.
====================== 8< ============================
TODO parser.
Author: TODO TODO
Creation date: YYYY-mm-DD
"""
# TODO:... | pwnieexpress/raspberry_pwn | src/pentest/metagoofil/hachoir_parser/template.py | Python | gpl-3.0 | 1,927 |
"""Tests for the AdGuard Home component."""
| fbradyirl/home-assistant | tests/components/adguard/__init__.py | Python | apache-2.0 | 44 |
class Foo(object):
bar = True
class FooMaker(object):
__call__ = tuple
fm = FooMaker()
f3 = fm()
f3.count() | asedunov/intellij-community | python/testData/completion/instanceFromCallableAssignedToCallAttr.after.py | Python | apache-2.0 | 118 |
#
# gdb helper commands and functions for Linux kernel debugging
#
# load kernel and module symbols
#
# Copyright (c) Siemens AG, 2011-2013
#
# Authors:
# Jan Kiszka <jan.kiszka@siemens.com>
#
# This work is licensed under the terms of the GNU GPL version 2.
#
import gdb
import os
import re
from linux import module... | gazoo74/linux | scripts/gdb/linux/symbols.py | Python | gpl-2.0 | 6,521 |
from django.conf import settings
from django.contrib.admin import ModelAdmin
from django.contrib.gis.admin.widgets import OpenLayersWidget
from django.contrib.gis.gdal import OGRGeomType
from django.contrib.gis.db import models
class GeoModelAdmin(ModelAdmin):
"""
The administration options class for Geographi... | ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.2/django/contrib/gis/admin/options.py | Python | bsd-3-clause | 5,095 |
# -*- coding: utf-8 -*-
"""
pygments.lexers.parsers
~~~~~~~~~~~~~~~~~~~~~~~
Lexers for parser generators.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, DelegatingLexer, \
include... | emineKoc/WiseWit | wisewit_front_end/node_modules/pygmentize-bundled/vendor/pygments/pygments/lexers/parsers.py | Python | gpl-3.0 | 25,805 |
#!/usr/bin/env python
#
# Copyright 2015 clowwindy
#
# 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 ... | warjiang/shadowsocks | tests/nose_plugin.py | Python | apache-2.0 | 1,164 |
import sys, os
# Delay import _tkinter until we have set TCL_LIBRARY,
# so that Tcl_FindExecutable has a chance to locate its
# encoding directory.
# Unfortunately, we cannot know the TCL_LIBRARY directory
# if we don't know the tcl version, which we cannot find out
# without import Tcl. Fortunately, Tcl will itself ... | leighpauls/k2cro4 | third_party/python_26/Lib/lib-tk/FixTk.py | Python | bsd-3-clause | 2,844 |
from OpenGL.GL import *
from .GLMeshItem import GLMeshItem
from .. MeshData import MeshData
from ...Qt import QtGui
import numpy as np
__all__ = ['GLSurfacePlotItem']
class GLSurfacePlotItem(GLMeshItem):
"""
**Bases:** :class:`GLMeshItem <pyqtgraph.opengl.GLMeshItem>`
Displays a surface plot on a r... | AOtools/soapy | soapy/pyqtgraph/opengl/items/GLSurfacePlotItem.py | Python | gpl-3.0 | 5,204 |
# -*- 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... | diogocs1/comps | web/addons/crm_claim/__openerp__.py | Python | apache-2.0 | 2,067 |
import re
from six.moves.urllib.parse import urljoin
from w3lib.html import remove_tags, replace_entities, replace_escape_chars
from scrapy.link import Link
from .sgml import SgmlLinkExtractor
linkre = re.compile(
"<a\s.*?href=(\"[.#]+?\"|\'[.#]+?\'|[^\s]+?)(>|\s.*?>)(.*?)<[/ ]?a>",
re.DOTALL | re.IG... | bdh1011/wau | venv/lib/python2.7/site-packages/scrapy/linkextractors/regex.py | Python | mit | 1,181 |
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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 3 of the License, or
# (at your option) an... | goozbach/ansible | lib/ansible/playbook/helpers.py | Python | gpl-3.0 | 4,255 |
import datetime
from django.conf import settings
from django.db.backends.util import truncate_name, typecast_date, typecast_timestamp
from django.db.models.sql import compiler
from django.db.models.sql.constants import MULTI
from django.utils import six
from django.utils.six.moves import zip, zip_longest
from django.u... | mariosky/evo-drawings | venv/lib/python2.7/site-packages/django/contrib/gis/db/models/sql/compiler.py | Python | agpl-3.0 | 14,014 |
import re
from django import forms
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.forms import formsets, ValidationError
from django.views.generic import TemplateView
from django.utils.datastructures import SortedDict
from django.utils.decorators import classonlymethod
f... | mariosky/evo-drawings | venv/lib/python2.7/site-packages/django/contrib/formtools/wizard/views.py | Python | agpl-3.0 | 28,430 |
def foo():
if xy<caret>
def xyzzy():
pass | asedunov/intellij-community | python/testData/completion/completeBeforeSyntaxError.py | Python | apache-2.0 | 50 |
from lib.hachoir_core.i18n import _
from lib.hachoir_core.tools import (
humanDuration, humanBitRate,
humanFrequency, humanBitSize, humanFilesize,
humanDatetime)
from lib.hachoir_core.language import Language
from lib.hachoir_metadata.filter import Filter, NumberFilter, DATETIME_FILTER
from datetime import ... | Branlala/docker-sickbeardfr | sickbeard/lib/hachoir_metadata/register.py | Python | mit | 7,003 |
"""
EFI Platform Initialization Firmware Volume parser.
Author: Alexandre Boeglin
Creation date: 08 jul 2007
"""
from hachoir_parser import Parser
from hachoir_core.field import (FieldSet,
UInt8, UInt16, UInt24, UInt32, UInt64, Enum,
CString, String, PaddingBytes, RawBytes, NullBytes)
from hachoir_core.endian... | pwnieexpress/raspberry_pwn | src/pentest/metagoofil/hachoir_parser/misc/pifv.py | Python | gpl-3.0 | 8,472 |
"""Miscellaneous functions for testing masked arrays and subclasses
:author: Pierre Gerard-Marchant
:contact: pierregm_at_uga_dot_edu
:version: $Id: testutils.py 3529 2007-11-13 08:01:14Z jarrod.millman $
"""
from __future__ import division, absolute_import, print_function
import operator
import numpy as np
from nu... | LumPenPacK/NetworkExtractionFromImages | win_build/nefi2_win_amd64_msvc_2015/site-packages/numpy/ma/testutils.py | Python | bsd-2-clause | 10,375 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class WorkstationWorkingHour(Document):
pass
| mahabuber/erpnext | erpnext/manufacturing/doctype/workstation_working_hour/workstation_working_hour.py | Python | agpl-3.0 | 281 |
import logging
import re
import sys
import time
import warnings
from contextlib import contextmanager
from functools import wraps
from unittest import skipIf, skipUnless
from xml.dom.minidom import Node, parseString
from django.apps import apps
from django.conf import UserSettingsHolder, settings
from django.core impo... | RossBrunton/django | django/test/utils.py | Python | bsd-3-clause | 20,636 |
"""
Tests for POSIX-compatible `echo`.
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html
"""
from helpers import check, check_version
def test_version():
"""Check that we're using Boreutil's implementation."""
# Can't test echo directly, since it ignores --version.
assert check_versio... | duckinator/boreutils | test/test_echo.py | Python | isc | 1,150 |
from socket import *
def myrecv(sock, msglen):
msg = ''
while len(msg) < msglen:
chunk = sock.recv(msglen-len(msg)) ... | khoteevnd/stepic | server.py | Python | mit | 2,149 |
# -*- coding: utf-8 -*-
from django.apps import AppConfig
VERSION = (0, 3, 0, 'beta', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
... | thrive-refugee/thrive-refugee | swingtime/__init__.py | Python | mit | 839 |
import os
import sys
from Bio import Seq
from Bio import SeqIO
from Bio import SeqRecord
import pandas as pd
import numpy as np
import ms_module as ms
import re
############################
from Bio import Entrez
from Bio import SeqIO
from StringIO import StringIO
import time
from urllib2 import HTTPError # for Python... | sergpolly/GlycoMadness | SILAC_stage2_assign_pulled_proteins.py | Python | mit | 10,886 |
"""Enumerate values specific to Structured Report IODs."""
from enum import Enum
class ValueTypeValues(Enum):
"""Enumerated values for attribute Value Type.
See :dcm:`Table C.17.3.2.1 <part03/sect_C.17.3.2.html#sect_C.17.3.2.1>`.
"""
CODE = 'CODE'
"""Coded expression of the concept."""
CO... | MGHComputationalPathology/highdicom | src/highdicom/sr/enum.py | Python | mit | 6,522 |
from multiprocessing import Process, Queue, Pool, cpu_count
from osgeo import ogr
import json
import csv
import ast
import time
import sys
from operator import itemgetter
from shapely.wkb import loads
def check_contains(shape_f,lon1,lat1,poly_name):
driver = ogr.GetDriverByName('ESRI Shapefile')
try:... | idl/Tweet_correlation | apply_polygons.py | Python | mit | 2,892 |
"""
onfido signals.
Signals are fired when corresponding callbacks are received.
See https://documentation.onfido.com/#webhooks
"""
from django.dispatch import Signal
# fired after the status of a report /check is updated
# e.g. (obj, 'report.completed', 'pending', 'complete')
# providing_args=["instance", "event",... | yunojuno/django-onfido | onfido/signals.py | Python | mit | 734 |
import twitter
import os
import sqlitedict
import requests
from bs4 import BeautifulSoup
import time
dbdict = sqlitedict.SqliteDict('tgt.db', autocommit=True)
api = twitter.Api(consumer_key=os.environ['TWITTER_CONSUMER_KEY'],
consumer_secret=os.environ['TWITTER_CONSUMER_SECRET'],
a... | mathisonian/twitter-github-trending | twitter-github-trending.py | Python | mit | 2,397 |
import sys
import os.path
#sys.path.insert(0, '/home/andy/theano/tool_examples/theano-lstm-0.0.15')
from theano_lstm import Embedding, LSTM, RNN, StackedCells, Layer, create_optimization_updates, masked_loss
from utilities import *
import dill
import argparse
#import cPickle
import pickle
import numpy
from collections... | darongliu/Lstm_Turing_LM | lstm-neural-turing-machines-lm/analysis/v1-one-weight-same-entropy/lm_v4.py | Python | mit | 26,033 |
__version__ = '9999'
| Ch00k/gun | gun/__init__.py | Python | mit | 21 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
author: Kaio Cesar
Email: tecnico.kaio@gmail.com
Exercicio da Lista I exercícios 3
Escreva um programa que leia a quantidade de dias, horas, minutos e segundos do usuário.
Calcule o total em segundos.
"""
dias=int(raw_input("Digite a quantidade d... | kaiocesar/Listasexerciciosppz | lista_1/exercicio_3.py | Python | mit | 661 |
import clodius.tiles.utils as hgut
import json
def tileset_info(df, x_column, y_column):
minx = df[x_column].min()
maxx = df[x_column].max()
miny = df[y_column].min()
maxy = df[y_column].max()
return {
"min_pos": [minx, miny],
"max_pos": [maxx, maxy],
"max_width": max(max... | hms-dbmi/clodius | clodius/tiles/points.py | Python | mit | 1,729 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: consume_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_consumer/pb/consume_url_resp_pb2.py | Python | mit | 2,715 |
'''
Wifi Facade.
=============
The :class:`Wifi` is to provide access to the wifi of your mobile/ desktop
devices.
It currently supports `connecting`, `disconnecting`, `scanning`, `getting
available wifi network list` and `getting network information`.
Simple examples
---------------
To enable/ turn on wifi scannin... | bhaveshAn/crisscross | crisscross/facades/wifi.py | Python | mit | 2,974 |
from flask import Flask, jsonify
from marshmallow import Schema, fields
from marshmallow_jsonschema import JSONSchema
app = Flask(__name__)
class UserSchema(Schema):
name = fields.String()
address = fields.String()
@app.route("/schema")
def schema():
schema = UserSchema()
return jsonify(JSONSchema(... | fuhrysteve/marshmallow-jsonschema | example/example.py | Python | mit | 1,368 |
from setuptools import setup
setup(name='parsing',
version='1.0.0',
author='Darren M. Struthers',
author_email='dstruthers@gmail.com',
py_modules=['parsing'],
description='Combinatorial parsing framework',
license='MIT',
tests_require=['pytest']
)
| dstruthers/python-parsing | setup.py | Python | mit | 297 |
from datetime import datetime
from unittest.mock import patch
import demistomock as demisto
import importlib
import Elasticsearch_v2
import pytest
from dateutil.parser import parse
import requests
import unittest
from unittest import mock
"""MOCKED RESPONSES"""
ES_V6_RESPONSE = {
'took': 1,
'timed_out': False... | VirusTotal/content | Packs/Elasticsearch/Integrations/Elasticsearch_v2/Elasticsearch_v2_test.py | Python | mit | 23,745 |
#!/usr/bin/env python
# coding=utf-8
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
ans = 0
def findTilt(self, root):
"""
:type root: TreeNode
... | xijunlee/leetcode | 563.py | Python | mit | 787 |
# 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/network/azure-mgmt-network/azure/mgmt/network/v2021_02_01_preview/models/_network_management_client_enums.py | Python | mit | 5,095 |
import _biopsy as B
import cPickle
sequences = B.SequenceVec()
sequences.append('acgt')
sequences.append('tttt')
sequences.append('gggg')
sequences_copy = cPickle.loads(cPickle.dumps(sequences))
for s, c in zip(sequences, sequences_copy):
assert s == c
| JohnReid/biopsy | C++/python_test/test_sequence_vec_pickle.py | Python | mit | 260 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('oj_core', '0009_auto_20150902_0258'),
]
operations = [
migrations.AlterField(
model_name='status',
n... | oj-development/oj-web | oj_core/migrations/0010_auto_20150902_1210.py | Python | mit | 388 |
# 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 ... | lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2015_06_15/models/ip_configuration.py | Python | mit | 2,913 |
"""
@author: dhoomakethu
"""
from __future__ import absolute_import, unicode_literals
import sys
import os
import time
from signal import SIGTERM
# http://code.activestate.com/recipes/66012-fork-a-daemon-process-on-unix/
def deamonize(stdout='/dev/null', stderr=None, stdin='/dev/null',
pidfile=None, st... | dhoomakethu/apocalypse | apocalypse/utils/deamonize.py | Python | mit | 3,630 |
"""Functions for interpolated version of the QCDF spectator scattering
corrections.
Rationale for this is that
a) The QCDF corrections are very small, in fact smaller than hadronic uncertainties
for most observables (except maybe isospin asymmetries)
b) They are very costly computing-wise as they involve numerical int... | flav-io/flavio | flavio/physics/bdecays/bvll/qcdf_interpolate.py | Python | mit | 1,739 |
from __future__ import absolute_import
from celery import Celery
from flask import Flask
from flask.ext.migrate import Migrate
def create_app(config='app.config.DevConfig'):
app = Flask(__name__)
app.config.from_object(config)
app.config.from_pyfile('settings.py')
from .models import db
# sqla... | artyomboyko/financial-api | src/app/__init__.py | Python | mit | 955 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-18 10:13
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('primus', '0010_auto_20160418_1155'),
]
operations = [
migrations.AlterField(... | sighill/shade_app | primus/migrations/0011_auto_20160418_1213.py | Python | mit | 814 |
# -*- coding:utf-8 -*-
"""
这个文件主要是提供:
1、通过case的id获取到最近的execute id
2、如果最近的execute id是空 就创建一个
"""
from datetime import datetime
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from django.views.generic import View
from django.core.exceptions import PermissionDenied
from utils.mixins ... | codelieche/webpts | projects/webptspy/apps/tcase/views/api.py | Python | mit | 4,177 |
#!/usr/bin/env python
from bottle import route, static_file, debug, run, get, redirect
from bottle import post, request
import os, re, inspect
import json
import psutil
import datetime
#enable bottle debug
debug(True)
# WebApp route path
routePath = '/RpiMonitor'
# get directory of WebApp (pyWebMOC.py's dir)
rootPat... | oopsmonk/rpi-monitor | web-server/rpi_monitor_web.py | Python | mit | 4,237 |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Frappe Technologies and contributors
# See license.txt
from __future__ import unicode_literals
import unittest
import frappe
test_dependencies = ['User', 'Connected App', 'Token Cache']
class TestTokenCache(unittest.TestCase):
def setUp(self):
self.token_cache = frap... | saurabh6790/frappe | frappe/integrations/doctype/token_cache/test_token_cache.py | Python | mit | 963 |
#!/usr/bin/python3
"""Copyright 2018-2020 Advanced Micro Devices, Inc.
Expand hipBLAS YAML test data file into binary Arguments records"""
import re
import sys
import os
import argparse
import ctypes
from fnmatch import fnmatchcase
try: # Import either the C or pure-Python YAML parser
from yaml import CLoader as ... | amcamd/hipBLAS | scripts/performance/blas/hipblas_gentest.py | Python | mit | 23,338 |
import numpy as np
from test.test_base import Test
from predictor import predict
from test.confusion_matrix import ConfusionMatrix
class KFoldTest(Test):
def __init__(self, examples, targets, n_folds=10):
super().__init__(examples, targets)
self.n_folds = n_folds
def split_examples(self):
... | MLNotWar/decision-trees-algorithm | src/test/k_folding.py | Python | mit | 1,225 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
from frappe.modules.export_file import export_to_files
class ModuleOnboarding(Document):
def on_update(self):
if frappe.conf... | mhbu50/frappe | frappe/desk/doctype/module_onboarding/module_onboarding.py | Python | mit | 1,376 |
# https://oj.leetcode.com/problems/lru-cache/
# 17 / 17 test cases passed.
# Design and implement a data structure for Least Recently Used (LRU) cache.
# It should support the following operations: get and set.
#
# get(key) - Get the value (will always be positive) of the key
# if the key exists in the cache, otherwise... | saruberoz/leetcode-oj | leetcode-solutions/python/lru_cache.py | Python | mit | 5,825 |
import random
import string
from datetime import datetime
_random_string_pool = string.ascii_lowercase + string.digits
def random_string(samples: str = _random_string_pool, length: int = 12) -> str:
"""
Generate a random string on specific length.
Args:
samples (str, optional): Random characters... | shapiromatron/bmds-server | bmds_server/common/utils.py | Python | mit | 570 |
"""
This module contains the implementation of the flow syntax for creating
event streams and signals
@author: Matt Pryor <mkjpryor@gmail.com>
"""
from pyutil import result
from pyreact.eventstream import EventStream as BaseEventStream
from pyreact.core import Reactor, Emitter
class EventStream(BaseEventStream, ... | mkjpryor/pyreact | pyreact/flow.py | Python | mit | 2,906 |
"""This scripts utilizes functions provided by lexer to build a PCFG grammar.
"""
import os, sys
import argparse
from helper import open_, load_dawg, check_resource, isascii
from pcfg.lexer_helper import Date, RuleSet, ParseTree
import honeyvault_config as hny_config
from honeyvault_config import MIN_COUNT
from pcfg.le... | rchatterjee/nocrack | newcode/buildPCFG.py | Python | mit | 4,063 |
import six
class SimpleModel(object):
def _json_to_obj(self, json_dict):
for key, val in six.iteritems(json_dict):
if hasattr(self, key):
setattr(self, key, val)
@classmethod
def from_json(cls, json_dict):
obj = cls()
obj._json_to_obj(json_dict)
... | jmvrbanac/lplight | lplight/models.py | Python | mit | 4,377 |
# Extracted from https://docs.python.org/3/library/decimal.html
from decimal import *
def pi():
"""Compute Pi to the current precision.
>>> print(pi())
3.141592653589793238462643383
"""
getcontext().prec += 2 # extra digits for intermediate steps
three = Decimal(3) # substitute "three=... | maniatic0/rasppi-printer | Utilities/decimalMath.py | Python | mit | 2,518 |
from unittest import TestCase
import mock
import time
from longshot import LongshotDevice, LongshotPathpoint
import requests
class TestRegistering(TestCase):
class FakeResponse(object):
def __init__(self, val):
self.val = val
self.status_code == 200 if val is not None else 500
... | smok-serwis/longshot-python | longshot/tests/test_test.py | Python | mit | 1,013 |
from catsql.database import Database
def connect(db, verbose=False, tables=None, columns=None):
return Database(db, verbose=verbose, tables=tables).query(columns=columns)
| paulfitz/catsql | catsql/__init__.py | Python | mit | 177 |
#!/usr/bin/env python
#
#pylint: disable=line-too-long,invalid-name,missing-docstring,redefined-outer-name,too-many-arguments,too-many-locals,too-many-statements,logging-format-interpolation
#
import os
import sys
import time
import json
import subprocess
import logging as log
def setup_logging(loglevel=log.INFO):
... | pantheon-systems/docker_iptables | docker_iptables.py | Python | mit | 11,580 |
# -*- coding: utf-8 -*-
# ProjectEuler/src/python/problem375.py
#
# Minimum of subsequences
# =======================
# Published on Saturday, 10th March 2012, 10:00 pm
#
# table.p375 td { padding: 0px 3px 0px 3px; vertical-align: bottom;
# text-align: left; } Let Sn be an integer sequence produced with the
#... | olduvaihand/ProjectEuler | src/python/problem375.py | Python | mit | 711 |
import signal, time, sys, glob, os, codecs, pybonjour, atexit, tornado
import inflection, copy, types
# Infastructure
from event_emitter import EventEmitter
from print_job_queue import PrintJobQueue
# Routes
from construct_socket_handler import ConstructSocketHandler
from construct_job_upload_handler import ConstructJ... | eldir/construct_server.py | construct_server/construct_server.py | Python | mit | 8,591 |
import os
app_config = {}
keys = ['heroku',
'devid',
'discord_token',
'cryptokey',
'database',
'whitelistedbots']
if os.getenv('heroku'):
for k in keys:
app_config[k] = os.getenv(k)
else:
import json
with open('config/config.json') as data_file:
app... | fp12/pyChallongeDiscordBot | src/config.py | Python | mit | 351 |
#!/usr/bin/env python
"""
This file includes basic helper functions.
"""
from __future__ import division, print_function
import numpy as np
import matplotlib.colors as colors
def assignNestedItem(lst, index, value):
"""
Assign a value to an item of an arbitrarily nested list. The list is manipulated inplace.... | christophmark/bayesloop | bayesloop/helper.py | Python | mit | 4,484 |
#!/usr/bin/python
from __future__ import absolute_import
from __future__ import print_function
import os
import time
import sys
import logging
import socket
from apiclient import errors as api_errors, http as api_http
logger = logging.getLogger(__name__)
def get_file_data(service, filename, folder_id=None):
""... | TheGU/gdrive-upload | gdrive_upload/gdrive_uploader.py | Python | mit | 7,724 |
from datetime import datetime
import uuid
from tracking_async import set_warning_async, register_event_async
from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.conf import settings
import json
from django.core.signing import Signer, BadSignature
from signals import user_tracking_event_... | joebos/django-user-tracking | usertracking/tracking.py | Python | mit | 5,369 |
"""
Given a formula in conjunctive normal form (2-CNF), finds a way to assign
True/False values to all variables to satisfy all clauses, or reports there
is no solution.
https://en.wikipedia.org/wiki/2-satisfiability
Format:
- each clause is a pair of literals
- each literal in the form (name, is_neg... | keon/algorithms | algorithms/graph/satisfiability.py | Python | mit | 4,076 |
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'openlc.views.home', name='home'),
# url(r'^blog/', include('blog.urls'))... | Astrogel/test | openlc/openlc/urls.py | Python | mit | 763 |
# Copyright (C) 2013-2015 MetaMorph Software, Inc
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this data, including any software or models in source or binary
# form, as well as any drawings, specifications, and documentation
# (collectively "the Data"), to deal in the Data ... | pombredanne/metamorphosys-desktop | metamorphosys/META/src/JobManager/get_workspace_zip_from_swift.py | Python | mit | 4,095 |
"""Pythontutor: http://goo.gl/6JvdZc"""
class DistanceChecker:
def __init__(self, delta, points):
self.delta = delta
self.points = sorted(points)
self.validDistances = self.count_valid_distances()
def count_valid_distances(self):
validPoints = 1
ref = self.points.pop(0... | obestwalter/pet | unfinished/examples/count-distances/bid_counting_simple.py | Python | mit | 1,035 |
#Something tells me it won't be this simple....based on number size....
#If it's not....
#Maybe I only need to add up the beginnings of the numbers
#How many extra digits would I need?
#How long does it take for "carrying" to propagate?
#We are adding numbers 100 times, after all....
def get_nums_from_file(file_name... | ctlewitt/Project-Euler | prob13-large_sum.py | Python | mit | 877 |
# Based on code from: https://github.com/j4cbo/j4cDAC/blob/master/tools/tester/talk.py
import dac
from itertools import combinations
import math
import sys
from leapyosc import client
from leapyosc.client import (BaseLeapListener, RealPartTrackerMixin,
BundledMixin, LinearScalingMixin, OSCLeapList... | topher515/laser-fingers | leaplaser.py | Python | mit | 14,168 |
# -*- coding: utf-8 -*-
import os
import shutil
import cv2
import glob
ROOT = os.path.abspath(os.path.dirname(__file__))
SRCDIR = ROOT.replace("src/yamashita/preprocessing", "data/rugby/goromaru/raw_goromaru/")
TARDIR = ROOT.replace("src/yamashita/preprocessing", "data/rugby/goromaru/pre_goromaru/")
NODIR = ROOT.repl... | yossan4343434/TK_15 | src/yamashita/preprocessing/capture_face.py | Python | mit | 1,798 |
# sigtools - Collection of Python modules for manipulating function signatures
# Copyright (C) 2013-2021 Yann Kaiser
#
# 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, inc... | epsy/sigtools | sigtools/tests/test_combination.py | Python | mit | 2,635 |
# coding: utf-8
def f_pass():
pass
#$ header fi(int, int) results(int)
def fi(x, n=5):
y = x+1+n
return y
#$ header function fd(double, double) results(double)
def fd(u,v):
t = u - v
return t
#$ header g(double, double) results(double, double)
def g(x,v):
m = x - v
t = 2.0 * m
z = ... | ratnania/pyccel | src_old/tests/scripts/core/ex5.py | Python | mit | 548 |
import dummyserial
class VjDummySerial(dummyserial.Serial):
def __init__(self, port):
super(VjDummySerial, self).__init__(port=port)
def isOpen(self):
return self._isOpen
| j-be/vj-control-server | vjdummyserial.py | Python | mit | 180 |
#!/usr/bin/env python
#-*-Mode:python;coding:utf-8;tab-width:4;c-basic-offset:4;indent-tabs-mode:()-*-
# ex: set ft=python fenc=utf-8 sts=4 ts=4 sw=4 et nomod:
#
# MIT License
#
# Copyright (c) 2017-2021 Michael Truog <mjtruog at protonmail dot com>
#
# Permission is hereby granted, free of charge, to any person obtain... | CloudI/CloudI | src/tests/count/count.py | Python | mit | 3,260 |
import lacuna.bc
import lacuna.building
import lacuna.ship
class policestation(lacuna.building.MyBuilding):
path = 'policestation'
def __init__( self, client, body_id:int = 0, building_id:int = 0 ):
super().__init__( client, body_id, building_id )
@lacuna.building.MyBuilding.call_returning_meth... | tmtowtdi/MontyLacuna | lib/lacuna/buildings/ss_modules/policestation.py | Python | mit | 4,663 |
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
count = 0
for word in words:
flag = True
for char in word:
if char not in allowed:
flag = False
break
if flag is True:... | AHJenin/acm-type-problems | leetcode/AC/Easy/count-the-number-of-consistent-strings.py | Python | mit | 370 |
#!/usr/bin/python
import json
# import collections
jsonFile='data.json'
with open(jsonFile,'r') as inputFile:
data = json.load(inputFile)
print "%d accidents in %s" % (len(data),jsonFile)
types = []
typesAndCount = []
for accident in data:
industry = accident['Province']
if industry in types:
... | ArtezGDA/MappingTheCity-Data | ChinaIndustryAccidents/oefening3.py | Python | mit | 765 |
import os.path
from click.testing import CliRunner
from fio_metasay.scripts.cli import metasay
def test_cli_crs():
filename = os.path.join(os.path.dirname(__file__), 'data/coutwildrnp.geojson')
runner = CliRunner()
result = runner.invoke(metasay, [filename, '--item', 'crs'])
assert result.exit_code ... | geowurster/fio-plugin-example | tests/test_cli.py | Python | mit | 393 |
import _plotly_utils.basevalidators
class ValueValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="value",
parent_name="scattergeo.marker.colorbar.tickformatstop",
**kwargs
):
super(ValueValidator, self).__init__(
plotly... | plotly/plotly.py | packages/python/plotly/plotly/validators/scattergeo/marker/colorbar/tickformatstop/_value.py | Python | mit | 462 |
def fazAlgo(string):
pos = len(string)-1
stringMi = string.lower()
string = string.upper()
stringRe = ""
while pos >= 0:
if string[pos] == 'A' or string[pos] == 'E' or string[pos] == 'I' or string[pos] == 'O' or string[pos] == 'U':
stringRe = stringRe + string[pos]
else:
... | marcelomiky/PythonCodes | Coursera/CICCP2/trataString.py | Python | mit | 632 |
'''
The MIT License (MIT)
Copyright (c) 2016 Nordeus LLC
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, copy, modify, merge, p... | korhner/pushkin | pushkin/sender/nordifier/constants.py | Python | mit | 1,812 |
#!/usr/bin/env python
# author: brendan@shellshockcomputer.com.au
import ConfigParser
from bottle import route, install, run, template, static_file, response, PasteServer, post, get, request, debug
from bottle_sqlite import SQLitePlugin
import json
import urllib
import urllib2
import datetime
import math
config = C... | NeXTHorizon/nhzpool | webserver.py | Python | mit | 8,712 |
#
# -*- coding: utf-8 -*-
#
# Copyright (c) 2007 Jared Crapo
#
# 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, copy, mod... | kotfu/tomcat-manager | src/tomcatmanager/tomcat_manager.py | Python | mit | 26,817 |
import os
from django.db import migrations
def add_timeslots(apps, schema_editor):
Region = apps.get_model('app', 'Region')
WeeklyTimeSlot = apps.get_model('app', 'WeeklyTimeSlot')
timeslots = list(WeeklyTimeSlot.objects.all())
regions = Region.objects.filter(opened=True)
for region in regions:... | malaonline/Server | server/app/migrations/0030_add_timeslots.py | Python | mit | 624 |
from Framework.Pedido import Pedido
from Framework.ErroNoHTTP import ErroNoHTTP
class PedidoEditar(Pedido):
def __init__(self,variaveis_do_ambiente):
super(PedidoEditar, self).__init__(variaveis_do_ambiente)
try:
self.id = self.corpo['id']
self.codigo = self.corpo['codigo']
self.id_resp_sala = self.corp... | AEDA-Solutions/matweb | backend/Models/Sala/PedidoEditar.py | Python | mit | 607 |
from distutils.core import setup
setup(
name='python-pentabarf-xml',
packages=['pentabarf'],
version='0.20',
description='Generate pentabarf XML schedule for events/conferences',
author='Niranjan Rajendran',
author_email='niranjan94@yahoo.com',
url='https://github.com/niranjan94/python-pent... | niranjan94/python-pentabarf-xml | setup.py | Python | mit | 523 |
# vim: set fileencoding=utf-8
import app_specific
import time
def get_time_offset(t):
"""
Given a local time, return the floating number of hours that one needs to
add to UTC time to get the original one back. For instance, in France
during summer:
UTC: 20:50
local: 22:50
return: 2.0
... | daureg/ajoissa | Activity.py | Python | mit | 3,273 |
#!/usr/bin/env python
#
# Copyright (C) 2014 Dustin Fraze <df@cromulence.co>
#
from generator.actions import Actions
import random
class Contact():
first = ""
def genderToStr(self):
return {"M":"Male","F":"Female","T":"Trans-Gender"}.setdefault(self.gender, "Other")
def __init__(self, first=None, last=None, p... | f0rki/cb-multios | original-challenges/yolodex/poller/for-release/machine.py | Python | mit | 10,232 |