content stringlengths 4 20k |
|---|
from collections import namedtuple
class Environment(object):
def __init__(self, config_file=""):
Kintone = namedtuple("Kintone", ["domain", "app_id", "api_token"])
Watson = namedtuple("Watson", ["watson_id", "password", "classifier"])
Twitter = namedtuple("Twitter", ["consumer_key", "con... |
import unittest
import uuid
import json
import os
import tempfile
import shutil
from pymongo import MongoClient
import helpers
class FilesTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmpdir = tempfile.mkdtemp()
cls._dbname = str(uuid.uuid4())
test_data = [{
... |
"""
Handles 'cfy ssh'
"""
import os
import platform
from distutils import spawn
from cloudify_cli import messages
from cloudify_cli.logger import get_logger
from cloudify_cli.exceptions import CloudifyCliError
from cloudify_cli.cli import get_global_verbosity
from cloudify_cli.utils import get_management_user
from cl... |
"""Tests Keras multi worker fault tolerance."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
import sys
import tempfile
import threading
from absl.testing import parameterized
from tensorflow.python.distribute import collective_all_r... |
from __future__ import absolute_import, print_function
import sys
import logging
import pprint
import random
from decimal import Decimal
from math import exp
# todo: this was the date format used in the original debug(). Use it?
# logging.basicConfig(filename='logs/joinmarket.log',
# stream=sy... |
# -*- coding: utf-8 -*-
from flask import request
from django.db.models import Q
from framework.auth.decorators import must_be_logged_in
from osf.models.citation import CitationStyle
from website.project.decorators import (
must_have_addon, must_be_addon_authorizer,
must_have_permission, must_not_be_registrat... |
from msrest.serialization import Model
class TaskUpdateOptions(Model):
"""Additional parameters for the Task_update operation.
:param timeout: The maximum time that the server can spend processing the
request, in seconds. The default is 30 seconds. Default value: 30 .
:type timeout: int
:param c... |
from annotypes import Anno, add_call_types
from malcolm.core import (
APartName,
Display,
NumberMeta,
Part,
PartRegistrar,
Widget,
config_tag,
)
from ..hooks import ReportStatusHook, UInfos
from ..infos import MinTurnaroundInfo
with Anno("Initial value for min time between non-joined poin... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
'''
The four adjacent digits in the 1000-digit number that
have the greatest product are 9 × 9 × 8 × 9 = 5832.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
125406987471... |
#!/usr/bin/python
"""
"""
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.metrics import confusion_matrix
def my_validator(clf, features, labels, n_splits=1000, test_size=0.3,
method='mean_over_count', random_state=42):
"""Calculate the metrics of a classifier
argu... |
# Webhooks for external integrations.
from __future__ import absolute_import
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
from zerver.models import Client, UserProfile
from django.http ... |
import os
import unittest
import sys
from splinter import Browser
from .base import BaseBrowserTests
from .fake_webapp import EXAMPLE_APP
@unittest.skipIf(sys.version_info[0] > 2,
'zope.testbrowser is not currently compatible with Python 3')
class ZopeTestBrowserDriverTest(BaseBrowserTests, unittest... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : Virtual layers plugin for DB Manager
Date : December 2015
copyright : (C) 2015 by Hugo Mercier
email : hugo dot mercier at oslandia dot com
*******... |
from __future__ import absolute_import
from future.builtins import ( # noqa
bytes, dict, int, list, object, range, str,
ascii, chr, hex, input, next, oct, open,
pow, round, super,
filter, map, zip)
from functools import wraps
import logging
from elasticsearch import Elasticsearch
from conf.appconfig im... |
import btsocket as socket
# For deferred translation
_ = lambda s:s
class BluetoothClient(object):
"""Communication over Bluetooth.
"""
def __init__(self, app):
self.socket = None
self.app = app
def is_connected(self):
"""Returns whether the client is connected.
"""
... |
from __future__ import (absolute_import, division, print_function)
import mantid
from isis_powder.abstract_inst import AbstractInst
from isis_powder.routines.instrument_settings import InstrumentSettings
from isis_powder.routines.param_map_entry import ParamMapEntry
from isis_powder.routines import run_details
impor... |
import pytest
import requests
from mock import patch, Mock
from shutil import copyfile
from skylines.lib import files
from skylines.model import IGCFile
from skylines import weglide
from tests.data import users, igcs
@pytest.fixture
def test_data(db_session):
# create test user
john = users.john()
db_se... |
#!/bin/python
import os, subprocess
import logging
from autotest.client import test
from autotest.client.shared import error
class perl_Digest_SHA(test.test):
"""
Autotest module for testing basic functionality
of perl_Digest_SHA
@author Charishma M <<EMAIL>> ##
"... |
"""
class ImportWorkbench ( Workbench ):
"Import workbench object"
def Activate(self):
# load the module
try:
Log ('Loading ImportGui module')
import Import
import ImportGui
except:
Err('Cannot load ImportGui')
raise
def GetIcon(self):
# returns an icon for the workbench
return... |
codelist="""0 SP SP 00 2 1 2 2 2 2
1 ! ! 01 2 2 2 1 2 2
2 " " 02 2 2 2 2 2 1
3 # # 03 1 2 1 2 2 3
4 $ $ 04 1 2 1 3 2 2
5 % % 05 1 3 1 2 2 2
6 & & 06 1 2 2 2 1 3
7 ' ' 07 1 2 2 3 1 2
8 ( ( 08 1 3 2 2 1 2
9 ) ) 09 2 2 1 2 1 3
10 * * 10 2 2 1 3 1 2
11 + + 11 2 3 1 2 1 2
12 ... |
from graph_diff.graph import GraphWithRepetitiveNodesWithRoot, lr_node
from graph_diff.graph_diff_algorithm import GraphMap, GraphMapComparator, \
GraphMapComparatorByEdgeNum, GraphDiffAlgorithm
class BaselineAlgorithm(GraphDiffAlgorithm):
"""
Baseline graph diff algorithm.
Main idea - brute-force sea... |
import tensorflow as tf
import numpy as np
import gensim
import pickle
import os
import time
import collections
import itertools
from itertools import groupby
import random
_PAD = "<pad>"
_UNK = "<unk>"
_BOC = "<boc>"
#_EOS = "<eos>"
def softmax_stable(logits):
logits = logits-tf.expand_dims(tf.reduce_max(logits, ... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""Python module to download videos.
This module contains the actual downloaders responsible
for downloading the video files.
Note:
downloaders.py is part of the youtubedlg package but it can be used
as a stand alone module for downloading videos.
"""
from __f... |
from praw.models import Message, Redditor, Subreddit, SubredditMessage
import mock
import pytest
from ... import IntegrationTest
class TestMessage(IntegrationTest):
@mock.patch('time.sleep', return_value=None)
def test_attributes(self, _):
self.reddit.read_only = False
with self.recorder.use_... |
from __future__ import absolute_import
from __future__ import unicode_literals
from threading import Thread
from six.moves import _thread as thread
try:
from Queue import Queue, Empty
except ImportError:
from queue import Queue, Empty # Python 3.x
STOP = object()
class Multiplexer(object):
"""
C... |
"""\
Particle Swarm Optimization
@author: Aaron Mavrinac
@organization: University of Windsor
@contact: <EMAIL>
@license: GPL-3
"""
import numpy
from random import uniform
class Particle(numpy.ndarray):
_gbest = None
_gbest_fitness = None
def __init__(self, *args):
self.velocity = numpy.ndarray... |
#/###################/#
# Import modules
#
#ImportModules
import ShareYourSystem as SYS
#/###################/#
# Build the model
#
#set
BrianingDebugVariable=25.
#Define
MyPredicter=SYS.PredicterClass(
).mapSet(
{
'BrianingStepTimeFloat':0.01,
'-Populations':[
('|Sensor',{
'LeakingMonitorIndexInt... |
"""
UrlResolver site plugin
Copyright (C) 2018 gujal
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 3 of the License, or
(at your option) any later version.
... |
from ktransit import FitTransit, LCModel, plot_results
import kplr
import numpy as np
def med_filt(x, y, dt=4.):
"""
De-trend a light curve using a windowed median.
"""
x, y = np.atleast_1d(x), np.atleast_1d(y)
assert len(x) == len(y)
r = np.empty(len(y))
for i, t in enumerate(x):
... |
import boto3
import os
from datetime import datetime, timezone
backup_region = os.getenv('BACKUP_REGION', 'us-west-2')
primary_region = os.getenv('PRIMARY_REGION', 'us-east-1')
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
def lambda_handler(event, context):
print('Task sta... |
"""
Copyright 2013 Steven Diamond
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 agreed to in writing, software... |
"""bwdist.py
"""
__license__ = "Apache License, Version 2.0"
__author__ = "Roland Kwitt, Kitware Inc., 2013"
__email__ = "E-Mail: <EMAIL>"
__status__ = "Development"
from optparse import OptionParser
import SimpleITK as sitk
import numpy as np
import sys
import os
def invert(orgImg):
"""Compute image inve... |
import gm_base.geometry_files.format_last as gs
import bgem.polygons.polygons as polygons
#from gm_base.polygons.decomp import Point
"""
TODO: Try to remove dependency on `decomp` module.
"""
def set_indices(decomp):
"""
Asign index to every node, segment and ppolygon.
:return: None
"""
for shap... |
"""
Copyright (c) 2015-2016 Cisco Systems, Inc. and others. All rights reserved.
This program and the accompanying materials are made available under the
terms of the Eclipse Public License v1.0 which accompanies this distribution,
and is available at http:#www.eclipse.org/legal/epl-v10.html
"""
from B... |
'''Module to use google to fix spelling in artist names.
This is risky, but it works surprisingly well. You do a query for 'artistname wiki',
and 90% of the time the first hit will be the wikipedia page for that artist with
perfect spelling. Of course you need to validate that it's the page you think it i... |
import numpy as np
import pyquil.quil as pq
from pyquil.gates import X
from math import floor
def changed_bit_pos(a, b):
"""
Return the index of the first bit that changed between `a` an `b`.
Return None if there are no changed bits.
"""
c = a ^ b
n = 0
while c > 0:
if c & 1 == 1:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pprint
import logging
import datetime
import traceback
from gevent import pywsgi
class FormattedWSGIHandler(pywsgi.WSGIHandler):
logger = logging.getLogger('gevent.wsgi')
status_level_map = {
200: logging.INFO,
300: logging.INFO,
4... |
from __future__ import absolute_import
from cStringIO import StringIO
from bzrlib import (
osutils,
progress,
trace,
)
from bzrlib.ui import ui_factory
from bzrlib.i18n import gettext
class RenameMap(object):
"""Determine a mapping of renames."""
def __init__(self, tree):
self.tree = tre... |
import smtplib
from oslo_config import cfg
from oslo_log import log
from storyboard.plugin.base import PluginBase
from storyboard.plugin.email import get_email_directory
from storyboard.plugin.email.smtp_client import get_smtp_client
CONF = cfg.CONF
LOG = log.getLogger(__name__)
class EmailPluginBase(PluginBase):
... |
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.utils.translation import ugettext as _
from django.views.decorators.vary import vary_on_headers
from wagtail.utils.pagi... |
from django.core.cache.backends.base import DEFAULT_TIMEOUT
from django_redis.cache import RedisCache as PlainRedisCache
from redis_lock import Lock
from redis_lock import reset_all
class RedisCache(PlainRedisCache):
@property
def __client(self):
try:
return self.client.get_client()
... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.shortcuts import render
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from beauty_and_pics.consts import project_constants
from notify_system_... |
from odoo import models, api
from odoo.tools.misc import formatLang
import logging
_logger = logging.getLogger(__name__)
class ReportGiornale(models.AbstractModel):
_name = 'report.l10n_it_central_journal.report_giornale'
@api.model
def render_html(self, docids, data=None):
lang_code = self._con... |
__all__ = ["ResizableTableWdg", "TestResizableTableWdg"]
from pyasm.web import Table, DivWdg
from pyasm.widget import IconWdg
from tactic.ui.common import BaseRefreshWdg
class ResizableTableWdg(BaseRefreshWdg):
def __init__(my, **kwargs):
my.table = Table()
my.table.add_style("border-collapse: c... |
import os
import shutil
import unittest
from hp.camera_handler import API_Camera_Handler
from hp.hp_data import process
from maskgen.maskgen_loader import MaskGenLoader
from mock import Mock
from hp import data_files
class TestHPTool(unittest.TestCase):
def test_process_data(self):
def get_key(key, *args,... |
import re, sys, traceback
from xml.etree import ElementTree
from urllib import urlencode, unquote
from urlparse import parse_qs
from twisted.internet.defer import inlineCallbacks
from twisted.internet.error import ConnectionRefusedError
from twisted.web import http
from twisted.web.resource import Resource
from twiste... |
"""
cube_util.py - utility functions for the datacube.
"""
from __future__ import absolute_import
import os
import time
import datetime
import logging
import errno
import inspect
#
# Set up logger
#
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.INFO)
#
# Utility Functions
#
def get_datacube_roo... |
'''
Configuration file for Deep dive Transect Extraction
Requires: python 2.7, Arcpy
Author: Emily Sturdivant
email: <EMAIL>; <EMAIL>; <EMAIL>
Date last modified: 11/22/2016
'''
import arcpy, time, os, pythonaddins, sys, math
sys.path.append(r"\\Mac\Home\GitHub\plover_transect_extraction\TransectExtraction") # path to ... |
from time import time
from os import path
from scheduler.scheduler import Scheduler
from extra.printer import pprint, GREEN, BLUE, RED
def schedulerLargeValuesPerf(plant, orderList, testNum):
machines = plant.machines[:]
orders = orderList.orders[:]
pprint("PERF Starting benchmark test " + str(testNum) + " with ... |
import os
import sys
import logging
import pprint
from csv import DictReader
from mongoengine import Document, StringField, DictField
from jamsession.util import FIELD_TYPE_TRANSLATIONS
class ClassProperty(property):
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
clas... |
import abjad
from abjad.tools import abctools
class TimespanCollectionNode(abctools.AbjadObject):
r'''A node in a timespan collection.
'''
### CLASS VARIABLES ###
__slots__ = (
'_balance',
'_height',
'_left_child',
'_node_start_index',
'_node_stop_index',
... |
# noinspection PyTypeChecker
import debug
class Environment(dict):
def __init__(self, parent, *args, **kw):
"""
:rtype : Environment
"""
self.parent = parent
super(Environment, self).__init__(*args, **kw)
def __call__(self, item):
return self[item]
def __se... |
from sklearn.base import BaseEstimator
import numpy as np
''' This contains a collection of feature extraction classes which can
be used in the Pipeline and GridSearch.
To create another class, you need to have a fit, transform, and
fit_transform method. The fit method must return itself, and the
fit_transform me... |
from pilas import control
from pilas import fisica
from pilas.escena import Gestor, Normal
from pilas import dev
class Mundo(object):
"""Representa un objeto unico que mantiene en funcionamiento al motor.
Mundo tiene como responsabilidad iniciar los componentes del
motor y mantener el bucle de juego.
... |
#!/usr/bin/env python
"""
Project Euler Problem 9
=======================
A Pythagorean triplet is a set of three natural numbers, a < b < c, for
which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a +... |
import WebIDL
def WebIDLTest(parser, harness):
parser.parse("""
interface TestNullableEquivalency1 {
attribute long a;
attribute long? b;
};
interface TestNullableEquivalency2 {
attribute ArrayBuffer a;
attribute ArrayBuffer? b;
};
... |
from compmod.models import CuboidTest
from abapy import materials
from abapy.misc import load
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import pickle, copy
import platform
def field_func(outputs, step):
"""
A function that defines the scalar field you want to plot
"""... |
# Django settings for outfitter project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '<EMAIL>'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # ... |
'''
Created on Jan 27, 2015
@author: y2joshi
'''
class TraceCSVFormatter:
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
def writeHeader(self):
'''
'''
return ""
def writeTrailer(self):
'''
'''
return ""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Measure the crosstalk between ADC0 and ADC1
'''
import numpy as np
import os
import time
import matplotlib.pyplot as plt
from fft import FFT
from koheron import connect
host = os.getenv('HOST', '192.168.1.16')
client = connect(host, 'fft', restart=False)
driver = FFT... |
from nevow import inevow
from nevow import appserver
from nevow import testutil
from nevow import util
from nevow import testutil
class Render:
__implements__ = inevow.IResource,
rendered = False
def locateChild(self, request, segs):
return self, ()
def renderHTTP(self, request):
se... |
from copy import deepcopy
import io
import requests
from oslo_log import log as logging
from oslo_serialization import jsonutils
from networking_odl._i18n import _
from networking_odl.common import client
from networking_odl.common import constants as odl_const
LOG = logging.getLogger(__name__)
OK = requests.code... |
"""
The below code comes from the "leviathan" project by jaksi
https://github.com/jaksi/leviathan
"""
import usb.core
import helper
class Cooler:
COLOR_MODE_NORMAL = 1
COLOR_MODE_ALTERNATING = 2
COLOR_MODE_BLINKING = 3
COLOR_MODE_OFF = 4
COLOR_MODES = [COLOR_MODE_NORMAL, COLOR_MODE_ALTERN... |
#!/usr/bin/env python2
import struct
import datetime
from . import error
class RootEntry(object):
ENTRY_SIZE = 32
TYPE_FAT12 = 0
TYPE_FAT16 = 1
TYPE_FAT32 = 2
class AttrFlag(object):
READ_ONLY = 0x01
HIDDEN = 0x02
SYSTEM_FILE = 0x04
VOLUME_LABEL = 0x08
... |
# -*- coding: utf-8 -*-
"""Climate data portal data analysis DSL
For security reasons, this is designed to be a non-Turing complete,
non-recursive
(i.e. no function definition) language.
The DSL needs to be:
* robust (accept various forms of argument),
* fail-fast (no guessing, raise exceptions quickly.),
* unam... |
from .element import Element
from .groups import GroupXI
from .periods import PeriodIV, PeriodV, PeriodVI, PeriodVII
class Cu(Element, PeriodIV, GroupXI):
__slots__ = ()
@property
def atomic_number(self):
return 29
@property
def isotopes_distribution(self):
return {63: 0.6917, 64... |
class Solution(object):
def dfssearch(self,grid,i,j, dist, buildingcnt):
row=len(grid)
col=len(grid[0])
visitied = [[False for _ in xrange(col)] for _ in xrange(row)]
visitied[i][j] = True
queue = [(i, j, 0)]
while queue:
i, j, depth = queue.pop(0... |
from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import utc
from datetime import timedelta, datetime
from django.utils.timezone import now
import uuid
from dispatcher.models import Pilot
from storage.models import DataObject
from dispatcher import scheduler
import ... |
"""
@author: Andrew Case
@license: GNU General Public License 2.0
@contact: <EMAIL>
@organization:
"""
from rekall.plugins.overlays import basic
from rekall.plugins.linux import common
class CheckModules(common.LinuxPlugin):
"""Compares module list to sysfs info, if available.
Sysfs contains... |
from unittest.mock import patch
import tempfile
from shutil import copyfile
from ..base import BaseTest
from ...views import migration
from ...lib.Config import Config
class Test(BaseTest):
config_path_to_copy = 'src/unittest/assets/migration/legacy-config'
vault_path = 'src/unittest/assets/migration/legacy... |
import itertools
import os
import random
from typing import Any, Dict, List
import orjson
from scripts.lib.zulip_tools import get_or_create_dev_uuid_var_path
def load_config() -> Dict[str, Any]:
with open("zerver/tests/fixtures/config.generate_data.json", "rb") as infile:
config = orjson.loads(infile.re... |
import os
from collections import OrderedDict
DEFAULT_INCLUDE = "include"
DEFAULT_LIB = "lib"
DEFAULT_BIN = "bin"
DEFAULT_RES = "res"
class _CppInfo(object):
""" Object that stores all the necessary information to build in C/C++.
It is intended to be system independent, translation to
specific systems w... |
"""Module with functions for Psi4/Cfour interface. Portions that require
calls to Boost Python psi4 module are here, otherwise in qcdb module.
Also calls to qcdb module are here and not elsewhere in driver.
Organizationally, this module isolates qcdb code from psi4 code.
"""
import os
import re
import sys
import uuid
... |
from nose.tools import assert_almost_equal
from nose.tools import assert_in, assert_equal, assert_false
from mock import patch, Mock
import numpy as np
from ..graph import Greengraph
from ..map import Map
import os
import yaml
def test_build_default_params():
with open(os.path.join(os.path.dirname(__file__),'fixt... |
'Use for communications regarding the NXT filesystem and such ***ADVANCED USERS ONLY***'
def _create(opcode):
'Create a simple system telegram'
from .telegram import Telegram
return Telegram(False, opcode)
def _create_with_file(opcode, fname):
tgram = _create(opcode)
tgram.add_filename(fname)
... |
"""Console Proxy Service."""
import socket
from oslo.config import cfg
from oslo import messaging
from nova.compute import rpcapi as compute_rpcapi
from nova import exception
from nova import manager
from nova.openstack.common import importutils
from nova.openstack.common import log as logging
from nova import utils... |
"""
Packetizer.
"""
import errno
import select
import socket
import struct
import threading
import time
from paramiko.common import *
from paramiko import util
from paramiko.ssh_exception import SSHException
from paramiko.message import Message
got_r_hmac = False
try:
import r_hmac
got_r_hmac = True
except ... |
from openerp import models, fields
from openerp.tools import drop_view_if_exists
class StockMoveOut(models.Model):
_name = "stock.stock_move_out"
_description = "Stock Move Out"
_auto = False
move_id = fields.Many2one(
string="Move",
comodel_name="stock.move",
)
name = fields.... |
import os
from os.path import join, exists, isdir
import datetime
from driver import SessionDriver
from extends.torndsession.session import SessionConfigurationError
utcnow = datetime.datetime.utcnow
try:
import cPickle as pickle # py2
except:
import pickle # py3
class FileSession(SessionDri... |
import numpy as np
import matplotlib.pyplot as plt
def network_architecture(model, xmin=0.0, xmax=1.0, ymin=0.0, ymax=0.6):
"""Plot a feed forward fully connected network architecture."""
ymid = (ymin + ymax) * 0.5
nlyrs = len(model.layers)
# we add + 1 so we have a potential bias node for each layer... |
__all__ = ["Map"]
import datetime
import logging
from collections import defaultdict
from io import BytesIO
from math import ceil, floor
from pathlib import Path
from urllib.parse import urlparse
import aiohttp
import dateutil.tz
import discord
from PIL import Image, ImageDraw, ImageFont
from dog.ext.time.drawing im... |
import pytest
from api import files
def test_extension():
assert files.guess_type_from_filename('example.pdf') == 'pdf'
def test_multi_extension():
assert files.guess_type_from_filename('example.zip') == 'archive'
assert files.guess_type_from_filename('example.gephysio.zip') == 'gephysio'
def test_nifti... |
"""
MIT License
Copyright (c) 2018 Claude SIMON (https://q37.info/s/rmnmqd49)
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
... |
# -*- coding: utf-8 -*-
from __init__ import _
from Components.config import config
try:
AT_unit = config.plugins.autotimer.unit.value == "hour" and _("hour") or _("minute")
except:
AT_unit = "hour"
tstrings = {'mo': _("Mo"),
'tu': _("Tu"),
'we': _("We"),
'th': _("Th"),
'fr': _("Fr"),
'sa': _("Sa"),
'su': _... |
from optparse import make_option
from django.core.management.base import BaseCommand
from casexml.apps.case.models import CommCareCase
from corehq.apps.locations.models import Location
from dimagi.utils.couch.database import get_db
class Command(BaseCommand):
args = 'loc_uuid'
help = 'DELETE a location, all it... |
"""simple script to do replacements on translated strings inside po files"""
# this is used as the basis for other scripts, it currently replaces nothing
from translate.storage import po
class poreplace:
def convertstring(self, postr):
"""does the conversion required on the given string (nothing in thi... |
"""
prefix.py
Created by Diego Garcia del Rio on 2015-03-12.
Copyright (c) 2015 Alcatel-Lucent. All rights reserved.
Based on work by Thomas Morin on mac.py
Copyright (c) 2014-2015 Orange. All rights reserved.
Copyright (c) 2014-2015 Exa Networks. All rights reserved.
"""
from exabgp.protocol.ip import IP
from exabg... |
from flask import request, current_app
from cifsdk.client.zeromq import ZMQ as Client
from cifsdk.exceptions import AuthError
from ..common import pull_token, jsonify_success, jsonify_unauth, jsonify_unknown
from flask.views import MethodView
from cif.constants import ROUTER_ADDR
import logging
remote = ROUTER_ADDR
T... |
import array
from PyQt5.QtCore import QAbstractTableModel, Qt, QModelIndex, pyqtSignal
from PyQt5.QtGui import QFont
from urh import settings
from urh.signalprocessing.ChecksumLabel import ChecksumLabel
from urh.signalprocessing.MessageType import MessageType
from urh.signalprocessing.ProtocoLabel import ProtocolLabe... |
import random
import bpy
from bpy.props import FloatProperty, StringProperty, BoolProperty, EnumProperty, IntProperty
from sverchok.core.socket_data import SvNoDataError
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode, ensure_nesting_level, zip_long_repeat, throttle_... |
from __future__ import print_function
from weboob.capabilities.library import CapBook, Book
from weboob.tools.application.repl import ReplApplication
from weboob.tools.application.formatters.iformatter import PrettyFormatter
__all__ = ['Boobooks']
class RentedListFormatter(PrettyFormatter):
MANDATORY_FIELDS = (... |
"""
operations on [a..b[ intervals
"""
__author__ = "Philippe Guglielmetti"
__copyright__ = "Copyright 2012, Philippe Guglielmetti"
__credits__ = []
__license__ = "LGPL"
from sortedcontainers import SortedListWithKey
def _order(interval):
""":return: (a,b) interval such that a<=b"""
if interval[... |
from __future__ import division, absolute_import, print_function
import re
import os
import sys
import warnings
import platform
import tempfile
from subprocess import Popen, PIPE, STDOUT
from numpy.distutils.cpuinfo import cpu
from numpy.distutils.fcompiler import FCompiler
from numpy.distutils.exec_command import ex... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
SetZValue.py
--------------
Date : July 2017
Copyright : (C) 2017 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
*****************************... |
import pytest
from django.contrib.auth.models import User
from dissemin.celery import app as celery_app
from papers.models import Paper
from papers.tests.test_ajax import JsonRenderingTest
from publishers.tests.test_romeo import RomeoAPIStub
@pytest.mark.usefixtures('mock_doi')
class PublisherAjaxTest(JsonRendering... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
ServerSimpleBrowseer.py
---------------------
Date : August 2014
Copyright : (C) 2014-2015 by Alessandro Pasotti
Email : apasotti at gmail dot com
******... |
import unittest
import mock
from hpOneView.connection import connection
from hpOneView.resources.resource import ResourceClient
from hpOneView.resources.storage.volumes import INVALID_VOLUME_URI
from hpOneView.resources.storage.volumes import Volumes
class VolumesTest(unittest.TestCase):
def setUp(self):
... |
import IECore
import Gaffer
import GafferUI
## Supported plug metadata :
#
# - "nameValuePlugPlugValueWidget:ignoreNamePlug", set to True to ignore the name plug and instead show a
# label with the name of the NameValuePlug. This is the same behaviour you get by default if the plug
# is not dynamic
class NameVal... |
"""
A program for calculating elasticities
This program is the extension package for E-Cell System Version 3.
"""
__program__ = 'Elasticity'
__version__ = '1.0'
__author__ = 'Kazunari Kaizu <<EMAIL>>'
__copyright__ = ''
__license__ = ''
from util import RELATIVE_PERTURBATION, ABSOLUTE_PERTURBATION, allzero, createIn... |
#!/usr/bin/env python3
import time
import unittest
import cereal.messaging as messaging
from selfdrive.test.helpers import with_processes
# only tests for EON and TICI
from selfdrive.hardware import EON, TICI
TEST_TIMESPAN = 30 # random.randint(60, 180) # seconds
SKIP_FRAME_TOLERANCE = 0
LAG_FRAME_TOLERANCE = 2 # m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.