text stringlengths 3.07k 12.6k |
|---|
from typing import List
import sys
EXTENSIONS = ["b", "bf"]
OPERATORS = [">", "<", "+", "-", ".", ",", "[", "]"]
def parse(program: List[str]) -> List[tuple]:
"""
Parse the program and convert to a way we can execute
:param program List[str]: Each line of the program
:return: Program we ... |
#This python file generates a kml file designated by periodic placemarks that can be used to visualise the data in an external API.
from math import radians, cos, sin, asin, sqrt
import os
import sys
import re
import time
from datetime import datetime, timedelta
def decimalat(DegString):
# This function r... |
from typing import TYPE_CHECKING
from rlcard.games.dummy.player import DummyPlayer
if TYPE_CHECKING:
from .game import DummyGame
import numpy as np
from rlcard.games.dummy.action_event import ACTION, get_action
from rlcard.games.dummy.utils import ID_2_ACTION
from .melding import *
from rlcard.games.dummy.action_... |
"""
Some of the code in this module was taken and modified from the python-colormath
package, which is located at
https://github.com/gtaylor/python-colormath
Below is the Copyright notice for that code:
Copyright (c) 2014, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.normal import Normal
from clustering.kmeans import lloyd
eps = 1e-8
class PlanarNormalizingFlow(nn.Module):
"""
Planar normalizing flow [Rezende & Mohamed 2015].
Provides a tighter bound on the ELBO by giving more ... |
import supervisely_lib as sly
import sly_globals as g
import tags_tab
import ui
import tag_utils
# to register callbacks
import sly_functions as f
@g.my_app.callback("manual_selected_image_changed")
@sly.timeit
@g.my_app.ignore_errors_and_show_dialog_window()
def image_changed(api: sly.Api, task_id, context, stat... |
import asyncio
from collections import Counter
from time import perf_counter
from twitch_client import TwitchClient
from streamer import StreamerPipe, Streamer
from colors import Col
from typing import Set
from dataclasses import dataclass
@dataclass
class FollowerNetwork:
streamer_id: str
min_mutual: int = 3... |
'''
https://github.com/hunkim/ReinforcementZeroToAll/blob/master/07_2_dqn_2013_cartpole.py
This code is based on:
https://github.com/hunkim/DeepRL-Agents
CF https://github.com/golbin/TensorFlow-Tutorials
'''
import numpy as np
import tensorflow as tf
import random
from collections import deque
import gym
env = gym.mak... |
from PyQt4 import QtCore
from xml.dom.minidom import parseString
import re
from xml.parsers.expat import ExpatError
__author__ = 'postrowski'
# -*-coding: utf-8-*-
class Playlist(object):
"""
Class Playlist which get information and show it.
"""
def __init__(self, parent):
self.nowPla... |
import cv2
from data.dataset import image_transforms
import matplotlib.pyplot as plt
import numpy as np
from os.path import exists
import torch
from tqdm import tqdm
from utils import dice_coef_metric, load_checkpoint, plot_plate_overlap
def predict_single(args, model, device, threshold=0.5):
image_path = args.... |
import argparse, os, json, io, re
from os.path import isfile, join
from os import listdir
def dir_path(string):
if os.path.isdir(string):
return string
else:
raise NotADirectoryError(string)
# Parse CONTROL File
def simpleInsert(dic, line):
dic[line.split(':')[0].strip()] = ':'.join([s.... |
import math
def create_data_set2():
data_set = [['青年', '高', 'yes'],
['青年', '高', 'yes'],
['青年', '中', 'yes'],
['青年', '中', 'yes'],
['青年', '中', 'yes'],
['青年', '中', 'yes'],
['青年', '中', 'yes'],
['青年', '低', 'y... |
from discord.ext import commands
from collections.abc import MutableMapping
from typing import Callable, Union
import asyncio
import aiofiles
import json
class TransformedDict(MutableMapping):
"""A pseudo-dictionary object"""
def __init__(self, *args, **kwargs):
self._store = dict()
self.upda... |
import dataclasses
import logging
from typing import Union, Tuple, List, Iterable
from cltl.combot.event.emissor import TextSignalEvent, AnnotationEvent
from cltl.combot.infra.config import ConfigurationManager
from cltl.combot.infra.event import Event, EventBus
from cltl.combot.infra.resource import ResourceManager
f... |
"""Tests for the climber module"""
# Copyright 2019 <NAME>
#
# 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... |
import os
import argparse
import random
import pandas as pd
import numpy as np
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
import sklearn
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.feature_selection impo... |
from sys import path
from colorama import Fore
from random import shuffle
from compilation.tokenizer import Tokenizer
from compilation.utils import split_lines
from compilation.parser import Parser
from simulation.environment import Environment
from simulation.rider import Rider
from simulation.bike import Bike
from ... |
"""
Data loading and plotting utility functions.
"""
import torch
from torchvision import datasets, transforms
import glob
from PIL import Image
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
import numpy as np
def load_data(dataset, batch_size, no_validation=False, shuffle=False, data_f... |
#blit7s: blit 7 segment
import pkg_resources as pkg
import os
import RPi.GPIO as GPIO
import time
def chart():
import subprocess, sys
cha=pkg.resource_filename("blit7s","chart.PNG")
opener ="open" if sys.platform == "darwin" else "xdg-open"
subprocess.call([opener, cha])
## except:
## import... |
import pyvibdmc as pv
import numpy as np
from scipy import interpolate
r1_eq = pv.Constants.convert(0.95784, 'angstroms', to_AU=True)
r2_eq = pv.Constants.convert(0.95783997, 'angstroms', to_AU=True)
theta_eq = np.deg2rad(104.5080029)
theta_freq = pv.Constants.convert(1668.4590610594878, 'wavenumbers', to_AU=True)
inv... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# All right reserved by <NAME>, Gdansk 2009
import numpy as np
from Point import Point
try:
from multiprocessing import Process, Queue, cpu_count
class Multi(Process):
pass
except ImportError:
from threading import Thread
from Queue import Queue
... |
"""Parser for KSPTOT bodies file"""
from math import pi
from orbit import Orbit
from body import Body
import re
def dicts_from_ini_file(ini, path=True):
if path:
data = open(ini, "r").read()
else:
data = ini
# removes semicolon comments
data = re.sub('(?m);.*', '... |
from datetime import datetime
try:
import configparser as parser
except ImportError:
import ConfigParser as parser
transaction_datetime = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
class VisaDirectTransactionModel(object):
"""Abstract VISA Transaction object model.
Constructs and pop... |
from PIL import Image
#THis was more about making the directory path and not building the plausible path
def get_destination_path(self):
while not self.cached_destination_path:
# sort out which root directory to use when searching for result
project_root_dir_prefix, project_num_prefix = ArchiverHelp... |
import json
import glob
import os
import re
import csv
from collections import defaultdict
######################################
##### GET NAMES OF DESIRED FILES #####
######################################
def get_file_names(rootdir):
comments_file_names = []
#or file.endswith(".h")
md_file_names = []
for root, ... |
import unittest
import pgn
def game_fixture():
game = pgn.PGNGame(
'F/S Return Match',
'Belgrade, <NAME>|JUG',
'1992.11.04',
'29',
'<NAME>.',
'<NAME>.',
'1/2-1/2'
)
game.annotator = 'Renato'
game.plycount = '3'
game.timecontrol = '40/7200:360... |
from argparse import ArgumentParser
import math
from typing import Callable
from convokit import Corpus, download
import numpy as np
from scipy.stats import mode
from sklearn.metrics import precision_recall_fscore_support
import torch
from torch import nn
from torch.cuda.amp import GradScaler, autocast
from torch.opti... |
import random
import threading
import time
import unittest
from chan import Chan, chanselect, quickthread
from chan import ChanClosed, Timeout
from chan.chan import RingBuffer
def sayset(chan, phrases, delay=0.5):
for ph in phrases:
chan.put(ph)
time.sleep(delay)
chan.close()
def distribute... |
import sys
from time import sleep, time
import dask
from dask.distributed import Client
from distributed.utils_test import loop # noqa: F401
import pytest
from dask_jobqueue import PBSCluster, MoabCluster
@pytest.mark.parametrize('Cluster', [PBSCluster, MoabCluster])
def test_header(Cluster):
with Cluster(wall... |
#!/usr/bin/python
#
# Generate fixed-size benchmarks from the descriptions in parametric Promela.
# To use this script, you should install bymc first:
#
# http://forsyte.at/software/bymc
#
# <NAME>, 2014
from genUtil import *
def gen_params_byz():
for n in range(3, 11):
for t in range(1, (n / 3 + 1) + 1)... |
import csv
import sys
import getopt
import json
import random
from collections import OrderedDict
def main(args):
try:
opts, _ = getopt.getopt(args[1:], 'ho:s:', ['help', 'output=','seed='])
except getopt.GetoptError as err:
print(err)
usage()
sys.exit(2)
outputFormat = 'pr... |
import sys
import tempfile
import subprocess
from collections import namedtuple
import djclick as click
import xml.etree.ElementTree as etree
from django.core.management.base import CommandError
from typing import List, Any
# This is based on:
#
# https://gist.github.com/danielrehn/d2e6f2129e5f853c3166
RAINBOW_COLOR... |
import sys
import os
from typing import List, Union, Tuple, Dict
from MMOEASA.mmoeasaSolution import MMOEASASolution
from Ombuki.ombukiSolution import OmbukiSolution
from FIGA.figaSolution import FIGASolution
from problemInstance import ProblemInstance
from data import open_problem_instance
from MMOEASA.mmoeasa import ... |
"""
Finetuning the BERT model for topic shift classification on WIKI_727K.
"""
import os
import sys
import logging
import argparse
import numpy as np
import pandas as pd
import ipdb as pdb
import time
from tqdm import tqdm
from collections import defaultdict
import transformers
from transformers import BertModel, Bert... |
import io
import csv
from collections import defaultdict
from django.db import connections
from django.db.models import Count, Q
from capdb.models import Reporter, Jurisdiction, CaseMetadata, Snippet, Court
import json
from capweb.templatetags.api_url import api_url
from tqdm import tqdm
def update_all():
update... |
from graphicslib import pighelp
import time
import pigpio
import math
# this code was taken from the Adafruit_PWM_Servo_Driver
# a small bug was fixed for full on
# and it was modified to use pigpio and print
class PwmDevice():
# Registers/etc.
__MODE1 = 0x00
__MODE2 = 0x01
... |
import numpy as np
import argparse
from tensorflow.keras.layers import Input, Flatten, Dense, Reshape, Dropout, Embedding, Multiply, Activation, Conv2D, ZeroPadding2D, LocallyConnected2D, Concatenate, GRU, Lambda, Conv2DTranspose
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers impor... |
import numpy as np
import os.path as osp
import torch
import torch.nn.functional as F
from data_class import prepare_raw_dataset_edge, prepare_raw_dataset_node, full_geo_Abakan
from torch_geometric.data import Data
import pandas as pd
import numpy as np
from evaluate_points import prepare_dataset, prepare_args, prepar... |
import matplotlib.pyplot as plt
import torch
from random import choice
from typing import Tuple
import numpy as np
def visualize_input_tensor(input_tensor):
rows, cols, axes, = 2, 4, []
figs = input_tensor.shape[0]
fig = plt.figure(figsize=(20, 6))
for a in range(figs):
b = input_tensor[a]
... |
#%%
import time
import numpy as np
import scipy.stats
import matplotlib.pyplot as plt
import logging
logging.basicConfig(level=logging.INFO) # sometimes this is required to enable logging inside Jupyter
# %matplotlib inline
# %precision 2
# Set an arbitrary seed and a global random state to keep the randomly genera... |
import unittest
from operator import (
attrgetter,
)
from unittest.mock import (
patch,
)
from uuid import (
UUID,
uuid4,
)
from minos.aggregate import (
Action,
Entity,
EntitySet,
IncrementalSetDiff,
IncrementalSetDiffEntry,
)
from minos.common import (
NULL_UUID,
Declarati... |
import numpy as np
import keras
from keras.initializers import RandomNormal
from keras.layers import Dense, LeakyReLU
from keras.regularizers import l2
import chess_environment.chessboard as cb
from dqn_tools.memory import SimpleMemory
from dqn_tools.trainers import DQNTrainer, load_trainer
from training_tools import ... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from joblib import Memory
import datetime
from azure_table_interface import query_aq_data
# Set up caching for the Azure table access
memory = Memory('./_cache_')
ID_to_name = {'nesta-1': 'Priory Rd (South)',
'nesta-2': 'Priory Rd ... |
"""Test script for the Facebook Detectron."""
# Copyright (c) 2022, ABB
# 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 copyri... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from transformers import Wav2Vec2Tokenizer
import numpy as np
import json
import re
from typing import List, Union
import yaml
import argparse
from pathlib import Path
MODEL_NAME = "facebook/wav2vec2-large-960h-lv60-self"
MS = 0.02 # tokens per seconds output of wav2vec 2.0
EXTRA_MS = 3 # this number of MS are expa... |
import torch
import random
import torch.autograd as autograd
import torch.nn as nn
import os
from utils.conf import args, set_random_seed
from models.Seq2Seq import Seq2Seq
from preprocesses.DataIterator import FruitSeqDataset
from preprocesses.Voc import Voc
def train_epoch(model, data_batch, param_optimizer, decod... |
# @file
# Descriptor definition for BIOS Sub Regions
#
# Copyright (c) 2019, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause
#
import json
import uuid
FMP_CAPSULE_TSN_MAC_ADDRESS_FILE_GUID = uuid.UUID("6fee88ff-49ed-48f1-b77b-ead15771abe7")
FMP_CAPSULE_TSN_IP_CONFIG_FILE_GUID = uuid.UU... |
"""Contains classes describing linguistic tasks of interest on annotated data."""
import numpy as np
import torch
import string
class Task:
"""Abstract class representing a linguistic task mapping texts to labels."""
@staticmethod
def labels(observation):
"""Maps an observation to a matrix of labels.
... |
import json
import os
import sys
import struct
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(os.path.abspath(__file__))) # model
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.use('Agg')
def save_sdf_bin(bin_fn, output_sdf, res):
f_sdf_bin = ... |
# **************************************************************************** #
# #
# ::: :::::::: #
# ISE.py :+: :+: :+: ... |
import sys
import os
import dlib
import glob
from skimage import io
import numpy as np
import cv2
import mxnet as mx
import cv2
import os
import time
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics.pairwise import euclidean_distances
predictor_path = 'shape_predictor_68_face_landmarks.dat'
face... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import pytest
import scanpy as sc
import scanpy.external as sce
from anndata.tests.helpers import assert_equal
import pandas as pd
import anndata as ad
from scanpy.get import _get_obs_rep
import numpy as np
import scanpy.preprocessing as pp
import scipy.sparse as sparse
def test_scrublet():
"""
Test that Scr... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "l... |
from math import sqrt
import pathlib
import time
import numpy as np
import torch
from nqs_playground import *
from nqs_playground.core import Unpack
from nqs_playground._tabu_sampler import _sample_using_zanella
from nqs_playground.monte_carlo import _log_amplitudes_to_probabilities
np.random.seed(1183472)
torch.manua... |
#!/usr/bin/env python3
from netmiko import ConnectHandler
import random
import json
import click
import csv
from collections import defaultdict
import pprint as pp
import logging
hp_procurve = {
'device_type': 'hp_procurve',
'ip': '10.0.1.11',
'username': 'manager',
'password': '<PASSWORD>',
'port... |
from gensim.models import KeyedVectors
from tqdm import tqdm
import pandas as pd
import numpy as np
import multiprocessing as mp
import argparse
import pickle
import json
import time
import os
import sys
sys.path.append('../')
from feature_modeling import FeatureModelingTool
from isanlp_srl_framebank.convert_corpus_... |
# coding=utf-8
import importlib
import configobj
from lxml import html
import requests
import randua
import dotmap
from . import utils, logger, decorators, constants
class Settings(object):
"""Class for keep settings from configuration file."""
def __init__(self, filename):
"""
Initializa... |
import numpy as np
#
# Copyright (c) 2014-2022 The Voxie Authors
#
# 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 the rights
# to use, copy,... |
# -*- coding: utf-8 -*-
import json
import logging
from pale.errors import ArgumentError
from pale.fields import BaseField
class BaseArgument(BaseField):
"""The base class for Pale Arguments.
Arguments in this context are values passed in to Pale Endpoints from the
HTTP layer. These Argument objects are... |
import wx
### from wx import ALIGN_BOTTOM, ALIGN_CENTER, ALIGN_LEFT, ALIGN_RIGHT, ALL, HORIZONTAL, VERTICAL, ID_ANY, EXPAND, RAISED_BORDER, SL_HORIZONTAL
### from wx import EVT_BUTTON, EVT_SCROLL_THUMBRELEASE, FONTFAMILY_DEFAULT, FONTSTYLE_NORMAL, FONTWEIGHT_NORMAL
### from wx import BoxSizer, Button, CallLater, CheckB... |
import os
import struct
import pytest
from contextlib import closing
import numpy as np
from taskloaf.allocator import *
block_manager = BlockManager('/dev/shm/pool', taskloaf.shmem.page4kb)
def get_memory_used():
import os
import psutil
process = psutil.Process(os.getpid())
return process.memory_inf... |
# Funcția Fernet este folosită la criptarea și decriptarea mesajului
# Fernet reprezintă o implementare a criptării simetrice
from cryptography.fernet import Fernet
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
class Encryptor():
# Funcția de generare a cheii (aceasta este de... |
from example import *
import pytest
def test_c2f():
#assert some right cases
assert c2f(0) == 32.00
assert c2f(100) == 212.00
assert c2f(999) == 1830.20
#assert some error here
assert c2f("String") == "ERROR -----> It is not a number"
assert c2f("-123") == "ERROR -----> It is not a number"
assert c2f("... |
# import classes
from MonteCarlo.SpinConfiguration import *
from MonteCarlo.SingleDimensionHamiltonian import *
import matplotlib.pyplot as plt
import math
# for now only produces the configurations with two elements, should change soon
def generateSpinConfigurations(n):
"""Calculates a list of all possible spin... |
from discord.ext import commands
import discord
from math import ceil
from humanfriendly import format_timespan
class Help(commands.Cog):
def __init__(self, client):
self.client = client
self.info = {
"passthebomb": "Come up with a word quickly, or the bomb will explode on yo... |
COMPARISONS = {
'!=': 'NOTEQUAL',
'==': 'ISEQUAL',
'>=': 'GTE',
'>': 'GT',
'<=': 'LTE',
'<': 'LT',
}
OPERATORS = {
'-': 'MINUS',
'+': 'PLUS',
'/': 'SLASH',
'*': 'TIMES',
}
DELIMITERS = {
'(': 'OPEN_PAREN',
')': 'CLOSE_PAREN',
'{': 'OPEN_BRACE',
'}': 'CLOSE_BRACE... |
#!/usr/bin/env python
#
#
# TODO:
# - implement cProfile or yappi, or use threading.setProfile and sys.setProfile, or implement one's own multi-threaded profiler:
# http://code.google.com/p/yappi/
# http://code.activestate.com/recipes/465831-profiling-threads/
# http://effbot.org/librarybook/sys.htm
#
#
# CHANGELOG:
#... |
import json
import requests # to get image from the web
import shutil # to save it locally
import uuid
import webbrowser
import os, re
path = "/proc/self/cgroup"
DEFAULT_COLOR = "#505558"
UPLOAD_FOLDER = os.getcwd()+'/uploads/'
SETTINGS_FOLDER = os.getcwd()+'/settings/'
ALLOWED_EXTENSIONS = set(
['txt', 'pdf',... |
# coding=utf-8
import numpy as np
import pandas as pd
from loganalysis.log import Log
from loganalysis.log import LogFile
from loganalysis.const import *
from loganalysis.lte.ue import Ue
from loganalysis.lte.cell import Cell
class LteLog(Log):
''' LTE调度模块Log分析接口类
主要提供如下3类功能:
a) 信息呈现
b)问题发... |
import random
import uuid
from django.contrib import auth
from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
# Create your models here.
from django.utils.safestring import mark_safe
from libraryMgntSystem.validators import EmailValidator
class BaseModel(models.Model):... |
'''
utilities functions here
'''
import json
import socket
import struct
from bitarray import bitarray
def objEncode(obj):
""" obj,返回binary对象 """
return json.dumps(obj,indent=4, sort_keys=True,separators=(',',':')).encode('utf-8')
def objDecode(binary):
""" binary 返回dict对象 """
return json.loads(binary... |
from django.db import models
from django.contrib.auth.models import User
class AuthGroup(models.Model):
name = models.CharField(unique=True, max_length=80)
class Meta:
db_table = 'auth_group'
class AuthGroupPermissions(models.Model):
group = models.ForeignKey(AuthGroup, models.DO_NOTH... |
import pygame
import math
from queue import PriorityQueue
#Window
WIDTH = 800
WIN = pygame.display.set_mode((WIDTH,WIDTH))
pygame.display.set_caption("A* Path Finding Algo")
FPS = 60
#Color
BLACK = (0,0,0)
WHITE = (255,255,255)
GREY = (128, 128, 128)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
PURPLE = (128, 0... |
# -*- coding: utf-8 -*-
from PySide6.QtCore import (
QSettings,
Signal
)
from PySide6.QtGui import *
from PySide6.QtWidgets import *
from .mergetool import MergeTool
import os
is_win = (os.name == "nt")
def fixedFont(pointSize):
"""return a fixed font if available"""
font = QFont("monospace", poin... |
import asyncio
import uuid
from datetime import timedelta
from typing import Any, Callable, List, NoReturn, Optional, Tuple, Type
from temporalio import activity, workflow
from temporalio.client import Client
from temporalio.worker import (
ActivityInboundInterceptor,
ActivityOutboundInterceptor,
ContinueA... |
import unittest
import yota
from yota.validators import *
from yota.nodes import *
from yota.exceptions import *
class TestValidators(unittest.TestCase):
""" Testing for all our built-in validators """
def run_check(self, values, validator):
""" a utility method to run the check by hand. Pass it key ... |
#!/usr/bin/python
# Copyright (c) 2018, Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for detail... |
from qdep.internal.common import *
def dephash(*packages, project=False, pkgpath=False):
for package in packages:
pkg_url, pkg_branch, pkg_path = package_resolve(package, project=project)
if pkgpath:
print(pkg_hash(pkg_url, pkg_path) + ";" + pkg_path)
else:
print(pkg_hash(pkg_url, pkg_path))
def pkgres... |
from django.shortcuts import render, redirect, HttpResponseRedirect
from .models import Post
from .forms import postForm
from django.contrib.auth.decorators import login_required
from accounts.models import Account, User
from django.contrib import messages
from .forms import postForm, postEditForm
from comments.models ... |
# Copyright (c) 2018 Graphcore Ltd. All rights reserved.
import enum
from enum import Enum
import fnmatch
import functools
import inspect
import os
import re
from typing import Dict
import pytest
import popart
def filter_dict(dict_to_filter, fun):
sig = inspect.signature(fun)
filter_keys = [
param.n... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Imported from the Kubespray project and modified by École
# Polytechnique Fédérale de Lausanne; see ../LICENSE
from io import StringIO
import yaml
from ansible.module_utils.six import string_types
from ansible.plugins.action import ActionBase
from ansible.parsing.yaml.obje... |
import pywikibot, re, requests, os, toolforge
from datetime import date, timedelta
yesterday = date.today() - timedelta(1)
lastday = yesterday.strftime('%Y/%m/%d')
#os.chdir(r'projects/lv')
headers = {
'User-Agent': 'w:lv:User:Edgars2007/Missing popular2'.encode('utf8')
}
LANG_FOR = 'lv'
def chunks(l... |
# Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file accom... |
import os
import sys
from math import ceil
from pathlib import Path
from textwrap import wrap
from typing import Union
import matplotlib.pyplot as plt
import pandas as pd
class GenericError(Exception):
pass
def plot(base_path: str,
mod_path: str,
cols: Union[str, list] = None,
low_ro... |
import os
import h5py
import glob
import tensorflow as tf
import threading
from src.utils.stopwatch import StopWatch
from src.utils.averagenumber import AverageNumber
from src.utils.timeframe import TimeFrame
import numpy as np
import sys
import time
max_threads = 8
goal_folder = os.path.abspath(os.path.join(os.path.... |
import os
import subprocess
from collections import deque
from pathlib import Path
import tomlkit
import typer
from graiax.cli.prompt import Choice
from ..prompt.export import BooleanPrompt, FChoice, SelectPrompt
from ..util import pprint
extras_intro = """<b><cyan>\
Scheduler: 任务计划器
Alconna: 复杂但强大的命令解析器
FastAPI: 用... |
"""Class for reading the output.cmd file from calcsfh"""
from __future__ import print_function
import argparse
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
from match.scripts.config import EXT, match_base
from match.scripts.fileio import read_match_cmd
from match.scripts.graphics import mat... |
#!/usr/bin/env python
# # -*- coding: utf-8 -*-
"""
Contains tools for helping set up matplotlib keywords, defaults, and drawing objects, like PyQt pens.
Also has the more complicated plot keyword translator that uses basic translations and the tools.
"""
# Basic imports
from __future__ import print_function, divisi... |
import os
import time
import numpy as np
HMNIST_PATH = os.path.join('hmnist', 'hmnist_mnar.npz')
ZEROS = np.zeros(shape=(64, 64, 3))
N1 = 9000 # reduce 60000 to 9000
N2 = 2664 # reduce 10000 to 2664
F = 8
def _retrieve_by_key(path, key):
with np.load(path) as data:
output = data[key]
return output
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Colony Framework
# Copyright (c) 2008-2020 Hive Solutions Lda.
#
# This file is part of Hive Colony Framework.
#
# Hive Colony Framework is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apach... |
from typing import Optional, List, Tuple, Dict
from sinkhorn import compute_alignment_cost, compute_entropy
import torch
import numpy as np
from classify.metric.abstract import AlignmentAverageMetric
from utils.utils import prod
from sklearn.metrics import f1_score, precision_score, recall_score
def compute_raionale... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
# from tracemalloc import start
from flair.data import Sentence
from flair.models import SequenceTagger
from flair.models.sequence_tagger_model import MultiTagger
from flair.data import Token
from tqdm import tqdm
import base as be
import mspacy as msp
class Flair:
"""Base class for Flair, reads in the basic para... |
import sublime
import sublime_plugin
import os.path
import re
import json
from . import cache
from . import logger
from . import tools
log = logger.getLogger(__name__)
class LtxCompletionsListener(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
if not view.matc... |
# log21.StreamHandler.py
# CodeWriter21
import os as _os
import re as _re
from logging import StreamHandler as _StreamHandler
from log21.Colors import ansi_esc, get_colors
__all__ = ['IS_WINDOWS', 'ColorizingStreamHandler', 'StreamHandler']
IS_WINDOWS = _os.name == 'nt'
if IS_WINDOWS:
import ctypes
class Stre... |
import torch
class BaseFeedWrapper(object):
"""A base class for feed wrappers."""
def __init__(self, feed):
self.feed = feed
def __iter__(self):
raise NotImplementedError
def __len__(self):
return len(self.feed)
def __repr__(self):
return f"{type(self).__name__}... |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015, 2016 <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publish... |
import sys
import numpy as np
from os.path import join, dirname, basename, splitext
import progressbar
import glob
import numbers
import pandas as pd
import cv2
import io
import h5py
import argparse
import zipfile
import utils
from datasets.preprocessing import imencode, depth_centered_keypoints, \
extended_key_po... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.