text stringlengths 3.07k 12.6k |
|---|
#For calcualting Interfacial resistance
from scipy import integrate
import numpy as np
import matplotlib.pyplot as plt
#-------The size of system are read from NPT_data in MD simulation-------#
def Area(NPT_data,logfile):
'''Area of out of plane is obtained from NPT data.'''
with open(NPT_data,'r')as data,open(logfi... |
#!/usr/bin/env python
# coding: utf-8
import os
import time
import copy
import argparse
import torch
import pytorch_lightning as pl
import pandas as pd
from torch.utils.data import Dataset, DataLoader
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
from transformers import T5Tokenizer, T5ForCondit... |
#!/usr/bin/env python
# _*_ coding: UTF-8 _*_
import torch
import torch.nn as nn
import torch.distributed as dist
import os
import glob
import logging
from tqdm import tqdm
from pipeline_train import forward_worker
from loader_audio_visual_pdf import get_data_loader
from network.network_index import AVSRWorker
from t... |
#!/usr/bin/python
# 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
# "... |
from typing import Dict, List
import torch as th
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.torch.recurrent_net import RecurrentNetwork as TorchRNN
from ray.rllib.models.torch.misc import SlimFC
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.utils import override
f... |
import json
import math
import requests
import tkinter
from tkinter import Label, Button, filedialog, Menu
from PIL import Image, ImageTk, ImageFont, ImageDraw, ImageFont
from rich.console import Console
console = Console()
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from se... |
#!/usr/bin/env python
import os, sys
import threading
import time
import daemon
import daemon.pidfile
import argparse
import signal
import logging
# adapted from https://raw.githubusercontent.com/ggmartins/dataengbb/master/python/daemon/daemon1
PATHCTRL = '/tmp/' # path to control files pid and lock
parser = argpa... |
#####
#
# visualize_incoming_annotations.py
#
# Spot-check the annotations received from iMerit by visualizing annotated bounding
# boxes on a sample of images and display them in HTML.
#
#####
#%% Imports
import json
import os
import re
import pandas as pd
from tqdm import tqdm
# Assumes ai4eutils is on the path ... |
import pytest
from pynextion.events import (
Event,
MsgEvent,
TouchEvent,
CurrentPageIDHeadEvent,
PositionHeadEvent,
SleepPositionHeadEvent,
StringHeadEvent,
NumberHeadEvent,
CommandSucceeded,
EmptyMessage,
EventLaunched
)
from pynextion.exceptions import NexMessageException
... |
#!/usr/bin/env python3.6
import os
import re
import sys
import logging
import requests
import logging.config
from deluge_client import DelugeRPCClient
from sshtunnel import SSHTunnelForwarder
from delugeUtils import getConfig, BASE_DIR
from torrent import Torrent
logger = logging.getLogger('deluge_cli')
def split_... |
import dolfin as fem
import matplotlib.pyplot as plt
import numpy as np
from buildup import common, utilities
from mtnlion.newman import equations
def run(time, dt, return_comsol=False):
dtc = fem.Constant(dt)
cmn, domain, comsol = common.prepare_comsol_buildup()
comsol_j = utilities.interp_time(comsol.... |
import base64
import email
import io
from ScamSifter.helpers import *
from ScamSifter.maps import *
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
f... |
from datetime import datetime
from pathlib import Path
import pandas as pd
from tqdm import tqdm
from pyconsolida.budget_reader import read_full_budget, sum_selected_columns
from pyconsolida.posthoc_fix_utils import fix_tipologie_df
def find_all_files(path):
PATTERNS = ["*nalis*", "*RO-RO*", "*ACC.QUADRO*", "*S... |
from .exceptions import ReservedTagNameError
class TagHandler(object):
def __get__(self, obj, type):
raise NotImplementedError(self._niemsg('get'))
def __set__(self, obj, value):
raise NotImplementedError(self._niemsg('set'))
def __delete__(self, obj):
raise NotImplementedError(... |
"""
bnn_model.py
This module implements a Bayesian neural network in tensorflow probability.
It reuses code from
@misc{Hafner2018,
title={Noise Contrastive Priors for Functional Uncertainty},
author={<NAME> and <NAME> and <NAME> and <NAME> and <NAME>},
year={2018, accessed 28.09.2020},
eprint=... |
import collections
import math
import numpy as np
import unittest
import measures
import models
class TestModels(unittest.TestCase):
def test_eca(self):
eca = models.ECA(30)
rule_30 = {
(0, 0, 0): 0, (0, 0, 1): 1, (0, 1, 0): 1, (0, 1, 1): 1,
(1, 0, 0): 1, (1, 0, 1): 0, (1... |
import numpy as np
import pytest
from opencv_wrapper.model import Rect, Point
class TestPoint:
@pytest.mark.parametrize(
"point1, point2, expected",
[
(Point(5, 3), Point(1, 2), Point(6, 5)),
(Point(1.2, 4.6), Point(3.1, 7.8), Point(4.3, 12.4)),
(Point(1.2, 4.6... |
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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 applicab... |
#DB API
#standard modules
import logging
from os import environ
#PIP modules
import pandas as pd
import sqlite3
from datetime import datetime
if 'FLASK_ENV' in environ:
if environ['FLASK_ENV']=="development":
db_path = "DrillMaster_dev.sqllite"
else:
db_path = "/var/www/DrillMaster/DrillMaster/DrillMa... |
#!/usr/bin/env python
import argparse
import sys
from pygrap import *
def parse_arguments():
"""
Parse the arguments of the program.
"""
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
# Arguments
group.add_argument("-v", "--verbosity", action="count", def... |
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.sites.shortcuts import get_current_site
from django.core import mail
from django.core.mail import EmailMultiAlternatives
from django.db.models import Sum
f... |
from __future__ import (
absolute_import,
unicode_literals,
)
import importlib
import logging
import sys
__all__ = (
'django_main',
'simple_main',
)
if sys.path[0] and not sys.path[0].endswith('/bin'):
# When Python is invoked using `python -m some_module`, the first item in the path is always ... |
import sys, os, pytest
sys.path.append(os.getcwd())
from do_grader_lib import PartQuality
from setcover import grader
with open('setcover/data/sc_6_1', 'r') as input_data_file:
input_data = input_data_file.read()
quality = PartQuality('test', 3, 2)
greedy_submission = '3.0 0\n0 1 0 1 1 0\n123\n'
opt_submission... |
#!/usr/bin/python3
from struct import unpack
class BitStream(object):
def __init__(self, data, offs=0):
self.data = data
self.idx = offs
self.mask = 1
def getBits(self, size, value=0):
"""Transfer 'size' bytes from input strem to 'value'."""
while size:
va... |
from django.conf import settings
from django.shortcuts import reverse
from django.utils import timezone
from rest_framework.test import APITestCase
from model_bakery import baker
from glitchtip import test_utils # pylint: disable=unused-import
from organizations_ext.models import OrganizationUserRole
from ..models imp... |
# 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... |
import os
from os import path
from urllib.request import urlopen
import shutil
import gzip
import re
import numpy as np
import torch
import math
import time
from tqdm import tnrange
from collections import Counter
from concurrent.futures import ProcessPoolExecutor
import random
# Helper functions for initializing data... |
import numpy as np
import sys
import datetime
from Parameters import Parameters
from SetupUtil import SetupUtil
from SPMModel import SPMModel
from MONDModel import MONDModel
from NBIModel import NBIModel
from Integrator import Integrator
from IOUtil import IOUtil
class Run:
def __init__(self):
self.params = Pa... |
from django.conf import settings
from django.test import RequestFactory
import htmls
from model_bakery import baker
from unittest import mock
class MockRequestResponse(object):
"""
Return type of :meth:`.TestCaseMixin.mock_request`,
:meth:`.TestCaseMixin.mock_http200_getrequest_htmls` and
:meth:`.Tes... |
import base64
import logging
from dataclasses import dataclass
from typing import Iterable, Optional, Set, Tuple
import crc32c
import numpy as np
import qrcode
from pyzbar import pyzbar
from qr_tx import lt
log = logging.getLogger(__name__)
# config about QR image data capacity
FRAME_SZ = 1046
VERSION = 18
ECC_LVL ... |
import string
from datetime import date
from lxml import etree
from nltk.corpus import stopwords
from pymystem3 import Mystem
from string import punctuation
from stop_words import get_stop_words
def stem_and_delete_stopwords(text):
tokens = mystem.lemmatize(text.lower())
tokens = [token for token in tokens if... |
from node_buffer import Buffer
from node_io.stream_base import Stream
from internals.bufferlist import BufferList
from internals.debug import debug, debugwrapper
class ReadableState:
def __init__(self, *, highWaterMark=None):
self.buffer = BufferList()
self.highWaterMark = highWaterMark or 16 * 2 ... |
from collections import deque
from idaapi import *
import codecs
import json
# IDA Pro 7.4
def rebase(json_content):
current_image_base = get_imagebase()
print(json_content[0])
new_image_base = int(json_content[0]['address'], 16)
delta = new_image_base - current_image_base
return rebas... |
# izriše škatle, skale, igralca in jih shrani v mapo "slike"
from PIL import Image, ImageDraw
import os
from barve import bar, slovar_velikosti
from model import znaki
from pathlib import Path
cwd = os.getcwd()
starš = Path(__file__).parent
os.chdir(starš) # gremo eno mapo gor, da lahko gremo nazaj eno mapo dol
o... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright 2021 The NiPreps Developers <<EMAIL>>
#
# 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 ... |
import argparse, traceback, json, shutil
from pathlib import Path
SIMPLE_BACKGROUND = 412368
WHITE_BACKGROUND = 515193
sketch_tags = [513837, 1931] # grayscale, sketch
include_tags = [470575, 540830] # 1girl, 1boy
hair_tags = [87788, 16867, 13200, 10953, 16442, 11429, 15425, 8388, 5403, 16581, 87676, 16580, 94007, 403... |
import datetime
import logging
import pickle
import requests
from collections import namedtuple
from lxml import html
from requests import RequestException
class Game:
def __init__(self, title):
self.title = title
self._states = []
@property
def state(self):
return self._states[-1... |
"""
Helper classes for generating file list HTML
"""
# Standard library imports
from collections import defaultdict
# Third party imports
import dash_html_components as html
import dash_bootstrap_components as dbc
from flask import url_for
# Local application imports
from app.utils.func import multisort
from app.fac... |
# Copyright 2015 Google Inc. All Rights Reserved.
"""Utilities for configuring platform specific installation."""
import os
import re
import shutil
from googlecloudsdk.core.credentials import gce as c_gce
from googlecloudsdk.core.util import console_io
from googlecloudsdk.core.util import platforms
# pylint:disable... |
from __future__ import division
import numpy as np
from math import exp
from vispy import app
from vispy import gloo
from vispy.scene.shaders import ModularProgram
from vispy.scene.visuals import Visual
from vispy.scene.transforms import STTransform, LogTransform
class PanZoomTransform(STTransform):
def move(sel... |
import copy
import geometry_utils.three_d.axis_aligned_box3
import geometry_utils.two_d.edge2
from geometry_utils.two_d.point2 import Point2, is_point2
from geometry_utils.two_d.vector2 import Vector2, is_vector2
class AxisAlignedBox2:
"""
A class to create a 2D box
Attributes:
___________
min: ... |
"""Tools for working with lists."""
from array import array
from bisect import bisect, bisect_left, insort
from collections import deque
from heapq import heapify, heappop, heappush, heappushpop, nlargest
from math import floor
from typing import Callable, Deque, List, Sequence
import pytest
def test_array() -> Non... |
# Copyright 2016 Intel Corporation
#
# 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 wri... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
import struct
import random
import threading
import queue
#the client class contains all the sockets and send/read utilities
# for the client process
class client:
def __init__(self,multicast_group):
self.multicast_group = multicast_grou... |
import imlib as im
import numpy as np
import pylib as py
import tensorflow as tf
import tf2lib as tl
import tqdm
import data
import module
# ==============================================================================
# = param =
# ===============... |
import sys
import numpy as np
from numpy.lib.function_base import diff
import pandas as pd
import plotly.graph_objects as go
from tqdm import tqdm, trange
def mean_normalise(table):
N = table.shape[0]
n = np.arange(start=0, stop=N / 100, dtype=int)
groups = np.repeat(n, 100)
table['groups'] = group... |
#
# Copyright (c) 2019-2020, NVIDIA CORPORATION.
# Copyright (c) 2019-2020, BlazingSQL, 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... |
from decouple import config
import sys, os
from .datasets.REDD import reddLoader as redd
import numpy as np
from datetime import datetime, timedelta
import pytz
from .websocket import wsManager
from . import chart
from . import data as dataHp
from django.http import JsonResponse
from .usefulFunctions import time_f... |
from functools import reduce
from operator import or_
import django_filters
from django.db.models import Count, Q
from django_filters import CharFilter, ModelChoiceFilter, ChoiceFilter
from django_filters.constants import EMPTY_VALUES
from django_filters.widgets import CSVWidget
from .models import Paper, StudentClub... |
import tensorflow as tf
import argparse
import os
from functools import partial
import train_utils
from vocab import Vocab
# from model_ori import LISAModel
from model import LISAModel
import numpy as np
import sys, pdb
# tf.enable_eager_execution()
arg_parser = argparse.ArgumentParser(description='')
arg_parser.add_... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
#-------------------------------------------
# ---------- displayRectOnImg ------------------
# INPUT :
# image : lthe image on which we want to put rectangle
# rect_coord : coor... |
from django.shortcuts import render, redirect
from user.models import UserLogin, User
from esialogin.settings import SYSTEMNAME
import logging
log = logging.getLogger('request')
def getPasswordLogin(username, password):
loginInfo = UserLogin.objects.filter(login = username)[:1]
loginIsCorrect = False
se... |
import os
import sys
import time
import glob
import tqdm
import torch
import utils
import logging
import argparse
import torch.utils
import numpy as np
import torch.nn as nn
import torch.utils.data
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from torch import optim
from typing import Dict
from... |
#!/usr/bin/python
# -*-coding: utf-8 -*-
import csv
import json
from itertools import chain
from typing import Dict, Optional
import jsonschema
from pycsvschema import defaults, definitions, validators, utilities
class Cell(object):
def __init__(self, value, row_number: int, column_name: str):
self.valu... |
import ast
import numpy as np
import pandas as pd
from clevercsv import csv2df
from collections import Counter
from src import constants
def get_sequence(dataset, column, annotations):
for item in annotations[dataset]:
if item["header"] == column:
return item["sequence"], item["tokens"], list... |
import tensorflow as tf
import argparse, os, gc
from functools import partial, wraps
from datetime import datetime
from inspect import signature
class HelpFormatter(argparse.HelpFormatter):
def _format_args(self, action, default_metavar):
if hasattr(action, "format_meta"):
return action.format_... |
#coding:utf-8
"""
calculer les coordonnées de chaque position possibles sur une trajectoire et couper la trajectoire au moment où
les coordonnées coincident avec d'autres pièces
"""
def towerPossibleMovements(coordinates: tuple) -> list:
#generation des trajectoires
trajectoires = [[], [], [], []]
... |
import numpy as np
import math
import itertools
def GraspPointFiltering(numPts, P, N, C):
# create superset of all possibilities:
counter = list(range(0, numPts))
points = list(itertools.combinations(counter, 2))
curvatureVals = []
for i in range(0, len(points)):
x = points[i][0]
... |
import os
from functools import partial
import maya.cmds as mc
class attributeComparerWindow:
def __init__(self):
self.dictionaries = [0] * 2
self.texts = []
self.nodeTextField = None
win = mc.window(title = "Attribute Checker")#, wh=(158,512))
col = mc.columnLayo... |
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .forms import GigCreationForm, GigEditForm, ShowcaseForm, CommentForm, PlanForm, PlanEditForm
from django.http.response import Http404
from django.shortcuts import redirect, render
from .models import Comment... |
from __future__ import annotations
import time
from typing import List, Union
from Fancy_term import Style
from .options import ProgressBarOptions
from .utils import length_of_terminal
from .tokens import *
# for type hinting only
def get_progress() -> int:
pass
class ProgressBar():
_default_animation = ... |
import asyncio
from datetime import datetime
from dateutil.relativedelta import relativedelta
from discord.ext import commands
import cogs.utilities as utilities
class RemindMe(commands.Cog):
def __init__(self, client):
self.client = client
@commands.group()
async def remindme(self, ctx):
... |
from django.shortcuts import render, redirect, Http404
from .models import Sensor, Order, Employee, Responsable
from django.contrib.auth.models import auth
from django.contrib import messages
from datetime import datetime, timedelta
def index(request):
if request.method == 'GET':
return render(request, 'i... |
"""Collected utility functions, many are taken from Drew's utils.py in
Cuisine CVS and Hiss's Utility.py."""
import sys
__author__ = "<NAME> <<EMAIL>>, " + \
"<NAME> <<EMAIL>>"
__cvsid__ = "$Id: TLUtility.py,v 1.1 2003/05/25 08:25:35 dmcc Exp $"
__version__ = "$Revision: 1.1 $" [11:-2]
def make_attribu... |
import os, sys
import pandas as pd
import numpy as np
from sklearn.feature_selection import RFECV
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import RobustScaler
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
# make dep imports work when runnin... |
import json
import logging
import requests
from requests.exceptions import SSLError
from requests.exceptions import Timeout
from .exceptions import FBConnectionException
from .exceptions import FBException
from .exceptions import FBHTTPException
from .exceptions import FBJSONException
BASE_GRAPH_URL = "https://grap... |
#!/usr/bin/python
from valarie.dao.document import Collection
CHUNK_SIZE = 65536
def create_binary_file(parent_objuuid, name = "New Binary File", objuuid = None):
collection = Collection("inventory")
binary_file = collection.get_object(objuuid)
binary_file.object = {
"type" : "binary fi... |
# -*-coding:utf-8-*-
import jieba
import os
import time
from gensim.corpora import dictionary
from gensim.models import tfidfmodel
from gensim.similarities import docsim
from simhash import Simhash
def send(message):
print("the folder_path : ", message['message']['folder_path'])
print("the stop_word_file : "... |
import easygui as g
import random as r
legal_x = [0, 5]
legal_y = [0, 5]
class Turtle:
def __init__(self):
self.hp = 10
self.x = r.randint(legal_x[0], legal_x[1])
self.y = r.randint(legal_y[0], legal_y[1])
# self.x = 0
# self.y = 0
g.msgbox('乌龟的初始位置为:【%s,%s】' % (se... |
import math
from contextlib import contextmanager
from ..base import *
from .context import *
from .frontend import *
from .signals import *
def Log2Floor(n):
return int(math.floor(math.log2(n)))
def Log2Ceil(n):
return int(math.ceil(math.log2(n)))
class CatOperator(Operator):
def __init__(self, signal... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import os
import sys
import pickle
import nltk
import tensorflow as tf
from nnli import tfutil
from nnli.models import ConditionalBiLSTM
from nnli.models import FeedForwardDAM
from nnli.models import FeedForwardDAMP
from nnli.models import FeedForwar... |
from flask import *
# from flask_compress import Compress
from subprocess import Popen, PIPE
import os
import json
import uuid
import shutil
import recognizer.board
import recognizer.grid
UPLOAD_FOLDER = '/tmp/codenames-upload'
PASSWORD = os.environ.get('PASSWORD')
last_ocr_board_filename = UPLOAD_FOLDER + '/last-ocr-... |
import numpy
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import metrics
from sklearn import datasets
import LaplacianEigenmap as Le
import LLE
'''
MDS, Isomap, LLE, LE流形学习算法的可视化
'''
# 最小路径的Floyd算法
def floyd(D, n_neighbors=15):
Max = numpy.max(D) * ... |
################################################################################
#
# MIT No Attribution
#
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the... |
from os import environ
import cloudinary
from cloudinary.uploader import upload as cloudinary_upload
from flask import (Flask, flash, jsonify, redirect, render_template, request,
send_file, session, url_for)
from flask_heroku import Heroku
from flask_migrate import Migrate
from flask_uuid import Fla... |
"""
@Author : <NAME>
@Email : <EMAIL>
@CreateTime : 2019/3/16
@Program : 小野人快跑的小游戏
"""
import pygame
from pygame.locals import *
from itertools import cycle
import random
SCREENWIDTH = 800
SCREENHEIGHT = 270
FPS = 30
class GameMap():
def __init__(self, x, y):
self.bg = pygame.image.l... |
import matplotlib.pylab as plt
from matplotlib.patches import Ellipse
import matplotlib.animation as animation
import numpy as np
from numpy import polysub
import pandas as pd
import argparse
from r2p2py.logfile_parser import LogFileParser, Reward
class LogFileAnimator:
def __init__(self, fname: str, start_in_seco... |
"""
Creating the visibility masks for all of the scenes.
"""
import pycuda
import pycuda.autoinit
import pycuda.driver as cuda
import torch
_ = torch.cuda.FloatTensor(8) # somehow required for correct pytorch-pycuda interfacing, assuring they use the same context
from pycuda.compiler import SourceModule
from datasets... |
import unittest
from typing import Union
from unittest.mock import patch
from goose.defaults import N_SPACES, BRIDGE_START, BRIDGE_END, GOOSE_SPACES
from goose.exceptions import GameOver, WrongDiceRolled, InvalidDiceValue
from goose.game import Game, PositionValidator, roll_dice, create_default_game
from goose.reposit... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import resnet18, resnet50
from torchvision.models.video import r2plus1d_18
from torchvision.models.video.resnet import BasicBlock, Conv2Plus1D
from utils import freeze_all, freeze_layer, freeze_bn, initialize_linear, initialize_3... |
from enum import Enum
import enum
import re
from src.database_access import database_access as Database
db = Database("InCollege.sqlite3")
# class to store a job
class PostedJob():
def __init__(name, title, description, employer, location, salary):
name = name
title = title
description = d... |
import datetime
import itertools
import json
import os
import shutil
import tempfile
import traceback
from os.path import join
import arrow
import click
from click.exceptions import UsageError
try:
text_type = (str, unicode)
except NameError:
text_type = str
def _style_tags(tags):
if not tags:
r... |
'''
* Date: 14-12-16
* Desc: All Surface-holding objects
* Comments: Obviously, this is snatched from my vtes-client, and needs to be tidied.
* Author: <NAME>
'''
import pygame
def loadImage(fileName):
'''
This is an example docstring.
This function loads an image of an arbitrary format and returns ... |
# -*- coding: utf-8 -*-
import bpy
import re
def find_armature(amarture_name):
for o in bpy.data.objects:
if o.type == 'ARMATURE':
if o.data.name == amarture_name:
arma = o.data
arma_obj = o
return {'armature': arma, 'armature_obj': arma_obj}
... |
"""Modified NMS ops as static/dynamic layers"""
import numpy as np
import torch
from torchvision.ops import boxes as box_ops
from torchvision.ops import nms # BC-compat
__all__ = ['batched_nms', 'ml_nms']
def batched_nms(boxes: torch.Tensor, scores: torch.Tensor, idxs: torch.Tensor, iou_threshold: float):
"""
... |
from typing import Tuple
from IMLearn.learners import UnivariateGaussian, MultivariateGaussian
import numpy as np
import plotly.graph_objects as go
import plotly.io as pio
pio.templates.default = "simple_white"
def plot_pdf(uni_gauss: UnivariateGaussian, samples: np.ndarray,
show: bool = True) -> None:
... |
# -*- coding: utf8 -*-
__author__ = 'wangqiang'
'''
reportlab用于生成pdf文件
pip install reportlab
'''
from reportlab.pdfgen import canvas
from reportlab.platypus import SimpleDocTemplate, Paragraph, Table, TableStyle, Image, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.pag... |
#!/usr/bin/env python3
# -*- coding: ascii -*-
"""
Helper functions using standard libraries.
"""
from math import factorial as _factorial
# memoization dictionaries
_MEMO_MULTI_INDICES = {}
_MEMO_MULTI_INDICES_KN_L = {}
#=========================================
# multi-indices and multinomial coefficients
def mult... |
from framedata import *
from theorydata import plucker,nonplucker36
def eq(x,y):
return abs(x-y) < 1e-10
def test_signs_A1A2():
def a(i,j):
return plucker(vl, [i,j])
fd = computeFrames(theoryname="A1A2", R=1, theta=0, pde_nmesh=127, oper=False)
vl = fd.vertexlist
x1 = (a(2,3)*a(1,5))/(a(1... |
# Copyright (c) 2005-2009 <NAME>
#
# Distributed under the MIT license (See accompanying file
# LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt)
#
# portions of the code taken from http://www.antigrain.com, file
# agg_bezier_arc.cpp
import math
"""Implements the following function for converting elliptical arc... |
# Copyright (C) 2019 by eHealth Africa : http://www.eHealthAfrica.org
#
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with
# the License. Y... |
import streamlit as st
import plotly_express as px
import pandas as pd
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import KNNImputer
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from numpy import percentile
from scipy import stats
# configuration
st.set_opt... |
import argparse
import json
import os
import random
import readline
import sqlite3
from cryptics.config import SQLITE_DATABASE
parser = argparse.ArgumentParser()
parser.add_argument("--source", type=str, nargs="?", default="times_xwd_times")
parser.add_argument("--train", dest="train", action="store_true")
parser.ad... |
#!/usr/bin/env python3# -*- coding: utf-8 -*-
import logging
from textwrap import indent
from . import agent, hook
from .. import settings as cfg
from .. import screen, shell
logger = logging.getLogger(__name__)
def showHeadLine(target, line):
tty = ttyOf(target)
if tty is None:
return
ttyWidth, _ = age... |
#!/usr/bin/python3
import os
import shutil
import logging
import argparse
import tempfile
import concurrent.futures
from multiprocessing import Lock
import cv2
from pathlib import Path
from zipfile import ZipFile
IMAGE_EXT = ('png', 'jpeg', 'jpg', 'emf', 'wmf')
logger = logging.getLogger(__name__)
logger.setLevel(l... |
# author: <NAME>
# license: see, LICENSE
# purpose: set up a project directory for digital publishing and conservation
# project
import os
import json
import argparse
def assert_first_not_second_proc(path1: str, path2: str) -> None:
"assert first path as true and second not true with isdir"
assert os.path.is... |
#!/usr/bin/env python3
# Copyright (c) 2017, <NAME> (www.karlsruhe.de)
#
# 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... |
import importlib
import json
from collections import OrderedDict
import click
import numpy as np
import tensorflow as tf
import xlsxwriter
from backports.tempfile import TemporaryDirectory
from shutil import rmtree
from experiment.config import load_config, read_config
from experiment.utils import logging_utils
cla... |
"""
Classifier Trainer
Project: Disaster Response Pipeline
Sample Script Syntax:
> python train_classifier.py <path to sqllite destination db> <path to the pickle file>
Sample Script Execution:
> python train_classifier.py ../data/disaster_response_db.db classifier.pkl
Arguments:
1) Path to SQLite destination d... |
#!/usr/bin/python3
import subprocess
import re
import statistics
import matplotlib.pyplot as plt
import csv
import commons
fname_output = "data/all-data-at-once.csv"
plot_fname_base = "img/multi-threading-tmp"
class Phase:
def __init__(self):
self.l2Miss = []
self.l3Miss = []
self.l2HitRa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.