content
stringlengths
5
1.05M
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
import qiskit from .cnx_halfdirty import cnx_halfdirty def cnx_any_dirty(circuit, controls, target, ancilla): def find_dirty(groups, g): d = [] for f in groups: for e in f: if e not in g and e not in d: d.append(e) if len(d) == le...
# TODO 1. Create dictionary {"a": "alpha", ...} import pandas df = pandas.read_csv("day26alpha.csv") nato_alpha = {row.letter:row.code for _, row in df.iterrows()} print(nato_alpha) # TODO 2. Create list of phonetic alphabet from user input while (user_input := input("Word: ").upper()) != "EXIT": print("\n".j...
""" Copyright 2016 Pawel Bartusiak 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, softwar...
# Based on the work done by the creators of the Dictation Toolbox # https://github.com/dictation-toolbox/dragonfly-scripts # # Modifications by: Tony Grosinger and Anders Sildnes # # Licensed under LGPL class FormatTypes: camelCase = 1 pascalCase = 2 snakeCase = 3 squash = 4 upperCase = 5 lower...
from backpack.core.derivatives.dropout import DropoutDerivatives from backpack.extensions.secondorder.diag_ggn.diag_ggn_base import DiagGGNBaseModule class DiagGGNDropout(DiagGGNBaseModule): def __init__(self): super().__init__(derivatives=DropoutDerivatives())
# Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved. # # 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 appli...
#%% import pandas import numpy as np fileName ="PathaoFoodDeliveryData" data= pandas.read_csv(fileName) data_sorted = data.sort_values(['restaurant_id'], ascending=False) print(data_sorted) setUid = set(data["user_id"]) setItemID = set(data["item_id"]) setRestaurantID = set(data["restaurant_id"]) uids = list(setUid...
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name='typegenie', version='0.0.6', url="https://github.com/abhitopia/TypeGenieApiClient", author="abhitopia", author_email="hi@typegenie.net", description='Client Library for...
# ----------------------------------------------------- # Analyse Annotations of the Dataset # # Author: Qiling Xu # Creating Date: May 25, 2018 # Latest rectifying: May 25, 2018 # ----------------------------------------------------- import json import os import os.path from PIL import Image def cro...
import os.path as osp import logging import time import argparse from collections import OrderedDict import options.options as option import utils.util as util from data import create_dataset, create_dataloader from models import create_model def main(): #### options parser = argparse.ArgumentParser() par...
import os os.environ['PYTHONUNBUFFERED'] = '1' os.environ['PYTHONASYNCIODEBUG'] = '1' import logging logging.basicConfig(level=logging.DEBUG) import asyncio asyncio.set_event_loop(None)
import logging import os from .Plugin import Plugin from localpdb.utils.config import Config from localpdb.utils.os import create_directory from localpdb.utils.network import download_url logger = logging.getLogger(__name__) # Plugin specific imports import gzip import pandas as pd from urllib.parse import urlparse ...
import os import inspect from pathlib import Path def file_path(path): frame = inspect.stack()[1] caller_module = inspect.getmodule(frame[0]) base_dir = os.path.realpath(__file__) + f'/../../' relative_to_base = caller_module.__file__[len(base_dir):] return os.path.realpath(f"resources/{relative_t...
from ..errors import OmbottException class RouteError(OmbottException): """ This is a base class for all routing related exceptions """ __slots__ = ('extra',) def __init__(self, *args, **kw): super().__init__(*args) self.extra = kw class RouteSyntaxError(RouteError): """ The route p...
""" mbed SDK Copyright (c) 2016 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 writing, so...
# # This sets up how models are displayed # in the web admin interface. # from django.conf import settings from evennia.typeclasses.admin import AttributeInline, TagInline from evennia.scripts.models import ScriptDB from django.contrib import admin class ScriptTagInline(TagInline): """ Inline script tags. ...
from django.shortcuts import render # Create your views here. from django.http import HttpResponse from django.shortcuts import render, redirect from .forms import * from django.conf import settings # for boto3 import boto3 import botocore from botocore.exceptions import ClientError # for filtering from PIL import ...
import ../daemon/scheduler/task_placer import unittest class TestTaskPlacer(): pass
import typing as T import numpy as np import numpy.random import gemini3d.read import gemini3d.write def perturb(cfg: T.Dict[str, T.Any], xg: T.Dict[str, T.Any]): """ perturb plasma from initial_conditions file """ # %% READ IN THE SIMULATION INFORMATION # trim ghost cells x1 = xg["x1"][2:-2...
from django import forms from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import User from .models import UserProfile, UserPost class ExtendedUserCreationForm(UserCreationForm): email = forms.EmailField(required=True, label='...
def funny_division3(anumber): try: if anumber == 13: raise ValueError("13 is an unlucky number") return 100 / anumber except ZeroDivisionError: return "Enter a number other than zero" except TypeError: return "Enter a numerical value" except ValueError: ...
from __future__ import absolute_import, division, print_function, unicode_literals import argparse import json from math import fmod, ceil from lib import octmps from src.python.octmps_io import show_version from src.python.mesh import load_mesh def read_opt_files(opt_file_name): regions = list() with open(op...
import nested_admin from django.contrib import admin from . models import (Page, PageBlock, PageCarousel, PageContact, PageHeading, PageHeadingLocalization, PageLink, ...
""" Implementation of different training methods """ import numpy as np from sklearn.model_selection import KFold, train_test_split, ShuffleSplit import pandas as pd import configparser from fb_rnn import FBRNN from forward_rnn import ForwardRNN from nade import NADE from bimodal import BIMODAL from one_hot_encoder im...
input = """ 1 2 0 0 1 3 0 0 1 4 0 0 1 5 0 0 1 6 0 0 1 7 0 0 1 8 0 0 1 9 0 0 1 10 0 0 1 11 0 0 1 12 0 0 1 13 0 0 1 14 0 0 1 15 0 0 1 16 0 0 1 17 0 0 1 18 1 1 19 1 20 1 1 21 1 22 1 1 23 1 24 1 1 25 1 26 1 1 27 1 28 1 1 29 1 19 1 1 18 1 21 1 1 20 1 23 1 1 22 1 25 1 1 24 1 27 1 1 26 1 29 1 1 28 1 1 1 1 18 2 30 2 0 1 22 20 ...
import pytest import diglet def test_live(): resp = diglet.Mkreq('google.com', qtype=diglet.QType.A) assert(len(resp['answers']) > 0) resp = diglet.Mkreq('google.com', qtype=diglet.QType.MX) assert(len(resp['answers']) > 0)
# Copyright 2020 The Pigweed Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
""" Grapevine network connection This is an implementation of the Grapevine Websocket protocol v 1.0.0 as outlined here: https://grapevine.haus/docs This will allow the linked game to transfer status as well as connects the grapevine client to in-game channels. """ import json from twisted.internet import protocol ...
from .mcmc_models import mcmcMLP from .mcmc_models import mcmcLeNet from .models import LeNet from .models import SmallCNN from .mcmc_models import mcmcSmallCNN
from pyshinobicctvapi.connection import Connection def test_create(): assert not Connection("") is None
"""Djangopress' Urls """ from django.conf.urls import url, include from .views import PostList, PostDetail, MonthArchive app_name = 'djangopress' # pylint: disable=invalid-name urlpatterns = [ url(r'^', include('djangopress.pages.urls')), url(r'^$', PostList.as_view(), name='home'), url(r'^page/(?P<page>...
# -*- coding: utf-8 -*- # File: myutils.py # Author: Rafał Nowak <rafal.nowak@cs.uni.wroc.pl> import os import logging import tarfile import urllib.request import pickle import numpy as np # pylint: CIFAR_DATA_URL = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' CIFAR_DIR_PATH = './cifar10_data/' CIFAR_FOL...
from plugin import plugin, require import requests @require(network=True) @plugin('countryinfo') class country_info: """ Welcome to the Countryinfo plugin documentation! Here you will be able to find all the functionalities of the plugin. Usage: Type countryinfo and follow the instructions. This p...
""" ============================================== Immunohistochemical staining colors separation ============================================== In this example we separate the immunohistochemical (IHC) staining from the hematoxylin counterstaining. The separation is achieved with the method described in [1]_, known a...
""" Provides the following multilateral methods: * :func:`time_dummy` * :func:`geary_khamis` * :func:`geks` paired with * :func:`carli` * :func:`jevons` * :func:`dutot` * :func:`laspeyres` * :func:`paasche` * :func:`geom_laspeyres` * :func:`geom_paasche` * :func:`drobish` * :func:`m...
################################################### ### ### ### Plot script for experiments on Tasic data ### ### written by Bettina Mieth, Nico Görnitz, ### ### Marina Vidovic and Alex Gutteridge ### ### ### ###############################################...
# -*-coding:utf8-*- import math import torch import torch.nn as nn from torchvision.models import efficientnet from torchvision.ops.misc import ConvNormActivation from utils.tensor_op import pixel_shuffle from utils.debug_utils import AverageTimer def initialize_weights(model): for m in model.modules(): i...
## Copyright 2016 - 2018 Raik Gruenberg ## This file is part of the LabHamster project (https://github.com/graik/labhamster). ## LabHamster is released under the MIT open source license, which you can find ## along with this project (LICENSE) or at <https://opensource.org/licenses/MIT>. from __future__ import unicode...
#!/usr/bin/env python # All of the argument parsing is done in the `parallel.py` module. import multiprocessing import time import numpy as np import Starfish from Starfish.model import ThetaParam, PhiParam import argparse parser = argparse.ArgumentParser(prog="plot_many_mix_models.py", description="Plot many mixtur...
""" [12/4/2012] Challenge #114 [Intermediate] Shortest word ladder https://www.reddit.com/r/dailyprogrammer/comments/149khi/1242012_challenge_114_intermediate_shortest_word/ Given any two words from [this list of 3,807 four-letter words](http://pastebin.com/zY4Xt7iB), output a [word ladder](http://www.reddit.com/r/da...
import pymongo from pymongo import collection if __name__ == "__main__" : client = pymongo.MongoClient("mongodb://localhost:27017/") db = client["VehicalDB"] collection = db["IndianVehicalInformation"] # data = [ # {"Car Number": "MH20DV2363", "Owner Name": "Raktim Midya", "Owner Phone Number":...
from .client import Client from .command import Command from .embed import Embed from .interaction import *
# # This file is executed by the makefile in ../ # #copy index.html to /docs folder and change the base href to point to "build/html/" def installIndexHtml(src, dst): task = "installing index html" print(task + "...", end="") try: with open(src, "r") as r, open(dst, "w") as w: w.write(...
import os from balsa import get_logger, Balsa, __author__ def test_balsa_sentry(): application_name = "test_balsa_sentry" if "SENTRY_DSN" in os.environ: balsa = Balsa(application_name, __author__, use_sentry=True, inhibit_cloud_services=False, is_root=False, sentry_dsn=os.environ["SENTRY_DSN"]) ...
# # @lc app=leetcode id=509 lang=python3 # # [509] Fibonacci Number # https://leetcode.com/problems/fibonacci-number/description/ # Tagged "tree". # import unittest # @lc code=start class Solution: def fib(self, N: int) -> int: """ Avoid re-computing numbers. For each number in the seq...
import glfw from window.base import BaseKeys class Keys(BaseKeys): """ Namespace defining glfw specific keys constants """ ACTION_PRESS = glfw.PRESS ACTION_RELEASE = glfw.RELEASE ESCAPE = glfw.KEY_ESCAPE SPACE = glfw.KEY_SPACE ENTER = glfw.KEY_ENTER PAGE_UP = glfw....
#19) Counting Sundays #You are given the following information, but you may prefer to do some research for yourself. #1 Jan 1900 was a Monday. #Thirty days has September, #April, June and November. #All the rest have thirty-one, #Saving February alone, #Which has twenty-eight, rain or shine. #And on leap years, twenty-...
from os.path import join, exists, dirname from sklearn.neighbors import KDTree from tool import DataProcessing as DP from helper_ply import write_ply import numpy as np import os, pickle, argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--dataset_path', type=str, requ...
import unittest import json from pyetherscan import client, response, error class BaseClientTestCase(unittest.TestCase): def setUp(self): self.client = client.Client() def base_etherscan_response_status(self, result): self.assertEqual(200, result.response_status_code) self.assertEqu...
# Copyright (c) Facebook, Inc. and its affiliates # SPDX-License-Identifier: MIT OR Apache-2.0 import numpy as np from dataclasses import dataclass import typing class SerializationError(ValueError): """Error raised during Serialization""" pass class DeserializationError(ValueError): """Error raised d...
from django.conf import settings from django.utils.module_loading import import_module from django.core.management.base import BaseCommand from ...contrib.fontforge.watcher import Watcher class Command(BaseCommand): args = '' help = 'ex: ./manage.py fontforge_watcher' def handle(self, *args, **options): ...
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/13_probabilistic_models.ipynb (unless otherwise specified). __all__ = ['MeanStdWrapper'] # Cell import numpy as np import torch from torch import nn from ..tabular.model import * from fastai.tabular.data import * from ..timeseries.model import * from fastai.tabular.all ...
from apps import App, action import smtplib import email.utils from email.mime.text import MIMEText class Main(App): def __init__(self, name, device, context): App.__init__(self, name, device, context) self.server = smtplib.SMTP('{0}:{1}'.format(self.device_fields['ip'], self.device_fields['port']...
import logging import datacloud.login import pytest from tests.base_test import BaseTest @pytest.mark.usefixtures("setup") class TestLogin(BaseTest): # "Login" Fixtures @pytest.fixture(scope="class") def good_login(self, request): return datacloud.login.CreateLoginAPI(request.cls.dc_host, reques...
# ----------------------------------------------------------------------------# # Imports # ----------------------------------------------------------------------------# import json import dateutil.parser import babel from flask import Flask, render_template, request, Response, flash, redirect, url_for, abort from fla...
""" overseer.urls ~~~~~~~~~~~~~ :copyright: (c) 2011 DISQUS. :license: Apache License 2.0, see LICENSE for more details. """ from django.conf.urls.defaults import * import os.path urlpatterns = patterns('', url(r'^media/(?P<path>.+)?$', 'django.views.static.serve', { 'document_root': os.path.join(os.pat...
from django.apps import AppConfig class FairshakeConfig(AppConfig): name = 'FAIRshakeHub'
# Copyright (C) 2020 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """ Change CycleTaskGroupObjectTask finished_date and verified_date type from DateTime to Date Create Date: 2019-02-13 10:24:27.731045 """ # disable Invalid constant name pylint warning for mandatory Alembi...
import pickle with open('raw.pickle', 'rb') as f: u = pickle._Unpickler(f) u.encoding = 'latin1' p = u.load() print(p.keys())
"""Tests for pickaxe.py using pytest.""" # pylint: disable=redefined-outer-name # pylint: disable=protected-access import hashlib import os import re import subprocess from filecmp import cmp from pathlib import Path import pymongo import pytest from pymongo.errors import ServerSelectionTimeoutError from rdkit.Chem i...
import numpy as np import imageio """ Utilities for generating example density distributions """ def generate_single_focus(width, height, fx, fy, variance): """ Generates a single focus density as a 2D gaussian. width, height: dimension of the map fx, fy: fraction of the map where the focus lies. ...
''' Created on Jun. 01, 2019 OpenDSS Mosaik interface, and Sensor/Actuator Models @file simulator_pflow.py @author Evandro de Souza @date 2019.06.01 @version 0.1 @company University of Alberta - Computing Science ''' import mosaik_api from SimDSS import SimDSS from LoadGenerator import LoadGenerator import n...
#!/usr/bin/env python3 import argparse import pprint import requests def login_admin(admin_id, admin_secret, url, verbose): headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'} payload = {'grant_type': 'client_credentials', 'response_typ...
# 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, software # distributed under t...
''' Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 Clarification: What should we return when nee...
# coding: utf-8 import time import os import shutil from dp_toolbox import * from pywinauto_recorder.player import * from pathlib import Path if __name__ == '__main__': os.chdir(os.path.dirname(os.path.abspath(__file__))) brian = Voice(name='Brian') obs = OBSStudio() ###########################################...
__author__ = 'Guorong Xu<g1xu@ucsd.edu>' import yaml ## parseing yaml file def parse_yaml_file(yaml_file): documents = {} samples = [] stream = open(yaml_file, "r") docs = yaml.load_all(stream) for doc in docs: for k,v in doc.items(): if k == "sample": samples....
import torch import torch.nn.functional as F from tqdm import tqdm import numpy as np from sklearn.metrics import confusion_matrix import argparse import logging import os from torch.utils.data import DataLoader from unet import UNet from utils.sar_dataset_loader import BasicDataset dataset_dir = './data/dataset/tes...
import digitalocean host_tag = 'ovirt-host' droplets = digitalocean.Manager().get_all_droplets() #droplets = digitalocean.Manager().get_all_droplets(tag_name=host_tag) for droplet in droplets: droplet.destroy()
import webbrowser import random import time while True: sites=random.choice(['google.com','amazon.in','flipkart.com','youtube.com']) visit="http://{}".format(sites) webbrowser.open(visit) seconds=random.randrange(0,2) #set time between 20 to 50 for testing time.sleep(seconds)
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
import codecs import os import sys import logging logging.basicConfig(filename="run.log", level=logging.INFO) def to_json(python_object): if isinstance(python_object, bytes): return {'__class__': 'bytes', '__value__': codecs.encode(python_object, 'base64').decode()} raise TypeError(rep...
import sys import itertools import pandas as pd from sklearn.model_selection import (StratifiedKFold, train_test_split, ParameterGrid, cross_val_score) from sklearn.metrics import balanced_accuracy_score from sklearn.base import clone import warnings from time import time from tempfile import mkdtemp from shutil import...
# type: ignore # flake8: noqa import os import sys import ray from ray import tune from sacred import Experiment # add project path to sys.path for easy import file_dir = os.path.dirname(os.path.abspath(__file__)) root_dir = os.path.abspath(os.path.join(file_dir, "..")) sys.path.append(root_dir) if not ray.is_initi...
import json import os import redis def run(): # 读取配置文件 with open('config.json', 'r', encoding='utf-8') as f: config = json.load(f).get('json_to_redis') if config is None: print('不能读取应用 `json_to_redis` 的配置。') exit() # 获取配置项 JSON_PATH = config.get('json_path') REDIS_HO...
"""Google's protocol buffer I/O support.""" import warnings import numpy as np from physt import __version__ from physt.histogram_base import HistogramBase from physt.io import require_compatible_version, create_from_dict from .histogram_pb2 import Histogram, Meta, HistogramCollection # Name of fields that are re-us...
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.alert import Alert from selenium.webdriver.support import expected_conditions as EC from selenium.common.excep...
# Copyright 2014 DreamHost, LLC # # Author: DreamHost, LLC # # 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 applicabl...
from typing import Any, List, Literal, TypedDict from .FHIR_code import FHIR_code from .FHIR_decimal import FHIR_decimal from .FHIR_Element import FHIR_Element from .FHIR_string import FHIR_string # An amount of economic utility in some recognized currency. FHIR_Money = TypedDict( "FHIR_Money", { # Un...
from tasks.supervised import SupervisedForecastTask __all__ = ["SupervisedForecastTask"]
#!/usr/bin/env python from tkinter import Tk, Spinbox import tkinter from tkinter.ttk import Style, Label, Button, Combobox top = Tk() Style().configure('TButton', foreground='white', background='red') Label(top, text='动物(成对的;最少:一对;最多:一打)').pack() Label(top, text='数量:').pack() Spinbox(top, from_=2, to=12, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # write a correct test! import unittest import pygimli as pg import numpy as np class TestMisc(unittest.TestCase): def test_Trans(self): """ """ f = pg.trans.Trans() x = pg.Vector(3, 1.0) np.testing.assert_array_equal(f(x), x...
from django.db import models from django.conf import settings import decimal, datetime from django.contrib.auth.models import AbstractUser class User(AbstractUser): #inherited from AbstractUser: #first_name #last_name #username #email #is_active #is_staff #date_joined #password? lemail = models.TextField(bl...
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'avocado', 'serrano', 'tests', 'tests.cases.base', 'tests.cases.resource...
#!/usr/bin/python import os import sys import struct import bsa import daggerfall.casttypes as casttypes class Tolerance(): def __init__(self, byte): self.toParalysis = bool(byte & casttypes.PARALYSIS) self.toMagic = bool(byte & casttypes.MAGIC) self.toPoison = bool(byte & casttypes.POI...
#!/usr/bin/env python """Exposes miscellaneous functions to interface with the CIL tool.""" """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 license and authors. """ import os import subproce...
from django.contrib.auth.models import User, Group from django.db.models import ( Model, TextField, DateTimeField, ForeignKey, CASCADE, OneToOneField, ManyToManyField, CharField, ) from asgiref.sync import async_to_sync from channels.layers import get_channel_layer class RoomModel(Mod...
# ------------------------------------------------------------------------ # Conditional DETR # Copyright (c) 2021 Microsoft. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from DETR (h...
#!/usr/bin/env python """ =========== {PROG} =========== ---------------------------------------------------- plot csv-ish input from stdin using matplotlib ---------------------------------------------------- :Author: skipm@trdlnk.com :Date: 2013-03-15 :Copyright: TradeLink LLC 2013 :Version: 0.1 :Manual section: 1...
class KNearestNeighbors: import numpy as np def __init__(self, n_neighbors=5): self.k = n_neighbors def fit(self, x, y): self.x = np.array(x) self.y = np.array(y) self.n_classes = len(np.unique(self.y)) # encode labels labels = np.unique(self.y) self....
import threading from thread import get_ident from collections import deque class Local(object): __slots__ = ('__storage__', '__ident_func__') def __init__(self): object.__setattr__(self, '__storage__', {}) object.__setattr__(self, '__ident_func__', get_ident) def __iter__(self): ...
import os from dotenv import load_dotenv, find_dotenv from requests import session import logging __author__ = "Gahan Saraiya" __all__ = ['TitanicDisaster'] class TitanicDisaster(object): def __init__(self): self.kaggle_login_url = 'https://www.kaggle.com/account/login' self.payload = { ...
import os, shutil import time import logging from pytest import approx from datetime import datetime from HSTB.kluster import fqpr_generation, fqpr_project, xarray_conversion, fqpr_intelligence try: # when running from pycharm console from hstb_kluster.tests.test_datasets import RealFqpr, RealDualheadFqpr, Synthe...
import os from pathlib import Path from joblib import dump, load from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from gensim.models import Word2Vec, Doc2Vec, FastText from gensim.models.phrases import Phrases from academia_tag_recommender.stopwords import stopwordlist from academia_tag_reco...
import os if "DISPLAY" not in os.environ: import matplotlib print("No DISPLAY found. Switching to noninteractive matplotlib backend...") print("Old backend is: {}".format(matplotlib.get_backend())) matplotlib.use('Agg') print("New backend is: {}".format(matplotlib.get_backend())) import utils.parall...
""" Operating on values of mappings (by default, dictionaries) while keeping keys aligned """ from linkup.base import ( map_op_val, key_aligned_val_op_with_forced_defaults, key_aligned_val_op, OperableMapping, )
from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from hub.models import (OneallToken, Company, Category, Job, JobApplication, IndeedJob, PremiumOrder, PaymentConfirmation) class OneallTokenAdmin(admin.TabularInline):...
from tkinter import * from tkinter.tix import Tk, Control, ComboBox # 升级的控件组包 from tkinter.messagebox import showinfo, showwarning, showerror # 各种类型的提示框 from tkinter import filedialog from PIL import Image, ImageTk from tkinter.messagebox import * import os import operator from numpy import * import cv2 from sklearn...
import numpy import chainer from chainer import backend from chainer.backends import cuda from chainer.backends import intel64 from chainer import configuration from chainer import function_node import chainer.functions from chainer.utils import argument from chainer.utils import conv from chainer.utils import type_ch...