content
stringlengths
5
1.05M
import copy arr = [[1, 2, 3], [3, 4, 5], [5, 3, 2], [3, 13, 300]] ans = [] arrNew = copy.copy(arr) arrNew.pop(0) for i in range(len(arr[0])): temp = arr[0][i] checker = [] for elem in arrNew: if temp in elem: checker.append(True) else: checker.append(False) if no...
#!/usr/bin/env python2 # Copyright (c) 2012-2016, Intel Corporation # Author: Andi Kleen # # This program is free software; you can redistribute it and/or modify it # under the terms and conditions of the GNU General Public License, # version 2, as published by the Free Software Foundation. # # This program is distribu...
""" security.py: defines security services (vpnclient, vpnserver, ipsec and firewall) """ import logging from typing import Tuple from core import constants from core.nodes.base import CoreNode from core.nodes.interface import CoreInterface from core.services.coreservices import CoreService class VPNClient(CoreServ...
#!/usr/bin/env python # -*- mode: python; encoding: utf-8 -*- """Contains tests for api_call_handler_utils.""" import hashlib import os import tarfile import zipfile import yaml from grr.gui import api_call_handler_utils from grr.lib import aff4 from grr.lib import flags from grr.lib import test_lib from grr.lib...
#!/usr/bin/python # -*- coding: UTF-8 -*- # flake8: noqa import os import re import sys import logging import requests books_dir = "/data1/download/mebook/" done_path = "/data1/download/mebook-done.txt" book_path = "/data1/download/mebook-books.txt" site = 'http://mebook.cc' referer = 'http://mebook.cc/22360.html' N...
import streamlit as st import pandas as pd import numpy as np from PIL import Image import plotly.express as px from plotly.subplots import make_subplots import plotly.graph_objects as go st.title("Smart Farmer") st.markdown("The dashboard will help a researcher to get to know \ more about the given datasets and it's...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from pykg2vec.core.KGMeta import ModelMeta class TransH(ModelMeta): """ `Knowledge Graph Embedding by Translating on Hyperplanes`_ ...
import requests import os r = requests.get("https://koyu.space/api/v1/custom_emojis") j = r.json() for item in j: if item["visible_in_picker"] == True: extension = item["url"].split(".")[len(item["url"].split(".")) - 1] os.system("wget -O "+item["shortcode"]+"."+extension+" "+item["url"])
import tnetwork.DCD.pure_python.estrangement_master.estrangement.utils as est_utils import tnetwork.DCD.pure_python.estrangement_master.estrangement.lpa as lpa import tnetwork.DCD.pure_python.estrangement_master.estrangement.agglomerate as agglomerate
""" *Configuration based Instance factories* Inversion of control style plugin factories that return an object instance based on a named definition from configuration. Makes use of :py:mod:`pyapp.conf` to store instance definitions in settings. An instance definition includes both the object type as well as arguments...
""" Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, using read function and display those words, which are less than 4 characters. """ F=open("story.txt","r") value=F.read() lines=value.split() count=0 for i in lines: if len(i)<4: print(i) ...
#!/usr/bin/env python # Copyright (c) 2016, Palo Alto Networks # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" A...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('resources', '0006_auto_20150723_1249'), ] operations = [ migrations.AlterField( model_name='resourcedata', ...
var = 3 print(type(var)) var = "string now" print(type(var)) print("="*10) var: int = 3 print(type(var)) var = "string now" print(type(var)) print("="*10) # change linter to mypy # https://docs.python.org/3/library/warnings.html
from parsons.etl.etl import ETL from parsons.etl.tofrom import ToFrom from parsons.utilities import files import petl import pickle import logging logger = logging.getLogger(__name__) DIRECT_INDEX_WARNING_COUNT = 10 class Table(ETL, ToFrom): """ Create a Parsons Table. Accepts one of the following: - A...
import bpy import bpy_types import pyconspack as cpk from pyconspack import Conspack import io_scene_consmodel.nodes from io_scene_consmodel.util import (AttrPack, defencode) class Consmodel(AttrPack): SCENE = None def preinit(self, **kw): self.stagings = cpk.Vector() def postinit(self, scenes=...
""" Utilities functions used in testing and demonstration.""" """ Copyright 2021 Hugo U.R. Strand 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 ...
# -*- coding: utf-8 -*- # Copyright (c) 2008, Mikio L. Braun, Cheng Soon Ong, Soeren Sonnenburg # 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 reta...
import numpy as np class NaiveBayes(): def __init__(self,train_data,label_data): ''' given train/label data initializes the NaiveBayes class Parameters ---------- train_data : numpy-array label_data : numpy-array ''' self.train_data = train...
import argparse import numpy as np from pathlib import Path import matplotlib.pyplot as plt # Local Moduels from asiCD.asiCD_utils import img_from_file from asiCD.asiCD_utils import load_json def gen_flat_img(img_inst, ann_inst): img_flat = np.zeros([img_inst.shape[0]*img_inst.shape[1], 4]) for i in range...
import unittest import numpy import six import chainer from chainer import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr from chainer.testing import condition @testing.parameterize( *testing.product({ 'batchsize': [5, 1...
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-10 21:34 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("stock", "0020_stockproductcds_stockproductdis")] operations = [ migrations.RenameField( ...
import datetime as DT import numpy as NP import matplotlib.pyplot as PLT import matplotlib.colors as PLTC import scipy.constants as FCNST from astropy.io import fits from astropy.io import ascii from astropy.table import Table import progressbar as PGB import antenna_array as AA import geometry as GEOM import my_DSP_mo...
# Copyright (C) 2013-2016 DNAnexus, Inc. # # This file is part of dx-toolkit (DNAnexus platform client libraries). # # 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.a...
from flask import g import sqlite3 import psycopg2 from psycopg2.extras import DictCursor """ def connect_db(): sql = sqlite3.connect('/home/vitalijus/Desktop/flask_app/lecture23/23/questions.db') sql.row_factory = sqlite3.Row return sql def get_db(): if not hasattr(g, 'sqlite_db'): ...
from typing import Iterable from pycparser import c_ast, c_parser from popsicle.code_transform_utils.expr_estimator import ExprEstimator, remove_non_extreme_numbers from popsicle.code_transform_utils.malloc_builder import MallocBuilder from popsicle.code_transform_utils.code_transform_utils import ArrayRefVisitor, ForV...
import rospy from sensor_msgs.msg import Image from std_msgs.msg import String from cv_bridge import CvBridge import cv2 import numpy as np import tensorflow as tf import classify_image class RosTensorFlow(): def __init__(self): classify_image.maybe_download_and_extract() self._session = tf.Sessio...
from dataclasses import dataclass, field from enum import Enum from typing import Optional __NAMESPACE__ = "NISTSchema-SV-IV-list-positiveInteger-enumeration-5-NS" class NistschemaSvIvListPositiveIntegerEnumeration5Type(Enum): VALUE_6342185648999798_682097_20799729_777373_3206854703627_904582_984418438148606_12_...
#!/usr/bin/env python """Exposes classes and functions to parse the models generated by SMT solvers in response to satisfiable SMT queries. """ """See the LICENSE file, located in the root directory of the source distribution and at http://verifun.eecs.berkeley.edu/gametime/about/LICENSE, for details on the GameTime ...
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name='tackle-dgi', version='0.0.4', url="https://github.com/konveyor/tackle-data-gravity-insights", author="IBM", description="Konveyor Tackle Data Gravity Insights", long_des...
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-02-15 14:35 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auth', '0007_alter_validato...
# coding: utf-8 """ Simple telent client. usage: telnet host [-p port] [--timeout N] """ from __future__ import print_function import sys import select import argparse import telnetlib import threading from stash.system.shcommon import K_CC, K_CD, K_HUP, K_HDN, K_CU, K_TAB, K_HIST, K_CZ, K_KB _SYS_STDOUT = sys.__std...
from oauthlib.oauth2 import BackendApplicationClient from requests.auth import HTTPBasicAuth from requests_oauthlib import OAuth2Session import os TWITTER_TOKEN_URL = 'https://api.twitter.com/oauth2/token' TWITTER_KEY = os.environ.get("TWITTER_KEY") TWITTER_SECRET = os.environ.get("TWITTER_SECRET") class TwitterAuth...
import unittest from unittest.mock import MagicMock from ignition.boot.configurators.utils import validate_no_service_with_capability_exists from ignition.service.framework import Capability class DummyCapability(Capability): pass class Test_validate_no_service_with_capability_exists(unittest.TestCase): def ...
#!/usr/bin/env python from pwn import * _libc_start_main_offset = 0x0000000000020740 # GADGETS of /lib/x86-64/libc-2.23.so POPRDI = 0x0000000000042c0d # leak for getting stack canary and __libc_start_main leak = "%17$p,%19$p" # padding padding = "A"*72 # pause for attaching with gdb for debugging purposes # pause...
#! /usr/bin/python # procdl.py # # FRT - A Godot platform targeting single board computers # Copyright (c) 2017 Emanuele Fornara # # 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 re...
# Copyright 2013-2014 Sebastian Kreft # # 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 ...
""" 1. Subset(second le) 2. LCS Given two strings 'X' and 'Y', find the length of the longest common substring. For example, if the given strings are "GeeksforGeeks" and "GeeksQuiz", the output should be 5 as longest common substring is "Geeks" [Solution](http://www.geeksforgeeks.org/longest-common-substring/) DP is O(...
import pytest from web3.utils.encoding import decode_hex def test_txn_request_payments(chain, web3, get_execute_data, RequestData): txn_request = RequestData(donation=12345).direct_deploy() request_data = RequestData.fro...
class Solution: def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ ans = [] def backtracks(S='', left=0, right=0): if len(S) == 2 * n: ans.append(S) return if left < n: backtracks(S + '(', left + 1, right) if right <...
""" 1.3 EUC-KR (CP949) EUC-KR - 한국 산업 표준으로 지정된 한국어 문자 집합, 모든 글자가 완성된 형태로만 존재하는 완성형 코드 - 한글처럼 초성, 중성, 종성을 조합해 문자를 만들 수 없기 때문에 EUC-KR로 표현할 수 없는 한글이 일부 존재함. - 문자하나를 표현하기 위해 2바이트를 사용 - EUC-KR에 표현하는 문자 집합의 문자 중, 아스키 코드에도 포함되는 문자를 표현할 때는 1바이트를 사용 (아스키 코드와 호환) - 하나의 문자 집합, 하나의 문자열 인코딩 CP949 ...
# -*- coding: utf-8 -*- import os,sys,textwrap,time from PySide6 import QtCore, QtGui, QtWidgets from PySide6.QtWidgets import QMessageBox from ui import Ui_MainWindow from MapManager import Map, NewMap from SoundProcessor import Song, ConcatenateSongs,EditSound from utility import * log = logger(__name__) class UI(...
# -*- coding: utf8 -*- # import packages needed import os import pandas as pd import sys import time # import configuration in parent dir import os, sys, inspect current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parent_dir = os.path.dirname(current_dir) sys.path.insert(0, parent_d...
from .client import connection # noqa: F401 from .document import ( Document, BaseModel, EmbeddedDocument, PrivatesAttrsMixin, Field, mark_parents ) # noqa: F401 from .query import Q # noqa: F401 from .queryset import QuerySet # noqa: F401
# results: # using np.random.normal # with 100000000 pts: can verify 5 sigma to 5%, 3/4 sigma to 1%, 2 sigma and below to 0.1% # with 10000000 pts: can verify 4 sigma to 5%, 3 sigma to 2%, 2 sigma to 0.5%, 1 sigma to 0.1% # with 1000000 pts: can verify 3 sigma to 5%, 2/1 sigma to 1% # with 100000 pts: can verify 2 sig...
#!/usr/bin/env python import sys import torch import itertools import numpy as np import matplotlib.pyplot as plt from mpnn.utils_mpnn import Rhombus from mpnn.utils_gen import myrc, loadpk, plot_2d_tri, linear_transform, cartes_list myrc() ########################################################################...
# # list_example=[1,2,3,4,1] # # print(list_example.count(1)) # list_example=[1,2,3,4,1] # # print(list_example.index(5)) # #clear # list_example=[1,2,3,4] # print(list_example.clear()) # print(list_example) # #reverse # list_example=[1,2,3,4] # list_example.reverse() # print(list_example) # #so...
import gym import numpy as np from tests.fixtures.envs.dummy import DummyEnv class LazyFrames(object): def __init__(self, frames): """ LazyFrames class from baselines. Openai baselines use this class for FrameStack environment wrapper. It is used for testing garage.en...
"""bad_news_bears URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Clas...
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Michael A.G. Aivazis # California Institute of Technology # (C) 1998-2005 All Rights Reserved # # {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~...
import os.path import pandas as pd import numpy as np from dotenv import load_dotenv, find_dotenv from optools.noarbitrage import covered_interest_parity from downstream import (get_options_data, get_fx_rates, get_interest_rates) load_dotenv(find_dotenv()) def save_prepared_data() -> None: TAU = 1/12 dat...
def getColumns(inFile, delim="\t", header=True): """ Get columns of data from inFile. The order of the rows is respected :param inFile: column file separated by delim :param header: if True the first line will be considered a header line :returns: a tuple of 2 dicts (cols, indexToName). cols di...
#! /usr/bin/python import sys,numpy as np from docReader import readDocsFine2 as readDocsFine # SAMPLE RUN # python2 eval_componentF1.py prediction/maj_best10.out.corr.abs ../../data/conll/Essay_Level/test.dat.abs 0.999 # alpha = 0.999 is the F1 level as described in the paper def extractComponents(lst,types): h...
from __future__ import (absolute_import, division, print_function, unicode_literals) from django.conf.urls import include, url from wagtail.wagtailcore import hooks from wagtail.wagtailcore.models import Page from . import urls from .menu import ApprovalAdminMenuItem, ApprovalMenuItem from .mo...
from logging import Logger from logging import getLogger from typing import List from typing import cast from pytrek.engine.ArcadePoint import ArcadePoint from pytrek.engine.GameEngine import GameEngine from pytrek.engine.Intelligence import Intelligence from pytrek.gui.MessageConsole import MessageConsole from pytre...
# Imports from apscheduler.schedulers.blocking import BlockingScheduler from covid_bot import * scheduler = BlockingScheduler() def bot_schedule(): """ A scheduler for the covid_bot script """ for numb in receiver_list: print(f"sending message to {numb}") send_message(numb, messages)...
import unittest import time from engine import DecisionEngine from server import ServerList, Server from config import Config class EngineTestCase(unittest.TestCase): def test_engine_initialization(self): server_list = ServerList() # decision algorithm 0 da = Config.decision_algorithm ...
from typing import Any from neo4j import Session from ..schemas import neo4j_schemas def link(db: Session, node_from_id, node_to_id, label: str, parameters: dict = None): db.run( "match (a), (b) where id(a) = $node_from_id and id(b) = $node_to_id create (a)-[:" + label + " $params]->(b)", ...
import os import numpy as np import random import tensorflow as tf import math def create_dirs(dirs): """ dirs - a list of directories to create if these directories are not found :param dirs: :return: """ try: for dir_ in dirs: if not os.path.exists(dir_): ...
import os import sys import cv2 import random import webbrowser import numpy as np import tkinter as tk import tkinter.messagebox as tkMessageBox from tkinter import * from tkinter import ttk from threading import Timer from PIL import Image, ImageTk from datetime import datetime class Gif(Label): def __init__(...
import time import cv2 import mediapipe as mp import HandTracking as ht pTime = 0 cTime = 0 cap = cv2.VideoCapture(0) detector = ht.handDetector() # Check if camera opened successfully if cap.isOpened() is False: print("Error opening video stream or file") while cap.isOpened(): ret, img = cap.read() ...
from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) name =...
import os import subprocess import errno import shutil import re import sys kernel_path = '' install_path = '' patch_rules = [] arch = '' def mkdir_p(path): try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Fichier: test_data.py # Auteur: Marc COATANHAY """ Tests pour le module csvdata. """ # Import des modules from data import * import unittest # Définitions constantes et variables globales # Définitions fonctions et classes class CsvTest(unittest.Test...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # %% [markdown] # # wave - eddy interactions - the horizontal fluxes # # The equation describing the rate of change of total $E$ energy for a QG mean flow $\pmb{u}$, and internal wave perterbations $\pmb{u}^\prime$, is the following: # # $$(\frac{\partial}{\partial t} + \...
import numpy as np from scipy import fftpack from matplotlib import pyplot as plt #constant variables num_samples=1000 plot_interval=0.01 xs=np.arange(0,num_samples*plot_interval,plot_interval) kill_frq=4.5 def plot_original(func): fig,ax=plt.subplots(figsize=(8,3)) ax.plot(xs,func(xs)) def apply_fft(...
class Holder: def __init__(self, value, argtype=None, access=None): self.__value = value self.__type = argtype or type(value) if access is None: from .instructions._core import READ access = READ self.__access = access @property def access(self): ...
########################################################################## # # Copyright (c) 2015, 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...
""" Note that: - We can only move forward - The gas tank starts empty - gas[i] represents the amount of gas at the station i - cost[i] represents the cost to go from the station i to the next one - the answer is guaranteed to be unique - if the station we're searching for doesn't exist, return -1 """ gas = [1, 5, 3, 3...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Contains model unit tests. """ from __future__ import unicode_literals import decimal from django.test import TestCase from django.utils import timezone from taggit.models import Tag from wagtail.wagtailcore.models import Page from wagtail.tests.testapp.models import...
# coding: utf-8 """ Uptrends API v4 This document describes Uptrends API version 4. This Swagger environment also lets you execute API methods directly. Please note that this is not a sandbox environment: these API methods operate directly on your actual Uptrends account. For more information, please visit ...
RUN_STRINGS = ( "Kau pikir mau kemana dirimu?", "Ya? apa? apakah mereka bisa lolos?", "ZZzzZZzz... Hah? Apa? oh, ternyata mereka lagi, jangan dipikirkan.", "Kembali ke sini!", "Tidak begitu cepat...", "Perhatikan kalau ada dinding!", "Jangan tinggalkan aku sendirian dengan mereka!!", "Ka...
# -*- coding: utf-8 -*- VERSION = (0, 0, 1) __title__ = "pyhubtel-sms" __description__ = "An easy to use wrapper for Hubtel's SMS APIs." __url__ = "https://github.com/idadzie/pyhubtel-sms" __version__ = ".".join(map(str, VERSION)) __author__ = "Isaac Dadzie" __author_email__ = "idadzie.dev@gmail.com" __license__ = "A...
# import the necessary packages import torch from pyimagesearch import mlp # define entry point/callable function # to initialize and return model def custom_model(): """ # This docstring shows up in hub.help() Initializes the MLP model instance Loads weights from path and returns the model """ # initialize the...
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # @Time : 2019/8/16 17:45 # @Author: Jtyoui@qq.com from types import FunctionType, ModuleType def string_function(module: [str, ModuleType], func: str, *args, **kwargs): """根据字符串方法名来进行调用模块方法 :param module: 模块名 :param func: 模块中的方法名字 :param args: 方法里面的参数值 ...
# apis_v1/documentation_source/twitter_sign_in_start_doc.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- def twitter_sign_in_start_doc_template_values(url_root): """ Show documentation about twitterSignInStart """ required_query_parameter_list = [ { 'name': ...
#!/usr/bin/env python import argparse import functools import io import logging import os import re import tarfile import tempfile from ruamel.yaml import YAML from ruamel.yaml.scalarstring import LiteralScalarString MAX_OUTPUT_SIZE = 24 * 1024 ERR_SUCCESS = 0 ERR_NOT_FOUND = 1 ERR_ALREADY_EXISTS = 2 ERR_FILE_TOO_L...
# run_spec.py [UNIT TEST] # (C) 2015 # Scott Ernst from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division import unittest import hello_lambda class run_spec(unittest.TestCase): def test_run(self): """ doc... "...
from datetime import datetime from typing import Union, Dict, Any from .BusInfo import BusInfo from app.utils import get_int class BusInfoDetails(BusInfo): def __init__( self, route_id: int, name: str, route_type: str, st_type: Union[str, int], ...
from par import * from sys import argv from matplotlib.cm import coolwarm as cm if len(argv) < 3: print u'usage: {} [field] [space1] [space2] ...'.format(argv[0]) exit() k = argv[1] for sp in argv[2:]: xx, xl, xs, xf = spaceinfo[sp[1]] yy, yl, ys, yf = spaceinfo[sp[0]] sr = sp[2] zz = DPA(r...
""" HyperInSPACE is designed to provide Hyperspectral In situ Support for the PACE mission by processing above-water, hyperspectral radiometry from Satlantic HyperSAS instruments. See README.md or README.pdf for installation instructions and guide. Version 1.0.9: Under development September 2021 (See Changelog.md) Dirk...
class dataStructuresOperations: def cdataStructuresOperations(inputFromUser, outputFromUser): modularInOperations = [float(index) for index in inputFromUser.split(' ')] modularInOperations.sort() modularOutOperations = [float(index) for index in outputFromUser.split(' ')] if modularInOperations==modul...
# getHrs.py # Creator: Robert Toribio # Date: 10/28/2021 import statsapi from datetime import date import re def totalhrsToday(all_hrs): total_hrs = 0 for element in all_hrs: total_hrs += int(element[1]) return total_hrs def getGames(date): game_ids = [] gamesToday = statsapi.schedule(d...
import warnings from pyinstrument.profiler import Profiler __version__ = "4.1.1" # enable deprecation warnings warnings.filterwarnings("once", ".*", DeprecationWarning, r"pyinstrument\..*") def load_ipython_extension(ipython): """ This function is called by IPython to load the pyinstrument IPython exte...
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- from datetime import datetime import time from bes.common.check import check class time_util(object): 'Time util' @classmethod def timestamp(clazz, delimiter = '-', milliseconds = True, timezone = False, when = None): ...
from pii_benchmarking.interfaces import presidio, aws, gcp class Masker: def __init__(self, engine='presidio'): self.engine = self._get_masker(engine) def mask_text(self, text): return self.engine.mask_text(text) def batch_mask(self, list_of_text): return self.engine.batch_mask(l...
import os import shutil import uvicorn from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from starlette.staticfiles import StaticFiles from huoguoml.server.api.experiment import ExperimentRouter from huoguoml.server.api.ml_model import MLModelRouter from huoguoml.server.api.ml_service imp...
'''Builds a 2-layer fully-connected neural network''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np # 使我们从输入数据到类分数 def inference(images, image_pixels, hidden_units, classes, reg_constant=0): '''Build the model...
#!/usr/bin/env python3 import sys import re import unicodedata from collections import namedtuple RE_WORD = re.compile('\w+') CharDescription = namedtuple('CharDescription', 'code_str name') def parse_query(query): if '?' in query or any(ord(char) > 127 for char in query): question_marks = query.count(...
from django.forms import ModelForm from .models import Content class Meme(ModelForm): class Meta: model = Content fields = [ "img", "caption" ,"type_meme" ]
# vim: sw=4:ts=4:et:cc=120 # # Carbon Black Collector # import json import datetime import dateutil.parser import logging import saq from saq import proxy from saq.collectors import Collector, Submission from saq.constants import * from saq.error import report_exception from saq.persistence import * from saq.util i...
# coding=utf8 import pickle import sys defaultencoding = 'utf-8' if sys.getdefaultencoding() != defaultencoding: reload(sys) sys.setdefaultencoding(defaultencoding) import pandas as pd import re from fuzzywuzzy import fuzz from fuzzywuzzy import process import json df = pd.read_excel('db2.xlsx') #print(d...
import argparse def main(output_file, beer_file): with open(output_file, 'r') as in_f,\ open(beer_file, 'w') as out_f: for line in in_f: tokens = line.strip().split() phns = ' '.join(tokens[1].split(',')) out_f.write(f'{tokens[0]} {phns}\n') if __name__ == '__main__': parser = argpa...
from django.shortcuts import render, get_object_or_404 from .models import Introduction, NewsItem, Link # Create your views here. def index(request): args = {} return render(request, 'home/index.html', { 'introductions': Introduction.objects.all(), 'news': NewsItem.objects.all().order...
""" Experiment code is this one and associated bash insilico_manifold_vgg16.sh insilico_ResizeManifold_script.py insilico_manifold_resize.sh insilico_manifold_resize_vgg16.sh """ import seaborn as sns import matplotlib.pylab as plt import pandas as pd import numpy as np from scipy.stats import ttest_rel...
#!/usr/bin/env python # Copyright 2015 Yelp 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 ag...
""" This is a django-split-settings main file. For more information read this: https://github.com/sobolevn/django-split-settings Default environment is `development`. To change settings file: `DJANGO_ENV=production python manage.py runserver` """ from os import environ from split_settings.tools import include, option...
''' Abstract class for the emission models. ''' class Emission(): def init_features(self, features): pass def update_features(self): pass def predict_features(self, features): pass def feature_ll(self, features): pass def lowerbound(self): pass
# coding=utf-8 u""" Description: Report statistic information. User: Jerry.Fang Date: 14-01-06 """
from sklearn.ensemble import RandomForestClassifier from rotation_forest import RotationForestClassifier from joblib import dump, load from lightgbm import LGBMClassifier #Supports SVC's for ThunderSVM, LibSVM, and Sklearn class GenericForest(object): def __init__(self,hyperParams): #create a co...