repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
ForceBru/PyVM | test_memory.py | import unittest
import os
import ctypes
from VM.Memory import Memory
class TestMemory(unittest.TestCase):
MEM_SIZE = 512
MAX_RANDOM_REPEAT = 10_000
def setUp(self):
self.mem = Memory(self.MEM_SIZE)
self.random_data = os.urandom(self.MEM_SIZE)
ctypes.memmove(self.mem.mem, self.ra... |
google-research/accelerated_gbm | solve_libsvm_instances.py | # Copyright 2020 The Google Authors. All Rights Reserved.
#
# Licensed under the MIT License (the "License");
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN... |
wolfiex/ipython-dev-reload | setup.py | from setuptools import setup
def readme():
with open('README.md') as f:
return f.read()
## test with python setup.py develop
setup(
name='ipyreload',
packages=['ipyreload'],
version= 1.2,
description='ipython productivity tools',
long_description=readme(),
url="https:/... |
Astutech/Pushwoosh-Python-library | setup.py | """A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.absp... |
AthosOrg/athos-core | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
# get requirements.txt
with open('requirements.txt') as f:
required = f.read().splitlines()
setup(name='athos-core',
description = 'Athos project core',
url = 'https://github.com/AthosOrg/',
packages = find_packages(),
entry_points... |
rosudrag/Freemium-winner | VirtualEnvironment/Lib/site-packages/nose/config.py | import logging
import optparse
import os
import re
import sys
import configparser
from optparse import OptionParser
from nose.util import absdir, tolist
from nose.plugins.manager import NoPlugins
from warnings import warn, filterwarnings
log = logging.getLogger(__name__)
# not allowed in config files
option_blacklist... |
AutorestCI/azure-sdk-for-python | azure-graphrbac/azure/graphrbac/models/domain.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 ... |
adamcaudill/yawast | yawast/scanner/plugins/http/servers/rails.py | # Copyright (c) 2013 - 2020 Adam Caudill and Contributors.
# This file is part of YAWAST which is released under the MIT license.
# See the LICENSE file or go to https://yawast.org/license/ for full license details.
import re
from typing import List
from yawast.reporting.enums import Vulnerabilities
from yawast.sc... |
ckolumbus/mikidown | setup.py | from distutils import log
from distutils.core import setup
from distutils.command.build import build
from distutils.command.install_scripts import install_scripts
import glob
import sys
from mikidown.config import __version__
class miki_build(build):
def run(self):
# Check the python version
try:
... |
5nizza/party-elli | helpers/main_helper.py | import logging
import os
import sys
from typing import List
from logging import FileHandler
from synthesis.z3_via_files import Z3NonInteractiveViaFiles, FakeSolver
from synthesis.z3_via_pipe import Z3InteractiveViaPipes
from third_party.ansistrm import ColorizingStreamHandler
from interfaces.solver_interface import Sol... |
napjon/moocs_solution | robotics-udacity/1.3.py | p=[0.2,0.2,0.2,0.2,0.2]
world=['green', 'red', 'red', 'green', 'green']
measurements = ['red','green']
Z = 'red'
pHit = 0.6
pMiss = 0.2
def sense(p, Z):
q=[]
for i in range(len(p)):
hit = (Z == world[i]) #hit return zero if false
q.append(p[i] * (hit * pHit + (1-hit) * pMiss)) #if hi... |
danhuss/faker | faker/providers/ssn/en_PH/__init__.py | from ... import BaseProvider
class Provider(BaseProvider):
"""
Provider for Philippine IDs that are related to social security
There is no unified social security program in the Philippines. Instead, the Philippines has a messy collection of
social programs and IDs that, when put together, serves as ... |
stonewell/pymterm | pymterm/term_pylibui/main.py | #coding=utf-8
import json
import logging
import os
from pylibui.core import App
from pylibui.controls import Window, Tab, OpenGLArea
import cap.cap_manager
from session import create_session
from term import TextAttribute, TextMode, reserve
import term.term_keyboard
from term.terminal_gui import TerminalGUI
from term... |
Seeed-Studio/Grove-RaspberryPi | Grove - Ultrasonic Ranger/ultrasonic.py | #!/usr/bin/env python
"""
* ultrasonic.py
* A library for ultrasonic sensor at RP
*
* Copyright (c) 2012 seeed technology inc.
* Website : www.seeed.cc
* Author : seeed fellow
* Create Time:
* Change Log :
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtai... |
jdavidrcamacho/Tests_GP | 02 - Programs being tested/05 - opt initial tests/Tests1_Kernel_opt.py | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 14 14:49:00 2017
@author: camacho
"""
import Kernel;reload(Kernel);kl=Kernel
import Kernel_likelihood;reload(Kernel_likelihood);lk=Kernel_likelihood
import Kernel_optimization;reload(Kernel_optimization);opt=Kernel_optimization
import RV_function;reload(RV_function);RVf... |
icyblade/pynga | setup.py | from setuptools import setup
about = {}
with open('./pynga/__version__.py', 'r') as f:
exec(f.read(), about)
with open('README.md', 'r') as f:
readme = f.read()
tests_require = [
'pytest>=3.5.0,<3.7.0',
'pytest-flake8>=1.0.0'
]
setup(
name=about['__title__'],
version=about['__version__'],
... |
pat-coady/trpo | trpo/utils.py | """
Logging and Data Scaling Utilities
Written by Patrick Coady (pat-coady.github.io)
"""
import numpy as np
import os
import shutil
import glob
import csv
class Scaler(object):
""" Generate scale and offset based on running mean and stddev along axis=0
offset = running mean
scale = 1 / (stddev ... |
bhylak/trello_things3_sync | tasks/sync_task.py | from task import Task
class SyncTask(Task):
def __init__(self, *remotes):
'''Init this task with all of the remote tasks'''
super(SyncTask, self).__init__()
self.remote_tasks = []
for arg in remotes:
print arg
self.remote_tasks.append(arg)
for tas... |
michelp/xodb | xodb/xaql.py | import pyparsing
"""
The query language that won't die.
Syntax:
Typical search engine query language, terms with boolean operators
and parenthesized grouping:
(term AND (term OR term OR ...) AND NOT term ...)
In it's simplest case, xaql searches for a list of terms:
term term term ...
... |
huyphan/pyyawhois | test/record/parser/test_response_whois_nic_fr_tf_status_available.py |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.nic.fr/tf/status_available
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parser import pars... |
lgaborini/decathlon_review_scraper | decathlon_scrapy/items.py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy_djangoitem import DjangoItem
# To get your settings from (settings.py):
from scrapy.utils.project import get_project_settings
settings = get_project_setti... |
tapasweni-pathak/Horoscope-API | server.py | from flask import Flask, jsonify
from pyhoroscope import Horoscope
from flask_cors import CORS
app = Flask (__name__)
CORS(app)
############################################
# Index
############################################
@app.route ('/', methods=['GET'])
def index_route () :
return jsonify({
'author' : '... |
godaddy/Thespian | thespian/system/utilis.py | from datetime import datetime, timedelta
import logging
import os
import tempfile
from thespian.actors import InvalidActorSpecification
###
### Logging
###
# Default/current logging controls
_thesplog_control_settings = (
logging.INFO,
False,
os.getenv('THESPLOG_FILE_MAXSIZE', 50 * 1024) # 50KB by defau... |
sotondriver/Lego_classification | Lego/extend.py | import os
import numpy as np
import cv2
import Levenshtein
temp_count = 1
train_box = 0
train_box_logo = 1
temp_img = None
predict_list = np.zeros((1, 5), dtype='float32')
count = 1
def denoise_info(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# _, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY... |
sgabe/Enumerator | enumerator/lib/nmap.py | #!/usr/bin/env python
"""This module is the first
step in gathering initial
service enumeration data from
a list of hosts. It initializes
the scanning commands and parses
the scan results. The scan results
are then passed to the delegator
module which determines what enumerator
should do next.
@author: Steve Coward (s... |
bdaroz/the-blue-alliance | tests/models_tests/notifications/test_event_level.py | from datetime import datetime
import unittest2
from google.appengine.ext import ndb
from google.appengine.ext import testbed
from consts.notification_type import NotificationType
from helpers.event.event_test_creator import EventTestCreator
from models.team import Team
from models.notifications.event_level import Ev... |
CARocha/sitioreddes | envivo/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Envivo'
db.create_table(u'envivo_envivo', (
(... |
donkeysharp/elvispy | elvis/climanager.py | import os
def create_peanut(peanut_name):
peanut_dir = './peanuts/%s' % peanut_name
if os.path.exists(peanut_dir):
print('Peanut already exists')
return
os.mkdir(peanut_dir)
os.mkdir(peanut_dir + '/templates')
f = open(peanut_dir + '/__init__.py', 'w')
f.write('')
f.flush()... |
thedeadparrot/ficbot | twitterbot.py | from __future__ import print_function
from twython import Twython
import util
class TwitterBot(util.SocialMediaBot):
""" Social Media Bot for posting updates to Tumblr """
NAME = "twitter"
def __init__(self, **kwargs):
super(TwitterBot, self).__init__(**kwargs)
self.client = Twython(*sel... |
prestontimmons/project-15053 | project_15053/urls.py | from django.conf.urls import url
from django.shortcuts import render
from django.template.response import TemplateResponse
def syntax_error(request):
return TemplateResponse(
request, "syntax.html", {"coconuts": lambda: 42 / 0},
)
def template_strings(request):
return TemplateResponse(
r... |
wonghoifung/learning-python | spider/spider_url_consumer/pb/consume_url_req_pb2.py | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: consume_url_req.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 a... |
finnss/ttm4115-server | webserver/webapp/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-31 00:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operation... |
liuxu0703/lx_bash_script | android_script/keyword_manager.py | #!/usr/bin/python
# AUTHOR : liuxu-0703@163.com
# used to extract keyword sets from xml
# used by aplog_helper.sh and adblogcat.sh
import os
import sys
import getopt
from xml.dom.minidom import parse, parseString
#=======================================
class KeywordSet:
def __init__(self, xml_node):
... |
shurain/archiver | archiver/sink.py | # -*- coding: utf-8 -*-
import hashlib
import binascii
from thrift.transport.THttpClient import THttpClient
from thrift.protocol.TBinaryProtocol import TBinaryProtocol
from evernote.edam.userstore import UserStore
from evernote.edam.notestore import NoteStore
import evernote.edam.type.ttypes as Types
import evernote.... |
Phonemetra/TurboCoin | test/functional/interface_rpc.py | #!/usr/bin/env python3
# Copyright (c) 2018-2019 TurboCoin
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Tests some generic aspects of the RPC interface."""
from test_framework.authproxy import JSONRPCException
from test_fram... |
MooseDojo/apt2 | modules/action/exploit_responder.py | import datetime
import os
from core.actionModule import actionModule
from core.utils import Utils
from core.keystore import KeyStore as kb
class exploit_responder(actionModule):
def __init__(self, config, display, lock):
super(exploit_responder, self).__init__(config, display, lock)
self.title = "... |
pinax/pinax-likes | pinax/likes/templatetags/pinax_likes_tags.py | from django import template
from django.contrib.contenttypes.models import ContentType
from django.template import loader
from django.template.loader import render_to_string
from ..conf import settings
from ..models import Like
from ..utils import _allowed, widget_context
register = template.Library()
@register.sim... |
krother/maze_run | 10_test_suite/maze_run/load_tiles.py |
from pygame import image, Rect, Surface
TILE_POSITIONS = [
('#', 0, 0), # wall
('o', 1, 0), # crate
(' ', 0, 1), # floor
('x', 1, 1), # exit
('.', 2, 0), # dot
('*', 3, 0), # player
]
SIZE = 32
def get_tile_rect(x, y):
"""Converts tile indices to a pygame.Rect"""
return Rect(x ... |
yandexdataschool/gumbel_lstm | gumbel_softmax.py | # -*- coding: utf-8 -*-
"""
a bunch of lasagne code implementing gumbel softmax
https://arxiv.org/abs/1611.01144
"""
import numpy as np
import theano
import theano.tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from lasagne.random import get_rng
from lasagne.layers import Layer
clas... |
okfn/datapackage-validate-py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import io
from setuptools import setup, find_packages
description = (
'(DEPRECATED) A Python library to validate Data Package datapackage.json'
' files.'
... |
mozman/ezdxf | tests/test_04_dxf_high_level_structs/test_414_block_reference_content.py | # Copyright (c) 2020-2021, Manfred Moitzi
# License: MIT License
from typing import cast, Union, List
import pytest
import ezdxf
import math
from ezdxf.entities import Ellipse, Point, Arc, DXFEntity, Insert
from ezdxf.math import Vec3
@pytest.fixture(scope="module")
def doc():
d = ezdxf.new()
blk = d.blocks... |
kbase/metrics | source/custom_scripts/dump_query_results.py | #!/usr/local/bin/python
import os
import mysql.connector as mysql
metrics_mysql_password = os.environ["METRICS_MYSQL_PWD"]
sql_host = os.environ["SQL_HOST"]
metrics = os.environ["QUERY_ON"]
def dump_query_results():
"""
It is a simple SQL table dump of a given query so we can supply users with custom tables... |
tjfontaine/linode-python | linode/api.py | #!/usr/bin/python
# vim:ts=2:sw=2:expandtab
"""
A Python library to perform low-level Linode API functions.
Copyright (c) 2010 Timothy J Fontaine <tjfontaine@gmail.com>
Copyright (c) 2010 Josh Wright <jshwright@gmail.com>
Copyright (c) 2010 Ryan Tucker <rtucker@gmail.com>
Copyright (c) 2008 James C Sinclair <james@irg... |
mcueto/djangorestframework-auth0 | rest_framework_auth0/authentication.py | import logging
from django.contrib.auth.backends import (
RemoteUserBackend,
get_user_model,
)
from django.contrib.auth.models import (
Group,
)
from django.utils.translation import ugettext as _
from rest_framework import exceptions
from rest_framework_auth0.settings import (
auth0_api_settings,
)
fro... |
dcf21/4most-4gp | src/pythonModules/fourgp_pipeline/fourgp_pipeline/pipeline.py | # -*- coding: utf-8 -*-
"""
The `Pipeline` class represents a pipeline which runs a sequence of tasks for analysing spectra. By defining new
descendents of the PipelineTask class, and appending them to a Pipeline, it is
possible to configure which 4GP classes it uses to perform each task within the
pipeline -- e.g. d... |
shacknetisp/vepybot | plugins/protocols/irc/auth/nickserv.py | # -*- coding: utf-8 -*-
import bot
import time
"""
load irc/auth/nickserv
nickserv set password hunter2
config set modules.nickserv.enabled True
config set modules.nickserv.ghost True
nickserv register email@do.main
nickserv verify register myaccount c0d3numb3r
nickserv identify
"""
class M_NickServ(bot.Module):
... |
mapattacker/cheatsheets | python/pyspark.py | import findspark #pyspark can't be detected if file is at other folders than where it is installed
findspark.init('/home/jake/spark/spark-2.2.0-bin-hadoop2.7')
## 1) SPARK DATAFRAME
#--------------------------------------------------------
from pyspark.sql import SparkSession
from pyspark.sql.functions import ... |
CristianCantoro/wikidump | wikidump/__main__.py | """Main module that parses command line arguments."""
import os
import io
import bz2
import gzip
import sys
import codecs
import argparse
import subprocess
import mw.xml_dump
import mwxml
import pathlib
from typing import IO, Optional, Union
from . import processors, utils
def open_xml_file(path: Union[str, IO]):
... |
fizz-ml/pytorch-aux-reward-rl | replay_buffer.py | import numpy as np
import random
class ReplayBuffer:
""" Buffer for storing values over timesteps.
"""
def __init__(self):
""" Initializes the buffer.
"""
pass
def batch_sample(self, batch_size):
""" Randomly sample a batch of values from the buffer.
"""
... |
tonyganchev/maven-deps | setup.py | #!/usr/bin/env python
# from distutils.core import setup
from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
import mavendeps
__author__ = 'Tony Ganchev'
class Tox(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_a... |
tintoy/seqlog | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'python_dateutil>=2.5.3',
'requests>=2.10.0',
'PyYAML>=3.11',
]
... |
msempere/yacontracts | src/yacontracts.py | """YAContrac module
"""
import inspect
from types import FunctionType, ListType, TupleType, StringType
def exec_validator(value, validator, error_message):
"""Run validation
Checks value against validator and returns error_message
in case of failure as a ValueError
"""
if not validator(value):
... |
mstepniowski/pygadu | pygadu/const.py | # -*- coding: utf-8 -*-
#
# 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, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be u... |
HuuHoangNguyen/Python_learning | Tuples.py | #!/usr/bin/python
# The list are enclosed in brackets ([]) and their element
# and size can be changed, while tuples are enclosed in parenthese
# ( () ) and cannot be updated. The Tuples can be thought of as
# read-only of list
aTuple = ( 'abcd', 786, 2.23, 'John', 70.2)
bTuple = ( 123, 'Vien')
print aTuple ... |
Lucasfeelix/ong-joao-de-barro | accounts/models.py | # coding=utf-8
import re
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, UserManager
from django.contrib.auth.models import PermissionsMixin
from django.core import validators
class User(AbstractBaseUser, PermissionsMixin):
'''
Modelo para sobreescrever o admin do Django.... |
htwenhe/DJOA | env/Lib/site-packages/openpyxl/writer/workbook.py | from __future__ import absolute_import
# Copyright (c) 2010-2017 openpyxl
"""Write the workbook global settings to the archive."""
from copy import copy
from openpyxl.utils import absolute_coordinate, quote_sheetname
from openpyxl.xml.constants import (
ARC_APP,
ARC_CORE,
ARC_WORKBOOK,
PKG_REL_NS,
... |
Azure/azure-sdk-for-python | sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_tags_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 ... |
chiubaka/serenity | server/api/migrations/0004_task_due_date.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-09 02:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0003_task_inbox'),
]
operations = [
migrations.AddField(
... |
BenaroyaResearch/bripipetools | bripipetools/postprocessing/stitching.py | """
Combine parsed data from a set of batch processing output files and write to a
single CSV file.
"""
import logging
import os
import re
import csv
import pandas as pd
from .. import io
from .. import parsing
from .. import util
logger = logging.getLogger(__name__)
class OutputStitcher(object):
"""
Given... |
simpeg/discretize | discretize/utils/code_utils.py | import numpy as np
import warnings
SCALARTYPES = (complex, float, int, np.number)
def is_scalar(f):
"""Determine if the input argument is a scalar.
The function **is_scalar** returns *True* if the input is an integer,
float or complex number. The function returns *False* otherwise.
Parameters
-... |
timrchavez/capomastro | jenkins/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'JenkinsServer'
db.create_table(u'jenkins_jenkinsserver', ... |
wright-group/WrightTools | WrightTools/artists/_interact.py | """Interactive (widget based) artists."""
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, RadioButtons
from types import SimpleNamespace
from ._helpers import create_figure, plot_colorbar, add_sideplot
from ._base import _order_for_imshow
from ._color... |
jimmysong/bitcoin | test/functional/test_framework/mininode.py | #!/usr/bin/env python3
# Copyright (c) 2010 ArtForz -- public domain half-a-node
# Copyright (c) 2012 Jeff Garzik
# Copyright (c) 2010-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Bitcoin P2P ... |
bouk/redshift_sqlalchemy | tests/test_copy_command.py | import pytest
import re
import sqlalchemy as sa
from redshift_sqlalchemy.dialect import CopyCommand, RedshiftDialect
def clean(query):
return re.sub(r'\s+', ' ', query).strip()
def quote(s):
return "'%s'" % s
def compile_query(q):
return str(q.compile(dialect=RedshiftDialect(),
... |
mehulsbhatt/phone-iso3166 | phone_iso3166/e212.py | # Generated by get_e212.py
# Based on https://www.itu.int/pub/T-SP-E.212B-2014
networks = \
{202: 'GR',
204: 'NL',
206: 'BE',
208: 'FR',
213: 'AD',
214: 'ES',
216: 'HU',
218: 'BA',
219: 'HR',
220: 'RS',
222: 'IT',
226: 'RO',
228: 'CH',
230: 'CZ',
231: 'SK',
232: 'AT',
234: 'GB',
235: 'GB',
238: 'DK',... |
maroy/TSTA | cse-581-project-2/src/extract_keywords.py | import re
import json
import sqlite3
import nltk
stop = nltk.corpus.stopwords.words("english")
stop.append('rt')
contractions = []
with open('contractions.txt', 'rb') as f:
contractions = [c.strip() for c in f.readlines()]
lemmatizer = nltk.stem.wordnet.WordNetLemmatizer()
tokenizer = nltk.tokenize.... |
steven-cutting/latinpigsay | test.py | # -*- coding: utf-8 -*-
__title__ = 'latinpigsay'
__license__ = 'MIT'
__author__ = 'Steven Cutting'
__author_email__ = 'steven.c.projects@gmail.com'
__created_on__ = '12/7/2014'
if __name__ == "__main__":
from tests import testscript as ts
from tests import contstests
from latinpigsay.tmp.experiments impor... |
cemsbr/python-openflow | pyof/v0x01/common/utils.py | """Helper python-openflow functions."""
# System imports
# Third-party imports
# Local source tree imports
# Importing asynchronous messages
from pyof.v0x01.asynchronous.error_msg import ErrorMsg
from pyof.v0x01.asynchronous.flow_removed import FlowRemoved
from pyof.v0x01.asynchronous.packet_in import PacketIn
from ... |
msullivan/advent-of-code | 2018/8a.py | #!/usr/bin/env python3
import sys
from collections import defaultdict, deque
from dataclasses import dataclass
@dataclass
class Nobe:
children: object
metadata: object
argh = 0
def parse(data):
global argh
children = data.popleft()
metadata = data.popleft()
print(children, metadata)
nobe... |
duomarket/openbazaar-test-nodes | qa/dispute_close_split.py | import requests
import json
import time
from collections import OrderedDict
from test_framework.test_framework import OpenBazaarTestFramework, TestFailure
class DisputeCloseSplitTest(OpenBazaarTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 3
def run_test(self):
... |
ActiveState/code | recipes/Python/83698_Patterns_using_classes_dictionary/recipe-83698.py | class Base:
def __init__(self,v):
self.v=v
class StaticHash(Base):
def __hash__(self):
if not hasattr(self,"hashvalue"):
self.hashvalue=hash(self.v)
return self.hashvalue
class ImmutableHash(Base):
def __init__(self,v):
... |
jalanb/kd | cde/timings.py | """Methods to handle times"""
import time
def now():
"""Current time
This method exists only to save other modules an extra import
"""
return time.time()
def time_since(number_of_seconds):
"""Convert number of seconds to English
Retain only the two most significant numbers
>>> expect... |
lethain/lifeflow | urls.py | from django.conf.urls.defaults import *
from lifeflow.feeds import *
from lifeflow.models import *
from lifeflow.sitemaps import ProjectSitemap
from django.contrib.sitemaps import GenericSitemap
from django.views.decorators.cache import cache_page
from django.contrib.syndication.views import feed
# Cache
def cache(typ... |
jairtrejo/doko | app/rohan/urls.py | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
from .views import HomeView
# Uncomment the next two lines to enable the admin:
admin.autodiscover()
urlpatterns = (
static(settings.MEDIA_URL, documen... |
bl8/bockbuild | packages/glib.py | class GlibPackage (GnomeXzPackage):
def __init__ (self):
GnomePackage.__init__ (self,
'glib',
version_major = '2.30',
version_minor = '3')
self.darwin = Package.profile.name == 'darwin'
if Package.profile.name == 'darwin':
#link to specific revisions for glib 2.30.x
self.sources.extend ([
'h... |
nint8835/NintbotForDiscordV2 | NintbotForDiscord/FeatureManager.py | from .Feature import Feature
from .BasePlugin import BasePlugin
from . import Bot
class FeatureManager(object):
def __init__(self, bot: "Bot.Bot"):
self.bot = bot
self.features = {}
def register_feature(self, owner: BasePlugin, name: str, description: str = "A feature.") -> Feature:
... |
boada/planckClusters | MOSAICpipe/plugins/_dust.py | import os
import sys
import time
# get the utils from the parent directory
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from utils import SEx_head
from pipe_utils import tableio, deredden
# Find the eBV dust correction for each source in the catalogs
def DustCorrection(self):
''' T... |
lepture/misaka | build_ffi.py | # -*- coding: utf-8 -*-
import cffi
# Block-level extensions
EXT_TABLES = (1 << 0)
EXT_FENCED_CODE = (1 << 1)
EXT_FOOTNOTES = (1 << 2)
# Span-level extensions
EXT_AUTOLINK = (1 << 3)
EXT_STRIKETHROUGH = (1 << 4)
EXT_UNDERLINE = (1 << 5)
EXT_HIGHLIGHT = (1 << 6)
EXT_QUOTE = (1 << 7)
EXT_SUPERSCRIPT = (1 << 8)
EXT_MA... |
mgraupe/acq4 | acq4/util/flowchart/Analysis.py | # -*- coding: utf-8 -*-
from acq4.pyqtgraph.flowchart.library.common import *
import acq4.util.functions as functions
import numpy as np
import scipy
#from acq4.pyqtgraph import graphicsItems
import acq4.pyqtgraph as pg
import acq4.util.metaarray as metaarray
#import acq4.pyqtgraph.CheckTable as CheckTable
from collec... |
zhirafovod/btcp-daemon | tracker.py | # pytorrent-tracker.py
# A bittorrent tracker
from logging import basicConfig, info, INFO
from pickle import dump, load
from socket import inet_aton
from struct import pack
import sys
import logging
from twisted.application import internet, service
from twisted.web.resource import Resource
from twisted.web.server imp... |
snowfarthing/nibbles_3d | vertex.py | # vertex.py
# This module contains all the things for creating
# and using vertices...starting with vector, and
# going on to edge and face.
# Observe two things, though:
# First, I tried to keep small numbers as "zeros"
# by rounding divisions (see __div__ and norm) to
# five significant digits. So if a number i... |
lahwran/distributed-crawler | crawler/central.py | import json
import random
import urlparse
import re
import itertools
from collections import deque
from twisted.internet.protocol import Factory
from twisted.web.server import Site
from klein import Klein
from crawler import util
class Job(object):
def __init__(self, job_id):
self.queue = deque()
... |
oliveirarodolfo/ipnm | ipnm/format_converter.py | #
"""
"""
import os
import json
try:
import vtk
has_vtk = True
except ImportError:
has_vtk = False
def convert(data, in_format, out_format='json'):
"""
"""
if in_format == 'json':
pnm = json_to_json(data)
elif in_format == 'dat':
pnm = imperial_to_json(data)
elif in... |
phoebeargon/BigDataForEducation | big_data_for_education/users/models.py | from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class User(AbstractUser):
# First Name a... |
DesertBot/DesertBot | desertbot/modules/utils/StringUtils.py | import json
import re
from collections import OrderedDict
from typing import List
from pyxdameraulevenshtein import normalized_damerau_levenshtein_distance as ndld
from twisted.plugin import IPlugin
from zope.interface import implementer
from desertbot.message import IRCMessage
from desertbot.moduleinterface import I... |
huhamhire/Hyper-hosts | hyperhosts/network/filter.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyleft (C) 2015 - huhamhire <me@huhamhire.com>
import ipaddress
import os
from abc import ABCMeta, abstractmethod
from hyperhosts.constants import RES_PATH
class FilterBase(object):
__metaclass__ = ABCMeta
def __init__(self):
super(FilterBase, se... |
maciejkula/spotlight | spotlight/cross_validation.py | """
Module with functionality for splitting and shuffling datasets.
"""
import numpy as np
from sklearn.utils import murmurhash3_32
from spotlight.interactions import Interactions
def _index_or_none(array, shuffle_index):
if array is None:
return None
else:
return array[shuffle_index]
de... |
drslump/pyshould | tests/expect.py | import unittest
from pyshould import *
from pyshould.expect import expect, expect_all, expect_any, expect_none
class ExpectTestCase(unittest.TestCase):
""" Simple tests for the expect based api """
def test_expect(self):
expect(1).to_equal(1)
expect(1).to_not_equal(0)
def test_expect_all... |
harpolea/advent_of_code_2016 | day20.py | import re
def firewall(in_file):
# read file
f = open(in_file, 'r')
ranges = []
for l in f:
m = re.match('(\d+)-(\d+)', l)
ranges.append([int(m.group(1)), int(m.group(2))])
ranges.sort()
lowest = 0
upper_lim = 0
for r in ranges:
if lowest < r[0]:
pri... |
mikedh/trimesh | trimesh/voxel/encoding.py | """OO interfaces to encodings for ND arrays which caching."""
import numpy as np
import abc
from ..util import ABC
from . import runlength as rl
from .. import caching
try:
from scipy import sparse as sp
except BaseException as E:
from ..exceptions import ExceptionModule
sp = ExceptionModule(E)
def _em... |
hallover/alloy-database | code/timeErrorPlot.py | import os as os
import zipfile as Z
from os.path import isfile, join
from getpass import getuser
from matplotlib import pyplot as plt
zipfiles = []
kptList = []
name = []
inputzips = []
netID = getuser()
zippath = "/fslhome/" + netID + "/vasp/alloydatabase/alloyzips/"
newpath = "/fslhome/" + netID + "/vasp/alloyd... |
Bringing-Buzzwords-Home/bringing_buzzwords_home | visualize/views.py | import operator
import json
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from .models import County, GuardianCounted, Geo, Item, Station, Crime, State
from .utilities import states, get_dollars_donated_by_year, format_money
from .utilities import get_... |
Strain88/VKapi2 | api.py | #!-*-coding:utf8-*-
from urllib import urlopen
class Api(object):
def __init__(self, session, **default_api_kwargs):
self._session=session
self._defauld_api_kwargs=default_api_kwargs
self._defauld_api_kwargs.update({'access_token': self._session.at})
self.stats.trackVisitor()
def make_... |
richardtran415/pymatgen | pymatgen/transformations/advanced_transformations.py | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module implements more advanced transformations.
"""
import logging
import math
import warnings
from fractions import Fraction
from itertools import groupby, product
from math import gcd
from string im... |
demisto/content | Packs/Vectra/Integrations/Vectra_v2/Vectra_v2.py | from CommonServerPython import *
# IMPORTS #
import json
import requests
import urllib3
from typing import Dict, List, Union
# Disable insecure warnings
urllib3.disable_warnings()
# CONSTANTS #
MAX_FETCH_SIZE = 50
DATE_FORMAT = "%Y-%m-%dT%H%M" # 2019-09-01T1012
PARAMS_KEYS = {
"threat_score": "t_score",
"th... |
laurivosandi/certidude | certidude/api/ocsp.py | import falcon
import logging
import os
from asn1crypto.util import timezone
from asn1crypto import ocsp
from base64 import b64decode
from certidude import config, const
from datetime import datetime, timedelta
from oscrypto import asymmetric
from .utils import AuthorityHandler
from .utils.firewall import whitelist_subn... |
louisLouL/pair_trading | capstone_env/lib/python3.6/site-packages/quandl/util.py | from inflection import parameterize
import dateutil.parser
import re
from six import string_types
class Util(object):
@staticmethod
def constructed_path(path, params={}):
for key in list(params.copy().keys()):
modified_path = path.replace(":%s" % key, str(params[key]))
if modif... |
mpetyx/pyrif | 3rdPartyLibraries/FuXi-master/test/OWLsuite.py | import unittest
import os
import time
# import itertools
from pprint import (
pprint,
pformat
)
from FuXi.DLP import non_DHL_OWL_Semantics # , MapDLPtoNetwork
from FuXi.DLP.ConditionalAxioms import AdditionalRules
from FuXi.Horn.HornRules import HornFromN3
from FuXi.Horn.PositiveConditions import BuildUnit... |
sharkySharks/PythonForDevs | Labs-Worked/Day3/lab21.py | def gen(start, stop):
for x in xrange(start, stop):
if x % 2 == 0:
result = x
else:
result = 'odd'
yield result
for y in gen(4,7):
print y
print 'Generator Finished.'
next_gen = gen(4, 7) # this one you run manually in the python shell
while True: ... |
ddboline/Garmin-Forerunner-610-Extractor_fork | ant/base/ant.py | # Ant
#
# Copyright (c) 2012, Gustav Tiger <gustav@tiger.name>
#
# 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, m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.