text stringlengths 3.07k 22.1k |
|---|
import tkinter
from PIL import *
import tkinter as tk
from tkinter import Button, Entry, Image,Menu, Label, OptionMenu, StringVar, Toplevel,filedialog, ttk, NSEW
import PIL
from ttkthemes import themed_tk as tkt
import time
import os
# Free to use and edit - Credit to youtube and various websites for helpin... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
# ERPNext - web based ERP (http://erpnext.com)
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json
import http.client
import mimetype... |
"""Module Description
Copyright (c) 2009 <NAME> <<EMAIL>>
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD License (see the file COPYING included with
the distribution).
@status: experimental
@version: $Revision$
@author: <NAME>
@contact: <EMAIL>
"""
# -------------... |
"""Support for RFXtrx devices."""
import binascii
from collections import OrderedDict
import logging
import RFXtrx as rfxtrxmod
import voluptuous as vol
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_STATE,
CONF_DEVICE,
CONF_HOST,
CONF_PORT,
EVENT_HOMEASSISTANT_START,
EVENT_HOMEASS... |
from random import randint
from sympy import Eq, symbols, solve, Mul, Add, sqrt, simplify, expand, factor
from sympy.printing import latex
# initialise used symbols
x, y = symbols(" x y ")
def quadratic():
# function that generates the question and solutions based on quadratic equation
# quadrati equation v... |
#!/usr/bin/env python
import datetime
import json
import os
import pathlib
import re
import sys
from typing import List, Optional, Tuple
from vaccine_feed_ingest_schema import location as schema
from vaccine_feed_ingest.utils.log import getLogger
from vaccine_feed_ingest.utils.validation import BOUNDING_BOX
logger ... |
# Copyright 2020 LMNT, Inc. 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 applicable law or ag... |
"""Module: Base Generator"""
import re
import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import List, Dict, Union, Any
from swagger2locustio.templates import locustfile_templates as l_templates
from swagger2locustio.templates import helpers_templates
from swagger2locustio.te... |
import pandas as pd
from fuzzywuzzy import fuzz
import numpy as np
import scipy.cluster.hierarchy as spc
from scipy.stats import rankdata
from itertools import compress
from typing import Callable
def compute_fuzzy_matrix(strings: list, ratio: Callable = None) -> pd.DataFrame:
"""Compute Matrix with Fuzzy Ratios
... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import cv2
import matplotlib.pyplot as plt
import numpy as np
import random
# In[2]:
# Read image and convert them to gray!! we need to use rgb2gray not bgr2gray
def read_image(path):
img = cv2.imread(path)
img_gray= cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
... |
# 正式bili小程序
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import biliClass.biliAid as biliv
import biliClass.biliMid as biliu
win = tk.Tk()
win.title('BiliTools (测试版v0.2)')
# win.geometry('400x400')
# 菜单部分
# menubar = tk.Menu(win)
# menu_set = tk.Menu(menubar,tearoff=0)
# menubar.add_ca... |
#!/usr/bin/env python3
'''
passthroughfs.py - Example file system for python-llfuse
This file system just mirrors the contents of a specified directory
tree.
Copyright (C) <NAME> <<EMAIL>>
This file is part of python-llfuse (http://python-llfuse.googlecode.com).
python-llfuse can be distributed under the terms of th... |
import paho.mqtt.client as mqtt
# import paho.mqtt.publish as publish
from ssl import PROTOCOL_TLSv1_2, CERT_REQUIRED, SSLError
from time import sleep, time
import random
# Configurações para usar os models do django
import os
import sys
import django
sys.path.insert(0, os.path.abspath(os.path.join(__file__, "../../..... |
import nipype.pipeline as pe
from nipype.interfaces.utility import Function
import numpy as np
def set_postfix(in_file, postfix):
""" Sets a postfix identifier for a specific filename. """
import os.path as op
return op.basename(in_file).replace('.nii.gz', '_%s' % postfix)
Set_postfix = Function(function... |
load("@bazel_version//:bazel_version.bzl", "bazel_version")
load("@bazel_skylib//lib:versions.bzl", "versions")
def sonarqube_coverage_generator_binary():
if versions.is_at_least(threshold = "2.1.0", version = bazel_version):
deps = ["@remote_coverage_tools//:all_lcov_merger_lib"]
else:
deps = ... |
"""Worker.
A "worker" starts a single instance of a Faust application.
See Also:
:ref:`app-starting`: for more information.
"""
import asyncio
import logging
import os
import sys
from collections import defaultdict
from itertools import chain
from pathlib import Path
from typing import Any, Dict, IO, Iterable, M... |
"""
genetic_salesman.py
Heuristic travelling salesman solver using genetic optimisation
"""
import random as rng
import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
np.random.seed(1)
class NodeList(object):
"""
A set of nodes implemented with comp... |
import numpy as np
import random
import copy
from collections import namedtuple, deque
from model import Actor, Critic
import torch
import torch.nn.functional as F
import torch.optim as optim
BUFFER_SIZE = int(1e5) # replay buffer size
BATCH_SIZE = 250 # minibatch size
GAMMA = 0.99 # discount fact... |
import numpy as np
import json
import re
import copy
import random
# test scripts:
# import json
# json.load(open('scriptfile.json'))
# helper function to write pretty output
def writescript(scriptdictlist, sfname, scriptdir='/data/exposure_scripts/'):
sfnameout = scriptdir + '/' + sfname + '.json'
with open(... |
import numpy as np
from scipy.special.basic import psi
from bayesian_combination.annotator_models.cm import ConfusionMatrixAnnotator
def state_to_alpha(logodds, var):
'''
Map the latent state moments to parameters of a Beta distribution.
:param logodds:
:param var:
:return: the first beta paramet... |
from __future__ import unicode_literals, division, absolute_import, print_function
import inspect
import logging
import re
import textwrap
from datetime import datetime, timedelta
from asn1crypto import x509, keys, core, ocsp
from asn1crypto.util import timezone
from oscrypto import asymmetric
def build(self, respo... |
"""
Copyright (C) 2018 Ridgeback Network Defense, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to... |
import time
import numpy as np
import torch
from pytorch_lightning import seed_everything, Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
from tqdm import tqdm
import corai
from config import ROOT_DIR
from corai.src.classes.pl.histo... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import backtrader as bt
import Backtrade.__main__ as main
import pandas as pd
import datetime
import Backtrade.Strategy_Calculations as SDC
import numpy as np
import os.path
home = os.path.expanduser("~")
BT_ho... |
import torch
import torch.nn as nn
import torchvision
class ResBlock(nn.Module):
def __init__(self, input_channel, \
channel_list = [64, 64, 256], is_first=False):
super(ResBlock ,self).__init__()
self.channel_list = channel_list
self.input_channel = input_channel
self.i... |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import arviz as az
def get_color(key):
""" return color for class key"""
color_dict = {0: "blue", 1: "red", 2: "green", 3: "orange", 4: "black"}
return color_dict[key]
def get_color_mean(key):
""" return mean color for class key"""... |
"""Utility functions for BERT squad data preprocessing"""
__all__ = [
'tokenize_and_align_positions', 'get_doc_spans',
'align_position2doc_spans', 'improve_answer_span', 'check_is_max_context',
'convert_squad_examples'
]
import collections
def tokenize_and_align_positions(origin_text, start_position, en... |
from torch.utils.data import DataLoader
from torch.utils.data import RandomSampler, SequentialSampler
from transformers import AdamW
from transformers import get_linear_schedule_with_warmup
from tqdm import tqdm, trange
import torch
import re
import logging
import os
import pandas as pd
import numpy as np
import random... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# 代码有问题别找我!虽然是我写的,并且我觉得它是没问题的,如果不是你的操作原因,或许是它自己长歪了!
"""
###############################################################################
BamAlignmentViewer
A program for plot the reads covered target position for BAM sequence alignment
files.
Author: JoeyHwong (<EMAIL>)
L... |
import unittest
import numpy as np
from scipy.spatial.transform import Rotation
from d3d.dataset.kitti import KittiObjectClass
from d3d.abstraction import Target3DArray, ObjectTarget3D, ObjectTag, TrackingTarget3D
from d3d.benchmarks import DetectionEvaluator, DetectionEvalStats, TrackingEvaluator
class TestDetection... |
# coding:utf-8
import random
import json
import os
import glob
from faker import Faker
fake = Faker('ja_JP')
Faker.seed(19700101)
random.seed(19700101)
DESCRIPTION_LINES_FILE = "./description.txt"
OUTPUT_SQL_FILE = "./result/1_DummyEstateData.sql"
OUTPUT_TXT_FILE = "./result/estate_json.txt"
VERIFY_DRAFT_FILE = "./res... |
#!/usr/bin/env python
"""
Graph playbook folder and role dependencies for OpenShift Ansible
"""
from __future__ import print_function
import os
from glob import glob
import subprocess
import pygraphviz as pgv
import yaml
# This constant can be used to control which folders are excluded from the graph
SKIP_FOLDERS = ... |
"""
Module to read / write Fortran unformatted sequential files.
This is in the spirit of code written by <NAME> and <NAME>.
"""
import warnings
import numpy as np
__all__ = ['FortranFile', 'FortranEOFError', 'FortranFormattingError']
class FortranEOFError(TypeError, IOError):
"""Indicates that the file ended ... |
#
# Copyright 2019 The FATE 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 appli... |
#!/usr/bin/env python3
from flask import Response, Flask, request
import redis,hiredis
import operator
import time
import ujson as json
app = Flask(__name__)
def isInt(astring):
""" Is the given string an integer? """
try: int(astring)
except ValueError: return 0
else: return 1
@app.route("/test")
d... |
# codplayer - Message hub core
#
# Copyright 2015 <NAME> <<EMAIL>>
#
# Distributed under an MIT license, please see LICENSE in the top dir.
"""This module provides a thin message hub abstractions on top of
ZeroMQ to make it easy to wire together different components and
daemons without having to know exactly how they ... |
"""A module for handling the project login related tasks."""
import time
import hashlib
import json
import re
import base64
import binascii
# aiohttp
import aiohttp.web
import keystoneauth1.exceptions.http
from multidict import MultiDictProxy
import typing
import urllib.error
from swift_browser_ui.ui._convenience ... |
from __future__ import annotations
from contextlib import contextmanager
from dataclasses import dataclass
from enum import Enum
from typing import Callable, Dict, Iterable, Iterator, List, Optional, Type
from commonmodel.base import Field, Schema, SchemaTranslation
from commonmodel.field_types import FieldType
from ... |
# Copyright 2020 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... |
# Implementation of "Thinking Like Transformers" (https://arxiv.org/pdf/2106.06981.pdf)
# full repo: https://github.com/tech-srl/RASP
# @yashbonde - 18.06.2021
# MIT License
#
# Why build this?
# - learning how to write languages is the best way to learn how to minimise useless shit
# and maximise simplicity of code ... |
import os
import sys
import time
from pathlib import Path
from collections import defaultdict
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils import clip_grad_norm_
import os
from loss.loss import sisnr_loss
sys.path.append(
os.path.dirname(__file__))
from logger.log... |
import logging
import os
from typing import Any, Tuple
import numpy as np
import eit_model.setup
import eit_model.fwd_model
import glob_utils.file.mat_utils
import glob_utils.file.utils
import glob_utils.args.check_type
from scipy.sparse import csr_matrix
from pyeit.mesh import PyEITMesh
## ===========================... |
# Copyright 2021 The usbmon-tools 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 t... |
# -*- coding: utf-8 -*-
#
# app 'account' models
# registration
#
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import login
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import pre_delete
from... |
from functools import partial
from glob import glob
from multiprocessing import Pool
from pprint import pprint
from typing import Dict
import os
import pickle as pkl
from Bio import SeqIO
import tensorflow as tf
from .remote_homology_serializer import serialize_remote_homology_sequence
from .vocabs import PFAM_VOCAB
... |
# This file is a part of Lector, a Qt based ebook reader
# Copyright (C) 2017-2019 BasioMeusPuga
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your o... |
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from time import sleep
import click
from apscheduler.schedulers.background import BackgroundScheduler
from requests.exceptions import ConnectionError
from . import BRANCH
from . import VERSION
from .lib.config import Config
fro... |
"""Motor blocks.
For now homing is implemented as *homing generators*. This might seem overly
complicated but we do this so that we can move blocking aspects to the caller
and home multiple motors / nodes in parallel. This results in quasi coroutines.
We do not use asyncio because we want to keep the core async free f... |
"""
Simple utils to get stuff out of Mappings (dict-like objects).
"""
import operator
from functools import reduce # forward compatibility for Python 3
from typing import Any
class NotSpecified:
pass
def key_chain(d, /, *keys, dflt: Any = NotSpecified):
"""Get a value from a mapping, from a list of possib... |
from .client import ActivityInfoClient
from .models import *
import copy
""" Reformatting json structure for each database """
def import_data_v4(ai_db):
client = ActivityInfoClient(ai_db.username, ai_db.password)
# main_db_id = ReportingYear.objects.get(current=True).database_id
main_db_id = ai_db.rep... |
'''Get the raw data from the DB, clean and organize it.
This script gets the raw dataset with all rent offers in the predefinated cities
in Germany, separate the meaningful information, clean it and organize it in
different columns.
Returns a new dataframe read to be used.
'''
# imports
import re
import os
impo... |
#!/usr/bin/env python
# (c) Copyright 2010 Cloudera, Inc.
import logging
import os
import re
try:
import simplejson
except ImportError:
import json as simplejson
import sys
from git_command import GitCommand
from git_repo import GitRepo
import trace
class Manifest(object):
def __init__(self,
bas... |
'''
Object that encapsulates the logic for handling communications between a
USB-attached pendant and a USB-attached GRBL-based CNC controller.
Fires up a pair of threads -- one for taking input from the pendant, updating
the local state, and sending (G-Code) commands to the grbl controller, and
another for taking ... |
import pytest
import json
import time
import brownie
@pytest.fixture(scope="module", autouse=True)
def invalid_collateral(weth):
return weth.address;
def user(accounts):
return accounts[9]
def mintUSDs(
amount,
usds_proxy,
spa,
vault_proxy,
owner,
usdt
):
deadline = 1637632800... |
# Test image_detail and image_detail_edit views.
import datetime
from bs4 import BeautifulSoup
from django.urls import reverse
from lib.tests.utils import BasePermissionTest, ClientTest
class PermissionTest(BasePermissionTest):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
... |
from datetime import date, datetime, time
from icemac.addressbook.i18n import _
import grokcore.component as grok
import icemac.ab.calendar.browser.base
import icemac.ab.calendar.browser.interfaces
import icemac.ab.calendar.event
import icemac.ab.calendar.interfaces
import icemac.addressbook.browser.base
import icemac.... |
"""
Radiant
"""
# Prevent this file to be imported from Brython
import sys
try:
import browser
sys.exit()
except:
pass
import os
import json
import jinja2
import pathlib
import importlib.util
from xml.etree import ElementTree
from typing import Union, List, Tuple, Optional
from tornado.web import Applica... |
import skimage.measure as measure
from skimage.morphology import disk
from features.Blobs_VerticalLines import *
#CREDITS TO Learn python and open cv documentation
def fillHole(img):
im_in = img
th, im_th = cv2.threshold(im_in, 220, 255, cv2.THRESH_BINARY_INV)
im_floodfill = im_th.copy()
h, w = im_th.... |
import os
import matlab.engine
from src.behavioral_cloning import BehavioralCloning
from src.experience import ExperienceSourceDiscountedSteps
from src.policies import DDPGPolicy, PerturbObservePolicy
from src.pv_array import PVArray
from src.pv_env import PVEnv
from src.reward import RewardPowerDeltaPower
from src.u... |
"""
Copyright (c) 2016 <NAME>, <NAME>
Under MIT License - https://github.com/Step7750/ScheduleStorm/blob/master/LICENSE.md
This file is a resource for Schedule Storm - https://github.com/Step7750/ScheduleStorm
"""
import threading
import requests
import pymongo
from bs4 import BeautifulSoup
import time
import re
fro... |
# Copyright 2016 <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
__all__ = ['HolzworthHS9000']
from .instrument import Instrument, M... |
import numpy as np
import matplotlib.pyplot as pyplt
import clarity.IO as io
import cv2, sklearn, os, time, sys, bcolz, pickle
import scipy.ndimage.filters as fi
import matplotlib.pyplot as pyplt
import clarity.Visualization.Plot as plt
import multiprocessing as mp
from functools import partial
def save_... |
# -*- coding:utf-8 -*-
"""
Simple static page generator.
Uses Jinja2 to compile templates.
"""
from __future__ import absolute_import
import inspect
import logging
import os
import re
import shutil
import warnings
from jinja2 import Environment, FileSystemLoader
from .reloader import Reloader
def _has_argument(... |
import optparse
import sys
import re
import string
from pyang import plugin
from pyang import statements
def pyang_plugin_init():
plugin.register_plugin(HyperTreePlugin())
class HyperTreePlugin(plugin.PyangPlugin):
def add_output_format(self, fmts):
self.multiple_modules = True
fmts['hypertr... |
# Copyright (c) 2018 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
import errno
import json
import os
import re
import socket
from collections import defaultdict
from collections import namedtuple
from toolz.curried import map as cmap, f... |
import configparser
import os
import numpy as np
from collections import namedtuple
from emacontrol.emaapi import ema # FIXME Move to __init__.py
# From ema.py TODO Move to __init__.py
default_config = os.path.join(os.path.expanduser('~'), '.robot.ini')
class ConfigEditor():
def __init__(self, config_file... |
# job.py
#
# Copyright 2017 <NAME> <<EMAIL>>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# ... |
# Process_Wikipedia
# Copyright 2021 by <NAME>, released under the MIT License
# https://github.com/jeffheaton
from urllib.parse import urlparse
import xml.etree.ElementTree as etree
import multiprocessing as mp
import posixpath
import bz2
import codecs
import csv
import time
import os,glob
import traceback
import urll... |
"""
Copyright 2020 Cisco
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
distribu... |
import datetime, dataset, math, out, random
from datetime import timedelta
from babel.dates import format_timedelta
modname = "ducc"
# TODO: create helper functions for decreasing or
# increasing health or stress
def ducc_hp_to_str(lvl):
""" convert health points to string """
hp_str = {
# 0 == deat... |
"""
This module handles all resource I/O (image and video files) from the camera to the local client.
:authors: <NAME>
:date: August 2019
"""
import re
import os # Handles paths and filenames
import io # File handlers for streams in saving SingleStorage
import cop... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, GreyCube Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import re
from io import BytesIO
import io
import openpyxl
import xlrd
from openpyxl import load_workbook
from openpyxl.styles import Font
from... |
#!/usr/bin/env python3
#----------------------------------------------------------------------------------------------------------------------#
# #
# Tuplex: Blazing... |
'''
require
> pip insall clang
'''
import pathlib
import re
from typing import List, Optional, Dict, Tuple
from clang import cindex
import pycpptool
def to_d(src: str) -> str:
dst = (src
.replace('&', '*')
.replace('*const *', '**')
)
if src[0] == 'I':
... |
import json, os, sys, re, glob, csv
from ekphrasis.classes.preprocessor import TextPreProcessor
from ekphrasis.classes.tokenizer import SocialTokenizer
from ekphrasis.dicts.emoticons import emoticons
EMOJI_PATTERN = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # sym... |
import numpy as np
import math
import os.path
from cv2 import imshow,waitKey,destroyAllWindows,filter2D,imread
from theano.tensor.signal import pool
from theano import tensor as T
from theano import function
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
def imageMaxPool(img):
my_dmatrix ... |
import os
import sys
from collections import deque
from datetime import datetime
from pprint import pformat
from application import log
from application.notification import IObserver, NotificationCenter, ObserverWeakrefProxy
from application.python.queue import EventQueue
from application.python import Null
from app... |
# Copyright 2018 <NAME>. 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 applicable law or agre... |
# -*- coding: utf-8 -*-
"""A library that provides a syslog-ng Apache Kafka destination.
"""
from __future__ import print_function
import ast
import json
from time import sleep
from confluent_kafka import KafkaException
from confluent_kafka import Producer
from .log import LOG
from .util import date_str_to_timesta... |
"""
Simplified transforms.py
(c) Delirium Digital Limited 2020
Written by <NAME>
"""
import cv2
import numpy as np
import math
# from scipy.spatial.transform import Rotation as R
import tensorflow as tf
import logging
logger = logging.getLogger(__name__)
def resize_image(data_numpy, x_scale, y_scale):
return c... |
#!/usr/bin/env python
import os
import fire
import yaml
import sys
from pathlib import Path
from typing import Union, Sequence, Tuple
import pytasker.task_keys
from pytasker.tasker_schemas import TaskGoTaskfileUnions, TaskGoTask, TaskGoStepTask
from pytasker.struct_utils import safe_get
from pytasker.world_map import... |
#!/usr/bin/python3
import sys
import importlib
import inspect
import time
import datetime
import warnings
#init packages
_packages = []
for packageName, packageImportPamras in {
#name, import params
#like import pandas as pandas
'pandas': 'pandas',
#like from dateutil.re... |
class Event(object):
def __init__(self, event_type, event_gen, clock, process, process_inst):
self.event_type = event_type
self.event_gen = event_gen # Event generator.
self.clock = clock
self.process = process
self.process_name = process.__name__
self.process_instan... |
import multiprocessing as mp
from math import ceil
import logging
from botocore.exceptions import ClientError # type: ignore
import s3fs # type: ignore
import tenacity # type: ignore
from awswrangler.utils import calculate_bounders, wait_process_release
logger = logging.getLogger(__name__)
def mkdir_if_not_exis... |
import base64
import json
TYPE_UNKNOWN = 'UNKNOWN'
TYPE_AIRPORT = 'AIRPORT'
TYPE_TOWN = 'TOWN'
TYPE_STATION = 'STATION'
def _apply_rewrites(parsed_result):
# A hack to get "Bayern" to resolve to "Bavaria" etc.
rewrites = {
'administrative_area_level_1': {
'Bayern': 'Bavaria',
'... |
"""
Tyrannosaurus command-line interface.
"""
from __future__ import annotations
import contextlib
import logging
import os
import enum
from pathlib import Path
from typing import Optional
import typer
from typer import completion
from tyrannosaurus.context import _Context
from tyrannosaurus.helpers import _License... |
import csv
import sys
import json
def convert_gvdb_to_span(gvdb_dict, role):
if gvdb_dict['startIndex'] != -1:
# +2 is for the ". " added to separate title and body
return ((int(gvdb_dict['startIndex']) + 2,
int(gvdb_dict['endIndex']) + 2,
role,
gvdb_dict['value']))
e... |
# Copyright 2016 Google Inc. 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 applicable law or ag... |
import os
import argparse
class BaseOption(object):
def __init__(self):
self.parser = argparse.ArgumentParser()
self.parser.add_argument('--debug', action='store_true', default=False, help='for checking code')
self.parser.add_argument('--gpu_ids', type=int, default=0, help='gpu number. If... |
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# 说明:
# 这个程序主要用来根据图片,找出一笔连接所有空格而不重复的连接方法
# 流程说明:
# 1. 根据图片格子,将图片平均分割
# 2. 判断每个格子的颜色,如果是黑色,则表明该格无空格;如果是白色,则表明该格是空格;如果
# 是其他颜色,则该格是连线起点格。
# 3. 给每个格子标上序号(从0开始),执行算法,找出对应的顺序---已完成
# 4. 根据计算结果,在原图上画出正确的路线。
import colorsys
from PIL import ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tkinter as tk
def make_expandable(widget, columnRange, rowRange):
for i in range(*columnRange):
widget.columnconfigure(i, weight=1)
for i in range(*rowRange):
widget.rowconfigure(i, weight=1)
class AutoScrollbar(tk.Scrollbar)... |
""" The script reads a file like
`data/sample_D3.5Mpc_Emin56EeV_1000nuclei.txt` obtained with
`psample.py` and then creates a sample of "UHECRs" coming from a
particular source, using "nucleus_NNNEeV.txt.xz" obtained with
galback.py and located in a directory that corresponds to the
selected Nside and the GMF model (e.... |
'''
FORCE
Copyright (c) 2020-present NAVER Corp.
MIT license
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from tensorboardX import SummaryWriter
from ignite.engine import create_supervised_evaluator
from ignite.metrics import Accuracy, Loss
from pruning.pruning_algos import iterative_prunin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 07 17:36:17 2020
@author: <NAME>
Code to
Communications are based on ROS (Robot Operating Sytem)
Inputs:
Outputs:
Note that
"""
import numpy as np
import math
import cv2
from shapely.geometry import Polygon
def dot(v,w):
x,y,z = v
X,Y... |
from __future__ import annotations
__all__ = ["Distribution", "RandomVar"]
import abc
from typing import (
Generic,
Optional,
Protocol,
TypeVar,
Union,
cast,
runtime_checkable,
)
import mpmath
from hall._event import EventEq, EventInterval
from hall.analysis import Function, Interval
fr... |
from PyQt5.QtWidgets import *
from MyWizardPage import MyWizardPage
from MapEditor import MapEditor
from fontTools.designspaceLib import AxisDescriptor
from PyQt5.QtCore import Qt, pyqtSlot, QRegularExpression
from PyQt5 import QtGui
from PyQt5.QtGui import QValidator
import re
tagToolTip = """<qt>Four letter tag for... |
from .helper import *
class Il2CppCodeRegistration(MetaDataClass):
methodPointersCount: Union[long, Version(Max=24.1)]
methodPointers: Union[ulong, Version(Max=24.1)]
delegateWrappersFromNativeToManagedCount: Union[ulong, Version(Max=21)]
delegateWrappersFromNativeToManaged: Union[
ulong, Vers... |
# coding: utf-8
import torch
from torch import nn
import math
import numpy as np
from torch.nn import functional as F
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
def position_encoding_init(n_position, d_pos_vec, position_rate=1.0,
sinusoidal=Tr... |
from data import CITIES, BUSINESSES, USERS, REVIEWS, TIPS, CHECKINS
import pandas as pd
from pandas import Series, DataFrame
import numpy as np
import random
"""Deze functie wordt gebruikt om de ratings voor de utility matrix te berekenen"""
def get_rating(ratings,user_id,business_id):
if ratings.loc[(rati... |
import curses
import re
import sys
COLORS = {
# yet to be initialized
"normal": None,
"white": None,
"highlighted-white": None,
"highlighted-green": None,
"highlighted-red": None,
"bold-red": None
}
PYHSTR_LABEL = "Type to filter, UP/DOWN move, RET/TAB select, DEL remove, ESC quit, C-f ad... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.