content stringlengths 4 20k |
|---|
"""Image cache manager.
The cache manager implements the specification at
http://wiki.openstack.org/nova-image-cache-management.
"""
import hashlib
import os
import re
import time
from nova import compute
from nova import context as db_context
from nova import db
from nova import flags
from nova import log as loggi... |
"""TensorFlow Debugger (tfdbg) Utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
from six.moves import xrange # pylint: disable=redefined-builtin
def add_debug_tensor_watch(run_options,
node_name,
... |
def donuts(count):
if count < 10:
return 'Number of donuts: ' + str(count)
return 'Number of donuts: many'
# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return in... |
from django.contrib.contenttypes.models import ContentType
from hamcrest import equal_to, assert_that, none, has_entry, all_of, has_key, has_length, is_not
from river.models import TransitionApproval
from river.models.factories import PermissionObjectFactory, UserObjectFactory
from river.models.hook import BEFORE
from... |
from datetime import timedelta
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, pre_delete
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from misago.signals import (delete_user_content, merge_thread, move_forum_conte... |
import os
import unittest
from ptraceplus.tracer import Tracer
from common import gen_test_progs, DATA_DIR
class TestTracerBasic(unittest.TestCase):
"""Basic Tracer tests"""
def setUp(self):
self._tracer = Tracer()
def test_no_processes(self):
"""Test if tracer has no process"""
... |
#!/usr/bin/env python3
"""Run AFL repeatedly with externally supplied generated packet from STDIN."""
import logging
import sys
import afl
from ryu.controller import dpset
from faucet import faucet
import fake_packet
ROUNDS = 1
logging.disable(logging.CRITICAL)
def main():
"""Run AFL repeatedly with externall... |
from .util import TimeoutManager
def iterate_with_timeout(iterator, timeout):
timeout_mgr = TimeoutManager(timeout)
for item in iterator:
yield item
if timeout_mgr.is_finished():
return
def generate(domain):
while True:
yield domain.generate_one()
def iterate_steps(... |
import asyncio
from . import exceptions
__all__ = ['Handler']
class Handler:
def __init__(self, protocol, request, response, payload):
self.transport = protocol.transport
self.request = request
self.response = response
self.payload = payload
def prepare_response(self):
... |
from auxiliary.iterable import iterable
from system.verify_state_feasibility import verify_state_feasibility
def execute_sequence(ps_obj, action_sequence):
# Perform actions according to sequence
states = []
for i, action in enumerate(action_sequence):
action_type = action[0]
index = actio... |
from nbxmpp.namespaces import Namespace
from nbxmpp.structs import StanzaHandler
from nbxmpp.structs import ChatMarker
from nbxmpp.modules.base import BaseModule
class ChatMarkers(BaseModule):
def __init__(self, client):
BaseModule.__init__(self, client)
self._client = client
self.handler... |
import unittest
import doctest
import time
import jsonpickle.util
from jsonpickle.compat import unicode, long, PY2
from jsonpickle import util
class Thing(object):
def __init__(self, name):
self.name = name
self.child = None
class DictSubclass(dict):
pass
class ListSubclass(list):
pa... |
from django.template.defaultfilters import filesizeformat
from rest_framework import serializers
from mkt.webapps.serializers import SimpleAppSerializer, SimpleESAppSerializer
from mkt.websites.serializers import ESWebsiteSerializer, WebsiteSerializer
class BaseFireplaceAppSerializer(object):
def get_icons(self... |
"""
Unit tests for :func:`iris.analysis.name_loaders._generate_cubes`.
"""
# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests # isort:skip
from unittest import mock
from iris.fileformats.name_loaders import NAMECoord, _generate_cubes
clas... |
"""The command group for cloud container clusters."""
from googlecloudsdk.calliope import actions
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.container import flags
from googlecloudsdk.core import properties
class Clusters(base.Group):
"""Deploy and teardown Google Container Engine clu... |
import subprocess
import tempfile
import socket
import shutil
import os
from sets import Set
from ansible.parsing.dataloader import DataLoader
from ansible.inventory.manager import InventoryManager
from ansible.vars.manager import VariableManager
class VariableManagerWrapper:
def __init__(self, vm):
se... |
from amcat.models import ArticleSet
from api.rest.resources.amcatresource import AmCATResource
from api.rest.viewsets.articleset import ArticleSetSerializer
class ArticleSetResource(AmCATResource):
model = ArticleSet
queryset = ArticleSet.objects.all()
serializer_class = ArticleSetSerializer |
from oslo_log import log
from oslo_utils import excutils
from dragonflow.tests.common import app_testing_objects
from dragonflow.tests.common import utils as test_utils
from dragonflow.tests.fullstack import test_base
LOG = log.getLogger(__name__)
class TestApps(test_base.DFTestBase):
def test_infrastructure(se... |
# -*- coding: utf-8 -*-
import unittest
from stockviderApp.sourceDA.symbols.yahooSymbolsDA import YahooSymbolsDA
class YahooSymbolsDATestCase(unittest.TestCase):
def setUp(self):
yahooSymbDAO = YahooSymbolsDA()
self.symbDict = yahooSymbDAO.returnSymbolsDict()
def tearDown(self):
... |
# -*- coding: utf-8 -*-
import itertools
import os
import urlparse
from github3 import GitHubError
import markupsafe
from modularodm import fields
from framework.auth import Auth
from website import settings
from website.util import web_url_for
from website.addons.base import exceptions
from website.addons.base imp... |
#!/usr/bin/python3
from gi.repository import GLib, PackageKitGlib
import sys
from debug import *
# progress callback
# http://www.packagekit.org/gtk-doc/PkProgress.html
def progress(progress, type, user_data):
if (type.value_name == "PK_PROGRESS_TYPE_PERCENTAGE" and
progress.props.package != None):
... |
# -*- coding: utf-8 -*-
"""
Viriyothai (2009) Variance Minimization Light Probe Sampling
============================================================
Defines the *Viriyothai (2009)* variance minimization light probe sampling
objects:
- :func:`colour_hdri.\
light_probe_sampling_variance_minimization_Viriyothai2009`
... |
from msrest.serialization import Model
class NodeTransitionResult(Model):
"""Represents information about an operation in a terminal state (Completed or
Faulted).
:param error_code: If OperationState is Completed, this is 0. If
OperationState is Faulted, this is an error code indicating the reason.... |
from django.shortcuts import render
from query_processor import QueryProcessor
from query_processor.probability import make_ngram_estimator
from query_processor.collocationer import Collocationer
from query_processor.ngram import NGram
from indexer.models import MainIndex
from forms import SearchForm
import logging
l... |
# Задача 13. Вариант 23
# Разработайте игру "Крестики-нолики".
#(см. М.Доусон Программируем на Python гл. 6).
# Сосновый М.С.
# 21.05.2016
from tkinter import *
import random
class Game:
crturn = True
field = []
def __init__(self):
for i in range (3):
self.field.append(['', '', ''])
... |
import gi, sys
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
from visual import vismol, vis_parser, vismol_shaders as vm_sh
def main():
frames = vis_parser.parse_pdb(sys.argv[1])
#vism = vismol.MyGLProgram(frames, vm_sh.vertex_shader_point_light, vm_sh.fragment_shader_point_lig... |
class DeviceMotionTestCommon(object):
def __init__(self):
pass
def clear_event_listener(self):
clear_script = """
window.removeEventListener("devicemotion", window.wrappedJSObject.deviceListener);
window.removeEventListener("devicemotion", window.wrappedJSObject.checkVa... |
import difflib
import logging
from django.conf import settings
from django.contrib.sites.models import Site
from django.urls import reverse as django_reverse
from django.utils.translation import ugettext as _, ugettext_lazy as _lazy
from bleach import clean
from tidings.events import InstanceEvent, Event, EventUnion
... |
__author__ = 'Dani'
from wikidata_exp.wdexp.wikidata.commands.category_detection_SPARQL import CategoryDetectionCommand
from wikidata_exp.wdexp.utils import rel_path_to_file
import unittest
import json
class TestCategoryDetectionSparql(unittest.TestCase):
def test_category_detection_slice(self):
... |
from lib.alerttask import AlertTask
from mozdef_util.query_models import SearchQuery, TermMatch, PhraseMatch
class TraceAudit(AlertTask):
def main(self):
self.parse_config('trace_audit.conf', ['hostfilter'])
search_query = SearchQuery(minutes=5)
search_query.add_must([
TermMat... |
#!python
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptool... |
import click
from globus_cli.parsing import command, endpoint_id_arg, security_principal_opts
from globus_cli.safeio import formatted_print
from globus_cli.services.auth import maybe_lookup_identity_id
from globus_cli.services.transfer import assemble_generic_doc, get_client
@command(
"create",
short_help="A... |
'''setup.py - Waqas Bhatti (<EMAIL>) - Nov 2016
This sets up the package.
Stolen from http://python-packaging.readthedocs.io/en/latest/everything.html and
modified by me.
'''
__version__ = '0.1.6'
import setuptools
import sys
# for f2py extension building
try:
from numpy.distutils.core import Extension, setup
... |
import warnings
from .base import BaseModel, Scraper
from .schemas.jurisdiction import schema
from .popolo import Organization
class Jurisdiction(BaseModel):
""" Base class for a jurisdiction """
_type = 'jurisdiction'
_schema = schema
# schema objects
classification = None
name = None
u... |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains th... |
"""
Wrapper around tests
"""
import io
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.utils import timezone
from .models import *
ADMIN_PASSWORD = '123456'
CLAIMED_A_PASSWORD = '123456'
CLAIMED_B_PASSWORD = '123456'
def create_users():
User.... |
from rpython.rtyper.test.tool import BaseRtypingTest
from rpython.rlib.rstruct.runpack import runpack
from rpython.rlib.rarithmetic import LONG_BIT
import struct
class TestRStruct(BaseRtypingTest):
def test_unpack(self):
pad = '\x00' * (LONG_BIT//8-1) # 3 or 7 null bytes
def fn():
re... |
# """This file contains the SQLAlchemy ORM models"""
from sqlalchemy.orm import synonym
from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
from sqlalchemy.schema import Sequence
from geoalchemy2.types import Geometry
from geoalchemy2.shape import from_shape, to_shape
import random
from datetime import da... |
"""
Constant definitions for connection handling.
"""
from webdav.Constants import NS_DAV, PROP_RESOURCE_TYPE
__version__ = "$Revision-Id:$"
# Constants for connection pooling
MAX_POOL_NUMBER = 10
MAX_CONNECTION_NUMBER = 4
# Defines special WebDAV properties
LINK_TARGET_PROPERTY = ("http://dlr.... |
import nova.openstack.common.cfg
import nova.openstack.common.importutils
def API(*args, **kwargs):
importutils = nova.openstack.common.importutils
compute_api_class = nova.openstack.common.cfg.CONF.compute_api_class
cls = importutils.import_class(compute_api_class)
return cls(*args, **kwargs) |
"""This module defines the abstract linear constraint class."""
import numpy as np
from .constraint import ConstraintType, DiscretizationType, Constraint
from ..interpolator import AbstractGeometricPath
class LinearConstraint(Constraint):
"""A core type of constraints.
Also known as Second-order Constraint.
... |
import inspect
import logging
import struct
import unittest
from nose.tools import eq_
from ryu.lib import addrconv
from ryu.lib.packet import dhcp
LOG = logging.getLogger(__name__)
class Test_dhcp_offer(unittest.TestCase):
op = dhcp.DHCP_BOOT_REPLY
chaddr = 'aa:aa:aa:aa:aa:aa'
htype = 1
hlen = 6
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
**********************************************************
*
* PiRC - auto
* version: 20170404a
*
* By: Nicola Ferralis <<EMAIL>>
*
***********************************************************
'''
print(__doc__)
import sys
sys.path.append('piRC_lib')
import piRC_gpio
... |
#!/usr/bin/env python
from __future__ import print_function
from __future__ import absolute_import
from builtins import zip
from builtins import object
import pandas as pd
from pandas import Series
#import urllib2
#import httplib
import json
import os
#import cached vocabulries as backup
from . import find_pmag_dir
fro... |
#!/usr/bin/env python
# coding: utf-8
#===================================================
from config import Log
#---------------------------------------------------
import sqlite3
import threading
import traceback
#===================================================
def _dict_factory(cursor, row):
aDict = {}
... |
from qingcloud.cli.misc.utils import explode_array
from qingcloud.cli.iaas_client.actions.base import BaseAction
class ResizeVolumesAction(BaseAction):
action = 'ResizeVolumes'
command = 'resize-volumes'
usage = '%(prog)s -v "volume_id,..." -s <size> [-f <conf_file>]'
description = 'Extend one or more... |
import re
from django.conf import settings
from django.http import Http404
from django.shortcuts import render
from django.urls import resolve
from django.utils.deprecation import MiddlewareMixin
from pootle.core.forms import MathCaptchaForm
URL_RE = re.compile("https?://", re.I)
CAPTCHA_EXEMPT_URLPATTERNS = (
... |
import Rapicorn # Load Rapicorn language bindings for Python
# Setup the application object, unsing a unique application name.
app = Rapicorn.init_app ("Test Rapicorn Bindings")
# Define the elements of the dialog window to be displayed.
hello_window = """
<Window declare="testbind-py">
<RapicornIdlTestWidget i... |
__author__ = 'labx'
import numpy
import Shadow
# Import elements from common Glossary
from optics.driver.abstract_driver import AbstractDriver
from optics.magnetic_structures.bending_magnet import BendingMagnet
from optics.beamline.beamline_position import BeamlinePosition
from optics.beamline.optical_elements.lens... |
# zimport.py - Import Zettels into an exising database
import os
import os.path
import sys
import frontmatter # to accommodate Markdown with YAML frontmatter
from . import zdb, zettel
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
de... |
XXXXXXXXX XXXXX
XXXX
XXXXXXXXX XXX XXXXXXXXXX XXXXXXXX X XXXXXXXXX XXXXXXXX XXX XXXXXX XXXXXXXXX
XXX XXXXXXXXXX XXX XXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXX
XXX
XXXXXX
XXXXXX
XXXXX XXXXXXXXXXXXXXXX
XXXXXXXXXXXX XXX XXXXXXXX XXXXXXXXX XXX XXXXXXX XXXXXXXX XXXXXXXXXXXXXX
XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXX... |
import os
import sys
import stat
import tools
import threading
import tempfile
from contextlib import contextmanager
import logger
class FIFO(object):
"""
interprocess-communication with named pipes
"""
def __init__(self, fname):
self.fifo = fname
self.alarm = tools.Alarm()
def de... |
import Pyro.core
import pathfinder
import time
class MapServer(Pyro.core.ObjBase):
def __init__(self):
Pyro.core.ObjBase.__init__(self)
self.mapserver = pathfinder.Graph()
self.routecache = {}
self.flush_time = time.time()
def route_comp(self, fromt, to_list):
map_bu... |
"""
Provides the core event loop
"""
import copy
import logging
import signal
from collections import defaultdict
from spock.utils import pl_announce
logger = logging.getLogger('spock')
class EventCore(object):
def __init__(self):
self.kill_event = False
self.event_handlers = defaultdict(list)
... |
from PySide import QtCore, QtGui
from PySide.QtCore import *
from PySide.QtGui import *
from view.gen.mainView import Ui_MainWindow
from view.otherViews import LoginView, MenuView
from model.model import *
from db import sessionScope
import view.gen.resources_rc
from datetime import datetime
MAX_ROOMS = 21
class Mai... |
"""
Contains functionality common to extensions.
"""
import sys
import logging
import importlib
import pkgutil
import argparse
import traceback
import testbed.settings
import testbed.core.logger
def logger_create():
""" Create logger for tbd application. """
console = logging.StreamHandler()
formatter = l... |
#!/usr/bin/python
import os
import sys
sys.path.insert(0, '../src')
os.environ['DJANGO_SETTINGS_MODULE'] = 'rhic_serve.settings'
from mongoengine.django.auth import User
#from django.contrib.auth.models import Group
from rhic_serve import settings
from rhic_serve.rhic_rest.models import *
def load_lines(lines, ma... |
# from optparse import make_option
# from pprint import pprint
import csv
import StringIO
# import re
#
from django.core.management.base import BaseCommand
from django.conf import settings
from pombola.core import models
class Command(BaseCommand):
help = """
Output CSV of all constituencies and their cu... |
# -*- coding: utf-8 -*-
import fauxfactory
import pytest
from cfme.automate.service_dialogs import DialogCollection
from cfme.rest.gen_data import service_catalogs as _service_catalogs
from cfme.services.catalogs.catalog_item import CatalogItem
from cfme.services.catalogs.service_catalogs import ServiceCatalogs
from c... |
#! /usr/bin/env python
""" Tests which show a differences between NMRPipe's and nmrglue's processing
functions and a fix is desired. """
import nmrglue.fileio.pipe as pipe
import nmrglue.process.pipe_proc as p
# FSH
# the first three tests will fail because MIN/MAX values are off a little
d, a = pipe.read("1D_freq_r... |
from __future__ import division
import warnings
import numpy as np
import scipy.sparse as sp
from .base import BaseEstimator, ClassifierMixin, RegressorMixin
from .utils import check_random_state
from .utils.validation import check_array
from .utils.validation import check_consistent_length
from .utils.random import ... |
from sys import stderr
from tempfile import mkstemp
from os import close, unlink
from math import hypot
from subprocess import Popen, PIPE
from osgeo import osr
try:
from PIL import Image
except ImportError:
import Image
from ModestMaps.Geo import Location
from ModestMaps.Core import Coordinate
from ModestMa... |
from typing import Dict
from tests.functional.services.catalog.utils.api.conf import catalog_api_conf
from tests.functional.services.utils import http_utils
def add_document(bucket: str, archiveid: str, object: Dict) -> http_utils.APIResponse:
if not bucket:
raise ValueError("Cannot add document to objec... |
from bambou import NURESTObject
class NUAggregateMetadata(NURESTObject):
""" Represents a AggregateMetadata in the VSD
Notes:
Metadata associated to a entity
"""
__rest_name__ = "aggregatemetadata"
__resource_name__ = "aggregatemetadatas"
## Constants
CONST_ENT... |
# coding=utf-8
import sys
import traceback
import inspect
_max_reported_output_size = 1 * 1024 * 1024
_reported_output_chunk_size = 50000
PY2 = sys.version_info[0] == 2
if PY2:
text_type = unicode # noqa: F821
binary_type = str
else:
text_type = str
binary_type = bytes
_sys_stdout_encoding = sys.s... |
import revlog
class filelog(revlog.revlog):
def __init__(self, opener, path):
revlog.revlog.__init__(self, opener,
"/".join(("data", path + ".i")))
def read(self, node):
t = self.revision(node)
if not t.startswith('\1\n'):
return t
s = t.inde... |
from torchtext.utils import (
download_from_url,
)
from torchtext.data.datasets_utils import (
_RawTextIterableDataset,
_wrap_split_argument,
_add_docstring_header,
_create_dataset_directory,
_create_data_from_csv,
)
import os
URL = {
'train': "https://raw.githubusercontent.com/mhjabreel/Ch... |
from django.db import models
from django.contrib.contenttypes.models import ContentType
from ..core.models import MockTag, AnotherMockModel, MockModel, AFourthMockModel
class Document(models.Model):
type_name = models.CharField(max_length=50)
number = models.IntegerField()
name = models.CharField(max_len... |
import re
import os
import errno
def evaluate_environment_variables(string):
p = re.compile("\${env:(.+?)}")
m = p.search(string)
while m:
env = m.group(1)
value = os.getenv(env)
if not value:
raise Exception("Environment variable %s is undefined" % (env))
string... |
# FreeCAD module providing base classes for document objects and view provider
# (c) 2011 Werner Mayer LGPL
import FreeCAD
class DocumentObject(object):
"""The Document object is the base class for all FreeCAD objects."""
def __init__(self):
self.__object__=None
self.initialised=F... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import json
from slackclient import SlackClient
class SlackApi(object):
def __init__(self, token, logger):
self.api = SlackClient(token)
self.logger = logger
def get_users(self):
response = self.api.api_call("users.list")
if not... |
# coding=UTF-8
from numpy import size, amax, where, empty
import numpy as np
from random import random
import maxflow
from seamcarving.utils import cli_progress_bar, cli_progress_bar_end
DEBUG = True
class video_seam_carving_decomposition(object):
#
# X: An fxnxmxc matrix (f = frame, n = rows, m = columns, c = c... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 13:46:53 2015
@author: Gerhard
"""
class Distributorsetup:
def __init__(self, numberofDistributors, starting_value_i, **Distributorattributes ):
self.numberofDistributors = numberofDistributors
self.Distributorattributelist = []
self.D... |
# encoding: utf-8
import 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 'Status'
db.create_table('djangovoice_status', (
('id', self.gf('django.db.mode... |
#! /usr/bin/env python
# Time-stamp: <2015-09-24 10:58 <EMAIL>>
""" Generates cards for a Stroop task """
import pygame
import random
def share(list1, list2):
""" returns True if list1 and list2 have at least
one element in common, at the same position."""
share = False
for i in range(len(list1)... |
"""
FILE: sample_detect_change_point.py
DESCRIPTION:
This sample demonstrates how to detect entire series change points.
Prerequisites:
* The Anomaly Detector client library for Python
* A .csv file containing a time-series data set with
UTC-timestamp and numerical values pairings.
Examp... |
#!/usr/bin/env python
#
#
'''
This example shows how to create a density fitting calculation.
See also
examples/scf/20-density_fitting.py
examples/pbc/11-gamma_point_all_electron_scf.py
'''
from pyscf import gto, scf, df
from pyscf.pbc import gto as pgto
from pyscf.pbc import dft as pdft
from pyscf.pbc import df as ... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.conf import settings
from model_utils.models import TimeStampedModel
class News(TimeStampedModel):
"""
News module main model
"""
user = models.ForeignKey(User,... |
"""Test cases for the ``ca_settings`` module."""
from datetime import timedelta
from unittest import mock
from django.test import TestCase
from .. import ca_settings
from ..subject import get_default_subject
from .base.mixins import TestCaseMixin
class SettingsTestCase(TestCase):
"""Test some standard settings... |
"""
Views - Tests
"""
# Imports #####################################################################
from unittest.mock import patch
import ddt
from django.conf import settings
from rest_framework import status
from instance.tests.api.base import APITestCase
from instance.tests.models.factories.openedx_instance im... |
#!usr/bin/python
# == Configuration file for AirMode ==
#
# This script is used for configure your installation of AirMode
# Follow the comments for a correct configuration, and please don't modify
# undocumented lines.
#
# Using correctly this file, it's possible to automate repetitive tasks, and
# make the program m... |
from werkzeug.utils import secure_filename
from flask import Flask,render_template, request
app=Flask(__name__)
app.route('/upload', methods=['POST'])
def upload():
dict_tmp = {}
f = request.files['imgFile']
dir = request.args.get('dir')
if dir == 'image':
if os.path.splitext(f.filename)[1] not ... |
# -*- coding: utf-8 -*-
""" base in common for our flask internal extensions """
# TO FIX: create a base object for flask extensions like the injector
import abc
import time
from flask import Flask, _app_ctx_stack as stack
from injector import Module, singleton, inject # , provider
from rapydo.utils.meta import Met... |
"""Run individual tasks within the Clusterk framework.
"""
import os
import shutil
import subprocess
import uuid
import yaml
from bcbio import utils
from bcbio.provenance import do
from bcbiovm.ship import pack, reconstitute
def runfn(fn_name, queue, wrap_args, parallel, run_args):
"""Run external function submi... |
import re
from ..punctuation import ALPHA_LOWER, ALPHA
from ...symbols import ORTH, NORM
_exc = {}
_abbr_period_exc = [
{ORTH: "A.B.D.", NORM: "Amerika"},
{ORTH: "Alb.", NORM: "albay"},
{ORTH: "Ank.", NORM: "Ankara"},
{ORTH: "Ar.Gör."},
{ORTH: "Arş.Gör."},
{ORTH: "Asb.", NORM: "astsubay"},
... |
import string
import types
from module_info import *
from module_game_menus import *
from process_common import *
from process_operations import *
def save_game_menu_item(ofile,variable_list,variable_uses,menu_item,tag_uses,quick_strings):
ofile.write(" mno_%s "%(menu_item[0]))
save_statement_block(ofile,0, 1, m... |
# This file is the program that interacts with the user and utilizes person.py's individual class.
import hourly_calculator
import household
import time
import os
import pickle
print "============================================="
print "Monthly expenditure report v1.0 by Danny Chen"
def main_menu():
print "=====... |
from intra import *
import matplotlib.pyplot as plt
import requests as r
import re
text = None
def load(url, html=False):
global text
res = r.get(url)
stream = res.text
if html:
p = re.compile(r'<.*?>')
stream = p.sub('', stream)
text = Text(stream)
print 'loaded'
def paste(s... |
import six
from sahara.api import acl
from sahara.service.api.v2 import jobs as api
from sahara.service import validation as v
from sahara.service.validations.edp import job_execution as v_j_e
from sahara.service.validations.edp import job_execution_schema as v_j_e_schema
import sahara.utils.api as u
rest = u.RestV2... |
import unittest
import sys
import logging
from ipwhois import (Net, IPDefinedError, ASNLookupError, ASNRegistryError,
WhoisLookupError, HTTPLookupError, HostLookupError)
LOG_FORMAT = ('[%(asctime)s] [%(levelname)s] [%(filename)s:%(lineno)s] '
'[%(funcName)s()] %(message)s')
logging.b... |
# -*- coding: utf-8 -*-
"""
OnionShare | https://onionshare.org/
Copyright (C) 2015 Micah Lee <<EMAIL>>
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 o... |
import datetime
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
from django.template.defaultfilters import escapejs_filter
from django_jinja import library
from django.utils.http import urlencode
from jinja2 import Markup
@library.global_function
def thisyear():
"""The current y... |
import datetime
from unittest import mock
import pytz
from testtools import matchers
from heat.engine.clients.os import swift
from heat.tests import common
from heat.tests import utils
class SwiftClientPluginTestCase(common.HeatTestCase):
def setUp(self):
super(SwiftClientPluginTestCase, self).setUp()
... |
import unittest
from tempfile import NamedTemporaryFile
from os.path import exists
from os import remove
from StringIO import StringIO
from crumbs.utils.file_utils import (compress_with_bgzip, uncompress_gzip,
fhand_is_seekable,
wrap_in_buffered... |
from typing import Optional
from src.models import ScibetMatch
from src.settings import match_cache, import_league_colors, Colors, Favourites
@match_cache
def prediction(match: ScibetMatch) -> Optional[str]:
if not match.full_data:
return None
if (
match.home_tip > 43
and 1.39 < match... |
PLATFORMS = [
{"id": 1, "desc": "ship"},
{"id": 2, "desc": "moored surface buoy"},
{"id": 3, "desc": "drifting surface float"},
{"id": 4, "desc": "drifting subsurface profiling float"},
{"id": 5, "desc": "autonomous underwater vehicle"},
{"id": 6, "desc": "offshore structure"},
{"id": 7, "de... |
"""
Debian installation
"""
import shutil
import os
import re
import oz.Guest
import oz.ozutil
import oz.OzException
class DebianGuest(oz.Guest.CDGuest):
"""
Class for Debian 5, 6, 7 and 8 installation.
"""
def __init__(self, tdl, config, auto, output_disk, netdev, diskbus,
macaddres... |
import random
from collections import deque
from twisted.internet.defer import inlineCallbacks
from battlesnake.outbound_commands import mux_commands
from battlesnake.plugins.contrib.factions.defines import ATTACKER_FACTION_DBREF, \
DEFENDER_FACTION_DBREF
from battlesnake.plugins.contrib.inventories.blueprints_ap... |
import time
from tempest.api.identity import base
from tempest.common.utils import data_utils
from tempest import test
class UsersV3TestJSON(base.BaseIdentityV3AdminTest):
@test.idempotent_id('b537d090-afb9-4519-b95d-270b0708e87e')
def test_user_update(self):
# Test case to check if updating of user... |
"""Tests for metrics_utils."""
from absl.testing import parameterized
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import test_util
from tensorflow.python.keras import combinations
from tensorflow.python.keras.utils import metrics_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.