code stringlengths 1 199k |
|---|
import mock
import lxml.etree as ET
from .utils import make_cobertura
def test_parse_path():
from pycobertura import Cobertura
xml_path = 'foo.xml'
with mock.patch('pycobertura.cobertura.os.path.exists', return_value=True):
with mock.patch('pycobertura.cobertura.ET.parse') as mock_parse:
... |
import time
from usb_vendor import PIC_USB
import traceback
comms = PIC_USB(0x0005)
def main():
print("START")
loop_time = .2 # How often to run the main loop, in seconds
while True:
start_time = time.clock()
# print(chr(27) + "[2J")
# quad_info()
try:
# debug_ua... |
import Orange
from orangecontrib.associate.fpgrowth import *
import pandas as pd
import numpy as np
import sys
import os
from collections import defaultdict
from itertools import chain
from itertools import combinations
from itertools import compress
from itertools import product
from sklearn.metrics import accuracy_sc... |
"""
pitchanalysis.py
--
Christopher Kuech
cjkuech@gmail.com
--
Requires:
Python 2.7
Instructions:
python pitchanalysis.py [wav-file-name]
"""
import matplotlib
from math import log
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import... |
from distutils.core import setup
setup(
name='Bioloid',
version='0.1.0',
author='Dave Hylands',
author_email='dhylands@gmail.com',
packages=['bioloid'],
scripts=[],
url='http://pypi.python.org/pypi/Bioloid/',
license='LICENSE',
description='Provides access to bioloid devices.',
l... |
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_PxMarkerDialog(object):
def setupUi(self, PxMarkerDialog):
PxMarkerDialog.setObjectName("PxMarkerDialog")
PxMarkerDialog.resize(400, 300)
self.btn_confirm_box = QtWidgets.QDialogButtonBox(PxMarkerDialog)
self.btn_confirm_box.setGeom... |
import sys
import os
import files.io
from StringIO import StringIO
from constants import *
added_path = os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))), "script")
sys.path.append(added_path)
import script
import mess
sys.path.pop()
def full_file(pointer):
pointer.seek(0)
return pointer.... |
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import sys
from heap import Heap
class Rectangle(object):
"""docstring for Rectangle"""
def __init__(self, dimension, entry=None):
super(Rectangle, self).__init__()
self.dimension = dimension
self.min_dim = [None for _ in xrange(dime... |
from ...errors.httpbadrequestexception import HttpBadRequestException
import saklient
class DnsAaaaRecordNotFoundException(HttpBadRequestException):
## 不適切な要求です。対応するAAAAレコードが見つかりません。
## @param {int} status
# @param {str} code=None
# @param {str} message=""
def __init__(self, status, code=None, messa... |
"""Production settings and globals."""
from base import *
MAIN_HOST = ['openbilanci.staging.deppsviluppo.org',]
HOSTS_COMUNI = [
'novara.comuni.deppsviluppo.org',
'rapallo.comuni.deppsviluppo.org',
'castiglionedellestiviere.comuni.deppsviluppo.org',
'firenze.comuni.deppsviluppo.org',
'terni.comuni.deppsviluppo.org'
]
A... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "web_sheets_django.settings.local")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
... |
import os
from os import path
import sqlite3
from .link import Link
class Links(object):
def __init__(self):
self._links = {}
def add(self, link):
self._links[link.url] = link
def find_by_tag(self, tag):
return [link for link in self._links.values() if tag in link.tags]
def get_a... |
"""
Django settings for dts_test_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(__fi... |
"""
Jedi EPC server.
Copyright (C) 2012 Takafumi Arakaki
Author: Takafumi Arakaki <aka.tkf at gmail.com>
This file is NOT part of GNU Emacs.
Jedi EPC server 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 v... |
from django.conf import settings
BACKENDS = getattr(settings, 'FAIREPART_BACKENDS', (
'fairepart.backends.facebook.FacebookBackend',
'fairepart.backends.google.GoogleOAuth2Backend',
))
RELATION_LIST_PAGINATE_BY = getattr(settings, 'FAIREPART_RELATION_LIST_PAGINATE_BY', 5)
GOOGLE_APP_NAME = getattr(settings, 'FA... |
from frasco.ext import *
from frasco.assets import expose_package, register_assets_builder
from frasco.utils import join_url_rule
from flask import render_template
import os
import json
import re
import htmlmin
import codecs
class FrascoAngular(Extension):
name = "frasco_angular"
defaults = {"static_dir": None,... |
""" Configuration for Flask app """
import os
import urllib
from flask import (Flask, abort, flash, Response)
from playhouse.flask_utils import FlaskDB
ADMIN_PASSWORD = 'secret'
APP_DIR = os.path.dirname(os.path.realpath(__file__))
DATABASE = 'sqliteext:///%s' % os.path.join(APP_DIR, 'blog.db')
DEBUG = False
SECRET_KEY... |
class Sample():
def __init__(self, name, number):
self.name = name
self.number = number
def print_values(self):
print(f"name: {self.name}")
print(f"number: {self.number}")
class SampleWithProperties():
def __init__(self, name, number):
self.name = name
self.nu... |
'''
Perform basic ELF security checks on a series of executables.
Exit status will be 0 if successful, and the program will be silent.
Otherwise the exit status will be 1 and it will log which executables failed which checks.
Needs `readelf` (for ELF) and `objdump` (for PE).
'''
import subprocess
import sys
import os
R... |
from __future__ import print_function
import sys
class ENUM:
instructions_list = []
def __init__(self, ID, mnemonic, properties, parsing, encoding, short_desc, execution, description):
self.ID = ID
self.mnemonic = mnemonic
self.properties = properties
self.parsing = parsing
... |
from setuptools import setup
setup(setup_requires=['pbr'],
pbr=True,
test_suite="") |
def run(whatweb, pluginname):
whatweb.recog_from_header(pluginname, "Webluker") |
from __future__ import unicode_literals
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
CREATE = 100
SUCCESS = 110
ACTIVATE = 130
AUTH = 150
VIEW = 180
UPDATE = 200
SUSPEND = 250
UNSUSPEND = 260
DELETE = 300
TERMINATE = 500
FAILED = 999
ERROR = 1000
LOG_ACTION_CHOICES_DEFAULT = ... |
"""
This file is part of pyCMBS.
(c) 2012- Alexander Loew
For COPYING and LICENSE details, please refer to the LICENSE file
"""
import unittest
from pycmbs.icon import Icon
class TestPycmbsIcon(unittest.TestCase):
def setUp(self):
# requires local installation of ICON sample files!
self.gridfile ='.... |
"""Docstring."""
import re
from functools import reduce
from collections import Counter
from common import get_input
class SSLTester:
"""."""
def __init__(self, input_list=[]):
"""Initialize."""
self.input_list = input_list
def find_aba(self, seq):
"""Return list: all 'aba's found in... |
import sys
import EulerPy
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def readme():
with open('README.rst') as f:
return f.read()
def requirements():
install_requires = []
with open('requirements.txt') as f:
for line in f:
instal... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from django_summernote.widgets import SummernoteInplaceWidget
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Speaker, Program
class EmailLoginForm(forms.Form):
email = forms.EmailF... |
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
from flask_login import LoginManager
from flask_restful import Api
from flask_wtf.csrf import CsrfProtect
from itsdangerous import URLSafeTimedSerializer
from sqlalchemy import create_engine
import AppConfig
from Re... |
import json # json
import threading # multi threading
import os # for listing directories
import Queue # queue used for thread syncronization
import sys # system calls
import argparse # for... |
import uuid
from random import randint
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Url
def index(request):
if request.session.has_key("has_url"):
url = request.session.get("has_url")
del request.session['has_url']
return render(request... |
from .tables import Base, Component, Mixture, Ref, Measurement, Listing, Property
from .utils import get_or_create
__all__ = ['Base', 'Component', 'Mixture', 'Ref', 'Measurement', 'Listing', 'Property', 'get_or_create'] |
import tornado.web
import tornado.ioloop
import os
from handlers import *
urls = [
(r'/', IndexHandler),
(r'/api/(?P<action>[a-zA-Z0-9-_]+)', ApiServiceHandler),
(r'/about', AboutHandler),
]
settings = {
"static_path" : os.path.join(os.path.dirname(__file__), "static"),
"template_path" : os.p... |
from __future__ import absolute_import
import logging
try:
from redis import Redis
from rq import Queue
except ImportError:
Redis = None
Queue = None
from kaneda.exceptions import ImproperlyConfigured
from .base import BaseQueue
class RQQueue(BaseQueue):
"""
RQ queue
:param queue: queue inst... |
"""
.. module:: radical.pilot.controller.pilot_launcher_worker
.. moduleauthor:: Ole Weidner <ole.weidner@rutgers.edu>
"""
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
from unit_manager_controller import UnitManagerController
from pilot_manager_controller import PilotManagerC... |
class MiddlewareMixin(object):
def __init__(self, get_response=None):
super(MiddlewareMixin, self).__init__() |
from json import JSONDecodeError
from flask import Blueprint, Flask, make_response, Response
from flask_cors import CORS
from google.appengine.api import wrap_wsgi_app
from werkzeug.routing import BaseConverter
from backend.api.handlers.district import (
district_events,
district_list_year,
district_ranking... |
import _plotly_utils.basevalidators
class LegendgroupValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(self, plotly_name="legendgroup", parent_name="choropleth", **kwargs):
super(LegendgroupValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_nam... |
from distutils.core import setup
execfile('modlunky/version.py')
with open('requirements.txt') as requirements:
required = requirements.read().splitlines()
kwargs = {
"name": "modlunky",
"version": str(__version__),
"packages": ["modlunky"],
"scripts": ["bin/modlunky"],
"description": "Library a... |
import datetime
import nose
from nose.tools import assert_equal
from pyomni.object.task import OmniTask
class TestOmniTask(object):
def test_get_xml(self):
return
if __name__ == '__main__':
nose.main(argv=['nosetests', '-s', '-v'], defaultTest=__file__) |
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
PYANNOTE_URI = 'uri'
PYANNOTE_MODALITY = 'modality'
PYANNOTE_SEGMENT = 'segment'
PYANNOTE_TRACK = 'track'
PYANNOTE_LABEL = 'label'
PYANNOTE_SCORE = 'score'
PYANNOTE_IDENTITY = 'identity'
from .time import T, TStart, TEnd
from .s... |
from .fcn import FCN |
import numpy as np
def zero_mean_normalize_image_data(data, axis=(0, 1, 2)):
return np.divide(data - data.mean(axis=axis), data.std(axis=axis))
def foreground_zero_mean_normalize_image_data(data, channel_dim=4, background_value=0, tolerance=1e-5):
data = np.copy(data)
if data.ndim == channel_dim or data.sha... |
from django.template.base import Library
from django.core.urlresolvers import reverse
from projects.models import ProjectBuild
register = Library()
@register.simple_tag()
def build_url(build_id):
"""
Fetches the ProjectBuild for a given build_id, if any.
"""
try:
build = ProjectBuild.objects.get... |
from allocine import allocine
from constants import *
from elcinema import elcinema
from imdb import imdby as Imdb
from rotten import rotten
from tmdb import tmdb
def search(query, site):
if site == "imdb":
provider = Imdb()
elif site == "elcinema":
provider = elcinema()
elif site == "rotten... |
"""Access and control log capturing."""
import logging
import os
import re
import sys
from contextlib import contextmanager
from io import StringIO
from pathlib import Path
from typing import AbstractSet
from typing import Dict
from typing import Generator
from typing import List
from typing import Mapping
from typing ... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('CareerTinder', '0004_auto_20160918_0152'),
]
operations = [
migrations.RenameField(
model_name='hiree',
old_name='first_name',
... |
DB_NAME = 'censusreporter_ke'
DB_USER = 'censusreporter_ke'
DB_PASSWORD = 'censusreporter_ke' |
from __future__ import unicode_literals
import bcrypt
class BCryptPassword(object):
def __init__(self, hash_):
self.hash = str(hash_)
def __eq__(self, value):
if not self.hash or not value:
# For security reasons we never consider an empty password/hash valid
return False... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_pesapal.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import os
from appdirs import AppDirs
class Config:
def __init__(self):
self.app_dir = get_app_dir()
def save_geometry(self, window):
path = os.path.join(self.app_dir, 'geometry.conf')
print(path)
with open(path, "w") as conf:
conf.write(window.geometry())
def rea... |
import json
from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTPError
from .exceptions import SparkPostAPIException
class TornadoTransport(object):
@gen.coroutine
def request(self, method, uri, headers, **kwargs):
if "data" in kwargs:
kwargs["body"] = kwargs.pop("data... |
import os
import Settings
'''
Generic Bytecode
Simply add, remove or modify bytecode for use in KHMS
'''
createFrame = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1',
'iconst_1', 'iadd', 'putfield', 'iload_1', 'aload_0', 'getfield', \
'invokevirtual', 'iadd', 'i2b', 'bastor... |
import unittest
from activity_feed import ActivityFeed
class UtilityTest(unittest.TestCase):
def test_key(self):
'should return the correct key for the non-aggregate feed'
a = ActivityFeed()
self.assertEquals(a.feed_key('david'), 'activity_feed:david')
def test_key_aggregate(self):
... |
import json
import time
import botogram
import progressbar
import redis
import config
r = redis.StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB, password=config.REDIS_PASSWORD)
bot = botogram.create(config.BOT_TOKEN)
def post(text, parse_mode="HTML", reply_markup=None, disable_web_page_pr... |
import sys, datetime, os, time
from mcstatus import MinecraftServer
serverList = []
def appendLog(host, time, pop):
fileName = host.replace(".", "")+ ".csv"
with open(fileName, "a") as logFile:
# If the file is empty add the column names
if not os.stat(fileName).st_size > 0:
logFile.write('"time","pop"')
# W... |
import django_filters
from django.contrib.auth.models import Group
from apps.authentication.models import OnlineUser as User
class PublicProfileFilter(django_filters.FilterSet):
year = django_filters.NumberFilter(field_name="year", method="filter_year")
group = django_filters.CharFilter(method="filter_group")
... |
from project_cron.utils import processutil
def open(app_name):
script = '''
if application "%s" is not running then
tell application "%s" to activate
end if
''' % (app_name, app_name)
processutil.call(['/usr/bin/osascript', '-e', script])
def close(app_name):
script = 'te... |
import numpy as np
def read_roi(fileobj):
'''
points = read_roi(fileobj)
Read ImageJ's ROI format
Parameters
----------
fileobj: should be a file-like object
Returns
-------
points: a list of points
'''
SPLINE_FIT = 1
DOUBLE_HEADED = 2
OUTLINE = 4
OVERLAY_LABELS =... |
import _plotly_utils.basevalidators
class ShowticklabelsValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self, plotly_name="showticklabels", parent_name="heatmap.colorbar", **kwargs
):
super(ShowticklabelsValidator, self).__init__(
plotly_name=plotly_name,
... |
__author__ = 'ByStudent'
def zhanzhuanxc(p,q,e):
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
return gcd, x, y
def modinv(a, m):
gcd, x, y = egcd(a, m)
... |
def hsd_inc_beh(rxd, txd):
'''|
| Specify the behavior, describe data processing; there is no notion
| of clock. Access the in/out interfaces via get() and append()
| methods. The "hsd_inc_beh" function does not return values.
|________'''
if rxd.hasPacket():
data = rxd.get() + 1
... |
""" Implementation of WaterFrame.plot_bar(key, ax=None, average_time=None)"""
import datetime
def plot_timebar(self, keys, ax=None, time_interval_mean=None):
"""
Make a bar plot of the input keys.
The bars are positioned at x with date/time. Their dimensions are given by height.
Parameters
---------... |
import unittest, uuid
from nixie.core import Nixie, KeyError
class NixieErrorsTestCase(unittest.TestCase):
def test_read_missing(self):
nx = Nixie()
self.assertIsNone(nx.read('missing'))
def test_update_missing(self):
nx = Nixie()
with self.assertRaises(KeyError):
nx.update('missing')
def te... |
"""CnbetaApi URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-b... |
from key_vault_agent import KeyVaultAgent
class SecretsAgent(KeyVaultAgent):
def get_secret(self):
self.data_client.restore_secret()
pass |
from c2cgeoportal_admin.views.layertree import itemtypes_tables
itemtypes_tables.update({
'lu_int_wms': 'lux_layer_internal_wms',
'lu_ext_wms': 'lux_layer_external_wms',
}) |
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
>>> get_ip_address('lo')
'127.0.0.1'
>>> get_ip... |
import discord
from discord.ext import commands
import time
import datetime
import pytz
class GameTime(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def time(self, ctx):
"""Displays current game time."""
locationName = self.bot.db.g... |
import unittest
import logging
import logging.config
import sys
import argparse
DESCRIPTION="""
Harness for tests in the cloaca/tests/ directory.
Run all tests with '--all' or provide a list dotted names
of specific tests (eg. legionary.TestLegionary.test_legionary).
"""
def setup_logging(
default_path='test_lo... |
import tkinter as tk
class ExampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
t = SimpleTable(self, 10,2)
t.pack(side="top", fill="x")
t.set(0,0,"Hello, world")
class SimpleTable(tk.Frame):
def __init__(self, parent, rows=10, columns=2):
# use black background so... |
"""
Franca abstract syntax tree representation.
"""
from abc import ABCMeta
from collections import OrderedDict
class ASTException(Exception):
def __init__(self, message):
super(ASTException, self).__init__()
self.message = message
def __str__(self):
return self.message
class Package(obj... |
"""
Test code for blackjack game. Tests can be run with py.test or nosetests
"""
from __future__ import print_function
from unittest import TestCase
from card_games import blackjack
from card_games.blackjack import BlackJack
print(blackjack.__file__)
class TestRule(TestCase):
def setUp(self):
pass
def ... |
"""Automabot bot for Discord."""
from os import path
from setuptools import setup, find_packages
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), 'r', encoding='utf-8') as f:
long_description = f.read()
setup(
name='automabot',
version='0.0.1.dev20170604', # see PEP-0440... |
"""
Base classes for writing management commands (named commands which can
be executed through ``tipi.py``).
"""
import os
import sys
from ConfigParser import ConfigParser
from optparse import make_option, OptionParser
from virtualenv import resolve_interpreter
class CommandError(Exception):
"""
Exception class... |
from keras.models import Sequential
from keras.layers import LSTM
import numpy as np
model = Sequential()
ly = LSTM(2, activation='tanh', recurrent_activation='relu',implementation = 1, stateful=False, batch_input_shape=(5, 3, 3))
model.add(ly)
model.compile(optimizer='sgd', loss='mse')
kernel = np.ones((3, 8))
rec_ker... |
"""
[2015-04-01] Challenge #208 [Intermediate] ASCII Gradient Generator
https://www.reddit.com/r/dailyprogrammer/comments/3104wu/20150401_challenge_208_intermediate_ascii/
A linear colour gradient is where an image transitions through a range of colours, [like
this](http://i.imgur.com/IPwnI8X.png). A gradient doesn't n... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('article', '0019_remove_article_ordering_featured'),
]
operations = [
migrations.RemoveField(
model_name='article',
name='issue',
... |
" tail boom flexibility "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled
class TailBoomFlexibility(Model):
""" Tail Boom Flexibility Model
Variables
---------
Fne [-] tail boom flexibility factor
deda [-] wing downwash derivati... |
"""
This script can generate automate scripts for open source python project.
Scroll to ``if __name__ == "__main__":`` for more info.
"""
from __future__ import print_function
import sys
import datetime
from os import walk, mkdir
from os.path import join, abspath, dirname, basename
def write(s, path, encoding="utf-8"):... |
"""
WSGI config for mozblog project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhi... |
from configparser import ConfigParser
import v20
config = ConfigParser()
config.read("../API_Connection_Oanda/pyalgo.cfg")
ctx = v20.Context(
'api-fxpractice.oanda.com',
443,
True,
application = 'sample_code',
token = config['oanda_v20']['access_token'],
datetime_format = 'RFC3339')
def get_Id_A... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Stat',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, ... |
import os, tempfile
import logging
import threading
class pipe():
def __init__(self, pipefile, queue, actions):
"""
Reads from a pipe
"""
self.pipefile = pipefile
self.queue = queue
actions["pipe"] = {}
self.__makefifo()
self.listening_thread = threadi... |
from jsbuild.attrdict import AttrDict
from time import strftime
class Manifest(AttrDict):
def __init__(self,*args,**kwargs):
super(AttrDict, self).__init__(*args,**kwargs)
self._buffer_ = None
self._parent_ = None
if not self.__contains__('_dict_'):
self['_dict_'] = {}
self['_dict_']['timest... |
import os
from io import open
from setuptools import setup
about = {}
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'stringsheet', '__init__.py'), encoding='utf-8') as f:
for line in f:
if line.startswith('__'):
(key, value) = line.split('=')
about[ke... |
"""
gists.gists
~~~~~~~~~~~
This single-function module defines the input parameters and the subparsers,
and coordinates the 'handlers'->'actions'->'formatters' execution workflow
"""
import argparse
from actions import (list_gists, show, get, post, delete, update, authorize,
fork, star, unstar)
fr... |
import unittest
from linked_list import (delete_node, list_cycle, remove_elements,
reverse_list)
from public import ListNode
class TestLinkedList(unittest.TestCase):
def test_delete_node(self):
so = delete_node.Solution()
head = ListNode(1)
head.next = ListNode(2)
... |
import numpy as np
import uncertainties.unumpy as unp
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy.optimize import curve_fit
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 13
plt.rcParams['lines.line... |
"""
This is part of WebScout software
Docs EN: http://hack4sec.pro/wiki/index.php/WebScout_en
Docs RU: http://hack4sec.pro/wiki/index.php/WebScout
License: MIT
Copyright (c) Anton Kuzmin <http://anton-kuzmin.ru> (ru) <http://anton-kuzmin.pro> (en)
Job class for FormBruter module
"""
from classes.jobs.GeneratorJob impor... |
from .resource import Resource
class VirtualNetworkGatewayConnectionListEntity(Resource):
"""A common class for general resource information.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:... |
import re
import requests
import pytesseract
from selenium import webdriver
from PIL import Image,Image
import time
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://higo.flycua.com/hp/html/login.html")
driver.implicitly_wait(30)
driver.find_element_by_name('memberId').send_keys('xxxxxx')
driver.... |
import argparse
import select
def no_piped_input(arguments):
inputs_ready, _, _ = select.select([arguments.file], [], [], 0)
return not bool(inputs_ready)
def parse_args(args, input):
parser = argparse.ArgumentParser()
parser.add_argument('--url', help="URL of the target data-set",
... |
def check_list(num_list):
"""Check if input is list"""
if num_list is None:
return False
if len(num_list) == 0:
return False
new_list = []
for i in num_list:
if i!='[' and i!=']' and i!=',':
new_list.append(i)
for x in new_list:
if type(x) != int:
... |
import re
def is_valid_username(s):
pattern = r'^[_\.][0-9]+[a-zA-Z]*_?$'
match = re.match(pattern, s)
return match
n = int(raw_input().strip())
for i in range(n):
s = raw_input().strip()
if is_valid_username(s):
print 'VALID'
else:
print 'INVALID' |
"""Implementations for various useful completers.
These are all loaded by default by IPython.
"""
from __future__ import print_function
import glob
import inspect
import os
import re
import sys
try:
# Python >= 3.3
from importlib.machinery import all_suffixes
_suffixes = all_suffixes()
except ImportError:
... |
class Indexer:
def __getitem__(self, index):
return index ** 2
x = Indexer()
for i in range(5):
print x[i],
class Stepper:
def __getitem__(self, index):
return self.data[index]
s = Stepper()
s.data = "spam"
for x in s:
print x,
print s.data[0] |
__author__ = "Osman Baskaya"
"""
Some utility functions for entailment project
"""
from collections import defaultdict as dd
from metrics import *
def get_eval_metric(metric_name):
if metric_name == "jaccard":
return jaccard_index
elif metric_name == "1":
return entail_score1
elif metric_nam... |
import numpy as np
import cv2
from matplotlib import pyplot as plt
face_cascade = cv2.CascadeClassifier('/home/tianyiz/user/601project/c/haarcascade_frontalface_alt.xml')
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
... |
a = "1"
b = 1
print("Arvud on " + 5 * a + " ja " + str(5 * b)) |
class Plugin(object):
__doc__ = '''Плагин предназначен для остановки бота.
Для использования необходимо иметь уровень доступа {protection} или выше
Ключевые слова: [{keywords}]
Использование: {keyword}
Пример: {keyword}'''
name = 'stop'
keywords = (u'стоп', name, '!')
protection = 3
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.