content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class PriceItem(scrapy.Item): # define the fields for your item here like: webId = scrapy.Field() name = scrapy.Field() brand = scrapy.Fi...
# -*- coding: utf-8 -*- """ Classes to handle reV h5 output files. """ import json import logging import numpy as np import pandas as pd import time from reV.version import __version__ from reV.utilities.exceptions import (HandlerRuntimeError, HandlerValueError) from rex.resource import BaseResource from rex.utilitie...
import urllib import zipfile if __name__ == '__main__': try: urllib.urlretrieve("http://goo.gl/PnJHp", './fernflower.zip') zf = zipfile.ZipFile('fernflower.zip') zf.extract('fernflower.jar', '../runtime/bin') except: print "Downloading Fernflower failed download manually from ht...
#! /data/salomonis2/LabFiles/Frank-Li/citeseq/scanpy_new_env/bin/python3.6 import pandas as pd import numpy as np import os,sys import scanpy as sc import matplotlib.pyplot as plt from sctriangulate import * from sctriangulate.preprocessing import * from sctriangulate.colors import bg_greyed_cmap ''' All the input, ...
from datetime import datetime from datetime import timedelta from pyosmo.model import TestStep class TestStepLog: def __init__(self, step: TestStep, duration: timedelta, error: Exception = None): self._step = step self._timestamp = datetime.now() self._duration = duration self._er...
class Allen: """ Utility class for Allen's interval algebra, https://en.wikipedia.org/wiki/Allen%27s_interval_algebra. """ # ------------------------------------------------------------------------------------------------------------------ X_BEFORE_Y = 1 X_MEETS_Y = 2 X_OVERLAPS_WITH_Y = 3 ...
import ciphers import jw_utils import sys try: colorInternal = sys.stdout.shell.write except AttributeError: raise RuntimeError("Use IDLE") colorDef = { "red": "stderr", "black": "stdin", "purple": "BUILTIN", "green": "STRING", "dark_red": "console", "blue": "stdout", "orange": "KEYWORD", "white_on_blac...
#!/usr/bin/env python3 import sys argv = sys.argv[1:] sys.argv = sys.argv[:1] import json import regex import datetime import dateutil.parser import pytz import common.http import common.postgres from common.config import config import sqlalchemy from sqlalchemy.dialects import postgresql import urllib.error engine, ...
""" Search and get metadata for articles in Pubmed. """ import xml.etree.ElementTree as ET import requests import logging from functools import lru_cache from time import sleep from indra.util import UnicodeXMLTreeBuilder as UTB logger = logging.getLogger(__name__) pubmed_search = 'https://eutils.ncbi.nlm.nih.gov/ent...
import os import tensorflow as tf import matplotlib.pyplot as plt import random import pandas as pd import numpy as np import keras.initializers import keras.optimizers from networkx import Graph, find_cliques from sklearn.metrics import roc_curve, auc from keras.layers import Concatenate, Input, Embedding, Lambda, Ac...
import pygame GREEN = (25, 111, 61) BLUE = (31, 97, 141) WHITE = (255, 255, 255) BLACK = (0, 0, 0) TURQUOISE = (64, 224, 208) class Cell: def __init__(self, row, col, width, total_rows): self.row = row self.col = col self.x = row * width self.y = col * width self.color = WHITE self.successors = [] self...
from flask_admin.contrib.sqla import ModelView class FeatureRequestModelView(ModelView): form_choices = { "client": [ ("Client A", "Client A"), ("Client B", "Client B"), ("Client C", "Client C"), ("Client D", "Client D"), ("Client E", "Client E")...
import unittest from decimal import Decimal from wexapi.models import OrderInfo class TestOrderInfo(unittest.TestCase): def test_create_valid(self): data = { "order_id": "343152", "pair": "btc_usd", "type": "sell", "start_amount": 13.345, "amount...
import tensorflow as tf import tensorflow_probability as tfp import numpy as np import matplotlib.pyplot as plt from data_preprocessing import preprocess_mr, get_slots from postprocessing import postprocess_utterance import sys from data_manager import load_data_tensors, load_text_data from models import Encoder, Bahda...
#! /usr/bin/env python3 import argparse from PyPDF2 import PdfFileReader, PdfFileWriter def main(pdf_file, new_chapters_file, output_file): with open(new_chapters_file) as f: new_chapters = [line.strip() for line in f.readlines()] reader = PdfFileReader(pdf_file) writer = PdfFileWriter() ol...
# -*- coding: utf-8 *-* import sys import os import errno import time import pprint # global configuration import vprimer.glv as glv import vprimer.utils as utl from vprimer.logging_config import LogConf log = LogConf.open_log(__name__) import vcfpy from vprimer.allele_select import AlleleSelect class Variant(obj...
from codecs import open from setuptools import find_packages, setup with open("README.md", "r", encoding="UTF-8") as f: README = f.read() EXTRAS = { "lint": ["black", "flake8", "isort"], } EXTRAS["dev"] = EXTRAS["lint"] setup( name="testcase-maker", version="0.2.0.post1", author="benwoo1110",...
from typer import Typer from tcli.commands.configure.credentials.credentials import CredentialsApp from tcli.typer_app import TyperApp class ConfigureApp(TyperApp): def on_create_app(self, app: Typer, *args, **kwargs) -> Typer: app.add_typer( CredentialsApp(self.config).create_app( ...
"""Test the file examples/ex_utils_static.py.""" import tempfile from pathlib import Path from .examples import ex_utils_static def test_smoke_test_write_plotly_html(): """Smoke test WritePlotlyHTML.""" try: with tempfile.TemporaryDirectory() as dir_name: # act filename = Path(dir_name)...
import sublime, sublime_plugin, os class ExpandTabsOnSave(sublime_plugin.EventListener): def on_pre_save(self, view): if view.settings().get('expand_tabs_on_save') == 1: view.window().run_command('expand_tabs')
from airview_api.models.models import *
def count_letters(msg): """ Zwraca pare (znak, liczba zliczeń) dla najczęściej występującego znaku w wiadomości. W przypadku równości zliczeń wartości sortowane są alfabetycznie. :param msg: Message to count chars in. :type msg: str :return: Most frequent pair char - count in message. :rtyp...
import numpy as np import healpy as hp import os from powspechi.pserrors import IsomapError # Read event file def readevtfile(infile, skip_header=True): r"""Read an event file with at least two columns, where the first should correspond to the particles' azimuthal (:math:`\phi`) coordinates and the second to t...
from .context import feature_infection import pytest import uuid from operator import attrgetter @pytest.fixture(scope="module") def test_feature(request): return feature_infection.CDC.get_infector("test") def infected(feature, entities): return map(feature.is_infected, entities) class Entity(object): ""...
import pkg_resources from subprocess import call '''pip_update_all Based on user515656's answer at https://stackoverflow.com/questions/2720014/how-to-upgrade-all-python-packages-with-pip ''' packages = [dist.project_name for dist in list(pkg_resources.working_set)] call("pip install --upgrade " + ' '.join(packages), sh...
import numpy as np import matplotlib.pyplot as plt import seaborn as sns import sys from vector_calculus import vector_calculus as vc def calc_and_plot_dists(field1, field2, field1_title=None, field2_title=None, units=None): r""" """ ...
from django.db import models # Create your models here. class Materia(models.Model): nombre = models.CharField(max_length=15) periodo = models.CharField(max_length=10) año = models.IntegerField(default=2020) id_clase = models.ForeignKey('clases.Clase', on_delete=models.CASCADE) def __str__(self)...
# flake8: noqa from enum import IntEnum, unique from deprecated import deprecated @deprecated( version="1.0.0", reason="This enum doesn't get maintained as it never made it to the first release", ) @unique class ItemTypeGC(IntEnum): """ An Enum referencing the different item types in C...
from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import * class CreateUserForm(ModelForm): class Meta: model = User fields = '__all__' class OrderGame(ModelForm): class Meta: model =...
import math n = float(input('Digite um valor: ')) print('O valor digitado foi {} e sua parte inteira seria {}'.format(n, math.trunc(n))) ''' from math import trunc n = float(input('Digite um valor: ' )) print('O valor digitado foi {} e sua parte inteira seria {}'.format(n, trunc(n))) '''
from oarepo_oai_pmh_harvester.decorators import rule from oarepo_oai_pmh_harvester.transformer import OAITransformer from nr_oai_pmh_harvester.rules.nusl.field24500 import get_title_dict @rule("nusl", "marcxml", "/24630", phase="pre") def call_title_alternate_2(el, **kwargs): return title_alternate_2(el, **kwarg...
keys = { "product_url": "http://airlabs.xyz/", "name": "Caspar Chlebowski", "email": "chleb@gmail.com", "message": "this is a test" }
""" Test `dodecaphony.fragment` module. Author: Nikolay Lysenko """ from collections import Counter from typing import Any import pytest from dodecaphony.fragment import ( Event, Fragment, FragmentParams, SUPPORTED_DURATIONS, calculate_durations_of_measures, calculate_number_of_undefined_ev...
import glob import os import cv2 import numpy as np import pickle WIDTH = 224 HEIGHT = 224 test_data_set = ['00'] train_data_set = ['01','02','03','04'] inp_dir = '../Prepare_dataset_resnet/output/' out_pickle_file = 'medico_v2_ensophagitis_normal_z_line_dataset.pickle' imgs_train = [] imgs_test = [] X_test = [] y_te...
# Copyright (c) 2015. Mount Sinai School of Medicine # # 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 o...
import warnings from ..water_viscosity_korson_1969 import water_viscosity def test_water_viscosity(): warnings.filterwarnings("error") # Table II (p. 38): assert abs(water_viscosity(273.15 + 0) - 1.7916) < 5e-4 assert abs(water_viscosity(273.15 + 5) - 1.5192) < 5e-4 assert abs(water_viscosity(273.15 ...
from typing import List, Dict, Any, Optional from mage.graph_coloring_module.components.individual import Individual from mage.graph_coloring_module.graph import Graph from mage.graph_coloring_module.components.correlation_population import ( CorrelationPopulation, ) from mage.graph_coloring_module.utils.generate_i...
import asyncio import discord from redbot.core import checks, commands from redbot.core.utils.chat_formatting import box from redbot.core.utils.predicates import MessagePredicate from .core import Core class Captcher(Core): @commands.group(name="setcaptcher", alias=["captcherset"]) @commands.guild_only() ...
# --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.11.2 # kernelspec: # display_name: pytg # language: python # name: pytg # --- # %% [markdown] # # Solve t...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 1 21:45:11 2018 @author: abhigyan """ import numpy as np #Default Parameters """Initialization --> Gaussian Random Learning Rate --> 0.1 Optimiser --> Gradient Descent""" "Layer class: Used by the Neural_Network class to create new ...
import os, random def list_dir_files(t_dir): f_list = [] if t_dir[-1] != '/': t_dir+='/' for dir in os.listdir(t_dir): f_list += [t_dir+dir+'/'+i for i in os.listdir(t_dir+dir)] return f_list def list_1perdir_files(t_dir): f_list = [] if t_dir[-1] != '/': t_dir += '/' ...
# coding: utf-8 # In[ ]: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome() driver.get("https://www.google.co.in/imghp?hl=en&tab=wi") elem = driver.find_element_by_name("q") elem.clear() x=input("enter the name of the wallpaper you want to download : ") x=x+"...
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # --------------------------------------------------------------------...
# -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies and Contributors # See license.txt from __future__ import unicode_literals import unittest import frappe class TestModuleProfile(unittest.TestCase): def test_make_new_module_profile(self): if not frappe.db.get_value("Module Profile", "_Test Module...
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # 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 th...
# Generated by Django 2.2.8 on 2020-03-24 06:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blogs', '0004_auto_20200324_1416'), ] operations = [ migrations.AlterField( model_name='article', name='abstract', ...
import numpy as np A = np.array([[1,2,3], [1,0,3], [1,2,3]]) B = np.array([[0,2,3], [0,2,3], [0,2,3]]) A = np.where(A<2, 6, A) B = np.where(A<2, 7, B) print(B)
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * ''' IMPORTS ''' import xml import tempfile import contextlib import OpenSSL.crypto from xml.sax.saxutils import escape import re ''' GLOBALS/PARAMS ''' FETCH_MAX_INCIDENTS = 500 SECURITY_INCIDENT_NODE_XPATH = ".//Sec...
class WydawnictwoNadrzednePBNAdapter: def __init__(self, original): self.original = original def pbn_get_json(self): if self.original.pbn_uid_id is not None: return {"objectId": self.original.pbn_uid_id} ret = {} for attr in "isbn", "issn", "title", "year": ...
try: from .poly_nms import poly_gpu_nms except ImportError: poly_gpu_nms = None def poly_nms(dets, thresh, force_cpu=False): """Dispatch to either CPU or GPU NMS implementations.""" if poly_gpu_nms is not None and not force_cpu: if dets.shape[0] == 0: return [] return poly_...
from dataclasses import dataclass import torch import torch.nn as nn import torch.nn.functional as F import math from pytorch3d.pathtracer.warps import ( square_to_cos_hemisphere, square_to_cos_hemisphere_pdf, NeuralWarp, MipMap, ) from pytorch3d.pathtracer.utils import ( pos_weak_sigmoid, cartesian_to_log_polar,...
from typing import Optional, Tuple from uuid import UUID from flask import request, current_app from functools import wraps from dateutil import parser from datetime import datetime from sqlalchemy import and_, or_ After = Tuple[Optional[datetime], Optional[str]] def paginated(f): @wraps(f) def paginated_w...
import asyncio from typing import Optional from sqlalchemy import BigInteger, cast, select from sqlalchemy.ext.asyncio import AsyncSession from Backend.core.errors import CustomException from Backend.crud.base import CRUDBase from Backend.crud.misc.persistentMessages import persistent_messages from Backend.database.m...
import sqlalchemy_utils from babel import Locale from wtforms import Form from tests import MultiDict from wtforms_alchemy import CountryField sqlalchemy_utils.i18n.get_locale = lambda: Locale('en') class TestCountryField(object): field_class = CountryField def init_form(self, **kwargs): class Test...
import magic from django import template from django.core import serializers from django.template.defaultfilters import safe from ..models.validators.file import VALID_FILE_TYPES register = template.Library() @register.filter def json_dump(values): # Return values as JSON data data = list(values) data = ...
from fits_align.ident import make_transforms from fits_align.align import affineremap from fits2image.conversions import fits_to_jpg import click from glob import glob import os from astropy.io import fits import numpy as np from astroscrappy import detect_cosmics import logging logger = logging.getLogger(__name__) l...
from setuptools import setup, find_packages packages = find_packages(include=('Arcapi', 'Arcapi.*')) setup( name='Arc_api', version='1.0', author='littlebutt', author_email='luogan199686@gmail.com', license='MIT License', url="https://github.com/littlebutt/Arcapi", description='An API for...
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-21 22:37 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Keywor...
# Copyright: 2005-2011 Brian Harring <ferringb@gmail.com> # License: GPL2/BSD """ base package class; instances should derive from this. Right now, doesn't provide much, need to change that down the line """ __all__ = ("base", "wrapper", "dynamic_getattr_dict") from snakeoil import klass from snakeoil.compatibility...
from __future__ import division, print_function import sys import numpy as np import pickle import tensorflow as tf from tqdm import tqdm from dnn_reco import detector class DataTransformer: """Transforms data Attributes ---------- trafo_model : dictionary A dictionary containing the transf...
import pandas import unittest from unittest.mock import Mock, patch from mstrio.report import Report class TestReport(unittest.TestCase): def setUp(self): self.report_id = '1DC7D33611E9AE27F6B00080EFE52FBC' self.report_name = 'UnitTest' self.connection = "test_connection" self.__...
# -*- coding: utf-8 -*- """ Created on Thu Apr 26 12:57:11 2018 @author: sosene """ #Przepisac na wersje kolumnowo-macierzowa... import random import numpy as np import seaborn as sb import pandas as pd #from sklearn import datasets import matplotlib.pyplot as plt random.seed(7) entityNumber = 100 worldSize = {'x': 1...
import pandas as pd import functools from trumania.core.util_functions import merge_2_dicts, merge_dicts, is_sequence, make_random_assign, cap_to_total from trumania.core.util_functions import build_ids, latest_date_before, bipartite, make_random_bipartite_data def test_merge_two_empty_dict_should_return_empty_dict(...
""" 币安推荐码: 返佣10% https://www.binancezh.pro/cn/register?ref=AIR1GC70 币安合约推荐码: 返佣10% https://www.binancezh.com/cn/futures/ref/51bitquant if you don't have a binance account, you can use the invitation link to register one: https://www.binancezh.com/cn/futures/ref/51bitquant or use the inv...
""" Pandora API Transport This module contains the very low level transport agent for the Pandora API. The transport is concerned with the details of a raw HTTP call to the Pandora API along with the request and response encryption by way of an Encyrpytor object. The result from a transport is a JSON object for the AP...
import mxnet as mx import numpy as np from mx_constant import MyConstant eps = 1e-5 def input_transform_net(data, batch_size, num_points, workspace, bn_mom=0.9, scope="itn_"): data = mx.sym.expand_dims(data, axis=1) # (32,1,1024,3) conv0 = mx.sym.Convolution(data=data, num_filter=64, kernel=(1, 3), stride=(...
from tkinter import * total = 0 pre_total = [] saletotal = 0 #=========================Events def add_ev(event): x = float(current_Price_str.get()) global total global pre_total total += x total_int.set(round(total)) current_Price_str.set("") note_str.set(str(round(x))+" Sucessfully added!") def calculate_ev(...
""" Created on 21 Jun 2019 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) """ import time from collections import OrderedDict from multiprocessing import Manager from scs_core.data.json import JSONable from scs_core.sync.interval_timer import IntervalTimer from scs_core.sync.synchronised_process import...
import FWCore.ParameterSet.Config as cms from Configuration.StandardSequences.RawToDigi_cff import * # RPC Merged Digis from Configuration.Eras.Modifier_run3_RPC_cff import run3_RPC run3_RPC.toModify(muonRPCDigis, inputTagTwinMuxDigis = 'rpcTwinMuxRawToDigi', inputTagOMTFDigis = 'omtfStage2Digis', inputT...
import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(__file__), 'docs.db'), } } SECRET_KEY = 'HASJFDYWQ98r6y2hesakjfhakjfy87eyr1hakjwfa' CACHE_BACKEND = 'locmem://' LOCAL_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__)...
from ..player import BasePlayer class DataKeeper(BasePlayer): ''' Player who keeps his most repeated pieces. ''' def __init__(self, name): super().__init__(f"DataKeeper::{name}") def filter(self, valids=None): valids = super().filter(valids) datas = {} for p1, p2 i...
from typing import List, Set from crosshair.statespace import MessageType from crosshair.test_util import check_states from crosshair.core_and_libs import standalone_statespace, NoTracing, proxy_for_type def test_dict_index(): a = {"two": 2, "four": 4, "six": 6} def numstr(x: str) -> int: """ ...
#!/usr/bin/python # This software was developed in whole or in part by employees of the # Federal Government in the course of their official duties, and with # other Federal assistance. Pursuant to title 17 Section 105 of the # United States Code portions of this software authored by Federal # employees are not subjec...
import RPi.GPIO as GPIO import time import requests from datetime import datetime GPIO.setmode(GPIO.BCM) TRIG = 23 ECHO = 24 ALERT = 17 start = datetime.now() print "calibration in progress" GPIO.setup(TRIG,GPIO.OUT) GPIO.setup(ALERT,GPIO.OUT) GPIO.setup(ECHO,GPIO.IN) content = "" api_token = 'your_api_token' ...
# @Title: 平衡二叉树 (Balanced Binary Tree) # @Author: 18015528893 # @Date: 2021-02-08 11:33:55 # @Runtime: 68 ms # @Memory: 19.6 MB # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = righ...
import unittest from importlib import import_module component = import_module('run.helpers.parse') class parse_Test(unittest.TestCase): # Actions def setUp(self): self.parse = component.parse # Tests def test(self): self.assertEqual(self.parse('1'), ((1,), {})) self.assertE...
# -*- coding: utf-8 -*- """ Intro ===== Sandhi splitter for Samskrit. Builds up a database of sandhi rules and utilizes them for both performing sandhi and splitting words. Will generate splits that may not all be valid words. That is left to the calling module to validate. See for example SanskritLexicalAnalyzer Exa...
# -*- encoding: utf-8 -*- #! /usr/bin/env python ''' 文件说明: 这是个Net局域网版本的极简交互式笔记程序 作者信息: penguinjing 版本自述: 0.0.2 程序参考: https://pymotw.com/2/socket/udp.html ''' # 全局引用 import socket import sys from os.path import exists # 全局变量 # PATH = "/path/2/work dir" # 函式撰写区 def print_usage(): print 'no or wrong specify mode, p...
import tensorflow as tf import numpy as np # Data generator for domain adversarial neural network class DataGeneratorDANN(tf.keras.utils.Sequence): 'Generates data for Keras' def __init__(self, source_images, source_labels, target_images, source_train = True, batch_size = 32, shuffle = True): self.so...
import numpy as np import torch as th import cv2 import argparse import tempfile from torch.utils.data import DataLoader import os import pyexr import cv2 import skimage.io as skio from ttools.modules.image_operators import crop_like import matplotlib.pyplot as plt from collections import defaultdict from sbmc import ...
from django.contrib import admin from models import * admin.site.register(Pantalla) admin.site.register(Carrusel) admin.site.register(Imagen)
""" Utility module with helper functions """ def clean_escaped_strings(dirty): return dirty.replace('\n', '').replace('\t', '') def rate_sort(rate_dict): return float(rate_dict['rate']) def calc_diff(rates): for i in range(len(rates)): if i == 0: rates[i]['diff'] = '-' els...
########################################################################## # # Copyright (c) 2018, Image Engine Design 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: # # * Redistrib...
import unittest from os import path import sys sys.path.append(path.join(path.dirname(path.dirname(path.abspath(__file__))), 'airodb_analyzer')) from models.accessPoint import AccessPoint from models.macAddress import MACAddress class TestAccessPointMethods(unittest.TestCase): def test_constructor_TestWithNoneMacA...
from Message.Parameters.Parameter import Parameter, ParameterType class Voltage(Parameter): def __init__(self, volts=0.0): super(Voltage, self).__init__(value=volts, length=2, type=ParameterType.IEEEFloat, resolution=0.01)
def fib1(n): if n == 0 or n == 1: return 1 return fib1(n - 1) + fib(n - 2) # python yield style # fib stream # this algo complexity is O(phi^n) exponential level # same as def fib(): yield 0 yield 1 f1 = fib() f2 = fib() f1.next() while 1: yield f1.next() + f2.next() ...
import logging import coloredlogs import sentry_sdk from aidbox_python_sdk.main import create_app as _create_app from sentry_sdk.integrations.aiohttp import AioHttpIntegration from sentry_sdk.integrations.logging import LoggingIntegration # Don't remove these imports import app.operations from app.sdk import sdk, sdk...
# -*- coding: utf-8 -*- """ Utilities for user interfaces Created on Tue Aug 3 21:14:25 2020 @author: Gerd Duscher, Suhas Somnath, Chris Smith """ from __future__ import division, print_function, absolute_import, unicode_literals import os import sys import warnings import ipyfilechooser if sys.version_info.major ...
''' Author: ZHAO Zinan Created: 12/21/2018 289. Game of Life ''' class Solution: def gameOfLife(self, data): """ :type data: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ if len(data) == 0 or len(data[0]) == 0: ...
# -*- coding: utf-8 -*- from unittest import TestCase import json import logging import os import shutil import subprocess import tempfile logger = logging.getLogger(__name__) class TorchtextTestCase(TestCase): def setUp(self): logging.basicConfig(format=('%(asctime)s - %(levelname)s - ' ...
import os.path from .parser import load_data import biothings.hub.dataload.uploader as uploader class UMLSUploader(uploader.BaseSourceUploader): name = "umls" def load_data(self, data_folder): umls_docs = load_data(data_folder) return umls_docs @classmethod def get_mapping(klass): ...
# mysql.connector from https://dev.mysql.com/downloads/connector/python/ import mysql.connector # creds to the TA led database lecture https://scs.hosted.panopto.com/Panopto/Pages/Viewer.aspx?id=1e68b000-e15c-4e52-af04-ac6800f82ae8 # for its guidance on using mysql through python # prior to running my game one...
from django.db import models # Create your models here. class Product(models.Model): prod_no = models.IntegerField() prod_name = models.CharField(max_length=50) prod_price=models.FloatField() prod_qty=models.IntegerField()
import string, Utils # list of directory options to offer in configure dir_options = { 'with-cachedir' : [ '${PREFIX}/var/locks', 'where to put temporary cache files' ], 'with-codepagedir' : [ '${PREFIX}/lib/samba', 'where to put codepages' ], 'with-configdir' ...
import tempfile import subprocess import os import glob from subprocess import Popen, PIPE from multiprocessing import cpu_count import numpy as np import montemodes.classes.results as res def create_tinker_input(molecule): temp_file_name = tempfile.gettempdir() + '/tinker_temp'+ '_' + str(os.getpid()) ti...
from flask import ( request, jsonify, render_template ) from api.extensions import db import datetime from flask_restful import Resource from flask_jwt_extended import create_access_token, decode_token from mods.users.models.user_model import UserModel, user_schema from utils.errors import errors, error_h...
# Copyright (c) 2017 Alex Pliutau from slackclient import SlackClient import logging import time import sys class SlackBot(object): def __init__(self, token, rasa_nlu): logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') self.sc = SlackClient(token) self.rasa_nlu = rasa_nlu def connect...
#!/usr/bin/env python2.7 # # a wrapper for olevba since it is python2 import argparse import codecs import json import os import os.path import sys import traceback parser = argparse.ArgumentParser(description="Analyzes a given file with olevba parser and saves the output in a useful way.") parser.add_argument('file...
from typing import List class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ i, j, k = 0, 0, len(nums) - 1 while j <= k: if nums[j] == 2: nums[j], nums[k] = nums[k], nums[j]...
import unittest from unittest.mock import MagicMock, patch import dbt.flags import dbt.compilation from dbt.adapters.postgres import Plugin from dbt.contracts.files import FileHash from dbt.contracts.graph.manifest import Manifest from dbt.contracts.graph.parsed import NodeConfig, DependsOn, ParsedModelNode from dbt.c...