content
stringlengths
4
20k
from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class Menu(Choreography): def __init__(self, temboo_session): """ Create a new inst...
import timing import sys ''' Created on Jul 6, 2013 @author: kyle ''' def run(upperBound): numList = list(upperBound * [True]) numList[0] = False; numList[1] = False; for (i, isprime) in enumerate(numList): if isprime: for n in range(i*i, upperBound, i): ...
# -*- coding: utf-8 -*- import pytest from TSBVMIP.value_containers import ValueFloat, ValueInt, ValueIntArrayRef, ValueFloatArrayRef, ValueReference, convert_values def test_eq(): assert ValueInt() == ValueInt() assert ValueInt(10) == ValueInt(10) assert ValueFloat() == ValueFloat() assert ValueFl...
""" Using the zipfile module to interact with Zip files. Can do all the *usual* zip operations, as well as get at the metadata. The zipfile module obviously transparently opens the file as well - as we can use the *with* syntax. Can solve this using regex patterns too as depicted before, but this worked, so I didn't t...
import sys import eventlet eventlet.monkey_patch() import netaddr from oslo.config import cfg from neutron.agent.common import config from neutron.agent import l3_agent from neutron.agent import l3_ha_agent from neutron.agent.linux import external_process from neutron.agent.linux import interface from neutron.agent....
__author__ = 'weirded' import json import urllib2 # set your params here app_id = "" keyword = "" group_name = "" api_url = 'https://api.vk.com/method/' def get_access_token(app_id, keyword): auth_url = 'https://oauth.vk.com/access_token?' + \ 'client_id=' + app_id + \ '&client_sec...
import numpy as np from .normal_form_game import NormalFormGame from ..util import check_random_state from .random import _random_mixed_actions from .utilities import _copy_action_profile_to class FictitiousPlay: """ Class representing a fictitious play model. Parameters ---------- data : NormalF...
#!/usr/bin/env python """ @file circlePolygon.py @author Daniel Krajzewicz @author Michael Behrisch @date 2010-02-20 @version $Id: circlePolygon.py 22608 2017-01-17 06:28:54Z behrisch $ Approximates a list of circles by polygons. SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/ Copyright (C) 2010-2...
from collections import Counter import unittest from luhn import Luhn class LuhnTests(unittest.TestCase): def test_addends(self): # uses a Counter to avoid specifying order of return value self.assertEqual(Counter([1, 4, 1, 4, 1]), Counter(Luhn(12121).addends())) def...
""" This file includes a function to predict pH dependent solubility using the original file and cxcalc result file. Since the cxcalc result file does not include SMILES string information, two files should be merged for final reporting. Now, I will use R-SMILES strings which represent molecules of oxidized form. 1...
import os from flask import Flask from flask_assets import Environment from flask_compress import Compress from flask_login import LoginManager from flask_mail import Mail from flask_rq import RQ from flask_sqlalchemy import SQLAlchemy from flask_wtf import CSRFProtect from app.assets import app_css, app_js, vendor_c...
from tkinter import * from tkinter import ttk class Dialog(Toplevel): """ Create a simple dialogue to rename an annotation text object """ def __init__(self, parent, title, canvas_SG, item, levelId): """ Initialize the GUI element :param parent: root window :param tit...
# Initialize App Engine and import the default settings (DB backend, etc.). # If you want to use a different backend you have to remove all occurences # of "djangoappengine" from this file. from djangoappengine.settings_base import * import os SECRET_KEY = ''''R*kmC"zvXEy^pp~arYJE?<YiepwtKD?R&cd\eo@VF-;J};#\a''' INS...
#!/usr/bin/env python # encoding: utf8 import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir)) import unittest from plucky import merge class TestMerge(unittest.TestCase): def test_leaf_int(self): self.assertEqual(merge(1, 2), 3) def test_leaf_int_none(self): ...
""" Baseclasses for tools and toolchains. """ import inspect import string import time import sys import os from util import ResettableType, deepish_copy import multiproc import analysis import settings import wrappers import monitor import diskio TOOLNAME_CHARS = ' -_' + string.ascii_letters + string.digits cla...
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal <<EMAIL>>' __docformat__ = 'restructuredtext en' import random from io impor...
""" Worker that receives input from Piped RDD. """ from __future__ import print_function import os import sys import time import socket import traceback from pyspark.accumulators import _accumulatorRegistry from pyspark.broadcast import Broadcast, _broadcastRegistry from pyspark.taskcontext import TaskContext from pys...
from pyasn1 import error __all__ = ['NamedValues'] class NamedValues(object): """Create named values object. The |NamedValues| object represents a collection of string names associated with numeric IDs. These objects are used for giving names to otherwise numerical values. |NamedValues| objects...
# -*- coding: utf-8 -*- """Test clustering.""" #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import numpy as np from numpy.testing import assert_array_equal as ae from pytest import raises from...
"""Truncated SVD for sparse matrices, aka latent semantic analysis (LSA). """ # Olivier Grisel <<EMAIL>> # Michael Becker <<EMAIL>> # License: 3-clause BSD. import numpy as np import scipy.sparse as sp from scipy.sparse.linalg import svds from ..base import BaseEstimator, TransformerMixin from ..util...
import textwrap from tests.package.test_python import TestPythonPackageBase class TestPythonPy3DBusNext(TestPythonPackageBase): __test__ = True config = TestPythonPackageBase.config + \ """ BR2_PACKAGE_DBUS=y BR2_PACKAGE_PYTHON3=y BR2_PACKAGE_PYTHON_DBUS_NEXT=y """ ...
from pyshell.register.loader.dependency import DependencyLoader from pyshell.register.utils.addon import getOrCreateProfile def _localGetAndInitCallerModule(profile=None): profile_loader = getOrCreateProfile(DependencyLoader, profile) return profile_loader def setDependencyLoadPriority(value, profile=None):...
import json import unittest import os from rateItSeven.scan.legacy.moviestore import MovieStore from rateItSeven.senscritique.domain.sc_list import ListType class TestMovieStore(unittest.TestCase): def setUp(self): self.basedir_abspath = os.path.abspath( __file__ + "/../../../resources/files...
"""Invoke a resource agent. This command may be useful in an application, but its most first use was to quickly get some code working for parsing and running resource agent methods.""" import argparse import logging import sys # from swarm.common import * from swarm import ra def _main(): # Define command line ...
#!/usr/bin/env python2.7 import os import sys import subprocess import argparse UMASK = 0 MAXFD = 1024 if (hasattr(os, "devnull")): REDIRECT_TO = os.devnull else: REDIRECT_TO = "/dev/null" def daemonize(): try: # Fork a child process so the parent can exit. This returns control to # th...
'''Use avbin to decode audio and video media. ''' from audio import AudioFormat, AudioData from exceptions import MediaFormatException from video import VideoFormat, ImageData __docformat__ = 'restructuredtext' __version__ = '$Id: avbin.py 2090 Jernej Virag $' import ctypes import lib av = lib.load_avbin() AVBIN_RE...
import os from HnTool.modules.rule import Rule as MasterRule class Rule(MasterRule): def __init__(self, options): MasterRule.__init__(self, options) self.short_name="vsftpd" self.long_name="Checks security problems on VsFTPd servers" self.type="config" self.required_files = ...
import os import time from ._compat import long, binary_type try: import threading as _threading except ImportError: import dummy_threading as _threading class EntropyPool(object): def __init__(self, seed=None): self.pool_index = 0 self.digest = None self.next_byte = 0 sel...
# -*- coding: utf-8 -*- import json import logging from uuid import UUID from cassandra import OperationTimedOut, InvalidRequest, Timeout from cassandra.query import dict_factory from elasticsearch import Elasticsearch from cassandra.cluster import Cluster from elasticsearch.client.indices import IndicesClient from e...
from .base import * from .commands import * from .command import * from .cybrowser import * from .session import * from .network import * from .node import * from .vizmap import * from .diffusion import * from .idmapper import * from .edge import * from .group import * from .view import * from .layout import * from .ta...
class Solution: # @param board, a 9x9 2D array # @return a boolean def validOneDirection(self, i, j, d1, d2, board) : mark = [0 for k in range(9+1)] while i < len(board) and j < len(board[0]) : if board[i][j] != '.' : mark[int(board[i][j])] += 1 i, j =...
import sys import java.io.FileReader as FileReader import java.lang.StringBuffer as StringBuffer import java.lang.Boolean as Boolean import weka.core.Instances as Instances import weka.classifiers.trees.J48 as J48 import weka.classifiers.Evaluation as Evaluation import weka.core.Range as Range """ Commandline parame...
# -*- coding: utf-8 -*- import base64 available = True try: import lxml.etree except ImportError: print('lxml module missed. Importing from CollectionStudio not available') available = False from PyQt5 import QtCore, QtGui from OpenNumismat.Collection.Import import _Import from OpenNumismat.Tools.Conve...
from typing import Dict, Optional from great_expectations.core import ExpectationConfiguration from great_expectations.execution_engine import ExecutionEngine from great_expectations.expectations.expectation import ColumnExpectation from great_expectations.expectations.util import render_evaluation_parameter_string fr...
#!/usr/bin/python #coding=utf-8 import requests import re import logging import time import threading import socket from bs4 import BeautifulSoup #1234 class sis001: def __init__(self): self.s = requests.Session() self.browse_headers ={"User-agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"} LOG_FILE...
"""Legal items and validators for the parsec test config file.""" from parsec.validate import validator as vdr SPEC = { 'title' : vdr( vtype="string" ), 'single values' : { 'integers' : { '__MANY__' : vdr( vtype="integer" ) }, 'booleans' : { '__MANY__' : vdr( vtype="bo...
import bottle, api_functions import logging as log from json import dumps # needed to return a top level JSON array api_functions.set_up_logs() api = api_functions.API() @bottle.get('/programs') @bottle.get('/programs/<program_id>') def get_programs(program_id=None): if program_id is None: # must set con...
import unittest import uuid from openstack.tests.functional import base @unittest.skipUnless(base.service_exists(service_type='object-store'), 'Object Storage service does not exist') class TestObject(base.BaseFunctionalTest): FOLDER = uuid.uuid4().hex FILE = uuid.uuid4().hex DATA =...
import os from django.contrib.gis.gdal import DataSource from django.contrib.gis.utils import LayerMapping from django.contrib.gis.geos import MultiPolygon from django.contrib.gis.gdal import OGRException from django.db.utils import IntegrityError from optparse import make_option from django.core.management.base impor...
#!/usr/bin/env python """ items. """ import copy from basinboa.system.uid import Uid from basinboa.system.loader import YamlLoader STYLE_BAG = 'bag' STYLE_WEAPON = 'weapon' STYLE_ARMOR = 'armor' STYLE_LIQUID = 'liquid' STYLE_FOOD = 'food' STYLE_KEY = 'key' STYLE_TOOL = 'tool' class Item(Uid): """docstring for Ite...
import _plotly_utils.basevalidators class ZValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="z", parent_name="isosurface.slices", **kwargs): super(ZValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data...
""" mbed SDK Copyright (c) 2011-2013 ARM Limited 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 wr...
#!/usr/bin/env python # add the solar directory to the path so we can import it import os import sys sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'solar')) # import the datetime library so we construct proper datetime instances from datetime import datetime # import the solar library import solar...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion import modelcluster.fields import wagtail.core.fields import wagtail.core.blocks class Migration(migrations.Migration): dependencies = [ ('wagtailimages', '0006_add_v...
from __future__ import unicode_literals __author__ = 'Victor Zarubkin' __copyright__ = 'Copyright (C) 2012 Victor Zarubkin' __credits__ = ['Victor Zarubkin'] __license__ = ['GPLv3'] __version__ = '1.3.0' # this is last application version when this script file was changed __email__ = '<EMAIL>' ##############...
#!/usr/bin/python2.7 import rrdtool import os.path from pycgminer import CgminerAPI def getCgminerFactory(): return CgminerAPI() def getSummary(): summary = getCgminerFactory().summary() summary = summary['SUMMARY'] summary = summary[0] return summary def getPoolCount(): cg...
import atmPy.atmos.air as air from numpy import abs class TestAir(object): def __init__(self): self.a = air.Air() self.mu_vals = {'T': [-5, 0, 10, 15, 25], 'mu': [1.7105007E-5, 1.7362065e-5, 1.7869785E-5, 1.8120528E-5, 1.861598E-5] } ...
import os import sys import subprocess import logging import time import platform import re from functools import partial from plumbum.path.local import LocalPath, LocalWorkdir from tempfile import mkdtemp from contextlib import contextmanager from plumbum.path.remote import RemotePath from plumbum.commands import Comm...
# -*- coding: utf-8 -*- """ Инструменты конфигурирования хранилища """ import re import importlib IO_PURPOSE_INDEX = 'IO_PURPOSE_INDEX' IO_PURPOSE_DATA = 'IO_PURPOSE_DATA' IO_BACKEND = 'io_backend' BASE_NAME = 'base_name' QUERY_API = 'query_api' def _import_thing(path, name, default_module): """ Возвращае...
import sys, os, random cwd = os.getcwd().split(os.sep) cwd[-1] = 'dose' cwd = os.sep.join(cwd) sys.path.append(cwd) import analytics def calc_average_distance(genomes): genetic_distance_list = [] for genome in genomes: chromosome = genome[0].sequence random_chromosome = random.choice(genomes)[...
{ 'name': 'Time Tracking', 'version': '8.0.1.0.0', 'category': 'Human Resources', 'sequence': 23, 'description': """ This module implements a timesheet system. ========================================== """, 'author': 'OpenERP SA', 'website': 'http://www.openerp.com', 'license': 'AGP...
import web import os import os.path import time import glob import subprocess import json import webbrowser web.config.debug = True urls = ( '/', 'IndexHandler', '/documentation', 'DocumentationHandler', '/bugs', 'BugsHandler', '/edit-bug/(.*)', 'EditBugHandler', '/new-bug', 'NewBu...
import numpy as np from collections import OrderedDict import theano import theano.tensor as T from foxhound.theano_utils import floatX, l2norm, shared0s, sharedX def clip_norm(g, c, n): if c > 0: g = T.switch(T.ge(n, c), g*c/n, g) return g def clip_norms(gs, c): norm = T.sqrt(sum([T.sum(g**2) f...
import os import re import subprocess import sys from trace_viewer import trace_viewer_project class AffectedFile(object): def __init__(self, input_api, filename): self._filename = filename self._input_api = input_api self._cached_contents = None self._cached_changed_contents = None self._cached...
"""Linter that warns about using the dangerous UserProperty. UserProperty's user_id value can change depending on whether or not Google currently has a Google account registered w/ an email address that matches UserProperty's email property. That means when a user changes email settings in their Google account it can ...
import mock from neutron.common import constants as n_const from neutron.tests import base from networking_ofagent.plugins.ofagent.agent import ports class TestOFAgentPorts(base.BaseTestCase): def test_port(self): name = 'foo03b9a237-0b' p1 = ports.Port(port_name=name, ofport=999) ryu_of...
import logging import pytest from dotmailer.address_books import AddressBook from dotmailer.exceptions import ErrorAddressbookNotFound, ErrorAddressbookNotwritable log = logging.getLogger(__name__) @pytest.mark.notdemo def test_delete_valid_address_book(sample_address_book): """ Test to confirm that the del...
# -*- coding: utf-8 -*- """ Unit tests for bulk-email-related forms. """ from nose.plugins.attrib import attr from opaque_keys.edx.locator import CourseLocator from bulk_email.forms import CourseAuthorizationAdminForm, CourseEmailTemplateForm from bulk_email.models import BulkEmailFlag, CourseEmailTemplate from xmodu...
import os import six from tero import CONTEXT from tero.setup import SetupTemplate, modify_config, stageFile, postinst class openssh_serverSetup(SetupTemplate): '''Setup the ssh daemon Note: AllowTcpForwarding Specifies whether TCP forwarding is permitted. The default is ``yes''. Note t...
import inspect import threading import typing as tp from ..decorators import wraps from ...exceptions import ResourceLocked, ResourceNotLocked, WouldWaitMore class LockedDataset: """ A locked dataset. Subclass like >>> class MyDataset(LockedDataset): >>> def __init__(self): >>> super...
""" Cached, database-backed sessions. """ import logging from django.contrib.sessions.backends.db import SessionStore as DBStore from django.core.cache import cache from django.core.exceptions import SuspiciousOperation from django.utils import timezone from django.utils.encoding import force_text KEY_PREFIX = "djan...
from __future__ import absolute_import from django.db import transaction from django.utils import timezone from rest_framework import serializers from sentry import features from sentry.api.authentication import DSNAuthentication from sentry.api.base import Endpoint from sentry.api.bases.project import ProjectPermiss...
# -*- coding: utf-8 -*- # Trimming a FASTQ file. # Author - Janu Verma # <EMAIL> import string baseQdict = {x:ord(x) for x in string.printable} class Trimming: """ Trimming a FASTQ sequence. Parameters ---------- sequence : The sequence to be trimmed. qualities : Base qualities of the bp's in the sequence. ...
from popkin.analyze.mmc_performance_tester import MMCPerformanceTester import argparse import pickle import matplotlib.pyplot as plt import numpy as np parser = argparse.ArgumentParser(description='Plot Errors under varying parameters') #parser.add_argument('-configuration', action='store', dest='configuration') parser...
#! Poisson Equation #! ================ #$ \centerline{Example input file, \today} #! Mesh #! ---- from sfepy import data_dir filename_mesh = data_dir + '/meshes/3d/cylinder.mesh' #! Materials #! --------- #$ Here we define just a constant coefficient $c$ of the Poisson equation, #$ using the 'values' attribute. Oth...
# -*- coding: utf-8 - # # This file is part of socketpool. # See the NOTICE for more information. import eventlet from eventlet.green import select from eventlet.green import socket from eventlet import queue from socketpool.pool import ConnectionPool sleep = eventlet.sleep Socket = socket.socket Select = select.sel...
# # Authors: Roy Dragseth (<EMAIL>) # Bas van der Vlies (<EMAIL>) # # SVN INFO: # $Id: PBSQuery.py 289 2013-02-26 09:22:59Z bas $ # """ Usage: from PBSQuery import PBSQuery This class gets the info from the pbs_server via the pbs.py module for the several batch objects. All get..() functions return an dicti...
import logging from hotness.patchers import Patcher from hotness.requests import SubmitPatchRequest from hotness import responses logger = logging.getLogger(__name__) class SubmitPatchUseCase: """ This class represents use case for submitting the patch to package with provided patcher. Attributes: ...
import logging import logging.handlers import os import string from six import moves from oslo.rootwrap import filters class NoFilterMatched(Exception): """This exception is raised when no filter matched.""" pass class FilterMatchNotExecutable(Exception): """Raised when a filter matched but no executa...
""" SPI interface ------------- This module is controlled / configured from the register bus. data can either be transferred from the register bus or it can be transferred from the streaming interface. """ from __future__ import absolute_import, division import myhdl from myhdl import (Signal, intbv, modbv, enum, co...
''' @author: davandev ''' import logging import os import json import urllib import traceback from threading import Thread,Event import davan.config.config_creator as configuration import davan.util.constants as constants from davan.util import application_logger as log_manager from davan.http.service....
DSN = 'dbname=test' ## some others parameters INSERT_THREADS = ('A', 'B', 'C') SELECT_THREADS = ('1', '2') ROWS = 1000 COMMIT_STEP = 20 SELECT_SIZE = 10000 SELECT_STEP = 500 SELECT_DIV = 250 # the available modes are: # 0 - one connection for all inserts and one for all select threads # 1 - connections generated u...
#!/usr/bin/env python # -*-coding:utf-8-*- # @Time : 2017/11/1 ~ 2019/9/1 # @Author : Allen Woo from apps.core.blueprint import api from apps.core.flask.permission import permission_required from apps.core.flask.response import response_format from apps.modules.verification_code.process.image_code import get_code from ...
from math import * import random from hw3_6_ParticleFilter import robot, bearing_noise, steering_noise, distance_noise, get_position class particle(robot): mutation_ratio = 0.05 # +- 5% clonal_selection_range = range(5) def __init__(self): robot.__init__(self) def move(self, motion): ...
# occiput # Stefano Pedemonte # Harvard University, Martinos Center for Biomedical Imaging # Apr. 2014, Boston, MA import numpy from occiput.Core import Image3D, Grid3D, Transform_6DOF from ilang.Models import Model class SSD_ilang( Model ): variables = {'source':'continuous','target':'continuous','transfo...
""" Page objects for common dialogs. Author: pnovotny, ltrilety, mkudlej """ # Copyright 2016 Red Hat # # 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/...
""" sentry.web.frontend.explore ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Contains views for the "Explore" section of Sentry. :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, division from sentry.models import TagKe...
import hashlib import logging import cbor import hkdf import json import sys import binascii import threading from Crypto.Cipher import AES from . import coapDefines as d from . import coapException as e from . import coapMessage as m from . import coapOption as o from . import coapUtils as u class NullHandler(logg...
"""Tests for backend.handlers.frontend.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import httplib import mock from loaner.web_app import constants from loaner.web_app.backend.api import permissions from loaner.web_app.backend.clients import directo...
from sys import exit prompt = "> " def gold_room(): print "Gold er-wer. How much u tak?" choice = raw_input(prompt) if "0" in choice or "1" in choice: how_much = int(choice) else: dead("thats not number ") if(how_much < 50): print "Nice, need before greed, winner" exit(0) else: dead("Your greed has ki...
import hashlib import os import pathlib import shutil import tempfile from functools import partial from pathlib import Path, PurePath from .. import humanize from ..core.base import AbstractNestedEntity, ExecutorEntity from ..core.formatter import FormattedEntity from . import StorageError, base __all__ = ( 'Asy...
#!/usr/bin/env python from basetest import BaseTest import sys, imp import unittest sys.path.insert(0, '..') from zeroinstall.injector import packagekit, model, fetch from zeroinstall.support import tasks import dbus class Connection: def remove(self): pass def makeFakePackageKit(version): class FakePackageKit:...
from docido_sdk.core import Interface __all__ = [ 'IndexAPI', 'IndexAPIConfigurationProvider', 'IndexAPIProcessor', 'IndexAPIProvider', 'IndexPipelineConfig', 'PullCrawlerIndexingConfig', ] class IndexAPIProvider(Interface): # pragma: no cover """ Provide an implementation of IndexAPI ...
from translate.filters import autocorrect class TestAutocorrect: def correct(self, msgid, msgstr, expected): """helper to run correct function from autocorrect module""" corrected = autocorrect.correct(msgid, msgstr) print(repr(msgid)) print(repr(msgstr)) print(msgid.encode...
# coding=utf-8 import numpy as np from imgProcessor.measure.sharpness import parameters from dataArtist.widgets.Tool import Tool class RelativeSharpness(Tool): ''' Calculate the sharpness of one or more input images. This method is suitable to best the best camera focus. ''' icon = 'sharpness.sv...
""" ============================================ Plotting the full vector-valued MNE solution ============================================ The source space that is used for the inverse computation defines a set of dipoles, distributed across the cortex. When visualizing a source estimate, it is sometimes useful to sho...
"""Buildgen expand filegroups plugin. This takes the list of libs from our yaml dictionary, and expands any and all filegroup. """ def excluded(filename, exclude_res): for r in exclude_res: if r.search(filename): return True return False def uniquify(lst): out = [] for el in ls...
import six from django.contrib.gis.geos import Point from rest_framework import generics, views, status from rest_framework import settings as rest_settings from rest_framework.permissions import DjangoModelPermissions from rest_framework.compat import OrderedDict from facilities.models import Facility from common.vi...
# -*- coding: utf-8 -*- from __future__ import print_function from ctypes import * import sys, re, types, ctypes, os import cheader def init(): ## System-specific code headerFile = [os.path.join(os.path.dirname(__file__), "AxMultiClampMsg.h")] replace = { 'AXMCCMSG': '', 'WINAPI': '' } ...
#!/usr/bin/env python import os from setuptools import setup, find_packages from tree import __version__ CURRENT_PATH = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(CURRENT_PATH, 'requirements.txt')) as f: required = f.read().splitlines() setup( name='django-tree', version=__versi...
#!/usr/bin/env python2 """ Author :Julio Sanz Website :www.elarraydejota.com Email :<EMAIL> Description :Generate net interface graph from netinterface.dat file Dependencies :Python 2.x, matplotlib Usage :python netinterface.py License :GPLv3 """ import matplotlib matplotlib.use('...
from lib.actions import OrionBaseAction from lib.utils import send_user_error class UpdateNodeCustomProperties(OrionBaseAction): def run(self, node, custom_property, value): """ Update a nodes Cutom Properties. """ self.connect() orion_node = self.get_node(node) i...
from django import forms from django.forms import Form, ModelForm from django.utils import timezone from webapp.models import Task, TaskGroup, TaskGroupSet from webapp.validators import validate_package from webapp.widgets import CustomSplitDateTimeWidget class TaskGroupForm(ModelForm): class Meta: model...
import ctypes import struct #from leptonica_structures import PIX import leptonica_functions as lep # from ctypes import c_* #invalid python, so we do this: globals().update((name, getattr(ctypes, name)) for name in dir(ctypes) if name.startswith("c_")) #lep = ctypes.cdll.LoadLibrary("liblept.so") #def getPix(poin...
"""Compute a minimum spanning forest(for each connected comp) or tree(if 1 CC) using Kruskal's algorithm.""" from AlgsSedgewickWayne.QuickUnionUF import QuickUnionUF from AlgsSedgewickWayne.MST_check import _check from heapq import heappush, heappop import sys class KruskalMST(object): """Compute a minimum spanning...
""" Byron C Wallace Tufts Medical Center pubmedpy.py -- Example use: >python pubmed_fetchr.py -e <EMAIL> -s biopython (NCBI wants your email address for the web services stuff). -s is the search string, here we search for abstracts related to "biopython". """ # std libraries import sys import getopt import pdb i...
import collections import os import sys import numpy try: from PIL import Image available = True except ImportError as e: available = False _import_error = e import chainer from chainer.dataset.convert import concat_examples from chainer.dataset import download from chainer import function from chaine...
#!/usr/bin/env python import ElfinUtils import json import argparse import numpy as np from decimal import Decimal import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt def main(): ap = argparse.ArgumentParser(description='Compute the number of combinations for a given MMC protein length'); ap....
""" Sitemap for the blog app. """ from django.contrib.sitemaps import Sitemap from .models import (Article, ArticleTag, ArticleCategory) class ArticlesSitemap(Sitemap): """ Sitemap for the blog's articles. """ changefreq = 'daily' priority = 0.5 de...
#!/usr/bin/env python3 from __future__ import annotations import json import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent headers = {"UserAgent": UserAgent().random} def extract_user_profile(script) -> dict: """ May raise json.decoder.JSONDecodeError """ data = script...