content stringlengths 4 20k |
|---|
"""Unit tests for descrparser module."""
import unittest
from nav.ipdevpoll import descrparsers
class TestNtnuConvention(object):
sysname = 'foo-sw'
def test_lan(self):
d = descrparsers.parse_ntnu_convention(
self.sysname, 'lan,math,staff')
assert d is not None
assert d... |
'''
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License");... |
from odoo import models, fields
from odoo.addons.component.core import Component
class ProductBuyerinfoAdapter(Component):
_name = 'oxigesti.product.buyerinfo.adapter'
_inherit = 'oxigesti.adapter'
_apply_on = 'oxigesti.product.buyerinfo'
_sql = """select b.CodigoArticulo, b.Codigo_Mutua, b.Descrip... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import management.models
import sorl.thumbnail.fields
import django.utils.timezone
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_... |
import re
import bs4, os.path
import urllib.request, urllib.parse
Hiraganas = [
'あ', 'い', 'う', 'え', 'お',
'か', 'き', 'く', 'け', 'こ',
'が', 'ぎ', 'ぐ', 'げ', 'ご',
'さ', 'し', 'す', 'せ', 'そ',
'ざ', 'じ', 'ず', 'ぜ', 'ぞ',
'た', 'ち', 'つ', 'て', 'と',
'だ', 'ぢ', 'づ', 'で', 'ど',
'な', 'に', 'ぬ', 'ね', 'の',
'は... |
# coding: utf8
""" Unit tests:
- :class:`TestFiniteDppSamplers`
"""
import unittest
from itertools import chain # to flatten list of samples
import numpy as np
import numpy.random as rndm
import scipy.linalg as la
from scipy.stats import chisquare
import sys
sys.path.append('..')
from dppy.finite_dpps import Fi... |
# -*- coding: utf-8 -*-
""" The users app views"""
# django
from django.contrib import messages
from django.contrib.auth import views as auth_views
from django.contrib.auth.decorators import login_required
from django.contrib.auth.tokens import default_token_generator
from django.urls import reverse
from django.shortc... |
import io
from lxml import etree
from oslo.serialization import jsonutils
import six
import webtest
from keystone.auth import controllers as auth_controllers
from keystone.common import serializer
from keystone import tests
from keystone.tests import default_fixtures
from keystone.tests.ksfixtures import database
c... |
"""
Copyright (c) 2014-2015, The University of Texas at Austin.
All rights reserved.
This file is part of BLASpy and is available under the 3-Clause
BSD License, which can be found in the LICENSE file at the top-level
directory or at http://opensource.org/licenses/BSD-3-Clause
"""
from blaspy im... |
'''
JSON related utilities.
This module provides a few things:
1) A handy function for getting an object down to something that can be
JSON serialized. See to_primitive().
2) Wrappers around loads() and dumps(). The dumps() wrapper will
automatically use to_primitive() for you if needed.
3) Th... |
from django.urls import reverse
# wger
from wger.core.tests.base_testcase import (
WgerAccessTestCase,
WgerAddTestCase,
WgerEditTestCase,
)
from wger.gym.models import Contract
class AddContractTestCase(WgerAddTestCase):
"""
Tests creating a new contract
"""
object_class = Contract
u... |
import json
from backend.entities.isreal_response import IsrealResponse
from backend.errors.api_errors import ApiError
from backend.errors.unexpected_error import UnexpectedError
from functools import wraps
from flask import Response
def response_adapter_wrapper(mimetype="text/plain"):
def func_wrapper(func):
... |
import cattle
import os
import pytest
import random
import time
import inspect
from datetime import datetime, timedelta
NOT_NONE = object()
DEFAULT_TIMEOUT = 90
_SUPER_CLIENT = None
@pytest.fixture(scope='session')
def cattle_url():
default_url = 'http://localhost:8080/v1/schemas'
return os.environ.get('CATT... |
from __future__ import unicode_literals
import os
from datetime import date
from unittest import skipUnless
from django.apps import apps
from django.conf import settings
from django.contrib.sitemaps import GenericSitemap, Sitemap
from django.contrib.sites.models import Site
from django.core.exceptions import Improper... |
# -*- coding: utf-8 -*-
import re
import urlparse
import urllib2
from pyparsing import *
class PostParser(object):
url_regex = r'''(?xi)
\b
( # Capture 1: entire matched URL
(?:
[a-z][\w-]+: # URL protocol and colon
(?:
... |
#!/usr/bin/python3
from ansible.module_utils.arvados_common import process
def main():
additional_argument_spec={
"hostname": dict(required=True, type="str"),
"uuid": dict(required=False, type="str"),
"owner_uuid": dict(required=False, type="str", default=None),
}
filter_property... |
""" You noticed that one of your employees has a weird performance rate: although his performance is usually
good and stable, from time to time it drops drastically. You suspect it has something to do with the famous
Code of Clones series: new episodes started to come out recently, and everyone watches and rewatches ... |
"""Sensors flow for Withings."""
import typing as types
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.util import slugify
from . import const
from .common import _LOGGER, WithingsDataMa... |
#!/usr/bin/env python
'''code description'''
# pylint: disable = I0011, E0401, C0103, C0321
class Solution(object):
'''Solution description'''
def readBinaryWatch(self, num):
'''Solution function description'''
if num==0:return ["0:00"]
total = []
rev = False
if num > 5:... |
from flask import (Blueprint, request, redirect, session, url_for,
render_template, flash, current_app as app)
from flask.ext.login import (login_required, login_user, current_user,
logout_user)
from users import User
from flask.ext.babel import gettext as _
from forms im... |
import os
import json
from sqlalchemy import func, desc
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.connections.reachability_tests.bcf_testpath_api import ControllerCluster
import openstack_dashboard.dashboards.project.connections.reachability_tests.reachability_test_db as db
result... |
bl_info = {
"name": "Legion Renderer scene format",
"author": "R. Keith Morley",
"blender": (2,6,5),
"version": (0,0,1),
"location": "File > Import",
"description": "Export Legion data format",
"category": "Export"
}
if "bpy" in ... |
"""
/***************************************************************************
Name : About STDM Dialog
Description : Provides a brief narrative of STDM
Date : 11/April/11
copyright : (C) 2011 by John Gitau
email : <EMAIL>
********************... |
"""API for interacting with cas client."""
import os
from recipe_engine import recipe_api
class CasApi(recipe_api.RecipeApi):
"""A module for interacting with cas client."""
def __init__(self, **kwargs):
super(CasApi, self).__init__(**kwargs)
self._instance = None
self._cached_version = None
@p... |
'''
Given: A positive integer N≤100000, a number x between 0 and 1, and a DNA string s of length at most 10 bp.
Return: The probability that if N random DNA strings having the same length as s are constructed with GC-content x
(see “Introduction to Random Strings”), then at least one of the strings equals s.
We allo... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# do alpha-blending of two images, but also clip with stencil
reader1 = vtk.vtkBMPReader()
reader1.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp")
reader2 = vtk.vtkPNMReader()
reade... |
# -*- coding: utf-8 -*-
"""update_spatial_params
Revision ID: 67a6ac9b727b
Revises: 4736ec66ce19
Create Date: 2017-12-08 08:19:21.148775
"""
import json
from alembic import op
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Text
from superset import db
# revi... |
import math
from record_reader import RecordItemReader
class ImuSpeed:
def __init__(self):
self.timestamp_list = []
self.speed_list = []
self.last_speed_mps = None
self.last_imu_speed = None
def add(self, location_est):
timestamp_sec = location_est.measurement_time
... |
"""
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import ctypes
import queue
import pyglet
from pyglet.app import windows, BaseEventLoop
from pyglet.window.carbon import carbon, types, constants, _oscheck
EventHandlerProcPtr = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int,
... |
import mock
from neutron.agent.common import ovs_lib
from neutron.plugins.ml2.drivers.openvswitch.agent.openflow.native \
import ofswitch
from neutron.tests.unit.plugins.ml2.drivers.openvswitch.agent \
import ovs_test_base
DPID = "0003e9"
class OVSAgentBridgeTestCase(ovs_test_base.OVSOSKenTestBase):
def... |
#Test checks if Deep Learning works fine with a categorical dataset that has many missing values (in both train & test
# splits)
import sys
sys.path.insert(1,"../../../")
import h2o, tests
def missing():
# Connect to a pre-existing cluster
missing_ratios = [0, 0.1, 0.25, 0.5, 0.75, 0.99]
errors = [0,... |
"""Replace for Babbage.
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicabl... |
from __future__ import unicode_literals
DESC = """clevertagger is a German part-of-speech tagger based on a linear-chain CRF and SMOR.
It requires tokenized and sentence-delimited input (one token per line, empty line between sentenes) in UTF-8 encoding."""
import sys
import os
import argparse
import pexpect
from sub... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Module : qpolygontablewidget.py
# Project : L5MapEditor
# Creation date : 2016-07-29
# Description :
#
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem
from PyQt5.QtCore import pyqtSlot, pyqtSignal
from editor import config_loader
class QPoly... |
def generate_mesh(request, project_id=None, stack_id=None):
skeleton_id = int(request.POST.get('skeleton_id',-1))
# retrieve all components for a given skeleton id
components = Component.objects.filter(
project = project_id,
stack = stack_id,
skeleton_id = skeleton_id
).all()
... |
"""
HDMI CEC component.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/hdmi_cec/
"""
import logging
import multiprocessing
import os
from collections import defaultdict
from functools import reduce
import voluptuous as vol
import homeassistant.helpers... |
import common.log as logging
import common.config as Conf
import camera
from os import listdir
from os.path import isdir, isfile, join
from random import shuffle
from sys import _getframe
Options = [
Conf.StrOpt(name = 'use',
group = 'camera.fakecam',
default = 'camera.fakecam:... |
"""
Possible types are:
pna-p1D-2D : 1D parameter set with 1 point sweep of PNA ---------------------------------------- 1
pna-p2D-2D : 2D parameter set with 1 point sweep of PNA and 1 point of one of the parameters --- 4
pna-p1D-3D : 1D parameter set with many-point sweep of PNA ---------------------------------------... |
#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
==========================
fMRI: SPM nested workflows
==========================
The fmri_spm.py integrates several interfaces to perform a first
and second level analysis on a tw... |
from setuptools import setup, find_packages
from os import path
import hibp
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md')) as f:
long_description = f.read()
setup(
name='hibp',
packages = ['hibp'], # this must be the ... |
"""This module contains the general information for AaaUser ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class AaaUserConsts:
ACCOUNT_STATUS_ACTIVE = "active"
ACCOUNT_STATUS_INACTIVE = "inactive"
ADMIN_ACTION_CLE... |
from __future__ import absolute_import
from pyface.tasks.action.schema import SToolBar
from pyface.tasks.task_layout import TaskLayout, PaneItem
from traits.api import Instance
# ============= standard library imports ========================
# ============= local library imports ==========================
from pychr... |
import yaml
try:
from unittest2 import TestCase
from mock import patch, Mock
except ImportError:
from unittest import TestCase
from mock import patch, Mock
from yaml.scanner import ScannerError
from cfn_sphere.exceptions import TemplateErrorException, CfnSphereException, CfnSphereBotoError
from cfn_s... |
"""Recipe to build CIPD package with sealed Conda environment.
Supposed to be used from manually triggered Buildbot builders. We aren't
expecting rebuilding this environment often, so setting up and periodic schedule
is a waste of resources.
To build a new package for all platforms:
1. Manually trigger all builders b... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
__author__ = 'Alexei Evdokimov'
'''
Change tutorial from RogueBasin to rogueliketutorials.com
More Pythonic style and seems more OOP-ish ))
'''
import tdl
from components.fighter import Fighter
from death_functions import kill_monster, kill_player
from entity import Entity, ... |
"""
Add dropout layer followed by last pooling layer.
Updated by Lin Xiong Jul-21, 2017
"""
import argparse,logging,os
import mxnet as mx
from symbol_se_resnext_w_d import resnext
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(message)s')
console ... |
import argparse
def ParsePrep(p_prep):
prep_inp = p_prep.add_argument_group('Input options')
prep_inp.add_argument('-s', dest='sg', required=True, help='sgRNA Information Table (required)', metavar='<sg file>')
prep_inp.add_argument('-f', dest='fwd', required=True, help='Forward Fastq File (required)', met... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from translate.storage import test_base, wordfast as wf
class TestWFTime(object):
def test_timestring(self):
"""Setting and getting times set using a timestring"""
wftime = wf.WordfastTime()
assert wftime.timestring is None
... |
# -*- coding: utf-8 -*-
import logging
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.shortcuts import get_object_or_404
from django.template import loader
from Instanssi.kompomaatti.models import VoteCodeRequest, TicketVoteCode, Compo, Event, Entry, Competitio... |
"""
From NumbaPro
"""
from __future__ import print_function, division, absolute_import
import dis
import sys
import inspect
from collections import namedtuple
from numba import errors, utils
from numba.config import PYVERSION
opcode_info = namedtuple('opcode_info', ['argsize'])
def get_function_object(obj):
"... |
from tests.testcase import TestCase
from edmunds.database.databasemanager import DatabaseManager
from sqlalchemy.engine.base import Engine
from edmunds.globals import g
class TestDatabaseServiceProvider(TestCase):
"""
Test the Database Service Provider
"""
def test_not_enabled(self):
"""
... |
import sys
import random
from datetime import datetime
# Check which version
import sys
if sys.hexversion < 0x03000000: # Python2 import
from urlparse import urlparse
else: # Python3 import
from urllib.parse import urlparse
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.m... |
from __future__ import absolute_import
from pprint import pformat
from django.utils.html import escape
def attrs(**kwargs):
def _inner(fun):
for attr_name, attr_value in kwargs.items():
setattr(fun, attr_name, attr_value)
return fun
return _inner
def display_field(short_descrip... |
import fcntl
import socket
import struct
from time import time, sleep as time_sleep
class IntervalCheck:
"""
Utility class which can be used to run code within a polling loop at most once per n seconds. Set up an instance
of this class with the minimum delay between invocations then enclose the guarded co... |
# -*- coding: utf-8 -*-#
import json
import time
import RPi.GPIO as GPIO
import Adafruit_MAX31855.MAX31855 as MAX31855
import rrdtool
import PiOvenConfig as cfg
# Raspberry Pi software SPI configuration.
# These are the pins I have the thermocouple connected to
CLK = 25
CS = 24
DO = 18
thermocouple = MAX31855.MAX31... |
"""Parser for a small subset of requirements.txt syntax.
This parser supports only equality requirements. See parse_requirements()
docstring for more details.
Definition of the full requirements.txt syntax can be found at
https://pythonhosted.org/setuptools/pkg_resources.html#requirement-objects
"""
import re
HASH... |
"""
===================
sra
===================
Functions for downloading / handling data from the
`Sequence Read Archive <https://www.ncbi.nlm.nih.gov/sra>`_ (SRA).
"""
import distutils.version
import multiprocessing
import os
import shutil
import subprocess
def fastqFromSRA(samples, fastq_dump, fastqdir, aspera... |
from django.db import models
import uuid
from django.core.urlresolvers import reverse
DOCUMENT_TYPE_CHOICES = (
('cpf', 'Brazilian CPF'),
('passport', 'Passport'),
)
class Speaker(models.Model):
def __unicode__(self):
return "%s (%s)" % (self.complete_name, self.email)
def ge... |
import logging
import urlparse
from dirtyfields import DirtyFieldsMixin
from django.conf import settings
from django.contrib.postgres import fields
from django.core.urlresolvers import reverse
from django.db import models
from osf.models import base
from osf.models.contributor import InstitutionalContributor
from osf... |
'''
PygalChart is a helper to convert a string chart name
into object instance from pygal
'''
import pygal, logging
class PygalChart(object):
''' Detect and check the pygal type '''
def __init__(self, name=None):
''' Check if the name submitted is valid pygal or not '''
self.name = None
... |
import numpy as np
from ray.rllib.utils.framework import get_activation_fn, try_import_torch
from ray.rllib.utils.framework import get_variable
torch, nn = try_import_torch()
class NoisyLayer(nn.Module):
"""A Layer that adds learnable Noise
a common dense layer: y = w^{T}x + b
a noisy layer: y = (w + \\... |
from datetime import datetime
from typing import Union
import rsa
from peewee import DateTimeField, ForeignKeyField, PrimaryKeyField, fn
from andreas.db.fields import BlobIntegerField
from andreas.db.model import Model
from andreas.models.user import User
class KeyPair(Model):
"""
Stores information about p... |
from enum import Enum
class ProvisioningState(Enum):
accepted = "Accepted"
running = "Running"
ready = "Ready"
creating = "Creating"
created = "Created"
deleting = "Deleting"
deleted = "Deleted"
canceled = "Canceled"
failed = "Failed"
succeeded = "Succeeded"
updating = "Up... |
import json
import apps.packages.package_service as package
from superdesk import get_resource_service
from superdesk.services import BaseService
from eve.utils import ParsedRequest
from superdesk.notification import push_notification
def init_parsed_request(elastic_query):
parsed_request = ParsedRequest()
p... |
IMAGE_VIEWER = True
MATCH_MODE_PASSTHROUGH = 0
MATCH_MODE_LANDMARK_SS = 1
MATCH_MODE_STRINGS = [ \
'Single structure landmarks'
]
COMPARISON_MODE_DATA2M = 0
COMPARISON_MODE_CHECKERBOARD = 1
COMPARISON_MODE_DIFFERENCE = 2
# import the frame, i.e. the wx window containing everything
import CoMedIFrame... |
import logging
from keystoneclient.middleware import auth_token
LOG = logging.getLogger(__name__)
class AuthProtocol(auth_token.AuthProtocol):
"""
Subclass of keystoneclient auth_token middleware which also
sets the 'X-Auth-Url' header to the value specified in the config.
"""
def _build_user_hea... |
import os
import shutil
import tempfile
import unittest
import mock
from infra.services.sysmon import puppet_metrics
class PuppetMetricsTest(unittest.TestCase):
def setUp(self):
puppet_metrics.reset_metrics_for_unittest()
self.tempdir = tempfile.mkdtemp()
self.filename = os.path.join(self.tempdir, 'l... |
#!/usr/bin/env python
import os, sys, commands, string
from buildtools import *
# usage:
# The following all work as you might expect:
# python build.py
# ./build.py debug
# python build.py release
# python build.py test
# ./build.py clean
# ./build.py release clean
# python build.py release test
# The command line a... |
import textwrap
import libbe
import libbe.bugdir
import libbe.command
import libbe.command.util
from libbe.storage.util.settings_object import EMPTY
class Set (libbe.command.Command):
"""Change bug directory settings
>>> import sys
>>> import libbe.bugdir
>>> bd = libbe.bugdir.SimpleBugDir(memory=Fa... |
import pytest
from translate.storage import factory
from django.contrib.auth import get_user_model
from django.utils import timezone
User = get_user_model()
def _update_translation(store, item, new_values):
unit = store.getitem(item)
if 'target' in new_values:
unit.target = new_values['target']
... |
"""Declares several transform functions that verify an argument is of a specified type."""
# standard library
from typing import Any
# first-party
from tcex.utils.utils import Utils
from .validation_exception import ValidationError
def _to_type(target_type, **kwargs):
"""Validate that an argument can be cast to... |
# -*- coding: utf-8 -*-
import random
import collections
import statistics
from hypothesis import given
import hypothesis.strategies as st
from hypothesis import find, settings, Verbosity
from hypothesis.strategies import lists, integers
import unittest
from strgen import StringGenerator as SG
SPECIAL_CHARACTERS = "... |
import unittest
import yaml
from bitarray import bitarray
from basil.dut import Dut
cnfg_yaml = """
transfer_layer:
- name : dummy_tl
type : Dummy
init:
mem : {0: 2, 14: 4} # module version for init of spi and mem bytes
hw_drivers:
- name : spi_module
type : spi
inte... |
"""
Given a sorted array and a target value, return the index if the target is
found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
"""
class... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: errors.py
import mcl.status
ERR_SUCCESS = mcl.status.MCL_SUCCESS
ERR_INVALID_PARAM = mcl.status.framework.ERR_START
ERR_NOT_IMPLEMENTED = mcl.status.... |
"""
pghoard - unit test setup
Copyright (c) 2015 Ohmu Ltd
See LICENSE for details
"""
# pylint: disable=attribute-defined-outside-init
from pghoard.config import find_pg_binary, set_and_check_config_defaults
from pghoard.rohmu import compat
from shutil import rmtree
from tempfile import mkdtemp
import logging
import o... |
import random, logging
N = 1000
DIE_FACES = 6
ATTACK_DICE = 3
DEFENCE_DICE = 2
def roll_dice(dice: list):
for i in range(len(dice)):
dice[i] = random.randint(1, DIE_FACES)
dice.sort()
dice.reverse()
def attack_result(a: list, d: list) -> int:
attack = 0
# compare the best attack dice with... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 18 17:01:10 2017
@author: Alfred
"""
import csv
#from utils.db_con import DBcon
class CsvPipeline():
"""
Pipeline to csv file
"""
@classmethod
def from_crawler(cls, crawler):
"""
Get item fields and file path throug... |
"""
SALTS XBMC Addon
Copyright (C) 2014 tknorris
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.
T... |
from msrest.serialization import Model
class RedisFirewallRuleCreateParameters(Model):
"""Parameters required for creating a firewall rule on redis cache.
:param start_ip: lowest IP address included in the range
:type start_ip: str
:param end_ip: highest IP address included in the range
:type end... |
from django.conf import settings
from django.test import TestCase
from .. import forms
try:
# Try to import from the Python 3.3+ standard library.
from unittest.mock import patch
except ImportError as e:
# Otherwise, import from the `mock` project dependency.
from mock import patch
class SupplierCreat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import curses
from cumodoro.timeconvert import time_to_sec
import os
import logging
import sys
import math
#import cumodoro.signal
HOME = os.path.expanduser("~")
CONFIG_DIR = HOME + "/.cumodoro"
DATABASE = CONFIG_DIR + "/data.db"
LOGFILE = CONFIG_DIR + "/cumodoro.log"
T... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'DBNNMain.ui'
#
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindo... |
import requests
class DebugHelper:
"""A helper for printing debug messages."""
@staticmethod
def setup(options):
"""Initialize debug/logging in third party libraries correctly.
Args:
options (:class:`nyawc.Options`): The options to use for the current crawling runtime.
... |
from openstack_dashboard.api.rest import json_encoder
from openstack_dashboard.api.rest import utils
from openstack_dashboard.test import helpers as test
class RestUtilsTestCase(test.TestCase):
def test_api_success(self):
@utils.ajax()
def f(self, request):
return 'ok'
request... |
from se34euca.lib.EucaUITestLib_Base import *
class EucaUITestLib_Snapshot(EucaUITestLib_Base):
def test_ui_delete_snapshot(self):
print
print "Started Test: Delete Snapshot"
self.verify_element_by_link_text("Launch new instance")
print
print "Test: Go to the Page Snapshot"... |
import os
import re
import json
import logging
import datetime
import decimal
import binascii
from pycoin import encoding
from lib import config
D = decimal.Decimal
decimal.getcontext().prec = 8
def round_out(num):
#round out to 8 decimal places
return float(D(num))
def normalize_quantity(quantity,... |
from pynestml.meta_model.ast_data_type import ASTDataType
from pynestml.meta_model.ast_node import ASTNode
class ASTParameter(ASTNode):
"""
This class is used to store a single function parameter definition.
ASTParameter represents singe:
output: spike
@attribute compartments Lists with compartm... |
"""
This file contains helper functions for configuring module_store_setting settings and support for backward compatibility with older formats.
"""
import copy
import warnings
import six
def convert_module_store_setting_if_needed(module_store_setting):
"""
Converts old-style module_store_setting configura... |
from datetime import datetime, timezone, timedelta
import sqlite3
from ...core.user.User import User
def saveUser(userToSave):
conn = sqlite3.connect('src/data/sqlite/data.db')
cur = conn.cursor()
timeZoneInformation = userToSave.timeZone.utcoffset(datetime.now())
cur.execute("""INSERT INTO user (user... |
from setuptools import setup, find_packages
def read(filename):
"""
Read a file relative to setup.py location.
"""
import os
here = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(here, filename)) as fd:
return fd.read()
def find_version(filename):
"""
Find ... |
"""
==== TTX/FontTools Compreffor ====
This module automatically subroutines the CFF table in
a TTFont object, for the purposes of compressing the
outputted font file. In addition to providing a Python
interface, this tool can be used on the command line.
Usage (python):
>>> font = TTFont(filename)
>>> options = { ...... |
import sys
import os
import copy
import util
import shutil
import customExceptions
import paths
sys.path.append(paths.SCHEMACONFIGPATH)
sys.path.append(paths.PYXB)
from schemaconfig import schemaconfig as schema
import pyxb
import subprocess
class Element():
"Class that wraps Pyxb and provides easier use of modi... |
import time
from django.conf import settings
from django.utils.cache import patch_vary_headers
from django.utils.http import cookie_date
from django.utils.importlib import import_module
class SessionMiddleware(object):
def process_request(self, request):
engine = import_module(settings.SESSION_ENGINE)
... |
class Solution:
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
"""
sample strings
'abcdedcbabc'
'ababababa'
'aaaaaaaaa' -> 2^(n-1) ways
"""
"""
Note:
how to check if each substring is a ... |
import os
import caffe
import utils.computeStatistics
from libs.foldernames import *
from libs.models import *
from modules.getFeatures import find_before
from modules.get_stats import get_stats
from random import random
from shutil import copyfile
def train(outputFolder,inputFile,net=1,stats=None,key='Descriptio',\
... |
import sys
import os
if os.environ["PWD"][-4:] == "/bin":
sys.path.append("../..")
else:
sys.path.append("../")
os.environ["DJANGO_SETTINGS_MODULE"] = "djangoid.settings"
from djangoid.users.models import ClaimedUri
def main():
uris = ClaimedUri.objects.all()
for uri in uris:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import click
HELP_COMMAND_EXPORT = 'Export existing datasets into file in YAML format.'
HELP_COMMAND_PLAN = 'Generate and show an execution plan.'
HELP_COMMAND_APPLY = 'Builds or changes datasets.'
HELP_COMMAND_DESTROY = 'Specify sub... |
"""Classes and functions that help to inspect Python source w.r.t. TF graphs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import os
import re
import zipfile
import absl
import numpy as np
from tensorflow.python.debug.lib import p... |
# -*- coding: utf-8 -*-
# In production it would be worth to study David Norvig approach.
import re
import requests
URL = 'http://canyouhack.it/Content/Challenges/Programming/Prog2.php'
COOKIES = {
'PHPSESSID': '***',
'SMFCookie416': '***',
}
solved = None
def solve(sstr):
global solved
def same_r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.