content string |
|---|
from abc import abstractmethod
from CachedMethods import cached_property
from collections import defaultdict
from itertools import permutations
from typing import Dict, Iterator, Any, Set
from .._functions import lazy_product
frequency = {1: 10, # H
6: 9, # C
8: 8, # O
7: 7, ... |
import pygame
from kezmenu3 import KezMenu
from game import settings
class Menu(object):
"""Display game options."""
def __init__(self, game):
"""Initializes the menu.
Args:
game: The running game instance.
"""
self.game = game
self.menu = KezMenu(["NEW G... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
import copy
from collections import namedtuple
Move = namedtuple('Move', 'source, target, disc')
def hanoi(discs):
seen = set()
def __solve(rods, depth=0):
if len(rods[2]) == discs:
return []
if rods in seen:
return None
seen.add(rods)
best ... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpR... |
#!/usr/bin/env python
import os,sys
import fastq
import fileinput
import multiprocessing
from PIL import Image, ImageDraw
from circledetector import CircleDetector
########################### BubbleDetector
class BubbleDetector:
def __init__(self, xmax, ymax, xmin, ymin, draw):
#TODO: these can ... |
import base64
import traceback
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpRequest, StreamingHttpResponse
from frontpage.management.magic import timestamp
from frontpage.management.mediatools.media_actions import PATH_TO_UPLOAD_FOLDER_ON_DISK
from frontpage.models import Media, A... |
"""
Extracts a list of features for a set of pages after batch computing stats.
Reads page_id[TAB]wikiproject_title[TAB]rating triplets from stdin and writes
feature[TAB]feature[TAB]...[TAB]rating to stdout.
Usage:
batch_extract_features -h | --help
batch_extract_features <features> <view-log>...
... |
__author__ = 'Simone Campagna'
__copyright__ = 'Copyright (c) 2013 Simone Campagna'
__license__ = 'Apache License Version 2.0'
__version__ = '1.0'
import os
def is_exe(file_path):
return os.path.exists(file_path) and os.access(file_path, os.X_OK)
def which(command, path_list=None):
command_path, command_filena... |
#!/usr/bin/python
import os
import shutil
import sys
if len(sys.argv) != 2:
print "Wrong number of arguments"
print "Usage compile_shaders [path to oslc]"
sys.exit(0)
oslc_cmd = sys.argv[1]
include_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), "include")
for root, dirname, files in os.w... |
from Components.ActionMap import ActionMap, NumberActionMap
from Components.GUIComponent import GUIComponent
from Components.Input import Input
from Components.Ipkg import IpkgComponent
from Components.Sources.StaticText import StaticText
from Components.MenuList import MenuList
from Components.Slider import Slider
fro... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import asyncio
import json
import os
import logging
import pathlib
import sys
from aiohttp import web
from fumbbl_trans import exc
import fumlocffbrep
import fumlochtmlmatch
import fumlocxmlmatches
import fumlocxmlgrouptourneys
import fumlocxmltourney
i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import autoslug.fields
import manoseimas.mps_v2.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Group',
... |
"""Unit tests for `distributions.py`."""
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import numpy as np
from rlax._src import distributions
class CategoricalSampleTest(parameterized.TestCase):
@chex.all_variants()
def test_categorical_sample(self):
key = n... |
# coding=utf-8
"""**SAFE (Scenario Assessment For Emergencies) - API**
The purpose of the module is to provide a well defined public API
for the packages that constitute the SAFE engine. Modules using SAFE
should only need to import functions from here.
Contact : <EMAIL>
.. note:: This program is free software; you ... |
"""
Flex Messaging compatibility tests.
@since: 0.3.2
"""
import unittest
import datetime
import uuid
import pyamf
from pyamf.flex import messaging
class AbstractMessageTestCase(unittest.TestCase):
def test_repr(self):
a = messaging.AbstractMessage()
a.body = u'é,è'
... |
#!/usr/bin/env python
from os.path import join, dirname, abspath
from IPython.terminal.ipapp import TerminalIPythonApp
from ipykernel.kernelapp import IPKernelApp
here = abspath(dirname(__file__))
options = join(here, 'source', 'config', 'options')
generated = join(options, 'generated.rst')
def write_doc(name, titl... |
"""Added favorites column to notes
Revision ID: 10c695123c4d
Revises: 4c1fb76895a6
Create Date: 2015-12-09 04:40:23.995528
"""
# revision identifiers, used by Alembic.
revision = '10c695123c4d'
down_revision = '4c1fb76895a6'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto gener... |
import binascii
import unittest
from hazelcast import six
from hazelcast.serialization.output import _ObjectDataOutput
class OutputTestCase(unittest.TestCase):
def setUp(self):
self._output = _ObjectDataOutput(100, None, True)
self.BOOL_ARR = [False, True, True, True]
self.INT_ARR = [1, 2... |
from dart.context.locator import injectable
from dart.model.workflow import WorkflowState, WorkflowInstanceState
from dart.model.action import ActionState
import logging
import boto3
_logger = logging.getLogger(__name__)
@injectable
class PendingActionsCheck(object):
def __init__(self, action_service):
s... |
import pyxb_114.binding.generate
import pyxb_114.binding.datatypes as xs
import pyxb_114.binding.basis
import pyxb_114.utils.domutils
import os.path
xsd='''<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="urn:trac-0071" targetNamespace="urn:trac-0071">
<xs:elem... |
from homework_parser.file_parser import detect_plugin
from sys import argv, stdin, stdout, stderr, exit
from argparse import ArgumentParser, FileType
parser = ArgumentParser(description='parse file/stdint and write to file/stdout')
parser.add_argument('in_format', help='plugin to load file/stdin')
parser.add_argument... |
from __future__ import print_function, absolute_import
import os, tempfile, json
from PySide2 import QtGui, QtWidgets
import learnbot_dsl.guis.CreateBlock as CreateBlock
from learnbot_dsl.blocksConfig.blocks import pathBlocks
from learnbot_dsl.blocksConfig.parserConfigBlock import pathConfig
from learnbot_dsl.learnbotC... |
# -*- coding: utf-8 -*-
"""Application configuration."""
import os
from pymongo import MongoClient
class Config:
"""Base configuration."""
SECRET_KEY = os.environ.get('NORMAN_SECRET', 'a9fb1b64-1f0f-11e7-95e2-7077816bf77d') # TODO: Change me
APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This d... |
"""
WSGI config for safarido project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION``... |
#!/usr/bin/env python
"""This is a selenium test harness used interactively with Selenium IDE."""
import copy
import socket
import threading
from wsgiref import simple_server
import logging
# pylint: disable=g-bad-import-order
from grr.gui import django_lib
# pylint: enable=g-bad-import-order
from grr.lib import a... |
"""Generates the all_tests.js file.
all_tests.js tells all_tests.html the paths to the files to test.
Usage:
$ python ./buildtools/gen_all_tests_js.py > generated/all_tests.js
"""
import common
def main():
common.cd_to_firebaseauth_root()
print "var allTests = ["
_print_test_files_under_root(common.TESTS_BASE_... |
from django.test import TestCase
from pages.cache import cache
from pages.models import Page, Content
from pages import settings as pages_settings
from pages.testproj import test_settings
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from djang... |
import fixtures
import json
import random
import string
import time
import uuid
import six
from sahara.tests.integration.tests import base as b
from sahara.tests.integration.tests import cinder
from sahara.tests.integration.tests import edp
from sahara.tests.integration.tests import map_reduce
from sahara.tests.integ... |
import unittest as ut
import unittest_decorators as utx
import espressomd
@utx.skipIfMissingFeatures(["LENNARD_JONES"])
class PairTest(ut.TestCase):
s = espressomd.System(box_l=[1.0, 1.0, 1.0])
def setUp(self):
self.s.time_step = 0.1
self.s.thermostat.turn_off()
self.s.part.clear()
... |
"""
Copyright (c) 2011, 2012, Regents of the University of California
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, thi... |
# -*- coding: utf-8 -*-
from nose.tools import eq_
import bot_mock
from pyfibot.modules import module_urltitle
import pytest
from vcr import VCR
my_vcr = VCR(path_transformer=VCR.ensure_suffix('.yaml'),
cassette_library_dir="tests/cassettes/",
record_mode=pytest.config.getoption("--vcrmode"))... |
import errno
import socket
try:
import ssl
except ImportError:
_TLS_SUPPORT = False
else:
_TLS_SUPPORT = True
if _TLS_SUPPORT:
try:
PROTOCOL_TLS = ssl.PROTOCOL_TLS
except AttributeError:
PROTOCOL_TLS = ssl.PROTOCOL_SSLv23
from bases.FrameworkServices.SimpleService import SimpleSer... |
"""RPC server implementation.
Note
----
Server is TCP based with the following protocol:
- Initial handshake to the peer
- [RPC_MAGIC, keysize(int32), key-bytes]
- The key is in format
- {server|client}:device-type[:random-key] [-timeout=timeout]
"""
# pylint: disable=invalid-name
from __future__ import absolute... |
"""Tornado handlers for kernels.
Preliminary documentation at https://github.com/ipython/ipython/wiki/IPEP-16%3A-Notebook-multi-directory-dashboard-and-URL-mapping#kernels-api
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import logging
from torn... |
"""
Utility classes for reporting linter results.
"""
from __future__ import absolute_import, print_function
import os
import re
from six.moves import range
from xsslint.utils import StringLines
class RuleViolation(object):
"""
Base class representing a rule violation which can be used for reporting.
"... |
#!/usr/bin/env python
"""
Filter Streaming API tweets on geolocation and some other stuff
(follower/ing counts, retweets)
Brendan O'Connor (brenocon.com)
"""
import sys, os, re
# sys.path.insert(0,'/h/brendano/proc')
# sys.path.insert(0,'/mal1/brendano/twi/twproc/proc')
# sys.path.insert(0, os.path.join(os.path.dirnam... |
"""SCons.Platform
SCons platform selection.
This looks for modules that define a callable object that can modify a
construction environment as appropriate for a given platform.
Note that we take a more simplistic view of "platform" than Python does.
We're looking for a single string that determines a set of
tool-ind... |
# -*- coding: utf-8 -*-
"""
Config management tool
"""
from copy import deepcopy
import uuid
import os
from functools import partial
from openre.helpers import randshift, from_json, to_json, set_default
from openre import types
import logging
class Config(dict):
def __init__(self, data=None):
if data is No... |
"""
Copyright (C) 2016 Hephaestos
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.
This program is distributed in the hope that... |
import numpy as np
import tensorflow as tf
from agents import TabularQAgent, capacities
class TabularQLambdaBackwardAgent(TabularQAgent):
"""
Agent implementing Backward TD(lambda) tabular Q-learning.
"""
def set_agent_props(self):
self.lr = self.config['lr']
self.lr_decay_steps = self... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import urllib
from django.db.models import Q
from treemap.audit import Audit, Authorizable, get_auditable_class
from treemap.models import Instance, MapFeature, InstanceUser, User
fro... |
#!/usr/bin/env python2
import argparse
import csv
from pprint import pprint
import os
import struct
import sys
import time
import threading
import queue
import numpy as np
import pygame
import pygame.fastevent
from pygame.locals import *
import m3_common
from m3_logging import get_logger
logger = get_logger(__name... |
import time
import json
import pprint
import hashlib
import struct
import re
import base64
import httplib
import sys
from multiprocessing import Process
ERR_SLEEP = 15
MAX_NONCE = 1000000L
settings = {}
pp = pprint.PrettyPrinter(indent=4)
class sherlockholmescoinRPC:
OBJID = 1
def __init__(self, host, port, usern... |
from __future__ import print_function
__author__ = 'cpaulson'
import pyKriging
from pyKriging.krige import kriging
from pyKriging.samplingplan import samplingplan
from pyKriging.CrossValidation import Cross_Validation
from pyKriging.utilities import saveModel
# The Kriging model starts by defining a sampling plan, we ... |
import socket
import re
from math import floor
ip = '195.154.53.62'
port = 1337
buffer_size = 1024
pattern = r'Question\s*\d+\s*:\s*(\d+)\s*([/*+%-])\s*(\d+)'
s = socket.socket()
s.connect((ip, port))
while True:
inp = s.recv(buffer_size).decode('ascii')
search = re.search(pattern, inp)
print(inp)
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import mock
from django.core.urlresolvers import reverse
from exam import fixture
from social_auth.models import UserSocialAuth
from sentry.models import UserOption, LostPasswordHash, User
from sentry.testutils import TestCase
class AppearanceSettings... |
from __future__ import print_function
import socket
import sys
import time
import logging
import pynmea2 as nmea
## Reads a Bluetooth GPS
#
class BluetoothGps:
## Constructor
#
# @param addr The bluetooth addresss of the GPS
#
def __init__(self, addr):
connected = False
while(not connected):
try:
... |
# -*- coding: 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):
# Deleting field 'ObjAttribute.db_value'
db.delete_column('objects_objattribute', 'db_value')
db.ren... |
#!/usr/bin/env python
import sys
from qt import *
from Qwt4.Qwt import *
from Qwt4.anynumpy import *
# from scipy.pilutil
def bytescale(data, cmin=None, cmax=None, high=255, low=0):
if ((hasattr(data, 'dtype') and data.dtype.char == UInt8)
or (hasattr(data, 'typecode') and data.typecode == UInt8)
... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2014-2016 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the... |
__author__ = 'Tom Schaul, <EMAIL>'
from scipy import array
from pomdp import POMDPTask
from pybrain.rl.environments.mazes import Maze
from pybrain.rl.tasks.task import Task
class MazeTask(POMDPTask):
""" a task corresponding to a maze environment """
bangPenalty = 0
defaultPenalty = 0
finalRewa... |
import unittest
import solvers.deck
ALL_CARDS = (
'Ac', '2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', 'Tc', 'Jc', 'Qc', 'Kc',
'Ad', '2d', '3d', '4d', '5d', '6d', '7d', '8d', '9d', 'Td', 'Jd', 'Qd', 'Kd',
'Ah', '2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', 'Th', 'Jh', 'Qh', 'Kh',
'As', '2s', '3s',... |
import os
import re
import logging
from gi.repository import Gtk, Gio
from ubuntutweak import system
from ubuntutweak.gui.containers import ListPack, GridPack
from ubuntutweak.modules import TweakModule
from ubuntutweak.factory import WidgetFactory
log = logging.getLogger('Misc')
class Misc(TweakModule):
__titl... |
import logging
import os
import dj_database_url
from lib.settings_base import CACHE_PREFIX, KNOWN_PROXIES, LOGGING, HOSTNAME
from .. import splitstrip
import private_base as private
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = private.EMAIL_HOST
SEND_REAL_EMAIL = True
ENGAGE_ROBOTS =... |
"""
This file is part of the reddit Data Extractor.
The reddit Data Extractor 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 ver... |
import time
class TokenBucket(object):
"""Implements token bucket algorithm.
https://en.wikipedia.org/wiki/Token_bucket
"""
def __init__(self, fill_rate, capacity):
self._fill_rate = float(fill_rate)
self._capacity = float(capacity)
self._count = float(capacity)
self.... |
# encoding: utf-8
"""
vpls.py
Created by Nikita Shirokov on 2014-06-16.
Copyright (c) 2014-2015 Nikita Shirokov. All rights reserved.
Copyright (c) 2014-2015 Exa Networks. All rights reserved.
"""
from struct import unpack
from struct import pack
from exabgp.protocol.ip import IP
from exabgp.protocol.family import AF... |
__author__ = "R B Wilkinson"
__date__ = "29/02/12"
__copyright__ = "(C) 2012 Science and Technology Facilities Council"
__license__ = "BSD - see LICENSE file in top-level directory"
__contact__ = "<EMAIL>"
__revision__ = "$Id$"
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup ... |
#!/usr/bin/env python
# coding: utf-8
"""The linear solvers used in Capytaine.
They are based on numpy solvers with a thin layer for the handling of Hierarchical Toeplitz matrices.
"""
# Copyright (C) 2017-2019 Matthieu Ancellin
# See LICENSE file at <https://github.com/mancellin/capytaine>
import logging
from functo... |
"""helpers.py contains convenient methods for writing tests."""
import mock
import os
import time
import types
class Matcher(object):
# pylint: disable=line-too-long
"""A class used for argument matching.
See:
https://docs.python.org/3/library/unittest.mock-examples.html#more-complex-argument-matching.
... |
#!/usr/bin/env python3
from __future__ import print_function
import inspect
from inform import indent, Color, render
from pathlib import Path
from types import ModuleType, FunctionType
import sys
__version__ = '0.3.10'
def p(*args, **kwargs):
frame_depth = 1
_print(frame_depth, args, kwargs)
def pp(*args, *... |
# -*- coding: utf-8 -*-
"""Docstring
Notes: Ss 105_bb presented with issues during computation of EOG projectors despite
having valid EOG data.
Ss 102_rs No matching events found for word_c254_p50_dot (event id 102)
"""
# Authors: Kambiz Tavabi <<EMAIL>>
#
#
# License: BSD (3-clause)
import numpy as np
import mnefu... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
'''
Dynamic model of a mobile inverted pendulum
'''
import numpy as np, math, scipy.integrate, matplotlib.pyplot as plt
import control.matlab
import my_utils as mu
#
# Parameters
#
class Param:
def __init__(self, sat=None):
self.R, self.L = 0.04, 0.1 ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from functools import wraps
from kokemomo.settings import SETTINGS
from kokemomo.plugins.engine.model.km_user_table import KMUser
from kokemomo.plugins.engine.model.km_group_table import KMGroup
from kokemomo.plugins.engine.model.km_role_table import KMRole
from .km_sessio... |
"""Version information for Invenio.
This file is imported by ``invenio.__init__``, and parsed by ``setup.py``.
"""
# Respect the following format: major, minor, patch, ..., "dev"?, revision?
#
# - major, minor, patch are numbers starting at zero.
# - you can put as much sub version as you need before 'dev'
# - dev ha... |
# -*- coding: UTF-8 -*-
from django.conf import settings
from django.core.management.base import NoArgsCommand, CommandError
from django.db import transaction, IntegrityError
from django.utils import simplejson
import os
from transifex.languages.models import Language
from transifex.languages.management.commands.txlan... |
"""Utilities for work with docker commands and images"""
import json
import logging
import os
from .agent import get_private_agents
from .command import run_command_on_master
from .file import copy_file
logger = logging.getLogger(__name__)
def docker_version(host=None, component='server'):
""" Return the vers... |
#!/usr/bin/env python
"""
Some simple tests for the promise_keeper module.
"""
from promise_keeper import Promise, PromiseKeeper
from time import sleep
from random import random
from unittest import TestCase
def slow_add(x, y):
sleep(random() * 1)
return x + y
def slow_div(x, y):
sleep(random() * 1)
... |
#!/usr/bin/env python
"""
Interface to SentiWordNet using the NLTK WordNet classes.
---Chris Potts
"""
import re
import os
import sys
import codecs
try:
from nltk.corpus import wordnet as wn
except ImportError:
sys.stderr.write("Couldn't find an NLTK installation. To get it: http://www.nltk.org/.\n")
sy... |
"""Browser code for the malone application."""
__metaclass__ = type
__all__ = [
'MaloneApplicationNavigation',
'MaloneRelatedPages',
]
from zope.component import getUtility
from lp.bugs.browser.bug import MaloneView
from lp.bugs.interfaces.bug import IBugSet
from lp.bugs.interfaces.bugtracker import IBu... |
import itertools
from typing import Mapping, Text, Union
import numpy as np
import torch
from torch_audiomentations.core.transforms_interface import BaseWaveformTransform
from torch_audiomentations.utils.config import from_dict as augmentation_from_dict
from pyannote.audio import Inference, Model
from pyannote.audio.... |
{
'name': 'Compassion CH Partner Communications',
'version': '10.0.5.1.0',
'category': 'Other',
'author': 'Compassion CH',
'license': 'AGPL-3',
'website': 'http://www.compassion.ch',
'depends': [
'report_compassion',
'child_switzerland',
'sms_939',
'auth_signu... |
# Creating a dictionary
crew_details = {
"Pilot":"Kumar",
"Co-pilot":"Raghav",
"Head-Strewardess":"Malini",
"Stewardess":"Mala"
}
# Accessing the value using key
print(crew_details["Pilot"])
# Iterating through the dictionary
for key,value in crew_details.items():
print(key,":",value)
# Bui... |
from hyperadmin.indexes import Index
class ModelIndex(Index):
@property
def model(self):
return self.resource.model
def get_primary_field(self):
return self.model._meta.pk
def get_url_params(self, param_map={}):
"""
returns url parts for use in the url regexp ... |
"""Archive commands for the star program."""
from .tar import add_tar_opts as add_star_opts
def extract_tar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a TAR archive."""
cmdlist = [cmd, '-x']
add_star_opts(cmdlist, compression, verbosity)
cmdlist.extend(['-C', outdir, 'file=... |
import argparse
import logging
import os
import sys
from datetime import datetime
from binascii import hexlify, unhexlify
from pyasn1.codec.der import decoder
from impacket import version
from impacket.dcerpc.v5.samr import UF_ACCOUNTDISABLE, UF_NORMAL_ACCOUNT
from impacket.examples import logger
from impacket.krb5 im... |
'''
Copyright (c) 2015, Salesforce.com, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the foll... |
import shutil
import subprocess
import unittest
from Queue import Queue
from os import makedirs
from os.path import abspath, exists, join
from re import compile
from shutil import rmtree
from config_rpm_maker import configuration
from config_rpm_maker.svnservice import SvnService
from config_rpm_maker.configuration.p... |
import time
import operator
import concurrent.futures
from array import array
from itertools import repeat
from itertools import count as counter
from concurrent.futures import FIRST_COMPLETED
from concurrent.futures import ThreadPoolExecutor
import polymr.storage
from polymr.storage import dumps
from toolz import cou... |
from collections import Counter
from openerp import models, fields, api
from openerp.addons import decimal_precision as dp
class ProductProduct(models.Model):
_inherit = 'product.product'
potential_qty = fields.Float(
compute='_get_potential_qty',
type='float',
digits_compute=dp.get_... |
from harpia.GladeWindow import GladeWindow
from harpia.amara import binderytools as bt
import gtk
from harpia.s2icommonproperties import S2iCommonProperties
#i18n
import os
import gettext
APP='harpia'
DIR=os.environ['HARPIA_DATA_DIR']+'po'
_ = gettext.gettext
gettext.bindtextdomain(APP, DIR)
gettext.textdomain(APP)
#-... |
import datetime
from django.test import TestCase
from samples.forms import FluVaccineForm
from samples.models import AdmissionNote, Patient
class FluVaccineFormTest(TestCase):
def setUp(self):
patient = Patient(name="Gabriel Test")
patient.save()
self.admission_note = AdmissionNote.obje... |
import os
import json
import importlib
import pip
import sys
from flask import send_from_directory, abort, render_template
from . import app, config, save_config, site, merge_dicts, root_logger
logger = root_logger.getChild("plugins")
IS_VIRTUAL_ENV = hasattr(sys, "real_prefix")
if not IS_VIRTUAL_ENV:
logger.... |
import json
import re
from django.db import models
from django.utils.translation import gettext as _
from starthinker_ui.account.models import Account
RE_IDENTIFIER = re.compile(r'@(.*?)(\.google)?\.iam\.gserviceaccount\.com', re.DOTALL)
class Project(models.Model):
account = models.ForeignKey(Account, on_delete... |
import unittest
import mock
import datetime
import uuid
from application import db
from application.frontend.server import app
from application.auth.models import User
from test_samples import title
class AuditTestCase(unittest.TestCase):
"""
Audit logging must have the 'info' level.
The tests below will... |
from datamodel import DataModel
from gen_utils import *
from gigs.config.strings import *
from ml_utils import *
from sklearn import ensemble, svm
import json
import math
class Experimenter:
"""Execute and manage machine learning experiments"""
def __init__(self, dm):
self.dm = dm
#enddef
d... |
# File Holds Constant values for Repy
#
#
# Holds the path to a python installation
#PATH_PYTHON_INSTALL = "\\Storage Card\\Program Files\\Python25\\python.exe"
#PATH_PYTHON_INSTALL = "\\Program Files\\Python25\\python.exe"
PATH_PYTHON_INSTALL = "C:\\Python26\\python.exe"
# Default Python Flags
# e.g. The "/new" flag... |
from __future__ import absolute_import
from copy import copy
from .utils import unpack
from six import string_types
class DRESTQuery(object):
def __init__(
self,
resource=None,
filters=None,
orders=None,
includes=None,
excludes=None,
extras=None
):
... |
from Screens.Screen import Screen
from Plugins.Plugin import PluginDescriptor
from Screens.MessageBox import MessageBox
from Components.ActionMap import ActionMap
from Components.Label import Label
from Components.ConfigList import ConfigListScreen
from Components.config import config, getConfigListEntry, ConfigSubsect... |
import json
from logging import StreamHandler
import re
import requests
import colorlog
from comparators import BaseComparator
logger = colorlog.logging.getLogger(__name__)
handler = StreamHandler()
handler.setLevel('INFO')
handler.setFormatter(colorlog.ColoredFormatter(
'%(log_color)s%(asctime)s - %(name)s - %... |
# Py-BOBYQA example: minimize the noisy Rosenbrock function
from __future__ import print_function
import numpy as np
import pybobyqa
# Define the objective function
def rosenbrock(x):
return 100.0 * (x[1] - x[0] ** 2) ** 2 + (1.0 - x[0]) ** 2
# Modified objective function: add 1% Gaussian noise
def rosenbrock_noi... |
from __future__ import division
import numpy as np
import chainer
from chainer.backends import cuda
import chainer.functions as F
from chainercv.experimental.links.model.fcis.utils.proposal_target_creator \
import ProposalTargetCreator
from chainercv.links.model.faster_rcnn.faster_rcnn_train_chain \
import _... |
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from ..compat import dict_items
from ..compat import dict_keys
class PathEngine(object):
"""
This module is responsible for computing the next-hop for every rou... |
from django.shortcuts import render
from django.urls import reverse
from django.http import HttpResponse
from django.template import RequestContext
from django.views import generic
from django.forms import ModelForm
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.utils impor... |
"""
`Fish-style <http://fishshell.com/>`_ like auto-suggestion.
While a user types input in a certain buffer, suggestions are generated
(asynchronously.) Usually, they are displayed after the input. When the cursor
presses the right arrow and the cursor is at the end of the input, the
suggestion will be inserted.
If... |
#!python
# coding=utf-8
import os
import collections
from copy import deepcopy
from collections import OrderedDict, Mapping
import numpy as np
import simplejson as json
from . import logger
class MetaInterface(Mapping):
VALID_KEYS = ['dimensions', 'variables', 'attributes']
@classmethod
def from_jsonf... |
# -*- coding: utf-8 -*-
import hashlib
import os
from common.lib.file import decompress_file_by_extension
import bz2
import gzip
# xz compression
try:
import lzma
except ImportError:
from backports import lzma
def get_checksum_regex(type_str):
if type_str == "sha256":
return "[a-z0-9]{64}"
... |
import logging
import os
import subprocess
import pysam
from collections import defaultdict
try:
from tempfile import TemporaryDirectory
except ImportError:
from backports.tempfile import TemporaryDirectory
from .fasta_io import write_sequences
logger = logging.getLogger(__name__)
class Description(object):... |
#!/usr/bin/python
import numpy as np
from scipy import linalg
import math
import argparse
import time
import sys
# Soft thresholding function
def soft(a,c,l):
if c < -l:
return (c + l)/a
elif c > l:
return (c-l)/a
else:
return 0.0
def gradientDescent(X, w, w0, t, l, d):
# calculate a's once
row... |
from Kamaelia.UI.Tk.TkWindow import TkWindow
from Kamaelia.Support.Tk.Scrolling import ScrollingMenu
from Axon.Ipc import producerFinished, shutdownMicroprocess
from ImportShardPanel import ImportShardPanel
import Tkinter
import pprint
from glom import glomfrompath
class ImportShardsGUI(TkWindow):
def __init__(se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.