code stringlengths 1 199k |
|---|
def assert_window_size(win_size):
"""
Asserts invalid window size.
Window size must be odd and bigger than 3.
"""
assert win_size >= 3, 'ERROR: win size must be at least 3'
if win_size % 2 == 0:
print('It is highly recommended to user odd window sizes.'\
'You provided %s, a... |
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize("readCheartData.pyx",language="c",compiler_directives={'profile': False, 'boundscheck' : False, 'wraparound': False, 'cdivision' : False})) |
"""I provide functionalities to serialize RDF-REST resource.
I act as a registry of serializers. Serializers can be
`iterated by decreasing preference <iter_serializers>`func:, selected based on
`content-type <get_serializer_by_content_type>`:func: or
`extension <get_serializer_by_extension>`:func:, and dedicated seria... |
"""
This sourcefile is intended to be imported in package.py files, in functions
including:
- the special 'preprocess' function;
- early bound functions that use the @early decorator.
"""
from rez.utils.system import popen
from rez.exceptions import InvalidPackageError
def expand_requirement(request, paths=None):
"... |
from abc import ABCMeta
from abc import abstractmethod
from eos.const.eve import EffectCategoryId
from eos.pubsub.message import EffectApplied
from eos.pubsub.message import EffectUnapplied
from .base import BaseItemMixin
class BaseTargetableMixin(metaclass=ABCMeta):
@abstractmethod
def _get_effects_tgts(self, ... |
import cadquery
from Helpers import show
length = 80.0
height = 60.0
thickness = 10.0
center_hole_dia = 22.0
cbore_hole_diameter = 2.4
cbore_diameter = 4.4
cbore_depth = 2.1
result = cadquery.Workplane("XY").box(length, height, thickness) \
.faces(">Z").workplane().hole(center_hole_dia) \
.faces(">Z").workplane... |
"""
Each user's settings are stored in a "registry". This is a git repository with a set of json files which store the state of the subuser installation.
"""
import os
import subuserlib.classes.subusers, subuserlib.classes.userOwnedObject, subuserlib.git
class Registry(subuserlib.classes.userOwnedObject.UserOwnedObject... |
'''
Created on 14 sept. 2010
@author: nico
'''
import os, sys
import karacos
import ConfigParser
_appsdirs = [os.path.join(karacos.homedir,'apps'), os.path.join(karacos._srvdir,'deploy')]
def listApps():
_apps = {}
for _appsdir in _appsdirs:
if not os.path.exists(_appsdir):
os.makedirs(_apps... |
"""
DO NOT EDIT THIS FILE!
It is automatically generated from opcfoundation.org schemas.
"""
from opcua import ua
def create_standard_address_space_Part8(server):
node = ua.AddNodesItem()
node.RequestedNewNodeId = ua.NodeId.from_string("i=2365")
node.BrowseName = ua.QualifiedName.from_string("DataItemType")... |
import urllib.request
import urllib.parse
import urllib.error
from html.parser import HTMLParser
import datetime
class HistQuoteHTMLParser(HTMLParser):
"""
Customized parser class for web page scraping historical stock quotes.
See the reference information at the bottom of this file to see
how the HTML ... |
from casadi import *
from numpy import *
import matplotlib.pyplot as plt
def create_integrator_euler():
u = SX("u") # control for one segment
# Initial position
s0 = SX("s0") # initial position
v0 = SX("v0") # initial speed
m0 = SX("m0") # initial mass
t0 = SX("t0") # initial time
tf = SX ("tf") # final t... |
import os
import sys
import subprocess
import json
import socket
DHCP_LEASES = "/tmp/dhcp.leases"
devnull = open(os.devnull, 'w')
self = sys.argv[0]
option = sys.argv[1] if len(sys.argv) > 1 else None
def get_DHCP_leases():
leases = {}
with open(DHCP_LEASES) as lease_file:
for line in lease_file:
fields = line.s... |
from urllib import urlretrieve
def firstNonBlank (lines):
for eachLine in lines:
if not eachLine.strip():
continue
else:
return eachLine
def firstLast (webpage):
f = open(webpage)
lines = f.readlines()
f.close()
print firstNonBlank(lines),
lines.reverse()
... |
from django.apps import AppConfig
class FcConfig(AppConfig):
name = 'fc' |
import numpy as np
import cv2
canvas = np.zeros((300, 300, 3), dtype = "uint8")
green = (0, 255, 0)
red = (0, 0, 255)
for (col, x) in enumerate(range(1, canvas.shape[0], 10)):
for (row, y) in enumerate(range(1, canvas.shape[1], 20)):
offset = 0
if col % 2 == 0:
offset = 10
cv2.re... |
from django.conf import settings
def custom_variables_processor(request):
""" Extend the template with custom variables """
return dict(SOCIAL_LINKS=settings.SOCIAL_LINKS) |
import os
import sys
import subprocess
import string
def runTest(implement_name):
os.system("mpirun ./bcast_skeleton " + implement_name + " -c 1000000 >> output.txt")
os.system("mpicc -O3 bcast_skeleton.c -o bcast_skeleton")
implement_name=["default_bcast", "naive_bcast", "asynchronous_pipelined_ring_bcast", "async... |
import sys
import sip
from PyQt4 import QtGui, QtCore
from epubcreator.gui import main_window
from epubcreator import config, version
if __name__ == "__main__":
# Necesito llamar a este método porque sino pyqt crashea cuando se cierra python (al menos en windows).
# No crashea siempre, sino que lo hace bajo alg... |
import os
import shutil
import sys
if len(sys.argv) > 1: package_name = sys.argv[1]
else: package_name = "amanda_3.0-1"
def main():
# Define some directory constants.
LINUX_DIR = os.path.dirname(os.path.abspath(__file__))
PACKAGE_DIR = os.path.join(LINUX_DIR, package_name)
BIN_DIR ... |
"""
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"); you may not use this ... |
"""Algebra-related questions, e.g., "Solve 1 + x = 2."."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import random
from mathematics_dataset import example
from mathematics_dataset.sample import linear_system
from mathematics_dataset.sam... |
import base64
from xdrlib import Packer, Unpacker
from ..type_checked import type_checked
from .base import Integer
from .scp_history_entry_v0 import SCPHistoryEntryV0
__all__ = ["SCPHistoryEntry"]
@type_checked
class SCPHistoryEntry:
"""
XDR Source Code::
union SCPHistoryEntry switch (int v)
{
... |
from __future__ import print_function
import demisto_client.demisto_api
from demisto_client.demisto_api.rest import ApiException
from pprint import pprint
api_key = 'YOUR API KEY'
base_url = 'YOUR DEMISTO URL'
api_instance = demisto_client.configure(base_url=base_url, api_key=api_key, debug=False)
update_data_batch = d... |
from __future__ import absolute_import
from __future__ import print_function
import inspect
import logging
import os
import re
import string_utils
import shlex
from abc import ABCMeta, abstractmethod, abstractproperty
import ruamel.yaml
from ruamel.yaml.comments import CommentedMap
from six import add_metaclass
from ku... |
from tellurium import *
import ParameterScan
import Export
import analysis
import notebooktools
import optimization
import visualization
import widgets |
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 'Repair_item'
db.create_table(u'SmartDataApp_repair_item', (
(u'id', self.gf('django.db.models.fields.AutoFi... |
def init(job):
from JumpScale.baselib.atyourservice81.AtYourServiceBuild import ensure_container
ensure_container(job.service, root=True)
def install(job):
from JumpScale.baselib.atyourservice81.AtYourServiceBuild import build
def build_func(cuisine):
cuisine.development.rust.install()
build... |
import gtk
def responseToDialog(entry, dialog, response):
dialog.response(response)
def getText(prompt, title=None , markup=None):
#base this on a message dialog
dialog = gtk.MessageDialog(
None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_QUESTION,
gtk.BUT... |
import csv
import logging
from collections import defaultdict
from algorithm import graph, dimensions
from algorithm.algorithms import KolmogorovSmirnov
from utils.dbpedia_access import DBpedia
def parse_props(config):
propfile = config['properties']
props = []
with open(propfile, 'r') as f:
csvr = ... |
"""Parsing of gitignore files.
For details for the matching rules, see https://git-scm.com/docs/gitignore
"""
import os.path
import re
from typing import (
BinaryIO,
Iterable,
List,
Optional,
TYPE_CHECKING,
Dict,
Union,
)
if TYPE_CHECKING:
from dulwich.repo import Repo
from dulwich.confi... |
"""Command-line flag library.
Emulates gflags by wrapping cfg.ConfigOpts.
The idea is to move fully to cfg eventually, and this wrapper is a
stepping stone.
"""
import os
import socket
import sys
from oslo.config import cfg
from raksha import version
FLAGS = cfg.CONF
def parse_args(argv, default_config_files=None):
... |
"""A formatter which formats phone numbers as they are entered.
An AsYouTypeFormatter can be created by invoking
AsYouTypeFormatter(region_code). After that digits can be added by invoking
input_digit() on the formatter instance, and the partially formatted phone
number will be returned each time a digit is added. clea... |
import math
try:
import property
import unicode_data
except ModuleNotFoundError:
from util import property
from util import unicode_data
WORD_BREAK_PROPERTY = "data/ucd/auxiliary/WordBreakProperty.txt"
PROP_LIST = "data/ucd/PropList.txt"
DERIVED_CORE_PROPERTIES = "data/ucd/DerivedCoreProperties.txt"
cod... |
import codecs
import cStringIO
import unittest
from chirp.library import bulk_tagging_form
TEST_FORM_1 = """
00123--------- A Perfect Circle
a7314af4 [ 1 ] 192 12 Mer de Noms
e2ebb0f2 [ 1 ] 128 12 Mer de Noms
55d1c5a4 [ ] 192 12 Thirteenth Step
A line to skip
1234abcd [ x ] 192 10 To Be Deleted
abcd1234 [ ? ] 222 7 ... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0004_auto_20170209_1725'),
]
operations = [
migrations.AlterField(
model_name='lesson',
name='lesson_code',
f... |
from itertools import zip_longest
import tensorflow as tf
from functools import reduce
from operator import mul
import numpy as np
VERY_BIG_NUMBER = 1e30
VERY_SMALL_NUMBER = 1e-30
VERY_POSITIVE_NUMBER = VERY_BIG_NUMBER
VERY_NEGATIVE_NUMBER = -VERY_BIG_NUMBER
def get_initializer(matrix):
def _initializer(shape, dtyp... |
"""
Module for creating and defining parametric programs.
"""
import inspect
from copy import copy
from quilbase import Slot
from quil import Program
def argument_count(thing):
"""
Get the number of arguments a callable has.
:param thing: A callable.
:return: The number of arguments it takes.
:rtype... |
"""
Test suite for the Hyper-V driver and related APIs.
"""
import contextlib
import datetime
import io
import os
import platform
import shutil
import time
import uuid
import mock
import mox
from oslo.config import cfg
from nova.api.metadata import base as instance_metadata
from nova.compute import power_state
from nov... |
import logging
import gym
import numpy as np
from typing import Callable, List, Optional, Tuple, Union, Set
from ray.rllib.env.base_env import BaseEnv, _DUMMY_AGENT_ID
from ray.rllib.utils.annotations import Deprecated, override, PublicAPI
from ray.rllib.utils.typing import (
EnvActionType,
EnvID,
EnvInfoDi... |
"""
Manages information about the host OS and hypervisor.
This class encapsulates a connection to the libvirt
daemon and provides certain higher level APIs around
the raw libvirt API. These APIs are then used by all
the other libvirt related classes
"""
import operator
import os
import socket
import sys
import threadin... |
from tempest_lib import exceptions as lib_exc
from tempest.api.image import base
from tempest.common.utils import data_utils
from tempest import test
class ImageMembersNegativeTest(base.BaseV1ImageMembersTest):
@test.attr(type=['negative', 'gate'])
def test_add_member_with_non_existing_image(self):
# Ad... |
from datetime import date
__version__ = '0.1.0'
__release_date__ = date(2013, 2, 14) |
"""UniFi Protect Platform."""
from __future__ import annotations
import asyncio
from datetime import timedelta
import logging
from aiohttp import CookieJar
from aiohttp.client_exceptions import ServerDisconnectedError
from pyunifiprotect import NotAuthorized, NvrError, ProtectApiClient
from homeassistant.config_entries... |
class OPLS_Dihedral(object):
"""Docstring for OPLS_Dihedral"""
opls_master1 = ""
opls_master2 = ""
opls_slave1 = ""
opls_slave2 = ""
k1 = ""
k2 = ""
k3 = ""
k4 = ""
def __init__(self,m1,m2,s1,s2,k1,k2,k3):
self.opls_master1 = m1
self.opls_master2 = m2
self... |
from lxml import etree
import webob
from nova.api.openstack.compute.contrib import extended_server_attributes
from nova import compute
from nova import db
from nova import exception
from nova.openstack.common import jsonutils
from nova import test
from nova.tests.api.openstack import fakes
UUID1 = '00000000-0000-0000-0... |
print 'Hello' |
"""
WSGI config for MES 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.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MES.settings")
from django.core.wsgi import g... |
import logging
from savu.plugins.base_recon import BaseRecon
from savu.data.plugin_info import CitationInformation
from savu.plugins.driver.cpu_plugin import CpuPlugin
import skimage.transform as transform
import numpy as np
from scipy import ndimage
from savu.plugins.utils import register_plugin
@register_plugin
class... |
import pytest
import networkx as nx
import gorynych
import gorynych.ontologies.gch.nodes.basic.agent as agent
import gorynych.ontologies.gch.nodes.basic.person as person
import gorynych.core.edge as edge
import gorynych.core.ontology as ontology
import gorynych.ontologies.gch.gch
def test_ontology():
a = agent.Agen... |
"""
Utility functions for ESX Networking.
"""
from nova import exception
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log as logging
from nova.virt.vmwareapi import error_util
from nova.virt.vmwareapi import vim_util
from nova.virt.vmwareapi import vm_util
LOG = logging.getLogger(_... |
from __main__ import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import json
import logging
import os, shutil, zipfile
import subprocess
from urllib.parse import urlparse
class DatabaseInteractor(slicer.ScriptedLoadableModule.ScriptedLoadableModule):
def __init__(self, parent):
slicer.S... |
import unittest
import time
from nova import service
from nova.log import logging
from nova.tests.integrated import integrated_helpers
from nova.tests.integrated.api import client
from nova.volume import driver
LOG = logging.getLogger(__name__)
class VolumesTest(integrated_helpers._IntegratedTestBase):
def setUp(se... |
import unittest
from django.test import TestCase
from tx_highered import models
from tx_highered.factories import (InstitutionFactory, EnrollmentFactory,
)
class InstitutionTestCase(TestCase):
def setUp(self):
self.obj = models.Institution.objects.get(
slug='the-university-of-texas-at-austin... |
from boto.dynamodb2.fields import HashKey
from boto.dynamodb2.table import Table
import boto.dynamodb2 as ddb
def dynamodb_update(table, data):
#print "Updating db with : {0}".format(data)
return table.put_item(data=data, overwrite=True)
def get_job(request, job_id):
dyntable = request.app.config['dyno.conn... |
from .database import *
from .dataset.data_blending import DataSetBlender
from .dataset.fields import (
DataSetFilterException,
DataType,
Field,
)
from .dataset.intervals import (
NumericInterval,
day,
hour,
month,
quarter,
week,
year,
)
from .dataset.joins import Join
from .data... |
from __future__ import absolute_import
import errno
import socket
import select
import time
from typing import TYPE_CHECKING, Tuple, List
if TYPE_CHECKING:
from proton._selectable import Selectable
PN_INVALID_SOCKET = -1
class IO(object):
@staticmethod
def _setupsocket(s: socket) -> None:
s.setsocko... |
import six
from .. import errors
from .. import utils
class ExecApiMixin(object):
@utils.check_resource('container')
def exec_create(self, container, cmd, stdout=True, stderr=True,
stdin=False, tty=False, privileged=False, user='',
environment=None, workdir=None, detach_k... |
"""Allows export of Lessons and Units to other systems."""
__author__ = 'psimakov@google.com (Pavel Simakov)'
from datetime import datetime
import os
import verify
RELEASE_TAG = '1.0'
def echo(unused_x):
pass
JS_GCB_REGEX = """
function gcb_regex(base, modifiers) {
// NB: base should already have backslashes es... |
import numpy as np
import numpy
class LinRegLearner(object):
def __init__(self):
super(LinRegLearner, self).__init__()
def addEvidence(self, XTrain, Ytrain):
self.XTrain=XTrain
self.Ytrain=Ytrain
final_XTrain = numpy.insert(XTrain, 0, values=np.ones(XTrain.shape[0]), axis=1)
... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Switch',
fields=[
('key... |
'''
Created on 17.12.2013
@author: heinz-peterlang
Before uploading a new repository, visit the web-interface and create the
repository (type: Java Native store).
ATTENTION: uploading the same dataset multiple times will lead to redundant data.
'''
from __future__ import print_function
from __future__ import unicode_li... |
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
import random
def init_err_casesKmeans():
# Connect to a pre-existing cluster
# connect to localhost:54321
# Log.info("Importing benign.csv data...\n")
benign_h2o = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/beni... |
from scanpointgenerator.generators.arraygenerator import ArrayGenerator
from scanpointgenerator.generators.linegenerator import LineGenerator
from scanpointgenerator.generators.lissajousgenerator import LissajousGenerator
from scanpointgenerator.generators.spiralgenerator import SpiralGenerator
from scanpointgenerator.... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db') |
#!/usr/bin/env python
from gimpfu import *
import gtk, pango
from gobject import timeout_add
DIREC_N, DIREC_NE, DIREC_E, DIREC_SE, DIREC_S, DIREC_SW, DIREC_W, DIREC_NW \
= range(8)
def python_fu_arrow_from_selection(img, layer, arrowangle, arrowsize,
x1, y1, x2, y2, cyc) :
""... |
from django.shortcuts import get_object_or_404
from django.views.generic import ListView, DetailView, CreateView
from django.shortcuts import render
from albums.models import Albums, CATEGORY
from utils.renders import JSONResponseMixin
import logging
class AlbumsDetailView(JSONResponseMixin, DetailView):
context_ob... |
from befh.clients.sql import SqlClient
import pymysql
class MysqlClient(SqlClient):
"""
Sqlite client
"""
def __init__(self):
"""
Constructor
"""
SqlClient.__init__(self)
def connect(self, **kwargs):
"""
Connect
:param path: sqlite file to conn... |
"""Tests for proposal_review views."""
import httplib
import mock
from google.appengine.ext import ndb
from django import http
from melange.request import exception
from soc.modules.gsoc.logic import proposal as proposal_logic
from soc.modules.gsoc.models import proposal as proposal_model
from soc.modules.gsoc.models.p... |
import cv2
import tensorflow as tf
import argparse
import numpy as np
from six.moves import zip
import os
import sys
from tensorpack import *
from tensorpack.tfutils.symbolic_functions import *
from tensorpack.tfutils.summary import *
class Model(ModelDesc):
def _get_inputs(self):
return [InputDesc(tf.float... |
from tempest.api.compute import base
from tempest.common.utils.data_utils import rand_int_id
from tempest.common.utils.data_utils import rand_name
from tempest import exceptions
from tempest.test import attr
from tempest.test import skip_because
class ServersAdminTestJSON(base.BaseComputeAdminTest):
"""
Tests S... |
"""
Robot Framework LDTP Library
LDTPLibrary is a gui application testing library for Robot Framework.
It uses the LDTP (Linux Desktop Test Project) libraries internally to control a gui application.
See http://ldtp.freedesktop.org/wiki/ for more information on LDTP.
@author: Wang Yang <wywincl@gmail.com>
@copyright: C... |
"""
Copyright [2009-2018] EMBL-European Bioinformatics Institute
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... |
"""Tests for checks."""
import os
import yaml
from grr.lib import config_lib
from grr.lib import flags
from grr.lib import rdfvalue
from grr.lib import test_lib
from grr.lib.checks import checks
from grr.lib.checks import checks_test_lib
from grr.lib.rdfvalues import checks as checks_rdf
from grr.parsers import config_... |
import copy
from oslo_config import cfg
from senlin.objects.requests import nodes
from senlin.tests.unit.common import base as test_base
CONF = cfg.CONF
CONF.import_opt('default_action_timeout', 'senlin.conf')
class TestNodeCreate(test_base.SenlinTestCase):
body = {
'name': 'test-node',
'profile_id'... |
from __future__ import print_function
from bcc import BPF
import argparse
from time import strftime
kallsyms = "/proc/kallsyms"
examples = """examples:
./ext4slower # trace operations slower than 10 ms (default)
./ext4slower 1 # trace operations slower than 1 ms
./ext4slower -j 1 ... |
import os
import words
from certain import Certain
PATH_RESULTS = 'results'
RESULT_SEP = ' '
USE_GAP = False
try:
if USE_GAP:
import automata_gap
except ImportError as e:
USE_GAP = False
""" Dear user,
I really need to warn you before you make use of the following code. This code
is not really part o... |
import scrapy
import logging
from scrapy.spiders import Spider
from scrapy.selector import Selector
from iherb.items import IherbItem
class IherbSpider(Spider):
name = "iherbspider"
allowed_domains = ["iherb.cn"]
max_page = 5
cur_page = 1
start_urls = [
"http://www.iherb.cn/Supplements?oos=t... |
from django.template import defaultfilters as filters
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
from horizon import exceptions
from horizon import tables
from openstack_dashboard.api import cinder
class CreateVolumeType(tables.LinkAction):
name = "cr... |
def assign_to_variable_spec(data, spec, value):
if not spec.startswith('@') or not spec.endswith('@'):
raise ValueError("{} is not a reference".format(spec))
parts = spec.strip('@').split('.')
data.setdefault(parts[0], []).append({})
gen = data[parts[0]][-1]
for part in parts[1:-1]:
... |
from django.contrib import admin
from reversion.admin import VersionAdmin
from poetry.apps.corpus.models import Poem, Theme, Markup, MarkupVersion
class PoemInline(admin.StackedInline):
model = Poem.themes.through
@admin.register(Poem)
class PoemAdmin(VersionAdmin):
model = Poem
@admin.register(Theme)
class The... |
"""Approximate calculation of appropriate thresholds for motif finding
"""
class ScoreDistribution(object):
""" Class representing approximate score distribution for a given motif.
Utilizes a dynamic programming approch to calculate the distribution of
scores with a predefined precision. Provides a number o... |
from azure.mgmt.web import WebSiteManagementClient
from ..azure_common import BaseTest, arm_template, cassette_name
from c7n_azure.session import Session
from mock import patch
from c7n.exceptions import PolicyValidationError
from c7n.utils import local_session
class AppServicePlanTest(BaseTest):
def setUp(self):
... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gradestats.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
from __future__ import print_function
import argparse
import json
import os
import sys
import time
from .. import compat, Catalog
__all__ = ['createservice', 'manageservice', 'managesite', 'deletecache',
'managecachetiles', 'createcacheschema',
'convertcachestorageformat', 'importcache', 'exportca... |
"""
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
import salt.modules.locate as locate
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase
class LocateTestCase(TestCase, LoaderModuleMockMixin):
"""
Test cases... |
"""
Copyright 2018 Google Inc.
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
distr... |
from py12306.log.base import BaseLog
from py12306.helpers.func import *
@singleton
class UserLog(BaseLog):
# 这里如果不声明,会出现重复打印,目前不知道什么原因
logs = []
thread_logs = {}
quick_log = []
MESSAGE_DOWNLAOD_AUTH_CODE_FAIL = '验证码下载失败 错误原因: {} {} 秒后重试'
MESSAGE_DOWNLAODING_THE_CODE = '正在下载验证码...'
MESSAGE_CO... |
from azure.mgmt.compute.models import HardwareProfile, VirtualMachineUpdate
from c7n_azure.actions.base import AzureBaseAction
from c7n_azure.provider import resources
from c7n_azure.resources.arm import ArmResourceManager
from c7n.filters.core import ValueFilter, type_schema
from c7n.filters.related import RelatedReso... |
"""
this is an model that only use to detact fashion_mnist images
using tensorflow and kears
"""
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.layers import (MaxPool2D , Conv2D , Activation,
Dropout , Flatten ,
... |
import json
import logging
from django.db.models import Q
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from desktop.lib.django_util import render, JsonResponse
from desktop.lib.json_utils import JSONEncoderForHTML
from desktop.models import Document2, Document
from not... |
"""setup.py file for a GRR Colab library."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
import shutil
import sys
from setuptools import setup
from setuptools.command.sdist import sdist
if sys.version_info.major == 2:
import ConfigParser as ... |
import pytest
import requests
import yaml
from settings import TEST_DATA
def get_weights_of_splitting(file) -> []:
"""
Parse yaml file into an array of weights.
:param file: an absolute path to file
:return: []
"""
weights = []
with open(file) as f:
docs = yaml.safe_load_all(f)
... |
from __future__ import absolute_import
import pexpect
import os
import unittest
class test_happy_node_shell(unittest.TestCase):
def setUp(self):
pass
def test_node(self):
os.system("happy-node-add node01")
os.system("happy-node-add -i node02")
os.system("happy-node-add --id node0... |
from google.cloud import aiplatform_v1
async def sample_create_training_pipeline():
# Create a client
client = aiplatform_v1.PipelineServiceAsyncClient()
# Initialize request argument(s)
training_pipeline = aiplatform_v1.TrainingPipeline()
training_pipeline.display_name = "display_name_value"
tr... |
import sys, os
extensions = ['sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.pngmath', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Manuales Publicos Vauxoo'
copyright = u'2013, Vauxoo'
version = '1'
release = '1'
exclude_p... |
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
kv = '''
FloatLayout:
TextInput:
id: text_input
pos_hint: {'top': 1}
size_hint: 1, None
height: 32
ToggleButton:
text: 'dock'
on_state: app.switch(self)
size_hint: 1... |
r"""Default configs for BERT finetuning on GLUE.
"""
import ml_collections
_GLUE_TASKS = [
'stsb', 'cola', 'sst2', 'mrpc', 'qqp', 'mnli_matched', 'mnli_mismatched',
'rte', 'wnli', 'qnli'
]
VARIANT = 'BERT-B'
INIT_FROM = ml_collections.ConfigDict({
'checkpoint_path': '',
'model_config': 'SET-MODEL-CONFIG',
}... |
from PySide import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(629, 722)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/dir/ftp/favicon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Mai... |
import ConfigParser
import daemon
import argparse
import time
from server import ServerFactory, SyncServer
CONFIG_PATH = os.path.join('etc', 'sync-nosql-dbs', 'config.ini')
class RunSync(object):
""" Class that runs sync daemon executing sync for all servers defined in
config file.
"""
def __init__(self... |
import os
from cread.geonodemanager import GeonodeManager
myfilepath = processing.getObject(Layer).dataProvider().dataSourceUri()
(myDirectory,nameFile) = os.path.split(myfilepath)
file_abs_path = myDirectory + '/' + nameFile
print file_abs_path
GeonodeManager(str(UserName), str(Password), str(DomainName)).publish_cove... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.