content string |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os.path
import time
import sys
import hashlib
import requests
from tencentyun import conf
from .auth import Auth
class Video(object):
def __init__(self, appid, secret_id, secret_key):
self.VIDEO_FILE_NOT_EXISTS = -1
self.VIDEO_NETWORK_ERROR = ... |
#패키지 호출
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import brown
from text_chunker import chunker
#브라운 말뭉치에서 데이터읽기
input_data = ' '.join(brown.words()[:5400])
# 단어 묶음에 포함될 단어수
chunk_size = 800
#텍스트를 단어 묶음으로 나눔
text_chunks = chunker(input_data, chunk_si... |
#!/usr/bin/env python
from __future__ import print_function
import csv
import sys
import json
import datetime
import importlib
class DatetimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.date):
return obj.strftime('%Y-%m-%d')
return json.JSONEncoder.d... |
###
# config.py
#
# Project configuration parser
###
def parse_line(ln):
ln = ln.split('=')
key = ln[0]
value = '='.join(ln[1:])
return (key,value.strip())
class ProjectConfig():
def __init__(self, **kwargs):
self._properties = {}
prop_defaults = {
'sourcelyzer.proje... |
#!/usr/local/bin/python
#-*- coding: utf-8 -*-
import unittest
from stupid import Cache
from pymongo import MongoClient
class CacheTest(unittest.TestCase):
def setUp(self):
self.mc = MongoClient()
self.dbname = 'stupid_test'
self.cache = Cache(self.mc, self.dbname)
def tearDown(self):... |
__title__ = "main generator for capacitor tht model generators"
__author__ = "scripts: maurice and hyOzd; models: see cq_model files"
__Comment__ = '''This generator loads cadquery model scripts and generates step/wrl files for the official kicad library.'''
___ver___ = "1.2 03/12/2017"
save_memory = True #reducing ... |
import sys
import numpy as np
def median(x):
'''The median of a list of numbers (integers or floats) is returned.'''
sorts = sorted(x)
length =len(sorts)
if length ==1:
return x[0]
elif not length % 2:
return (sorts[length // 2] + sorts[length //2 -1]) /2.0
else:
return ... |
"""
Support for interfacing with Monoprice 6 zone home audio controller.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.monoprice/
"""
import logging
import voluptuous as vol
from homeassistant.components.media_player import (
DOMAIN, ... |
from django.conf.urls import url
from xgds_image import views
urlpatterns = [
url(r'^getAnnotations/(?P<imagePK>[\d]+)$', views.getAnnotationsJson, {}, 'xgds_image_get_annotations'),
url(r'^getAnnotationColors/$', views.getAnnotationColorsJson, {}, 'xgds_image_get_annotation_colors'),
url(r'^saveImage/$', ... |
from coalib.output.ConsoleInteraction import (nothing_done,
acquire_settings,
print_section_beginning,
print_results,
finalize,
... |
from django.db import models
from django.contrib.auth.models import User, Group
from datetime import date
class Person(models.Model):
user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE)
adresse = models.TextField()
NICHT_SOFORT_LOESCHEN = 'nicht_sofort_loeschen'
SOFORT_LOESCHEN = 'so... |
from typing import Any, Dict
from overrides import overrides
from keras.layers import merge, Dense, TimeDistributed
from ...data.instances.sentence_pair_instance import SentencePairInstance
from ...training.pretraining.text_pretrainer import TextPretrainer
from ...training.models import DeepQaModel
class EncoderPr... |
import proto # type: ignore
__protobuf__ = proto.module(
package='google.ads.googleads.v7.services',
marshal='google.ads.googleads.v7',
manifest={
'GetCustomerClientRequest',
},
)
class GetCustomerClientRequest(proto.Message):
r"""Request message for
[CustomerClientService.GetCustom... |
from __future__ import print_function
import rethinkdb as r
from django.conf import settings
from djangotoolbox.db.creation import NonrelDatabaseCreation
class DatabaseCreation(NonrelDatabaseCreation):
def set_autocommit(self):
"""
There is no such thing as autocommit in RethinkDB.
"""
def create_t... |
"""dataset related classes and methods."""
import ctypes
import sys
import time
import numpy as np
import tensorflow as tf
MEAN_RGB = [123.68, 116.78, 103.94]
IMAGE_SIZE = 224
class Item(object):
def __init__(self, label, img, idx):
self.label = label
self.img = img
self.idx = idx
self.start = t... |
"""This example retrieves keyword traffic estimates.
Tags: TrafficEstimatorService.get
Api: AdWordsOnly
"""
__author__ = '<EMAIL> (Kevin Winter)'
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..', '..'))
# Import appropriate classes from the client library.
from adspygoogle import AdWordsC... |
#runas solve(1000000)
#pythran export solve(int)
def solve(a):
'''
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many ci... |
#!/usr/bin/env python
import datetime
import logging
import os
import re
import time
from utils import utils, inspector, admin
# https://www.va.gov/oig/apps/info/OversightReports.aspx
archive = 1996
# options:
# standard since/year options for a year range to fetch from.
#
# Notes for IG's web team:
#
REPORTS_UR... |
"""kwalitee factory for Flask application."""
from __future__ import unicode_literals
import os
from flask import Flask, Config
from flask_sqlalchemy import SQLAlchemy
from werkzeug.routing import BaseConverter
class ShaConverter(BaseConverter):
"""Werkzeug routing converter for sha-1 (truncated or full)."""
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
ogr2ogr.py
---------------------
Date : November 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*****************************... |
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <<EMAIL>>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
import copy
import re
im... |
import re
import pytest
from sqlalchemy import Table, MetaData, Column, select
from geoalchemy2.types import Geometry
def eq_sql(a, b):
a = re.sub(r'[\n\t]', '', str(a))
assert a == b
@pytest.fixture
def geometry_table():
table = Table('table', MetaData(), Column('geom', Geometry))
return table
c... |
from google.appengine.ext import endpoints
from protorpc import remote
from app.models.goal import GoalModel
@endpoints.api(name='goal', version='v1', description = 'API de Obejtivos')
class GoalApi(remote.Service):
@GoalModel.method(request_fields=('title', ' goalDescription', 'state', 'user', 'completed'),
... |
"""Installation script for Python nupic package."""
import os
import setuptools
import sys
from setuptools import setup, find_packages, Extension
REPO_DIR = os.path.dirname(os.path.realpath(__file__))
def getVersion():
"""
Get version from local file.
"""
with open(os.path.join(REPO_DIR, "VERSION"), "r") ... |
import os
from snactor.loader import create_actor, load
from snactor.registry import get_registered_actors, must_get_actor
from snactor.utils import get_chan
class UnresolvedDependenciesError(Exception):
"""
UnresolvedDependenciesError is thrown when the dependencies between actors can't be automatically res... |
import simpy
import numpy as np
class CrossValidation(object):
def __init__(self, data, target, result_merge_function, k_size=5):
self.is_data_list = not isinstance(data, np.ndarray)
self.is_target_list = not isinstance(target, np.ndarray)
self._check_input(data, self.is_data_list)
... |
import datetime
import pickle
import pandas as pd
import csv
# reformat.reformat_data_add_column(all_search_result, 'all_search', 'search', all_tracking, collection_all_search)
class Reformat(object):
@classmethod
def reformat_data_add_column(self, data_name, output_name, tracking_asin, database_collectio... |
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
@pytest.mark.parametrize(
"ufunc", [np.add, np.logical_or, np.logical_and, np.logical_xor]
)
def test_ufuncs_binary(ufunc):
# two BooleanArrays
a = pd.array([True, False, None], dtype="boolean")
result = ufunc(a, a)
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import curses
from collections import OrderedDict
import pytest
from rtv.submission_page import SubmissionPage
from rtv.docs import FOOTER_SUBMISSION
try:
from unittest import mock
except ImportError:
import mock
PROMPTS = OrderedDict([
(... |
# Extension to format a paragraph
# Does basic, standard text formatting, and also understands Python
# comment blocks. Thus, for editing Python source code, this
# extension is really only suitable for reformatting these comment
# blocks or triple-quoted strings.
# Known problems with comment reformatting:
... |
from numpy.linalg import inv, cholesky
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_array
class BaseMetricLearner(BaseEstimator, TransformerMixin):
def __init__(self):
raise NotImplementedError('BaseMetricLearner should not be instantiated')
def metric(s... |
"""
Django settings for giscube project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
import os
from config import STATIC_URL, MEDIA_ROOT, MEDIA_URL
# SECURITY... |
#!/usr/bin python
# -*- coding: utf-8 -*-
from __future__ import division
import os, sys
from PyQt5 import uic, QtCore, QtWidgets
import numpy as np
from pyqtgraph import BusyCursor
from lib.functions.tide import generate_tide
from lib.functions.general import isNumpyNumeric
from pyqtgraph.flowchart.Node import Node
fr... |
from nose.tools import *
from pillowncase import pncase
import os
import shutil
from datetime import datetime
import random
import hashlib
from tests import helper
import sys
verbose = 3
def setup():
print ("SETUP!")
helper.setup_environment()
def teardown():
print ("TEAR DOWN!")
def test_CC_hide_ran... |
"""
This script copies variables from the python model to the JavaScript model to
enable generating names from the web interface.
"""
import os
import argparse
import pickle
import json
from dump_checkpoint_vars import get_checkpoint_dumper
VARIABLES_DIR = os.path.join('web', 'src', 'vars')
AUTHOR_MAP_FILE = os.path... |
TRADING_DAYS_IN_YEAR = 250
TRADING_HOURS_IN_DAY = 6.5
MINUTES_IN_HOUR = 60
ANNUALIZER = {'daily': TRADING_DAYS_IN_YEAR,
'hourly': TRADING_DAYS_IN_YEAR * TRADING_HOURS_IN_DAY,
'minute': TRADING_DAYS_IN_YEAR * TRADING_HOURS_IN_DAY *
MINUTES_IN_HOUR}
# NOTE: It may be worth revi... |
# -*- coding: utf-8 -*-
"""Family module for Wikipedia."""
#
# (C) Pywikibot team, 2004-2017
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
from pywikibot import family
__version__ = '$Id$'
# The Wikimedia family that is known as Wikipedia, the Free En... |
"Misc tests of files, such as licensing and copyright"
# pylint: disable=function-redefined
# pylint: disable=missing-docstring
# pylint: disable=protected-access
# pylint: disable=invalid-name
import logging
import os.path as p
import re
import subprocess as subp
import parameterized # type: ignore
import unittest... |
"""Simple Page support
This module has been deprecated and will be gone in Zope 3.5.
$Id: page.py 67630 2006-04-27 00:54:03Z jim $
"""
# BBB 2006/04/19 -- to be removed after 12 months
import zope.deferredimport
zope.deferredimport.deprecated(
"It has moved to zope.publisher.browser.BrowserPage. This reference "... |
"""treetools: Tools for transforming treebank trees.
This module handles tree writing in different formats.
Author: Wolfgang Maier <<EMAIL>>
"""
from __future__ import division, print_function
import sys
from math import floor
from xml.sax.saxutils import quoteattr
from . import trees, treeanalysis
def parse_split_... |
from devlib.utils.csvutil import csvwriter
from wa import OutputProcessor, Parameter
from wa.framework.exception import ConfigError
from wa.utils.types import list_of_strings
class CsvReportProcessor(OutputProcessor):
name = 'csv'
description = """
Creates a ``results.csv`` in the output directory conta... |
from jenkins_jobs.config import JJBConfig
import jenkins_jobs.builder
from tests import base
from tests.base import mock
_plugins_info = {}
_plugins_info['plugin1'] = {'longName': '',
'shortName': '',
'version': ''}
@mock.patch('jenkins_jobs.builder.JobCache',... |
# -*- coding: UTF8 -*-
import os
import subprocess
import SCons
from racy.rutils import is_iterable, put_file_content
###############################################################################
class CommandNotFound(SCons.Warnings.Warning):
pass
#############################################################... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify specifying a list of initial commands through a config file.
"""
import TestSCons_time
test = TestSCons_time.TestSCons_time()
test.write_fake_scons_py()
test.write_sample_project('foo.tar.gz')
test.write('config', """\
def touch(arg):
op... |
import os
from windIO.Plant import WTLayout
import numpy as np
import pytest
import yaml
from jsonschema import validate, ValidationError
# The test directory
current_dir = os.path.dirname(__file__)
class TestWindTurbineSchema:
base = ""
def setup_method(self, method):
schema_file = current_dir + '/.... |
"""OSS multi-process library to be implemented."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import unittest
class Process(object):
"""A process simulating a worker for testing multi-worker training."""
def __init__(self, *arg... |
import os
import tempfile
from functools import partial
from django.conf import settings
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage as storage
from django.utils.encoding import force_str
import pytest
from olympia.amo.storage_utils import (
copy_stored_f... |
import os
import re
from setuptools import setup, find_packages
READMEFILE = "README.rst"
VERSIONFILE = os.path.join("Pyblosxom", "_version.py")
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
def get_version():
verstrline = open(VERSIONFILE, "rt").read()
mo = re.search(VSRE, verstrline, re.M)
if mo:
... |
#!/usr/bin/python
import sys
from subprocess import call
print "Usage: longranger_prepare_reference.py FastaFile"
try:
file = sys.argv[1]
except:
file = raw_input("Introduce FASTA file: ")
name = file.split(".")
name = ".".join(name[:-1])
extract = "perl /home/fruano/bin/extractSeqFromFasta.pl"
call("size... |
import logging
import os
import subprocess
from cuckoo.common.abstracts import Auxiliary
from cuckoo.common.constants import CUCKOO_GUEST_PORT, faq
from cuckoo.common.exceptions import CuckooOperationalError
from cuckoo.misc import cwd, getuser, Popen
log = logging.getLogger(__name__)
class Sniffer(Auxiliary):
d... |
import os
from optparse import make_option
from django.core.management import BaseCommand, call_command, CommandError
from django.core.management.commands.dumpdata import Command as DumpDataCommand
from django.conf import settings
from django.db import router, connections
from django.utils.importlib import import_modu... |
"""Piecewise-linear normalization to normalize standalone modality"""
import os
import numpy as np
from .standalone_normalization import StandaloneNormalization
from ..utils import check_npy_filename
class PiecewiseLinearNormalization(StandaloneNormalization):
"""Piecewise-linear normalization to normalize st... |
__all__ = [
'session_api',
'require_session',
'ClientAPI',
'application',
]
from wsgiref.simple_server import make_server
from webob import exc
from webob.dec import wsgify
from beaker.middleware import SessionMiddleware
from yubiauth.client import Client
from yubiauth.util import validate_otp
from yub... |
from . import AWSObject, AWSProperty
from .validators import boolean, double, integer, positive_integer
class ScalableTargetAction(AWSProperty):
props = {
'MaxCapacity': (integer, False),
'MinCapacity': (integer, False),
}
class ScheduledAction(AWSProperty):
props = {
'EndTime': ... |
""" Contains the Equation class.
Copyright (c) 2014 Kenn Takara
See LICENSE for details
"""
import re
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import factorial_notation, auto_number
class EquationError(ValueError):
""" Exception: An error in the equation specif... |
from django.core.management.base import BaseCommand
from apps.question.models import Answer, Question
from django.contrib.auth.models import User
from redis_cache import get_redis_connection
redis = get_redis_connection('default')
class Command(BaseCommand):
args = '<username amount...>'
help = 'Generates g... |
import sys, json, pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
def read_in():
lines = sys.stdin.readlines()
# Since our... |
from __future__ import absolute_import
from django.conf import settings
from horizon import exceptions
from openstack_dashboard.api import base as api_base
from openstack_dashboard.api import cinder
from openstack_dashboard.api import glance
from openstack_dashboard.api import keystone
from openstack_dashboard.test ... |
from marvin.codes import FAILED
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import (cleanup_resources,
is_snapshot_on_nfs,
validateList)
from marvin.lib.base import (VirtualMachine,
... |
# coding: utf-8
from datetime import datetime
from flask import Flask, render_template
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField, PasswordField, HiddenField
from wtforms.validators import Required, Email, Equ... |
import gevent
import gevent.queue
from lymph.exceptions import Timeout, Nack, RemoteError
from lymph.core.messages import Message
class Channel(object):
def __init__(self, request, container):
self.request = request
self.container = container
class RequestChannel(Channel):
def __init__(self... |
<?php
// Include the Dwolla REST Client
require '../lib/dwolla.php';
// Include any required keys
require '_keys.php';
// Instantiate a new Dwolla REST Client
$Dwolla = new DwollaRestClient($apiKey, $apiSecret, 'http://localhost:8888/offsiteGateway.php');
?>
<div>
<h2>Example 1: Simple checkout</h2>
<p>Create a new ... |
class IDLNode(object):
def __init__(self, classname, name, parent):
self._classname = classname
self._parent = parent
self._name = name
self._filepath = None
@property
def filepath(self):
return self._filepath
@property
def is_array(self):
return sel... |
"""
This module contains a base type which provides list-style mutations
without specific data storage methods.
See also http://www.aryehleib.com/MutableLists.html
Author: Aryeh Leib Taurog.
"""
from django.utils.functional import total_ordering
from django.utils import six
from django.utils.six.moves import xrange
... |
import types
class Petit(type):
def __new__(cls, cls_name, cls_parents, cls_attr):
cls.cls_attr = cls_attr
for parent in cls_parents:
cls.fix_names(parent.__dict__)
cls.fix_names(cls_attr)
return type.__new__(cls, cls_name, cls_parents, cls_attr)
@classmethod
... |
from django.conf.urls import patterns, url
from account.views import SignupView, LoginView, LogoutView, DeleteView
from account.views import ConfirmEmailView
from account.views import ChangePasswordView, PasswordResetView, PasswordResetTokenView
from account.views import SettingsView
urlpatterns = patterns("",
u... |
import subprocess
def create_input_file(target,fuel, g_reaction, bin_file_location):
global_reaction = ''
for i in g_reaction:
global_reaction += i
if target.input_file != None:
instring = open(target.input_file,'r').read()
elif target.target == "Tig":
instring = """############
# Numerics #
###########... |
import numpy as np, h5py as h5
from nose.tools import assert_raises
from horton import *
from horton.test.common import get_random_cell, compare_symmetries
def test_symmetry_attrs():
generators = np.random.uniform(-1, 1, (5, 3, 4))
fracs = np.random.uniform(0, 1, (4, 3))
numbers = np.array([1, 6, 6, 1])
... |
from pyramid.response import Response
from .constants import OK, NO_CONTENT
from .resources import Resource
class PyramidResource(Resource):
"""
A Pyramid-specific ``Resource`` subclass.
Doesn't require any special configuration, but helps when working in a
Pyramid environment.
"""
@classme... |
import numpy as np
from scipy.stats import uniform
from scipy.stats import norm
class Prior(object):
def __init__(self, prior_dict):
""" Class that describes the Prior object
Parameters
----------
prior_dict : dictionary that specifies the shape and prior distributions
... |
#!/usr/bin/env python
"""
This module provides functionalities for training an svr model
"""
from util.data_parser import DataParser
from util.keyword_extractor import KeywordExtractor
from lib.peer_extractor import PeerExtractor
import numpy as np
from sklearn.svm import LinearSVC as SKSVR
from util.top_similar import... |
# tree traversal
#
# checks:
#
# maps:
#
# doneskies:
# integer portion of number: no leading 0's (except for the number 0)
# no number overflow
# no duplicate keys in maps
# number literals to numbers
# no illegal control characters are in strings
# escape sequences from strings are valid
# unicod... |
import random
class OpGenerator:
""" Abstract class that generates operators for statements """
opName = None
index = None
maxIndex = None
stride = None
def __init__(self, kwargs):
""" Creates a new OpGenerator
Keyword Arguments
opName -- the name/prefix of t... |
#!/usr/bin/python3
"""
APP: Trumpatron
DESC: Bot.py Unit Test
CREATION_DATE: 2017-03-01
"""
# MODULES
# | Native
# | Third-Party
import argparse
import pytest
# | Custom
import lib.bannon
class DummyArgParse:
"""
A dummy object that mimics the object returned from ArgParse
"""
log_file = ''
... |
"""
Define RPC functions needed to generate
"""
# [ <ret-type>, [<arg_types>] ]
func_table = [
[ "int", [] ],
[ "int", ["int"] ],
[ "int", ["int", "int"] ],
[ "int", ["int", "string"] ],
[ "int", ["int", "string", "int"] ],
[ "int", ["int", "string", "string"] ],
[ "int", ["int", "string", ... |
from datetime import datetime, timedelta
from time import sleep
from django.core.exceptions import ObjectDoesNotExist
from django.db import IntegrityError, models, transaction
from django.conf import settings
AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
PAYMENT_MODE_CHOICES = (
(0, 'REAL'... |
# -*- coding: utf-8 -*-
"""
Test OpenAssessment XBlock data_conversion.
"""
import ddt
import mock
from django.test import TestCase
from openassessment.xblock.data_conversion import (
create_prompts_list, create_submission_dict, prepare_submission_for_serialization, update_assessments_format
)
@ddt.ddt
class D... |
import re
import traceback
from sickbeard import logger, tvcache
from sickbeard.bs4_parser import BS4Parser
from sickrage.helper.common import try_int
from sickrage.providers.torrent.TorrentProvider import TorrentProvider
class elitetorrentProvider(TorrentProvider):
def __init__(self):
TorrentProvider... |
from django.conf.urls import url
from . import views, api
from django.contrib.auth import views as auth_views
from django.shortcuts import redirect
app_name = 'user'
def anonymous_required(redirect_url):
"""
Decorator for views that allow only unauthenticated users to access view.
Usage:
@anonymous_r... |
"""SCons.Tool.gs
Tool-specific initialization for Ghostscript.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# ... |
# -*- coding: utf-8 -*-
import re
import time
from ..base.account import BaseAccount
class FilerNet(BaseAccount):
__name__ = "FilerNet"
__type__ = "account"
__version__ = "0.13"
__status__ = "testing"
__description__ = """Filer.net account plugin"""
__license__ = "GPLv3"
__authors__ = [
... |
from __future__ import unicode_literals
import frappe
import json
from frappe import _, _dict
from frappe.utils import nowdate
from frappe.utils.data import fmt_money
from erpnext.accounts.utils import get_fiscal_year
from PyPDF2 import PdfFileWriter
from frappe.utils.pdf import get_pdf
from frappe.utils.print_format i... |
def exactsum(l,s,i=0,r=[]):
n = len(l)
if s==0: return True
if s<0 or i==n: return False
if exactsum(l,s-l[i][1],i+1):
r.append(l[i]) #lgtm [py/modification-of-default-value]
return True if i else r
else:
return exactsum(l,s,i+1)
# a simple version of dynamic programming met... |
#!/usr/bin/env python
# coding: utf-8
__author__ = 'iceke'
import re
import os
import json
import wxbot
emoji_map = {}
fp = open("data/emoji.txt", 'r')
for line in fp.readlines():
a = line.split(' ')
if len(a) == 2:
key = a[0][3:].lower()
value = a[1][:-1].lower()
emoji_map[key] = val... |
import json
from abc import ABCMeta, abstractmethod
from flask import render_template
from superdesk.errors import SuperdeskApiError
from superdesk import get_resource_service
from bson import ObjectId
from superdesk.utc import utc_to_local, utcnow
from superdesk.metadata.item import PUBLISH_STATES, ITEM_STATE, ITEM_TY... |
import csv
import os
import re
import shlex
import stat
import sys
from functools import reduce
import numpy as np
try:
import configparser as ConfigParser
except:
import ConfigParser
from ep.evalplatform import debug
CONFIG_FILENAME = "evaluation.ini"
# Name suffixes
SUMMARY_SUFFIX = ".eval.summary.txt"
S... |
import unittest
import math
import numpy as np
from nose.tools import assert_equal
from networkx.classes.digraph import DiGraph
from scipy.spatial.distance import euclidean
from .lst import lst_dag, dp_dag_general, \
round_edge_weights_by_multiplying, \
make_variance_cost_func,\
get_all_nodes
from .dag_uti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2018-11-11
@author: marcel-odya
'''
base = [
["właśnie teraz", "za chwilę"],
["%s sekund temu", "za %s sekund", "%s sekundy temu", "za %s sekundy"],
["minutę temu", "za minutę"],
["%s minut temu", "za %s minut", "%s minuty temu", "za %s minu... |
#Rootul Patel
#HW12 - Spelling Checker
from Tkinter import *
import tkFileDialog
class SpellingChecker():
def __init__(self, text1, text2):
self.text1 = text1
self.text2 = text2
fin = open("dictionary.txt", 'r')
content = fin.read()
fin.close()
dictWords = re.find... |
from envisage.ui.tasks.preferences_pane import PreferencesPane
from traits.api import Bool, Str, Int
from traitsui.api import View, Item, VGroup
from pychron.envisage.tasks.base_preferences_helper import BasePreferencesHelper
class ExperimentDashboardClientPreferences(BasePreferencesHelper):
preferences_path = '... |
#!/usr/bin/env python
import os
import re
from datetime import datetime, timedelta
from publicsuffix import PublicSuffixList
from moulinette.utils.process import check_output
from yunohost.utils.network import dig
from yunohost.diagnosis import Diagnoser
from yunohost.domain import domain_list, _build_dns_conf, _ge... |
import os
import subprocess
import shutil
import libcalamares
from libcalamares.utils import check_target_env_call
def run():
""" Run mkinitcpio """
kernel = libcalamares.job.configuration['kernel']
check_target_env_call(['mkinitcpio', '-p', kernel])
""" Set hardware clock """
hwclock_rtc ... |
from ..util import strFunctions, global_variables
class ValidationRulesGeneral():
"""Class for creating the general validation rules"""
def __init__(self, spec_name, number, package, pkg_ref, level, version,
pkg_version, reqd_status):
# members from object
self.fullname = spe... |
import unittest
import ossie.utils.testing
import os
from omniORB import any
class ComponentTests(ossie.utils.testing.ScaComponentTestCase):
"""Test for all component implementations in mpsk_snr_est_cc"""
def testScaBasicBehavior(self):
#################################################################... |
import logging
from pprint import pformat
from queue import Empty
from time import time
from soco import SoCo, SoCoException
from soco.events import event_listener
from . import ThreadComponent, clamp_value
from .. import matrices
logger = logging.getLogger(__name__)
class Component(ThreadComponent):
MATRIX... |
import sys
import os
import os.path
import time
import sh
import fnmatch
import logging
import subprocess
import re
import unittest
import shutil
import glob
import fnmatch
from collections import namedtuple
from pynt import task
sys.path.insert(0,".")
def execute(prefix,cmd):
stmt=" ".join(cmd)
print prefix,... |
import os
import tvm
from tvm import te
from tvm.contrib import nvcc
import numpy as np
from tvm import topi
TASK = "reduce_map"
USE_MANUAL_CODE = False
@tvm.register_func
def tvm_callback_cuda_compile(code):
ptx = nvcc.compile_cuda(code, target="ptx")
return ptx
def write_code(code, fname):
with ope... |
import logging
import asyncio
from asyncio import coroutine
from concurrent.futures import CancelledError
from broadway.message import Envelop
from broadway.actor import Actor
from broadway.actorref import ActorRefFactory, ActorRef, Props
class ActorContext():
def __init__(self):
super().__init__()
... |
# project/views.py
from forms import AddTaskForm, RegisterForm, LoginForm
from functools import wraps
from flask import Flask, flash, redirect,\
render_template, request, session, url_for
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
# datetime
import datetime
# config
a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
from django.conf.urls import patterns, url
from snisi_web.url_regexp import RGXP_ENTITY, RGXP_PERIOD, RGXP_PERIODS
urlpatterns = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.