text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python3
# import from built-in packages
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter as ADHF, FileType
from sys import stdout, stderr, exit
from itertools import chain, product, combinations
from collections import deque
import csv
import re
# import from own packages
import data_... |
"""DeBruijnGenerator.py: Defines a simple class for generating
deBruijn sequences one symbol at a time.
It is based on a class I originally wrote some years ago in c++.
A function that generates the entire sequence is also provided
for testing purposes.
Developed and tested using python v2.7.10 and numpy v1.15.4
<NAME>... |
# reference https://github.com/FantacherJOY/Metal-Surface-Defect-Inspection/blob/master/Surface_defects_detection.ipynb
import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import os
import matplotlib.pyplot as plt
from tensorflow.k... |
"""
Example call on NT infrastructure:
mpiexec -np 8 python -m padertorch.contrib.examples.source_separation.pit.evaluate with model_path=<model_path> database_json=<path/to/database.json>
For usage with a single cpu:
python -m padertorch.contrib.examples.source_separation.pit.evaluate with model_path=<model_path> ... |
class Field:
def __init__(
self,
source=None,
commit=True,
transformer=None,
filters=[],
actions=[]
):
"""
All fields have:
:param str source: Name of column as it appears in source_database
:param boolean commit: Indicates if the f... |
# Databricks CLI
# Copyright 2017 Databricks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"), except
# that the use of services to which certain application programming
# interfaces (each, an "API") connect requires that the user first obtain
# a license for the use of the APIs from Databricks,... |
"""Eto SDK fluent API for managing jobs"""
import time
from typing import Iterable, Union
import pandas as pd
from eto._internal.model.dataset_details import DatasetDetails
from eto._internal.model.job import Job
from eto.connectors.coco import CocoConnector, CocoSource
from eto.connectors.rikai import RikaiConnector... |
import sys
from scipy import spatial
import numpy as np
import csv
import ast
import datetime
import math
def key_func(x):
date_ = x.split('/')[-1]
y = '00'
if date_[3] == '1':
y = '12'
elif date_[3] == '0':
y = '11'
m = date_[4:6]
d = date_[6:8]
if d == '29' and m == '02':... |
# binary classification spot check script
import warnings
from numpy import mean
from numpy import std
from matplotlib import pyplot
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import Min... |
import numpy as np
import scipy
from typing import Optional, Any, Union
from flare.kindling.mpi_tools import mpi_statistics_scalar
import torch
class PGBuffer:
"""
A buffer for storing trajectories experienced by an agent interacting
with the environment, and using Generalized Advantage Estimation (GAE-La... |
#!/usr/bin/python3
# coding: utf-8
import json
import copy
from numpy import random
from numpy.random import normal, rand
import os
import sys
import multiprocessing
import subprocess
from collections import OrderedDict
def error_loader(data, route):
result = []
for k, v in data.items():
if k == "mult... |
#=========================================================================
# MeshRouterRTL_test.py
#=========================================================================
# Test for RouterRTL
#
# Author : <NAME>, <NAME>
# Date : Mar 10, 2019
import hypothesis
from hypothesis import strategies as st
from pymtl3 im... |
from bokeh.plotting import figure, from_networkx
from bokeh.models import (Circle, HoverTool, TapTool, Div, Label, LabelSet, CustomJS,
MultiLine, NodesAndLinkedEdges, ColumnDataSource)
from bokeh.layouts import row, column
from bokeh.palettes import PuBu9 as color_palette
from bokeh.embed impo... |
# Author: <NAME>
# Copyright 2021 Institute of Advanced Research in Artificial Intelligence (IARAI) GmbH.
# IARAI licenses this file to You 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.a... |
# -*- coding: utf-8 -*-
from datetime import datetime
from random import shuffle
import json
import logging
import os
import subprocess
import sys
from address import shard, hash_file
LOGGER = logging.getLogger('mediadb')
DMODE = 0o700 # default directory creation mode
FMODE = 0o400 # default file creation mode
... |
import numpy as np
import torch
import unittest
from collections import defaultdict
from source.policy.policy import Policy
from test.helpers.parameters import TestParameters
from unittest.mock import MagicMock
class EvaluationTest(unittest.TestCase):
@staticmethod
def setup_test(input_size, output_size, num... |
import cv2
import numpy as np
import os
# Image-to-world mapping
def image_to_world_xy(image_xy, H,flip=False):
"""Convert image (x, y) position to world (x, y) position.
This function use the homography for do the transform.
:param image_xy: polygon image (x, y) positions
:param H: homography matrix
... |
import os
import pathlib
import sys
from dataclasses import dataclass
from typing import Any, Callable, List, Type, cast
@dataclass
class RegisteredPurePathClass:
missing: bool
cls: Type["PurePath"]
class PurePath(pathlib.PurePath):
_uri_cls_repository: List[RegisteredPurePathClass] = []
def __new_... |
# SD DIG M3102A
from colorama import init, Fore, Back
init(autoreset=True) #to convert termcolor to wins color
from os.path import basename as bs
mdlname = bs(__file__).split('.')[0] # module's name e.g. PSG
from time import time
from numpy import array, zeros, reshape
from si_prefix import si_format, si_parse
from ... |
import html
import uuid
from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional, Sequence, Type
from urllib.parse import unquote_plus
from django.core.exceptions import ValidationError
from django.utils.html import strip_tags
from django.utils.translation import gettext_lazy as _
from importo.constants imp... |
import sys
import argparse
import numpy as np
import torch
from torch import nn, optim
import torchvision
from torchvision import transforms, datasets, models
from collections import OrderedDict
from create_model import create_model
from get_device import get_device
from load_json import load_json
def main():
try:... |
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QDesktopWidget, QWidget
# help screen
class ui_MainWindowHelp(object):
def setupUi(self, MainWindowHelp):
MainWindowHelp.setObjectName("MainWindowHelp")
MainWindowHelp.re... |
import os
import numpy as np
import uvicorn
from fastapi import FastAPI, UploadFile, File, Query, HTTPException
from fastapi.responses import FileResponse
from fastapi.middleware.cors import CORSMiddleware
import cv2
from pydantic import BaseModel
from typing import List, Tuple
from PIL import Image
import base64
fro... |
import pytest
from diofant import (I, Symbol, assoc_legendre, conjugate, cos, cot, diff, exp,
factorial, pi, sin, sqrt)
from diofant.abc import m, n
from diofant.core.function import ArgumentIndexError
from diofant.functions.special.spherical_harmonics import Ynm, Ynm_c, Znm
__all__ = ()
def t... |
# -*- coding: utf-8 -*-
"""
@date: 2020/4/20 下午3:30
@file: voc_map.py
@author: zj
@description: PASCAL VOC版本的mAP计算
"""
import json
import shutil
import os
import numpy as np
def compute_tp_fp(dt_per_classes_dict, tmp_json_dir, cate, MIN_OVERLAP=0.5):
dt_list = dt_per_classes_dict[cate]
# {cate_1: [], cate2:... |
# sqwordle.py
import random
import re
import asyncio
import discord
from discord.ext import commands
from dotenv import dotenv_values
from numpy import average
from SqwordleFunctions import *
from SQLite3_tools import *
from SqwordleImage import GenerateImage
temp = dotenv_values(".env")
TOKEN = temp... |
"""Module bats."""
__author__ = '<NAME> (japinol)'
from enum import Enum
from random import randint
import pygame as pg
from snakes.actors import Actor, ActorType
from snakes.colors import Color
from snakes import constants as consts
from snakes.experience_points import ExperiencePoints
from snakes impo... |
"""
Actor-Critic using TD-error as the Advantage, Reinforcement Learning.
The cart pole example. Policy is oscillated.
View more on [莫烦Python] : https://morvanzhou.github.io/tutorials/
Using:
tensorflow 1.0
gym 0.7.3
"""
import numpy as np
import tensorflow as tf
import gym
np.random.seed(2)
tf.set_random_seed(2) ... |
# Run infinite with thread for second screen data
import sys
import pandas as pd
from polygon import RESTClient
import threading
import json
import requests
def get_todays_percent_change_of_symbol(symbol):
"""
fetch todays change in percent for the given symbol name
:param symbol: ticker name which will ... |
# lint-amnesty, pylint: disable=missing-module-docstring
from datetime import datetime, timezone
from unittest import TestCase
import pytest
from opaque_keys.edx.keys import CourseKey
import attr
from ...data import (
CourseOutlineData, CourseSectionData, CourseLearningSequenceData, VisibilityData, CourseVisibili... |
import inspect
import logging
import os
from typing import Any, cast, Dict, Iterator, List, Optional, Tuple
import requests
from wcmatch import glob
# E2E_SAFE_DEFAULT includes files that typically do not affect e2e tests.
# `*.txt` not included here because `requirements.txt` can affect tests.
E2E_SAFE_DEFAULT = [
... |
import matplotlib.pyplot as plt
from config import epochs, save_folder
from os import path
from glob import glob
from imageio import imread
from utils import get_checkpoint_folder, get_demo_output_image, get_fn_list
def get_loss_values(loss_fn, shrink):
losses = [0.0] * epochs
folder = get_checkpoint_folder(l... |
import moviepy.editor as mp
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
import scipy.io.wavfile as wav
from typing import Tuple
from itertools import zip_longest
import argparse
import os
import tempfile
class Moment:
def __init__(self, start, stop):
self.start = start
... |
class Node:
def __init__(self, value=None):
self.left = None
self.right = None
self.value = value
def display(self):
lines, *_ = self._display_aux()
for line in lines:
print(line)
def _display_aux(self):
"""
Returns list of strings, width... |
# TODO : may be good idea to use it because we would have similar to url filename
# from slugify import slugify
import json
import hashlib
import urllib3
import os
import errno
datasets_path = None
def set_dataset_path(new_dataset_path):
global datasets_path
datasets_path = new_dataset_path
def ensure_dir... |
from collections import defaultdict
from os import path
from csv import reader
source_file = 'TWL06.txt'
output_suffix = '.anagram.csv'
output_file = 'anagram_words.txt'
excludes_file = 'excludes.txt'
frequency_files = ['count_1w.txt', 'en.txt']
def main():
"""
If table does not exist, generate from frequen... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from pandas.api.types import is_numeric_dtype
sns.set()
def _dtypes(df: pd.DataFrame) -> pd.DataFrame:
"""A private function that returns the data types of all the columns in a dataframe
Parameters
----------
... |
from copy import deepcopy
import logging
from logging.config import dictConfig
import os
import sys
import threading
PALLADIUM_CONFIG_ERROR = """
Maybe you forgot to set the environment variable PALLADIUM_CONFIG
to point to your Palladium configuration file? If so, please
refer to the manual for more details.
... |
# Copyright 2019 Mycroft AI 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 in writin... |
import pygame
import random
import time
BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0)
GREEN = (0,255,0)
snake_block_size = 15
screen_dimensions = 400
while screen_dimensions % snake_block_size != 0:
screen_dimensions += 1
screenx = screen_dimensions
screeny = screen_dimensions
#________... |
from __future__ import print_function
import serial
import numpy as np
import time
import threading
import msvcrt
from tkinter import *
master = Tk()
def grabAngles():
global grabAnglesFlag
grabAnglesFlag = True
def exitPgm():
global globalAbortFlag
globalAbortFlag = True
b1 = Button(master, text="G... |
# coding: utf-8
# # Dataset boolean7: sentences conjoined by or
#
# Generating sentences of the form
#
# - 1) **c is P or d is Q, neither c is P nor d is Q** (contradiction)
#
# - 2) **c is P or d is Q, c is not P and d is not Q** (contradiction)
#
# - 3) **c is P or d is Q, c is not P or d is not Q** (non-contradict... |
import os
from glob import glob
import torch
from torch.utils.data import Dataset, DataLoader
from torch import stack
import numpy as np
class Dataset(Dataset):
"""
Class for load a train and test from dataset generate by import_librispeech.py and others
"""
def __init__(self, c, ap, train=True):
... |
"""gdb printing extension for Numba types.
"""
import re
import sys
_PYVERSION = sys.version_info[:2]
try:
import gdb.printing
import gdb
except ImportError:
raise ImportError("GDB python support is not available.")
class NumbaArrayPrinter:
def __init__(self, val):
self.val = val
def to... |
# -*- coding: utf-8 -*-
"""Turn-key solution for automatic frozen phonons calculations."""
from abc import ABCMeta, abstractmethod
from aiida.engine import WorkChain
from aiida import orm
from aiida_phonopy.calculations.functions.preprocess import phonopy_preprocess
from aiida_phonopy.calculations.functions.get_force_... |
import os
import re
from string import punctuation
import numpy as np
import pandas as pd
from nltk.tokenize import RegexpTokenizer
from scipy.sparse import csr_matrix, hstack
from sklearn.decomposition import NMF
from sklearn.grid_search import GridSearchCV
from sklearn.feature_extraction.text import CountVectorizer
... |
from __future__ import print_function
from . import utils, optimize, base
import numpy as np
from .ODL import ODL
class DLSI(base.BaseModel):
def __init__(self, k=10, lambd=0.01, eta=0.01, updateD_iters=100, updateX_iters=100):
self.lambd = 0.01
self.eta = 0.01
self.D = None
self.X ... |
import logging as log
import json
import requests
from flask import current_app as app
from uuid import UUID
from api import db, FUNCTION_NAME_PREFIX
from utils.common import build_result, build_error_result, success_result
from utils.db_common import query_db
from services.github_service import github_auth_headers, u... |
#170401041 <NAME>
import math
def dosya_oku():
dosya = open("veriler.txt")
y = dosya.readlines()
x=[]
for i in range(len(y)):
y[i]=int(y[i])
x.append(i)
return x,y
def matris_olustur(x,y,n,m):
matris=[]
for i in range(m+1):
satir=[]
for j in range(m+1):... |
from operator import itemgetter
from django.conf import settings
from django.core.urlresolvers import reverse
import regex
from elasticsearch import Elasticsearch
from elasticsearch.helpers import scan as scanner
from . import cts
es = Elasticsearch(hosts=[settings.ELASTICSEARCH_URL])
class SearchQuery:
def... |
"""
Convert stack-vm instructions to reg vm with Phi-node constructs.
This file is preserved for prospective Cython-like backends with Phi-node constructs.
Say, LLVM IR has Phi-nodes, as well as Julia IR
"""
from restrain_jit.becython.representations import Repr, Reg
import restrain_jit.becython.stack_vm_instructions a... |
import torch
import torch.nn.functional as F
from src.utils.utils import l2_normalize
class NCE(object):
def __init__(
self,
indices,
outputs,
memory_bank,
k=4096,
t=0.07,
m=0,
**kwargs
):
super().__in... |
import numpy as np
import cv2
import os
import matplotlib.pyplot as plt
def draw_organ(ax, array, color = 'b'):
N = array.shape[0]
for i in range(0, N):
x, y = array[i,:]
circ = plt.Circle((x, y), radius=3, color=color, fill = True)
ax.add_patch(circ)
return
def draw_lines(ax, arra... |
# Copyright 2020-2021 OpenDR European Project
#
# 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 agree... |
#!/usr/bin/env python
import numpy as np
import os
import six.moves.urllib as urllib
import sys
sys.path.append('E:/GitHub/TensorFlow/models/research')
sys.path.append('E:/GitHub/TensorFlow/models/research/object_detection')
import tarfile
import tensorflow as tf
import zipfile
from collections import defaultdict
from... |
# -*- coding: utf-8 -*-
from hashlib import md5
from app import app, db
import flask_whooshalchemy as whooshalchemy
from werkzeug.security import generate_password_hash, check_password_hash
categorias_table = db.Table('categorias_table',
db.Column('artigo_id', db.Integer,
... |
#
# Implement remove_min
#
import printTree
import random
def parent(i):
return (i-1)/2
def left_child(i):
return 2*i+1
def right_child(i):
return 2*i+2
def is_leaf(L,i):
return (left_child(i) >= len(L)) and (right_child(i) >= len(L))
def one_child(L,i):
return (left_child(i) < len(L)) and (r... |
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# ---[ DATA ]-------------------------------------------------------------------
"""Access data from json files as documents (paragraph level dicts)"""
# --... |
#!/usr/bin/env python
# coding: utf-8
# In[138]:
#PIC-SURE
import PicSureClient
import PicSureHpdsLib
#STATS
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
fig_size = matplotlib.rcParams["figure.figsize"]
# Prints: [8.0, 6.0]
fig_size[0] = 14
fig_size[1] = 8
matplotlib.rc... |
from pathlib import Path
from typing import Union, List
import json
import networkx
import z3
PathLike = Union[Path, str]
class MalformedDimacs(Exception):
"""
Exception raised when the DIMACS
parsing fail.
"""
pass
class CNFFormula:
"""
Class the represent a CNF formula in DIMACS form... |
##############################
# TheWallpaperProject Module #
##############################
import os
import random
from math import sqrt
from PIL import Image, ImageOps
def combine_images(input_path=None, images=None, output_path=None, target_size=None,
strictness=50, count=2, fact_main=2,
... |
import tensorflow as tf
from tqdm import tqdm, tqdm_pandas
import pandas as pd
import string
import numpy as np
import datetime
import os
import vectorutils
from functools import reduce
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__version__ = "0.0.1"
tqdm.pandas(tqdm())
project = "bittlingmayer/amazonreviews"
... |
# Copyright 2017 <NAME>
import functools
import importlib
import ipaddress
import logging
import re
import sublime
import sublime_plugin
logger = logging.getLogger("network_tech.increment.network.network")
Network = importlib.import_module("Network Tech.lib.search.network.network").Network
WILDCARD_RE = re.compile... |
#!/usr/bin/env python
#
# Copyright 2018 Import.io
#
# 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 ... |
# Copyright (C) 2017 <NAME> <<EMAIL>>
"""
Update
======
[2017-09-08]: Hide labels and ticks of both x and y axes.
[2017-09-08]: Hide label of colorbar
[2017-09-08]: Add scale of the image at the southwest.
Reference
=========
http://matplotlib.org/examples/axes_grid/demo_edge_colorbar.html?highlight=cbar
"""
import o... |
"""
Colored Noise generators module.
"""
import numpy
from scipy.signal import gaussian
from sona.generators.generator import SampleGenerator
import time
class NoiseGenerator(SampleGenerator):
"""A noise generator."""
def __init__(self,
spectrum_filter=lambda x, f: x,
high_... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import copy
import itertools
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Dict, List, Option... |
"""
Created by <NAME> (user ezxas5)
on 06 Feb 2017 at 11:43.
"""
import pandas as pd
##### test Appliances
def checkRequestedReceivedRow(row,resultsDF):
def checkIsEqual(buildingID, appID):
isequal = ( resultsDF['Building%i_Appliance%i_requested'%(buildingID,appID)]
== resultsDF['Bu... |
import numpy as np
from scipy.optimize import fminbound, brentq
class ConsumerProblem:
"""
A class that stores primitives for the income fluctuation problem. The
income process is assumed to be a finite state Markov chain.
Parameters
----------
r : scalar(float), optional(default=0.01)
... |
import sqlite3, datetime, sys
from tkinter import *
import tkinter.simpledialog as simpledialog
class TkTable:
def __init__(self,root,data):
rows = len(data)
columns = len(data[0])
for x in range(rows):
for y in range(columns):
if y == 0:
self... |
from pylo.language.kanren import c_var, c_pred, c_const
from pylo.engines.kanren import MiniKanren
class KanrenTest:
def simple_grandparent(self):
p1 = c_const("p1")
p2 = c_const("p2")
p3 = c_const("p3")
parent = c_pred("parent", 2)
grandparent = c_pred("grandparent", 2)
... |
# -*- coding: utf-8 -*-
from DateTime import DateTime
from datetime import datetime
from OFS.interfaces import IOrderedContainer
from parruc.devtools import profiled
from parruc.violareggiocalabria import _
from plone import api
from zc.relation.interfaces import ICatalog
from zope.component import getUtility
from zope... |
""" Forms for user related pages. """
from flask_login import current_user
from flask_babel import format_date
from flask_babel import lazy_gettext as _
from flask_wtf import FlaskForm
from flask_wtf.file import FileField
from wtforms import StringField, PasswordField, BooleanField, RadioField, \
ValidationError, S... |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... |
from math import pi, sin, cos
from itertools import product
from pathlib import Path
import numpy as np
from tqdm import tqdm
from matplotlib import pyplot as plt
from matplotlib import patches as mpatches
from src.agent.train import load
from src.mdp.action import a_int, a_str, NUM_A, is_left, is_right
from src.mdp... |
"""
Created on Wed Aug 12 01:37:16 2015
Author: <NAME> (<EMAIL>)
"""
import re
import sympy
from sympy.abc import _clash1
VAR_RE = '[A-Za-z*][\d_]*'
def matrix_to_tex(matrix_):
'''
Given a matrix, write out the TeX.
Args:
matrix_ (sympy.Matrix): Matrix to turn into TeX
Returns:
str
... |
from abc import ABC, abstractmethod
import numpy as np
from gym import Space
from gym.spaces import Discrete
from rl_algorithm.parameters import Constant, AlphaVisitDecay, Eligibility
from rl_algorithm.utils import mydefaultdict
class AgentObservation(object):
def __init__(self, state, action, reward, state2):
... |
import pandas as pd
from .utility_functions import *
def load_file(filepath):
"""
Loads a single data file into a dataframe and
appends any necessary identifier columns
This strips the sequences of moves out from the data,
along with any mousetracking data. A different file loading function
w... |
import scipy.signal
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
import numpy.ma as ma
#Applies a boxcar smooth of length nsmooth to the vector x
#returns the smoothed vector
def smooth(x, nsmooth):
#interpolates over masked values
if (sum(x==0)> 0)&(sum(x)>0):
bpix = x==0.0
gpix = ~bp... |
import asyncio
import asyncpg
import httpx
import os
import re
from asyncpg.exceptions import UniqueViolationError
from datetime import datetime
from datetime import timedelta
from functools import partial
from nio import RoomMessageText
from nio.responses import RoomResolveAliasError
from util import async_retry_exce... |
import numpy as np
from sklearn import svm
from sklearn import linear_model
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors.nearest_centroid import NearestCentroid
from Modules.ConsoleOutput import ConsoleOutput
from Modules.NaturalLanguage import NaturalLanguageObject
_MAX_DECIMAL_PLACES = 1... |
#!/usr/bin/env python
# This document is part of Pelagos Data
# https://github.com/skytruth/pelagos-data
# =========================================================================== #
#
# The MIT License (MIT)
#
# Copyright (c) 2014 SkyTruth
#
# Permission is hereby granted, free of charge, to any person obtain... |
import numpy as np
__all__=['int2bitarray','bitarray2int','Bin2Gray','Gray2Bin','RGB2Bin','Bin2RGB']
def int2bitarray(N,k):
"""
Changes array's base from int (base 10) to binary (base 2)
Parameters:
N: int N
k: Width of the binary array you would like to change N into. N must not be gre... |
import sublime
import sublime_plugin
import os
import json
import re
from .scripts import config
from .scripts import symbol_list
from .scripts.symbol_list import Symbol
from .scripts.common import pluginRootPath
from .scripts.settings_listener import SettingsListener
symbalMapFile = os.path.join(pluginRootPath, "buil... |
import lietorch
import torch
import torch.nn.functional as F
from .chol import block_solve, schur_solve
import geom.projective_ops as pops
from torch_scatter import scatter_sum
# utility functions for scattering ops
def safe_scatter_add_mat(A, ii, jj, n, m):
v = (ii >= 0) & (jj >= 0) & (ii < n) & (jj < m)
r... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistribution... |
#! /usr/bin/env python3
''' Report generation script for SJSU Senior Project '''
import os
import sys
import argparse
from multiprocessing.dummy import Pool as ThreadPool
FILES = ["report.yaml",
"chapters/chapter1/chapter1_introduction.md",
"chapters/chapter2/chapter2_background.md",
"chapt... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.io as pio
import IMLearn.learners.regressors.linear_regression as lnrg
import IMLearn.utils.utils as utl
pio.templates.default = "simple_white"
def process_temp_values(df):
df = df.drop(df[df.Temp < -10].index)
dayOfYear = ... |
"""Defines AuditableObject, something deletable with a ctime and an mtime etc."""
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
import six
import time
import gflags as flags
from . import common
from . import errors
from . import uid
... |
#! /usr/bin/env python2.7
import sys
import argparse
# Update a genome with a set of SNPs and write to a new file
def get_mutation_type(info):
'''
Return the value of the VT attribute from the info field
'''
attrs = info.split(';')
for a in attrs:
if a[:3] == 'VT=':
retu... |
import math
import numpy
import pandas
from app.models.evaluation import Evaluation
from sqlalchemy.orm import session
def prepare_and_store_dataframe(test_df: pandas.DataFrame, current_datetime: str, prediction: numpy.ndarray,
eval_identity: str, df_output_dir: str):
"""Prepares ... |
""" Direct HW Linux I2C Interface """
import fcntl
import ctypes
from typing import Optional, IO, List
from .types import I2CBase, I2CError, I2CMessage
class _CI2CMessage(ctypes.Structure):
_fields_ = [
("addr", ctypes.c_ushort),
("flags", ctypes.c_ushort),
("len", ctypes.c_ushort),
... |
"""\
Matrix inversion
Created on September 10, 2020
Much of this code translated from curve-fitter.js and others
from https://github.com/Pomax/BezierInfo-2
@author <NAME>
"""
import math
from .MatrixInversion import matrixInvert
binomialCoefficients = [
[1], # n = 0
[1, 1], ... |
import copy
################################
# Directed Acyclic Graph Class #
################################
class Graph:
def __init__(self):
""" Initialize an empty graph object """
self.vertices_ = set()
self.adjacency_lists_ = {}
self.vertex_labels_ = {}
self.edge_la... |
import random
from bio_info.util.graph import Graph
from bio_info.util.str import reverse_complement
def overlap_graph(pattern_list):
# TODO change to Graph form
adjacencies = dict()
for i in range(len(pattern_list)):
# Setup
pattern = pattern_list[i]
adjacencies[pattern] = list(... |
import ctypes
from itertools import count
import numpy as np
from ..gl_importer import OpenGL, gl
__all__ = []
class Indexer:
def __init__(self, shape, strides):
"""
Members
* shape:
The shapes of the indexed dimensions.
* strides:
The strides in bytes of th... |
import ast
import torch
import astpretty
import astor
class IRVisitor(object):
def visitProgram(self, ir):
raise NotImplementedError
def visitAssign(self, ir):
raise NotImplementedError
def visitSampling(self, ir):
raise NotImplementedError
def visitFor(self, ir):
rai... |
from celery.utils.log import get_task_logger
from django.utils.six import text_type
from que.erigonesd import cq
from que.mgmt import MgmtTask
from que.exceptions import MgmtTaskException
from que.utils import dc_id_from_task_id
from api.task.utils import mgmt_task, mgmt_lock
from api.mon.log import save_task_log
from... |
import reversion
from django.utils.encoding import python_2_unicode_compatible
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.utils import... |
"""
Wujiang API
"""
import os
from flask import abort, Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from sqlalchemy import exc
# init app
app = Flask(__name__)
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
DATA_DIR = os.path.join(BASE_DIR, 'data')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.