text stringlengths 3.07k 22.1k |
|---|
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
from fairseq.models.ls... |
from dnn_schedules.per_layer.hwc_schedule import conv2d_dw
from dnn_schedules.schedule import Schedule
import math
from attrdict import AttrDict
class HWFCSchedule(Schedule):
def __init__(self, hw_type, net, model_name, result_dir, verbose, hardware_yaml=None, hardware_dict=None):
super().__init__(hw_typ... |
# -*- coding: utf8 -*-
# ||
# +------+ / __ )(_) /_______________ _____ ___
# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 2011-2013 Bitcraze AB
#
# Crazyflie Nano Quadc... |
# room.py
# a space with a collection of items
from . import DIRECTIONS, enumerate_items
from .event import Event
from .echo import EchoMixin
from .text_template import TextTemplateMixin
from .item import Item
class Path(EchoMixin, TextTemplateMixin):
"""
path from one room to another
"""
TEXT = {
... |
#
# connect to expedition and create the profiles
# based on the data feed
#
import sys
import signal
import socket
#import thread
# import the UDP_IP and UDP_PORT
from expconf import *
# the following is created based on the usrchannel.h header file in Expedition
# format is metric, the expedition variable name and... |
# Copyright (c) 2017 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 i... |
"""
Attribute descriptors for resource classes.
This file is part of the everest project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Created on Apr 19, 2011.
"""
from everest.constants import CARDINALITIES
from everest.constants import DEFAULT_CASCADE
from everest.constants import RE... |
# Functions for annotating gene groups
from collections import Counter
import math
import logging
def createGroupAnnotation(db) :
'''Add functional annotation to this gene group'''
annotation = {}
for strain in db :
for contig in strain['contigs'] :
for tract in contig['tracts... |
# Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from functools import partial, wraps, WRAPPER_ASSIGNMENTS
from pipetools.debug import get_name, set_name, repr_args
from pipetools.compat import text_type, string_types, dict_items
class Pipe(object):
"""
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Test script for compare_wn
Latest version can be found at https://github.com/letuananh/omwtk
References:
Python unittest documentation:
https://docs.python.org/3/library/unittest.html
Python documentation:
https://docs.python.org/
PEP 0008... |
DATASET_DIR = '/home/ds/Projects/SARA/datasets/fields_segmentation'
SRC_IMAGES_PREFIX = '/home/ds/Projects/SARA/data/generated_images/document_crops_rotated/'
DST_IMAGES_PREFIX = '/home/ds/Projects/SARA/data/generated_images/fields_segm_resize_640_v1/'
SRC_MASKS_PREFIX = '/home/ds/Projects/SARA/annotations/fields_segme... |
import os
# os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
# os.environ["CUDA_VISIBLE_DEVICES"]="2"
import torch as T
from torch.autograd import Variable
import numpy as np
import pdb
import copy
import time
cuda = True
if cuda:
floatX = T.cuda.FloatTensor
intX = T.cuda.IntTensor
byteX = ... |
from collections import defaultdict
from math import prod
from aocd import data
from aoc.utils import rows
import regex as re
class Tile():
def __init__(self, id_, rows):
self.id = id_
self.rows = rows
reversed_sides = [''.join(reversed(side)) for side in self.sides]
self.possible... |
import torch
from vision.utils import box_utils, measurements
from vision.utils.misc import str2bool, Timer
from vision.datasets.coco_dataset import CustomCOCO
from torch.utils.data import DataLoader
import os
import argparse
import pathlib
import numpy as np
import logging
import sys
from vision.ssd.mobilenet_v2_ssd_l... |
'''
这一版只是随机选了一些案例把词云给打出来看了一下,用tfidf作为词频,也弃用
'''
import tensorflow.compat.v1 as tf
import numpy as np
import dill as pickle
import time
import json
import matplotlib.pyplot as plt
# import sys
# sys.path.append("model")
# sys.path.append("data")
import BARRE
import wordcloud
from sklearn.feature_extraction.text import T... |
# coding: utf-8
# # JDE ETL Source Design
# ## Goal: Generate source SQL with friendly names and built-in data Conversion
# 1. Pull *ALL* Field metadata based on QA 9.3: Name, Datatype, Decimals
# 2. Pull *Specific* Table fields
# 3. Create SQL mapiing pull with data-conversion
# In[254]:
import numpy as np
impor... |
import numpy as np
from pypex.base.conf import PRECISION, ROUND_PRECISION
from pypex.poly2d.intersection import sat
from pypex.poly2d.point import Point
from pypex.utils import det_2d, multiple_determinants
def intersection(p1, p2, p3, p4, in_touch=False, tol=PRECISION, round_tol=ROUND_PRECISION):
"""
... |
import argparse
from PIL import Image
from matplotlib.pyplot import imshow as ish
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
import json
import argparse
#checkpoint = ... |
from collections import defaultdict
from copy import deepcopy
from dataclasses import fields
from functools import partial
import re
from typing import Union
from sly import Lexer, Parser
from .types import (
Terminal,
Nonterminal,
Alternation,
Concatenation,
Repetition,
OptionalExpr,
Pass... |
__all__ = [
"ranges",
"list_to_range_string",
"range_string_to_list",
"pp",
"to_json",
"copy_attrs",
"Enumerator",
"isXML",
"count_file_lines",
"clean_mongo_key",
"safe_divide",
"safe_percent",
"pretty_bail",
"time_to_utc",
"time_to_local",
"setup_logging"... |
import atexit
import functools
import importlib
import logging
import multiprocessing
import os
import subprocess
import time
from typing import List, Optional, Tuple, Union
import celery
import requests
import rich
from openff.utilities import temporary_cd
from requests import HTTPError
from rich.padding import Paddi... |
"""von-Mises-Fisher complex-Angular-Centric-Gaussian mixture model
This is a specific mixture model to integrate DC and spatial observations. It
does and will not support independent dimensions. This also explains, why
concrete variable names (i.e. F, T, embedding) are used instead of unnamed
independent axes.
@artic... |
import sys
import os
import traceback
import labler
from labler import errors
from labler.cli import op
from labler.cli import opts
from labler.db.rdmbs.repr import ClaimFields, LabelFields
from labler.errors import FatalException
from labler.cli.opts import AppSession
def op_sync(app: AppSession, args):
from la... |
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
# JSONパーサー&レンダラー
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
# シリアライザ (db操作用のController的な役割)
from api_v1.serializers import UserSerializer, TokenSerializer, ImageSe... |
import argparse
from argparse import Namespace
import os
from pathlib import Path
import subprocess
from submit import submit_local, submit_job, format_kwargs_fairseq, get_name, check_not_known
import sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append... |
# -*- coding: utf-8 -*-
# fabfile for Django:
import time
import re
import os
import sys
from contextlib import contextmanager as _contextmanager
from fabric.api import *
from fabric.colors import *
from fabric.state import commands
from fabric.contrib.files import comment, uncomment
if sys.platform.startswith('linu... |
import datetime
import uuid
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
import requests, json
"""
<artist-list>
<artist id="86de477a-4c88-44f4-b0e3-9ef2efa954dc" type="Person" type-id="b6e035f4-3ce9-331c-97df-83397230b0df" ns2:score="100">
<name><NA... |
#!/usr/bin/env python
# coding: utf-8
# ## 2020-07-27: Exploring Bayesian Optimization
#
# *Last Updated*: 2020-07-28
#
# ### Authors
# * <NAME> (<EMAIL>)
#
# ### Overview
# In this Jupyter notebook, we explore Bayesian optimization.
#
# * The Gaussian process in the example uses the Matern kernel, which is a gene... |
"""
Copyright (c) 2017 E<NAME>, http://www.eyeware.tech
Communication interface for the GazeSense application.
Requirements:
- Zeromq: http://zeromq.org/bindings:python
"""
from threading import Thread, Lock
import json
import zmq
import time
import copy
import math
def insert_translation(dd, target_uid, translatio... |
# attributions.py
# Author: <NAME> <<EMAIL>>
import numpy
import numba
import torch
from tqdm import trange
from captum.attr import DeepLiftShap
class ProfileWrapper(torch.nn.Module):
"""A wrapper class that returns transformed profiles.
This class takes in a trained model and returns the weighted softmaxed
outp... |
#!/usr/bin/env python3
#
# ep3apid.py is responsible interfacing with EPrints for via the
# ep3apid web service (part of EPrinttools).
#
import os
import sys
import json
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
from urllib.parse import quote_plus
def dquote(s):
ret... |
import torch as t
import torch.nn as nn
from torch.nn import functional as F
def conv3x3(in_planes, out_planes, stride=1,padding=1,dilation=1):
return nn.Conv2d(in_planes,out_planes,3,stride=stride,padding=padding,dilation=dilation,bias=False)
def conv1x1(in_planes,out_planes,stride=1):
return nn.Conv2d(in_pla... |
import numpy as np
import random
from collections import namedtuple, deque
from models import DQN, DuelingDQN
import torch
import torch.nn.functional as F
import torch.optim as optim
BUFFER_SIZE = int(1e5) # replay buffer size
BATCH_SIZE = 64 # minibatch size
GAMMA = 0.99 # discount factor
TAU = ... |
import argparse
import dill
import jax
import numpy as np
import pomdp
pomdp.horizon = 25
parser = argparse.ArgumentParser()
parser.add_argument('--silent', action='store_true')
parser.add_argument('--bias', action='store_true')
args = parser.parse_args()
with open('data/data{}-meta.obj'.format('-bias' if args.bias ... |
# +
import torch
from torch.nn.modules import Module
from math import pi as math_pi
pi = torch.tensor(math_pi)
def split_and_rotate_tiny_if_too_close_to_zaxis(xyz, tiny_angle=1e-2):
"""
tiny_angle is chosen such that the calculated gradients (in Ylm) are
consistent with torch.autograd.
This depends b... |
# -*- coding: UTF-8 -*-
import pytest
from b3.utils import SBytes
from b3.item_header import *
# Item:
# [header BYTE] [15+ type# UVARINT] [key (see below)] [data len UVARINT] [ data BYTES ]
# ---------------------------- item_header ----------------------------- --- codecs ---
# --- header byte ---
# +---------... |
from collections import OrderedDict
from typing import Optional, Sequence
import torch
import torch.nn as nn
from ..registry import BACKBONES
from mmdet.models.backbones.base_backbone import BaseBackbone, filter_by_out_idices
__all__ = ['VoVNet27Slim', 'VoVNet39', 'VoVNet57']
model_urls = {
'vovnet39': 'https:/... |
import logging
import gzip
import orjson
import functools
import itertools
import pickle
import cld3
import re
import numpy as np
import keras.utils as ku
import multiprocessing as mp
from tqdm import tqdm
from optparse import OptionParser
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequen... |
from flask import Flask, render_template, request, redirect, flash, send_file
from .env import DB_URL, convert
from .utils import (
get_lyrics,
clean_arrangement,
allowed_file,
lyrics_plaintext,
clean_lyrics,
)
from sqlalchemy.dialects.postgresql import JSON
from flask_sqlalchemy import SQLAlchemy
f... |
# -*- encoding: utf-8 -*-
"""
License: MIT
"""
from app.main import blueprint
from flask import render_template, redirect, url_for, request
from flask_login import login_required, current_user
from app import login_manager, db
from app import constants as c
from jinja2 import TemplateNotFound
from flask import jsonify... |
#!/usr/bin/env python3
"""Grid6 is a discrete global grid system with unamiguous cell codes.
https://github.com/direvus/grid6
"""
import math
CODE = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789-=+*'
BASE_STEP = 45
WORDS = [
[
'barnstorm',
'conscripts',
'corkscrew',
'cornfields',
'emu... |
import logging
import os
import requests
import time
import pandas as pd
import geopy.distance
import shapefile
import numpy as np
from . import meetup_utils
def generate_coords(x0, y0, x1, y1, n):
'''Generate :math:`\mathcal{O}(\\frac{n}{2}^2)` coordinates in the bou... |
import copy
import geometry_utils.two_d.path2
from geometry_utils.maths_utility import is_int_or_float, is_float, floats_are_close
from geometry_utils.three_d.axis_aligned_box3 import AxisAlignedBox3
from geometry_utils.three_d.edge3 import Edge3, is_edge3
from geometry_utils.three_d.point3 import Point3
from geometr... |
"""
Salesforce utilities
"""
import json
import os
from datetime import datetime
from cumulusci.core.config import OrgConfig, TaskConfig
from cumulusci.core.runtime import BaseCumulusCI
from cumulusci.oauth.client import OAuth2Client, OAuth2ClientConfig
from cumulusci.oauth.salesforce import jwt_session
from cumulus... |
from collections import OrderedDict
import numpy as np
import pandas as pn
from menpo.visualize import print_progress as menpo_print_progress
def print_progress(iterable, prefix='', n_items=None, offset=0,
show_bar=True, show_count=True, show_eta=True,
end_with_newline=True, ver... |
#!/usr/bin/env python3
##############################################################################
# Project: arrayfunc
# Purpose: Generate the documentation for the math functions.
# Language: Python 3.4
# Date: 30-Apr-2018
#
###############################################################################
#
# ... |
# -*- coding: UTF-8 -*-
# Copyright (c) polakowo
# Licensed under the MIT license.
# !pip install python-telegram-bot --upgrade
from functools import wraps
import configparser
import argparse
import requests
from urllib.parse import urlencode
import requests
from requests.adapters import HTTPAdapter
from requests.pac... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 1 13:23:04 2021
@author: guo.1648
"""
# My 1st try to use simCLR features to do NN query.
import argparse
from torchvision import transforms, datasets
from torch.utils.data import Dataset, DataLoader
import numpy as np
import pandas as pd
impor... |
"""
.. module:: theoryPrediction
:synopsis: Provides a class to encapsulate the results of the computation of
reference cross sections and related functions.
.. moduleauthor:: <NAME> <<EMAIL>>
.. autofunction:: _getElementsFrom
"""
from smodels.theory import clusterTools, crossSection, el... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 13 11:16:17 2022
@author: erri
"""
import numpy as np
from scipy import optimize as opt
######################################################################################
# FUNCTIONS
############################################################... |
import sys
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
import torch
import os
class ApplyStyle(nn.Module):
def __init__(self, latent_size, channels, use_wscale):
super(ApplyStyle, self).__init__()
self.linear = FC(latent_size,
channels * 2,
... |
# !/usr/bin/env python
#
# 'LvN_Solver.py' implements the disorder-averaged calculation by solving
# the Liouville von Nuemann equation for populations at each site.
#
#
#
# MIT License. Copyright (c) 2020 <NAME>
#
# Source code at
# <htts://github.com/vijaymocherla/Localisation-in-Open-quantum-systems.git>
# Imp... |
import os
import re
import class_class
import argparse
import subprocess
from class_class import Version_class
import numpy as np
# regex_str to match the tag for hbase it's "[0-9]*\.[0-9]*\.[0-9]*\.*RC"
def extract_tags(folder, regex_str=".*"):
tags = []
cmd = "cd {}; git tag -l --sort version:refname".format... |
import os
import time
import random
from typing import List, Tuple, Dict, Set
from types import ModuleType
from PIL import Image, ImageDraw
from hata.discord import Message, Embed, CLIENTS, BUILTIN_EMOJIS, UserBase, DiscordException
from hata.backend import ReuBytesIO, sleep
from hata.ext.commands import utils
from... |
#-*- coding: utf-8 -*-
import logging
import datetime
from django.views.generic import View
from django.shortcuts import render, render_to_response, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.utils.decorators import method_decorator
from djan... |
from typing import Dict, List, Union
import json
import os
import glob
import logging
import requests
import logzero
import redis
logger = logzero.setup_logger(level=logging.INFO)
def connect_to_redis(host: str, port: int = 6379):
logger.debug(f"Creating connection to redis at {host}:{port}")
redis_client ... |
import inspect
import json
import os
import numpy as np
import cv2
from fastcore.test import nequals
__all__ = ['get_example', 'get_given_array']
from .ops import voc_keys
np.random.seed(1)
def get_example(image_sz: tuple, **kwargs):
"""Get an example image from the pth given for some image size for a feature... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# MeshPy: A beam finite element input generator
#
# MIT License
#
# Copyright (c) 2021 <NAME>
# Institute for Mathematics and Computer-Based Simulation
# Universitaet der Bundesw... |
import random
import gym
import numpy as np
import matplotlib.pyplot as plt
from itertools import count
import torch
torch.cuda.current_device()
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from tensorboardX import SummaryWriter
writer = SummaryWriter('log_ex')
BUFFER_SIZE ... |
import os
import pickle
from sklearn.model_selection import train_test_split, KFold
from numpy import array
import random
import json
import argparse
from collections import Counter
from copy import deepcopy
import math
def split_train_test_val(all_sentences_paths, output_dir, random_seed=0, max_words=mat... |
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2019, <NAME> <<EMAIL>>
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... |
#!/usr/bin/env python
#
# Copyright 2007 Google 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 o... |
# scaps/iv
import re
import numpy as np
import pandas as pd
from . import common
from .. import standard_functions as std
def content_to_data_sections( content ):
"""
:returns: List of data section each as a list of lines.
"""
lines = content.split( '\n' )
data_break_patte... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from os import path
from flask import Flask, redirect, request, session, escape, url_for, send_from_directory
from jinja2 import select_autoescape, ChoiceLoader, FileSystemLoader, Environment
from classes.pharrell import Pharrell
# from https://github.com/lf... |
"""
This file contains specific functions for computing losses of DNA
file
"""
import torch
from torch.nn import functional as F
from torch import nn
import os
from ..utils import concat_box_prediction_layers
from fcos_core.layers import IOULoss
from fcos_core.layers import SigmoidFocalLoss
from fcos_core.modeling.mat... |
r'''
--- Day 10: Syntax Scoring ---
You ask the submarine to determine the best route out of the deep-sea cave,
but it only replies:
Syntax error in navigation subsystem on line: all of them
All of them?! The damage is worse than you thought. You bring up a copy of
the navigation subsystem (your puzzle input).... |
"""
Source centroiding.
:func:`~centroid_iraf()`: given the initial guess, obtain a more accurate
source centroid position using the IRAF-like method.
:func:`~centroid_psf()`: given the initial guess, obtain a more accurate source
centroid position using Gaussian PSF fitting
:func:`~centroid_sources()`: given the in... |
# SaveDatabaseJSON.py
# <NAME>
# 2020-10-25
# MIT LICENSE
import DSGRN
import pychomp
import itertools
import json
def dsgrn_cell_to_cc_cell_map(network):
"""Return a mapping from the top dimensional cells
in the DSGRN complex to the top dimensional
cells in the pychomp cubical complex.
"""
# Con... |
"""
Module describes Lastline Process snapshot version 3.
:Copyright:
Copyright 2020 Lastline, Inc. All Rights Reserved.
"""
import struct
import tempfile
import json
import os
import logging
from os import path
from os import walk
from process_snapshot_toolkit import snapshot
from process_snapshot_toolkit.sna... |
#!/usr/bin/python
import os
import sys
import numpy as np
import cv2
import time
import threading
from multiprocessing import Process, Queue, Pipe, Manager, Lock
print(os.path.dirname(__file__))
print(os.path.basename(__file__))
print(sys.version_info)
print(cv2.__version__)
class fpsWithTick(object):
def __in... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# #*** <License> ************************************************************#
# This module is part of the repository CNDB.
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# #*** </License> ***************... |
import torch
import torchvision
import torch.nn as nn
import numpy as np
from torch.distributions import Categorical
import torch.nn.utils as utils
from torch.autograd import Variable
class AriaAC_ER(nn.Module):
def __init__(self,opt_params, with_memory=False, aidi=None):
super(AriaAC_ER, self).__init__()
... |
import sys
import os
import subprocess
import logging
from flask import Flask , render_template , request, flash, redirect, session, abort, g, url_for
from flask import jsonify
from werkzeug.security import generate_password_hash, check_password_hash
from vlcplayer import vlcplayer
app = Flask(__name__)
logger = log... |
import numpy as np
from scipy.optimize import leastsq, fmin
from matplotlib import pyplot
from scipy.interpolate import interp1d
import Pointing
from scipy.ndimage.filters import median_filter
from scipy.ndimage.filters import gaussian_filter,maximum_filter, gaussian_filter1d
from scipy.signal import medfilt
from skima... |
#!/usr/bin/env python
"""Graphite output for Splunk.
Dear Reader,
I've (gba) have made every effort to make this a 'sane' Python program.
However, compromises have been made due to the nature of Splunk's Omnibus
Python distribution. Please keep that in mind when engaging in future
development :).
"""
__author__ = ... |
import os
import threading
import time
import traceback
from abc import ABCMeta, abstractmethod
from typing import Type, Union, Dict, Any, Optional
from dbt import tracking
from dbt import ui
from dbt.contracts.graph.manifest import Manifest
from dbt.contracts.results import (
NodeStatus, RunResult, collect_timing... |
from pathlib import Path
from functools import partial
import torch
import torch.nn as nn
import sentencepiece as spm
import pandas as pd
import numpy as np
import joblib
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from helperbot.lr_scheduler import TriangularLR
from helperbot import set... |
#!/usr/bin/env python
def dimension_id_lookup_func(value, dim_table_name, key_field_name, value_field_name, **kwargs):
if not value:
return None
else:
db_schema = 'olap'
raw_template = """
SELECT {field}
from {schema}.{table}
where {dim_table_value... |
"""Entrypoint for the Game."""
import os
import time
from common import logic
from .level import Window
from .networking import Connection
BLOCK_CHAR = "█"
FPS = 15
# The numbers are lower score boundaries for each verdicts.
DEATH_VERDICTS = [
(0, "Pathetic."),
(1, "Try harder next time?"),
(5, "Almost ... |
# © All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE,
# Switzerland, Laboratory of Experimental Biophysics, 2016-2018
# See the LICENSE.txt file for more details.
"""Unit tests for the Localizations DatasetType.
Notes
-----
nosetests should be run in the B-Store parent directory.
"""
__author__ = '<NA... |
import warnings
from weakref import ref
import numpy as np
from ..layers.utils.layer_utils import dims_displayed_world_to_layer
from ..utils.action_manager import action_manager
from ..utils.transforms import Affine
from ..utils.translations import trans
from ._interaction_box_constants import Box
def inside_boxes(... |
from tkinter import *
from PIL import Image, ImageTk
import sqlite3
root = Tk()
root.title('Batman')
root.iconbitmap('images/batman.ico')
root.geometry('360x700')
# Database
# Create DB or Connect to one
conn = sqlite3.connect('addres_book.db')
# Create Cursor
cursor = conn.cursor()
# Tables
'''
cursor.execute("""... |
import os
import sys
from unittest.mock import patch
from click.testing import CliRunner
import matplotlib
matplotlib.use('Agg') # noqa: E402
import matplotlib.pyplot as plt
import numpy as np
import pytest
import correlateim
import correlateim.cpselect
from correlateim.main import main, main_from_file
@pytest.fix... |
from harmonoidservice import HarmonoidService
from fastapi import FastAPI, HTTPException, Response
from fastapi.responses import PlainTextResponse
from fastapi.encoders import jsonable_encoder
import json
import time
harmonoidService = HarmonoidService()
app = FastAPI()
@app.on_event("startup")
async def startupEve... |
""" API core commands for Cloudflare API"""
def api_v4(self):
""" API core commands for Cloudflare API"""
# The API commands for /user/
user(self)
user_audit_logs(self)
user_load_balancers(self)
user_load_balancing_analytics(self)
user_virtual_dns(self)
user_workers(self)
# The AP... |
#!/usr/bin/env python
"""combine list of tractor cats and match them along the way
Example of Matched Comparison:
from legacyanalysis.combine_cats import Matched_DataSet
import common_plots as plots
d= Matched_DataSet(list_of_ref_cats,list_of_test_cats)
plots.confusion_matrix(d.ref_matched.t,d.test_matched.t)
"""
fr... |
import io
import os.path
import PySimpleGUI as sg
from image_cnc import core
from image_cnc.core import ImageValueError
BASE_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
DEFAULT_IMAGE1_FILEPATH = os.path.join(BASE_DIR, 'resources/test_images/image_Peppers512rgb.png')
IMAGE_SIZE = (512, 512)
... |
import six
import chainer
import numpy as np
import chainer.links as L
import chainer.functions as F
import nutszebra_chainer
import functools
from collections import defaultdict
class Conv_BN_ReLU(nutszebra_chainer.Model):
def __init__(self, in_channel, out_channel, filter_size=(3, 3), stride=(1, 1), pad=(1, 1)... |
import pytest
from unittest.mock import patch
from collections import namedtuple
from datetime import date
from pathlib import Path
from braulio.version import Version
from braulio.git import commit_analyzer
from braulio.files import (
DEFAULT_CHANGELOG,
KNOWN_CHANGELOG_FILES,
_render_title,
_render_sub... |
#!/usr/bin/env python2
'''
# This is an 80 character line #
INTENT: take text file data and plot it. Saving both the text files and the
plots allows for simple replotting without recalculating.
Note: I'll need to generate another file which compares between simulations... |
import api
from threading import Thread
import Queue
import os
import sys
import Image
import cStringIO
import base64
import time
#Number of pixels on a side of a tile
side = 200
class Retriever(Thread):
"""Retrives tiles as part of a simple thread pool so that
trying to fetch 100 tiles doesn... |
#Do not forget to chang the sample name. Also do not make it too many characters!
names = ['ECD_2.5mms5psi2_h118w13bar23_8']
#names=['ECD_2.5mms5psi2_69B_h650w0bar11_3']
height = 0.059 #mm shift from the nozzle this is half the filament width, which we call h in the name
#waxs arc angle: 0 for the detector centered ... |
import logging
import logging.handlers
import os
import time
import re
import smtplib
import ssl
from .util import configManager
class ParallelTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
"""Alternative to TimedRotatingFileHandler: rewrite naming rules. https://stackoverflow.com/a/2538719... |
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
# how to use seaborn
from matplotlib.figure import Figure
# for the plot visualization
def filter_data(city,month,weekday):
'''function to get data from csv files devided by city
return
data... |
import json
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from enum import Enum
# This is a hard coded list of evidence, better organized for readability
ev_all = ['EXP', 'IDA', 'IMP', 'IGI', 'IPI', 'IEP', 'IGC', 'RCA', 'IBA', 'IKR', 'IC', 'NAS', 'ND', 'TAS', 'HDA', 'H... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# 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/lic... |
import sys
import numpy as np
import scipy as SCI
import scipy.sparse as Spar
import scipy.sparse.linalg as SparLinalg
import scipy.linalg as linalg
import matplotlib.pyplot as plt
import parameters as par
import Ham_gen as HG
np.set_printoptions(linewidth = 500)
class HAM_subClass:
def __init__(self,Junc_obj):
... |
#!/usr/bin/env python
"""Tests for `network_calc` module."""
from xstrm import network_calc
from xstrm import build_network
import pandas as pd
import pytest
data = [
{'xstrm_id': '1', 'seg_weight': 2, 'var1': 1, 'var2': 3},
{'xstrm_id': '2', 'seg_weight': 3, 'var1': 2, 'var2': 4},
{'xstrm_id': '3', 'seg... |
import sys
import os
import time
import math
import copy
import keras
import rl.agents
import rl.callbacks
import rl.memory
import numpy as np
import visualizer
# keras.backend.tf.compat.v1.logging.set_verbosity(keras.backend.tf.compat.v1.logging.ERROR)
# use XLA:CPU
os.environ["TF_XLA_FLAGS"] = "--tf_xla_cpu_global_j... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.