content
stringlengths
5
1.05M
# Looks at the sample def and determines which feature-counter calls can be disabled __MRO__ = """ stage DISABLE_FEATURE_STAGES( in map[] sample_def, out bool disable_crispr, out bool disable_antibody, src py "stages/common/disable_feature_stages", ) """ def main(args, outs): sample_def = ...
""" x = int(input()) y = int(input()) if x > 0: if y > 0: print(1) else: print(4) else: if y > 0: print(2) else: print(3) """ x = int(input()) if x == 1: print('One') elif x == 2: print('Two') elif x == 3: print('Three') else: print('Other')
from confvar import * from webkit import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * import PyQt5.QtWebEngineWidgets from PyQt5.QtWebEngineWidgets import * from PyQt5.QtPrintSupport import * from PyQt5.QtWebEngineCore import * import json import os import re import time exten...
import imp import os # all base settings for Django from .base import * from .installed import * ALLOWED_HOSTS = ['*'] HOME_PAGE_MSG = "Hello World, This is local" print("Using local") # Database # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.s...
from datetime import datetime def get_the_datetime() -> datetime: return datetime.now()
from random import choice import nmap """This class allow us to scan all ips address and hosts from the current machine """ class Network: def __init__(self, choice): self.choice = choice def networkscanner(self): network = "127.0.1.1/24" nm = nmap.PortScanner() nm.scan...
#!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': n = int(input()) if n%2: print('Weird') elif n%2 ==0 and 2<=n<=5: print('Not Weird') elif n%2 ==0 and 6<=n<=20: print('Weird') elif n%2 ==0 and n>20: print('Not Weir...
import pandas as pd import plotly.plotly as py import plotly df2 = pd.read_csv('input.csv', header=0) df2['promo_dep15'].astype(float) color = pd.Series(['rgb(100,100,100)', 'rgb(38,17,235)', 'rgb(17,93,235)', 'rgb(17,235,220)', 'rgb(49,235,17)', 'rgb(188,235,17)', 'rgb(235,202,17)', 'rgb(235,115,17...
# Copyright 2017 Cisco Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
class Solution: def isSubsequence(self, s: str, t: str) -> bool: i=0 for j in range(0, len(t)): if i < len(s) and s[i] == t[j]: i += 1 if i == len(s): return True else: return False # Other way to do it def isSubsequence2(s...
from __future__ import division import matplotlib matplotlib.use('Agg') import numpy as np import matplotlib.pyplot as plt import pandas as pd import argparse import itertools def get_breaks(model, N): if model == "resnet20_v2": breaks = { 432: [0, 353, 432], 2304: [0, 1847, 2229, ...
#!/usr/bin/env python2.7 import pysam, argparse, sys parser = argparse.ArgumentParser(description='Helps with genome curation using linked paired-end read information from subsetted regions of a genome.', formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False) #Required arguments required = parser.add...
#!/usr/bin/env python """An example of a tagging service using RESTful Open Annotation.""" import logging import re import sys from cgi import FieldStorage from http.server import BaseHTTPRequestHandler, HTTPServer from json import dumps from logging import info, warn import requests TAGGER_URI = 'http://tagger.jen...
import logging, os, platform, posixpath, subprocess, shlex, string, sys from docutils import nodes from docutils.parsers.rst import directives, states from docutils.parsers.rst.roles import set_classes from sphinx.util.compat import Directive from sphinx.util.osutil import ensuredir from .phix import (PhixError, ...
from . import data from . import manager from . import analyzer
from math import floor import wx from PIL import Image from ZMatrix import ZMatrix from svgelements import * """ Laser Render provides GUI relevant methods of displaying the given project. """ DRAW_MODE_FILLS = 0x000001 DRAW_MODE_GUIDES = 0x000002 DRAW_MODE_GRID = 0x000004 DRAW_MODE_LASERPATH = 0x000...
"""Defines a bidirectional LSTM-CNNs-CRF as described in https://arxiv.org/abs/1603.01354.""" import tensorflow as tf import opennmt as onmt def model(): return onmt.models.SequenceTagger( inputter=onmt.inputters.MixedInputter([ onmt.inputters.WordEmbedder( vocabulary_file_key="words_v...
import pytest from pathlib import Path import shutil from spikeinterface import set_global_tmp_folder from spikeinterface.core.testing_tools import generate_recording from spikeinterface.toolkit.preprocessing import clip, blank_staturation import numpy as np if hasattr(pytest, "global_test_folder"): cache_fold...
# -*- coding: utf-8 -*- """ Base components for wrappers. """ from abc import ABC import functools import inspect from types import FunctionType from types import MethodType from types import ModuleType import typing as tp Wrappable = tp.TypeVar('Wrappable', ModuleType, type, object) class WrapperInjector(ABC): ...
#!/usr/bin/env python # -*- coding:utf-8 -*- # # Author : cold # E-mail : wh_linux@126.com # Date : 14/01/16 12:00:06 # Desc : 读取URL信息(标题)插件 # import re from plugins import BasePlugin from _linktitle import get_urls, fetchtitle class URLReaderPlugin(BasePlugin): URL_RE = re.compile(r"(htt...
from webdnn.backend.webgpu.kernels.elementwise import register_elementwise_kernel from webdnn.graph.operators.softsign import Softsign register_elementwise_kernel(Softsign, "y = x0 / (fabs(x0) + 1.0f);")
from .constraint_rewriter import rewrite_constraints, rewrite_ast from .. import SuccessorsNode, SuccessorNode, DecisionNotTakenNode, TextDecisionNode, TextFlatNode, \ InputByteSwitchTableNode, ReadEvalLoopNode, ReadEvalNode, ActionsNode, DecisionNode from ..visitor import Visitor def readable_encode_dnf(dnf, con...
import operator class Explanation: def __init__(self, observation, shifts, ranges): """ Initializes an explanation with a dictionary from features to their shifts. """ self.shifts = shifts self.ranges = ranges self.observation = observation self.EPSILON = 1e...
import json import os import re import shutil import subprocess import sys import tempfile from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, cast import setuptools import tomlkit from editables import EditableProject # type: ignore...
import os from collections import defaultdict import h5py import numpy as np class ModelDataset(object): def __init__(self, dataset_name, overwrite=False, mode='a', difficulty="challenge"): self.dataset_name = dataset_name self.dataset_path = self.append_file_type(self.dataset_name) self....
import sys import os import re from collections import defaultdict TK_RE = re.compile( r"""[\s,]*(~@|[\[\]{}()'`~^@]|"(?:[\\].|[^\\"])*"?|;.*|[^\s\[\]{}()'"`@,;]+)""" ) INT_RE = re.compile(r"-?[0-9]+$") FLOAT_RE = re.compile(r"-?[0-9][0-9.]*$") class Symbol(str): pass class State: def __init__(self): ...
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 ...
from typing import Any from example8_4birds import * woody = Bird() alert(woody) alert_duck(woody) alert_bird(woody) def double(x: Any) -> Any: return x * 2
import unittest import nzmath.ring as ring import nzmath.rational as rational import nzmath.finitefield as finitefield import nzmath.poly.termorder as termorder import nzmath.poly.univar as univar import nzmath.poly.ring as poly_ring import nzmath.poly.uniutil as uniutil class DivisionProviderTest (unittest.TestCase...
filename = 'test.txt' filehandle = open('test.txt') row = 1 filelist = list() for item in filehandle: print(item) if item.startswith('4'): item = item.strip() item = int(item) if item == row: filelist.append(item) row = row + 1 else: ...
import copy import pathlib import random import string import typing import uuid import ditef_producer_shared.genetic_individual import ditef_router.api_client class Individual(ditef_producer_shared.genetic_individual.AbstractIndividual): def individual_type(self) -> str: return 'string' @staticmet...
# Copyright 2017 Bernhard Walter # # 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 writin...
# Imports from flask_login import LoginManager # Auth from flask_sqlalchemy import SQLAlchemy # Database from flask import Flask # App from flask_socketio import SocketIO # Socket IO for quick-chat feature import eventlet # Eventlet for async eventlet.monkey_patch() # Eventlet for async # Initialize the app app...
import pytest from evolution.population import Population from fixtures import get_example_model, TicTacToeMaker, SmallTicTacToeMaker from numpy.random import seed from test_game import first_open_square_player, always_middle_square_player def test_weights_change_in_evolution(): seed(0) model = get_example_m...
import logging import json import urllib from google.appengine.api import urlfetch, urlfetch_errors class PartOfSpeechTagger(object): def __init__(self, url, field_name): self.url = url self.field_name = field_name def tag(self, source): try: response = urlfetch.fetch( ...
from sqlalchemy.exc import DBAPIError from sqlalchemy.orm.exc import FlushError from pyramid.response import Response from pyramid.view import view_config from pyramid.response import Response from pyramid.httpexceptions import HTTPFound, HTTPNotFound, HTTPBadRequest, HTTPClientError from pyramid.security import NO_PER...
class BaseError(Exception): """Base class for exceptions from this package.""" class MockServerError(BaseError): pass class HandlerNotFoundError(MockServerError): pass
#!/usr/bin/python from opencv.cv import * from opencv.highgui import * from random import randint MAX_CLUSTERS = 5 if __name__ == "__main__": color_tab = [ CV_RGB(255,0,0), CV_RGB(0,255,0), CV_RGB(100,100,255), CV_RGB(255,0,255), CV_RGB(255,255,0)] img = cvCreateImage( ...
# script to convert files into a dataset import os import argparse import glob import json inputDir = r"/Users/prakrutigogia/Documents/Microsoft/AlwaysBeLearning/MSHack/Round7" dataset = "podcast_round7" location = "orcasound_lab" all_jsons = glob.glob(inputDir + "/*.json") all_wavs = glob.glob(inputDir + "/round7/...
import unittest from gentsp import TSPSolver class TestDamages(unittest.TestCase): def test_creation(self): distances = [ [1, 3], [3, 5] ] TSPSolver(distances) def test_creation_with_parameters(self): distances = [ [1, 3], ...
import argparse import os import utils.spectronaut as post_sn from utils.ms_prediction import * from utils.spectronaut import SpectronautLibrary as SNLib if __name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, description='''''') # library parser.add_arg...
from flask import Flask, render_template, request, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) app.config["DEBUG"] = True @app.route('/', methods=['GET']) def index(): return "evolved5G echo web-server started" @app.route('/monitoring/callback', methods=['POST']) def location_reporter(): ...
import asyncio import json from concurrent.futures import ProcessPoolExecutor def sort_in_process(data): nums = json.loads(data.decode()) curr = 1 while curr < len(nums): if nums[curr] >= nums[curr - 1]: curr += 1 else: nums[curr], nums[curr - 1] = nums[curr - 1], n...
import sublime import sublime_plugin import re SETTINGS_FILE = "JSTemplatify.sublime-settings" def js_templatify(string): string_quote = '' expressions_count = 0 strings_count = 0 within_expression = False string_template = '`' for c, char in enumerate(string): if string_quote == '' ...
"""Combine bounding boxes and labels obtained from imagej plugin and then overlay the bounding boxes and labels of cells on raw stack""" import argparse import cv2 as cv import numpy as np import pandas as pd import os import imagej.plot_rois as plot_rois import imagej.combine_label_annotations as combine_label_annota...
# -*- coding: utf-8 -*- """ Created on Sun Nov 12 16:48:00 2017 @author: gianni """ from scipy import constants import numpy as np from pythonradex import LAMDA_file,atomic_transition class Molecule(): "Represents an atom or molecule" def __init__(self,levels,rad_transitions,coll_transitions,partition_func...
from core import bot def cmd_start(): @bot.message_handler(commands=['start']) def function_start(message): bot.send_message(message.chat.id, f"<b>Welcome {message.from_user.first_name}</b> ༼ つ ◕_◕ ༽つ\n" + f"I'm <i>{bot.get_me().first_name}</i>...
from typing import Optional class CommandFailed(Exception): def __init__(self, cmd, stdout: Optional[bytes], stderr: Optional[bytes]): self.cmd = cmd self.stdout = stdout self.stderr = stderr
import requests import json response = requests.get("http://api.open-notify.org/astros.json") print(response.status_code) data = response.json() print(data) print(json.dumps(data, sort_keys=True, indent=4))
from HyperLogLog import HyperLogLog def wc_naive(dataset): st = set([]) with open(dataset, "r") as f: for line in f: for w in line.strip().split(): st.add(w) return len(st) def hloglog(dataset): hobj = HyperLogLog(b = 64, p = 14, plot = True) with open(dataset, "r") as f: for line in f: for w in li...
from random import randint print('-=-' * 11) print('Bem-vindo ao jogo da adivinhação') print('-=-' * 11) print('Em que número eu pensei?!') n = int(input('Escolha um número entre 0 e 10: ')) numero_secreto = randint(0, 5) if n == numero_secreto: print('Parabéns você acertou') else: print('Que pena você errou :...
"""Show some sweeps around the last 2 comments.""" import os import sys if not os.path.abspath('../../../') in sys.path: sys.path.append('../../../') import swhlab import matplotlib.pyplot as plt import numpy as np import warnings import time import webbrowser OUTPUT_PATH=R"X:\Data Analysis\SCOTT\SWHLab developme...
import numpy as np import pandas as pd import random from model import model_fit def data_from_model(baseline_params, startle_scaling_params, sound_scaling_params, prepulse_conditions, startle_sounds_each_condition, noise=0.01): data = [] for i, condition in enumerate(prepulse_conditions)...
# proxy module from traitsui.wx.themed_slider_editor import *
# coding=utf-8 import random import os if __name__ == "__main__": DATA_PATH='argoLog_pro_finish.txt' DATA_PATH_SF='argoLog_pro_finish_sf.txt' sentences=[] for sentence in open(DATA_PATH): sentences.append(sentence) sentences=[s.encode('utf-8').split() for s in sentences] # prin...
######################################################################### # Copyright (C) 2007, 2008, 2009 # Alex Clemesha <alex@clemesha.org> & Dorian Raymer <deldotdr@gmail.com> # # This module is part of codenode, and is distributed under the terms # of the BSD License: http://www.opensource.org/licenses/bsd-li...
import os import urllib from cosalib.cmdlib import run_verbose from tenacity import ( retry, stop_after_attempt ) @retry(reraise=True, stop=stop_after_attempt(3)) def remove_azure_image(image, resource_group, auth, profile): print(f"Azure: removing image {image}") try: run_verbose([ ...
#!/usr/bin/env python import numpy as np import time if "flush" in dir(np): np.flush() begin = time.time() #a = np.sum(((np.ones(100)+1.0)*2.0)/2.0) a = np.sum(np.random.random(50000000)) #a = np.multiply.accumulate(np.ones((8,8), dtype=np.float32)) print(a) if "flush" in dir(np): np.flush() end = time.time...
#!/usr/bin/python3 import timeit from jk_tokenizingparsing import * from jk_tokenizingparsing.tokenmatching import * tokens1 = [ Token("w", "someVar", None, None, None, None, None), Token("d", "=", None, None, None, None, None), Token("w", "a", None, None, None, None, None), Token("d", "+", None, None, None,...
from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.utils.validation import check_X_y, check_array import numpy as np from scipy import sparse from varsvm import CD class weightsvm(BaseEstimator, ClassifierMixin): """ the function use coordinate descent to update the drift linear SVM C \su...
import plotly import pandas as pd import numpy as np import plotly.express as px from pytest import approx import pytest import random def test_facets(): df = px.data.tips() fig = px.scatter(df, x="total_bill", y="tip") assert "xaxis2" not in fig.layout assert "yaxis2" not in fig.layout assert fig...
''' Plots a histogram showing the durations of the sound sampled. This script was written to verify that the vast majority of sound samples was exactly 4s of length (>95%). @date 2017-05-19 ''' import wave import contextlib import sys import os from os import listdir from os.path import isfile, isdir, join import mat...
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe def execute(): fields = {"Cost Center": "project", "Project": "cost_center"} for budget_against, field in fields.items(): frappe.db.s...
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2017, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
import numpy as np import time import torch from torch import nn, optim, distributions import torch.backends.cudnn as cudnn cudnn.benchmark = False from batchgenerators.dataloading import MultiThreadedAugmenter from trixi.util import Config, ResultLogDict from trixi.experiment import PytorchExperiment from model impo...
from setuptools import find_packages from setuptools import setup setup( name='ros2srv', version='0.6.3', packages=find_packages(exclude=['test']), install_requires=['ros2cli'], zip_safe=True, author='Dirk Thomas', author_email='dthomas@osrfoundation.org', maintainer='Dirk Thomas', ...
# Init Solution import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns from IPython.display import display, Markdown # Init Solution completed from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier, plot_tree from s...
from itertools import product import random import sys sys.path.append( '/home/rpl/Documents/rasmus/crazyswarm/ros_ws/src/crazyswarm/scripts/perceived-safety-study/utils' ) from Participant import Participant from globalVariables import DRONE_START_X, DRONE_START_Y, GOAL_OFFSET_X, GOAL_OFFSET_Y, HEIGHT_OFFSET, PA...
""" 29. 两数相除 https://leetcode-cn.com/problems/divide-two-integers/ 1. 如果被除数是0 则直接返回0 2. 先对结果的 符号 进行判定, 然后将被除数和除数 全部取正数 3. 由于不能用除法和乘法, 所以准备一个哈希 来存 除数的倍数, 例如 10/3, 哈希存储 {6:2, 3:1} 4. 对哈希的 倍数除数进行排序, 期望先取到最大的 5. 使用DFS 更新结果, 在循环时只要存在除数有效时 直接跳出循环 6. 对临界条件进行判定 """ def divide(dividend, divisor): if dividend == 0: ...
import os import sys import numpy as np import torch import torch.nn as nn import torch.optim as optim import torchvision.utils from torchvision import models import torchvision.datasets as dsets import torchvision.transforms as transforms from torchattacks import PGD, FGSM, MultiAttack import os os.environ["KMP_DU...
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% from collections import defaultdict import sys import logging import re import time from numpy.core.fromnumeric import alltrue import pandas as pd import numpy as np from torch.nn.modules import transformer from tqdm import tqdm ...
from pyrogram import Client, filters import os, shutil from creds import my from telegraph import upload_file import logging logging.basicConfig(level=logging.INFO) TGraph = Client( "Image upload bot", bot_token = my.BOT_TOKEN, api_id = my.API_ID, api_hash = my.API_HASH ) @TGraph.o...
import os import torch from torch import nn, optim from l5kit.configs import load_config_data from l5kit.data import LocalDataManager, ChunkedDataset from l5kit.data import get_dataset_path from l5kit.dataset import EgoDatasetVectorized from l5kit.planning.vectorized.closed_loop_model import VectorizedUnrollModel fro...
# -*- coding: utf-8 -*- """ :author: Grey Li (李辉) :url: http://greyli.com :copyright: © 2018 Grey Li <withlihui@gmail.com> :license: MIT, see LICENSE for more details. """ import logging import os from logging.handlers import SMTPHandler, RotatingFileHandler import click from flask import Flask, render...
import os from copy import deepcopy from core import string_to_component from _constants import * from plotting_settings import * from plotting_settings import plotting_parameters_GUI import matplotlib.pyplot as plt from matplotlib.patches import Rectangle png_directory = os.path.join(os.path.dirname(__file__), ".graph...
from brazilnum.cnpj import format_cnpj from brazilnum.cpf import format_cpf from django.contrib.postgres.search import SearchQuery, SearchRank from django.db.models import F from django.utils.safestring import mark_safe from jarbas.chamber_of_deputies.models import Reimbursement from jarbas.dashboard.admin import list...
#!/usr/bin/env python from sqlalchemy import create_engine from sqlalchemy import MetaData, Column, Table, PrimaryKeyConstraint from sqlalchemy import String, DateTime, Float from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base import datetime Base = declarative_base() metada...
from mgetool.tool import tt from mgetool.tool import tt from sklearn.datasets import load_boston from fastgplearn.skflow import SymbolicRegressor as FSR from gplearn.genetic import SymbolicRegressor as SR from bgp.skflow import SymbolLearning x, y = load_boston(return_X_y=True) sr1 = FSR(population_size=10000, gener...
import streamlit as st import tensorflow as tf from tensorflow import keras from tensorflow.keras.models import load_model import streamlit as st st.set_page_config( page_title='Find your X-men', page_icon='icon.png' ) st.image('icon.png') st.subheader("Upload an image and find which X-men character it contai...
from foo.bar import Grill class FooBarExample: def make_grill(self, grill): """ :rtype: Grill """ return Grill()
################################################################################################ # # # G code interpreter and executer for 2D CNC laser engraver using Raspberry Pi # # Xiang Zhai, Oct 1, 2013 ...
class Stoplight: def __init__(self, color): self.color = color sl = Stoplight("Green") print sl.color
from fastapi import FastAPI, HTTPException from fastapi.params import Depends from crawler_api.crawlers import COURTS from crawler_api.models.requests import LegalProcess from crawler_api.models.response import LegalProcessDetailResponse, Message from crawler_api.session import HttpAsyncSession app = FastAPI( tit...
# # Copyright (C) [2020] Futurewei Technologies, Inc. # # FORCE-RISCV is 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 # # THIS SOFTWARE IS PR...
import hfo class Goalie: def __init__(self): pass
# # Copyright 2014 ARM Limited and Contributors. # 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 ...
from pandas import DataFrame from shutil import rmtree from math import isclose from glob import glob import chemw import re, os def test_inits(): # import the class modules chem_mw = chemw.ChemMW() phreeq_db = chemw.PHREEQdb() print(os.getcwd()) for TF in [chem_mw.verbose, chem_mw.final, chem_mw....
""" Set the min/max for each panel based on input data """ from typing import Dict from ....tk.arrayTK import minmax from ..readFileOrList import readFileOrList import numpy def set_panel_minmax(params): # type: (Dict) -> Dict """See the min/max for each panel Args: params (dict): plotting parame...
import time import cv2 import numpy as np def run(): filename = '../../dataset/Hands/Hand_0000083.jpg' img = cv2.imread(filename) # small = cv2.resize(img, (0, 0), fx=0.9, fy=0.9) small = img gray = cv2.cvtColor(small, cv2.COLOR_BGR2GRAY) # subpixel - further refinement gray = np.float32...
#!/dark/usr/anaconda/bin/python #/usr/bin/env python i...
import pytest import numpy as np import pandas as pd from pandas.testing import assert_frame_equal from ..cifi import analyzeObservations from .create_test_data import createTestDataSet MIN_OBS = range(5, 10) def test_analyzeObservations_noClasses(): ### Test analyzeObservations when no truth classes are given ...
from collections import Counter def friends_of_friend_ids_bad(user): #"foaf" acrônimo friend of a friend return [foaf["id"] for friend in user["friends"] #para cada amigo de usuário for foaf in friend["friends"]] #para acada _their_friends def not_the_same(user, other_user): # doi...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone import datetime import django_extensions.db.fields class Migration(migrations.Migration): dependencies = [ ('coffee', '0002_auto_20140903_2207'), ] operations = ...
import datetime from pymongo import MongoClient from bson import ObjectId from werkzeug.security import generate_password_hash, check_password_hash from flask_restful import abort client = MongoClient(host="localhost", port=27017) db = client.blog User = db.user Post = db.post Comment = db.comment def create_user(...
import unittest import math from batchlib.util.elisa_results_parser import ElisaResultsParser class TestElisaResultsParser(unittest.TestCase): def test_elisa_results_parsing(self): elisa_results_parser = ElisaResultsParser() results = elisa_results_parser.get_elisa_values('C14d', test_names=['EL...
# -*- coding: utf-8 -*- # Copyright (c) 2014, 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. try: from IPython.html.widgets import DOMWidget from IPython.utils.traitlets import Unicode, Int, Bool except Exception as exp: # Init dummy objects needed t...
AUTOCFG_TEMPLATE = r""" PROJECT_NAME = "{project_name}" OUTPUT_DIRECTORY = {output_dir} GENERATE_LATEX = NO GENERATE_MAN = NO GENERATE_RTF = NO CASE_SENSE_NAMES = NO INPUT = {input} ENABLE_PREPROCESSING = YES QUIET = YES JAVADOC_AUTOBRIEF = YES JAVADOC_AUTOBRIEF = NO GENERATE_HTML =...
from object_detection.utils import visualization_utils as vis_util from object_detection.utils import ops as utils_ops from object_detection.utils import label_map_util from distutils.version import StrictVersion import tensorflow as tf from PIL import Image import numpy as np import cv2 # Check the version of the Ten...
""" Test various functions regarding chapter 8: MDI, MDA, SFI importance. """ import os import unittest import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score, accuracy_score from mlfinlab.u...
"""Add subtitles to a DASH OnDemand MPD.""" import os import re import sys from collections import namedtuple from argparse import ArgumentParser from backup_handler import make_backup, BackupError Format = namedtuple('Format', 'name mime_type extension') FORMATS = { 'ttml': Format('ttml', 'application/ttml+x...