text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python
__author__ = 'heroico'
import os
import io
import gzip
import logging
import numpy
from metax import WeightDBUtilities
from metax import PrediXcanFormatUtilities
from metax import ThousandGenomesUtilities
from metax import Logging
from metax import Utilities
from metax import Formats
from timeit ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def conv3x3(in_planes, out_planes, strd=1, padding=1, bias=False):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3,
stride=strd, padding=padding, bias=bias)
class ConvBlock(nn.Module)... |
#!/usr/bin/env python3
# Binary API checking.
from trabant import *
from trabant.objects import orthoscale
trabant_init()
def mix_args(aa,bb):
for a in aa:
for b in bb:
for i in range(len(a)):
for j in range(i,len(a)+1):
if i == j: yield True,a
... |
import numpy as np
import numbers
import math
import xxhash_cffi as xxhash
import socket
import sys
import numpy
from scipy import stats
import dpkt
def hll_rank(hash0, bits):
i=0
for i in range(1,32-bits):
if hash0 & 1:
break
hash0 = hash0 >> 1
return i
def hll_rawc(hll_reg,... |
"""Prettifiers for genshinstats api returns.
Fixes the huge problem of outdated field names in the api,
that were leftover from during development
"""
import re
from datetime import datetime
from math import ceil
from . import gachalog
def _recognize_character_icon(url: str):
"""Recognizes a character's icon url... |
"""Utility functions for videos, plotting and computing performance metrics."""
import os
import typing
#import cv2 # pytype: disable=attribute-error
import matplotlib
import numpy as np
import torch
import tqdm
import pdb
import sklearn
from sklearn.metrics import f1_score, classification_report, confusion_matrix, ... |
"""This module is used to extract syntactic features for the WriteprintsStatic class.
For every feature, we document the description of the original feature, the technical details we use to recover it, and
known differences between the original feature and our engineering.
"""
import re
# fmt: off
FUNCTION_WORDS = [... |
# -*- coding: utf-8 -*-
#
import os
from .parseUsfm import parseString
from .books import fullName, readerName, bookKeyForIdValue
class DummyFile(object):
def close(self):
pass
def write(self, str):
pass
class TokenStream(object):
def __init__(self, array):
self.tokens = array
... |
# All imports
import os
import boto3
import pandas as pd
from botocore.config import Config
from botocore import UNSIGNED
import toml
import shutil
import json
rootPath = "/Users/cocozhao/Documents/GitHub/rt-cloud/projects/openNeuroClient/"
class OpenNeuroOverview(object):
def __init__(self):
self.archive... |
"""ESMValTool CMORizer for CDS-UERRA version UERRA-HARMONIE.
Tier
Tier 3
Source
https://cds.climate.copernicus.eu/cdsapp#!/dataset/reanalysis-uerra-europe-soil-levels
Last access
20191104
Download and processing instructions
- Open in a browser the data source as specified above
- Put the right ticks:
... |
# Copyright 2019 The Forte Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
from __future__ import division
# LIBTBX_SET_DISPATCHER_NAME phenix.explore_metric_symmetry
from cctbx import sgtbx
from cctbx.sgtbx import pointgroup_tools as pgt
from cctbx.sgtbx import sub_lattice_tools as slt
from cctbx import crystal
from iotbx.option_parser import option_parser
from libtbx import easy_run
from l... |
#!/usr/bin/env python
# _*_ coding: UTF-8 _*_
import os
import time
import random
import numpy as np
import argparse
import logging
import torch
import torch.distributed as dist
from pipeline_train import main_train
from pipeline_predict import main_predict
from tool.data_io import safe_load, safe_store
from tool.mat... |
# Copyright (c) 2022-present, FriendliAI Inc. All rights reserved.
""" IPC utils
"""
import asyncio
import errno
import json
import os
import struct
from enum import Enum
from typing import Optional
from periflow_sdk.comm.errors import (
IpcChannelIOError,
IpcChannelNotOpenedError,
IpcConnectionError,
)
... |
from copy import deepcopy
from numpy import sin, cos, pi, tan, arctan, array, arctan2, square, arcsin, savetxt
from math import pi, inf, sqrt, radians
def fk(q):
# Geometry
a1 = 0.235
a2 = 0.355
a4 = 0.20098
a5 = 0.345
d1 = 0.505
d5 = 0.00837
d6 = 0.6928
# DH table
dh = array(... |
import json
from flask import render_template, redirect, abort, url_for, request, g
from flask_login import logout_user, current_user, login_required
from app import app, lm
from config import *
from .forms import *
from .models import *
# Set up our global user variable
@app.before_request
def before_request():
... |
import os
import logging
import requests
import json
from string import Formatter, Template
from datetime import datetime
import satsearch.utils as utils
import satsearch.config as config
import traceback
logger = logging.getLogger(__name__)
class SatSceneError(Exception):
pass
class Scene(object):
def _... |
"""
Copyright (c) 2015-2018 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, s... |
'''
Author: HaoZhang-Hoge<EMAIL>
Date: 2021-12-28 07:10:41
LastEditTime: 2022-03-26 09:50:13
LastEditors: Please set LastEditors
Description:
FilePath: /Aurora/main.py
'''
import imp
from multiprocessing import Condition
import read_circuit
import read_activate
import simulator
import type
import os
import numpy as n... |
from numpy.random import normal, randint, rand
import pandas as pd
from random import shuffle
import pickle
import os
class player:
"""
A class to model any sports player
"""
def __init__(self,skill,variance,name):
"""
The init function of the class
[param skill]: int, ... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
import os
import time
import platform
import asyncio as aio
import aiopyupbit
from component import Coin
import static
import strategy
def press_any_key() -> None:
"""프롬프트 아무키나 입력 기능
"""
try:
# Windows용 코드
import msvcrt
msvcrt.getch()
... |
"""
Module implementing various uncertainty based query strategies.
"""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
import numpy as np
from sklearn import clone
from sklearn.utils.validation import check_array
from ..base import SingleAnnotatorPoolQueryStrategy, SkactivemlClassifier
from ..utils import (... |
#!/usr/bin/env python3
import argparse
import math
import os
from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt
from astropy import units as u
import matplotlib
import numpy as np
import artistools as at
import artistools.inputmodel.opacityinputfile
# import artistools.inputmodel
# from mpl_... |
"""Test of structural conversions"""
import logging
from functools import partial
import numpy as np
import pytest
import qutip
import krotov
from krotov.conversions import (
discretize,
extract_controls,
extract_controls_mapping,
pulse_options_dict_to_list,
)
from krotov.shapes import qutip_callback
... |
import copy
import pickle
from collections import Set
from timeit import default_timer as timer
import itertools
from nltk import Variable
from nltk.draw.tree import TreeTabView
from nltk.featstruct import CelexFeatStructReader, TYPE, unify
from nltk.grammar import FeatStructNonterminal, FeatureGrammar, Production
fr... |
import inspect
import json
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import pydantic
from google.protobuf.json_format import MessageToDict
from pydantic import (
BaseModel,
NonNegativeFloat,
PositiveFloat,
NonNegativeInt,
PositiveInt,
validator,
... |
# -*- coding: utf-8 -*-
"""
Created on Thurs 5 27 2021
@name: USCensus ACS Migration Download Application
@author: <NAME>
"""
import sys
import os.path
import time
import warnings
import logging
import pandas as pd
MAIN_DIR = os.path.dirname(os.path.realpath(__file__))
ROOT_DIR = os.path.abspath(os.path.join(MA... |
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2020, <NAME>
#
# This module is part of anima and is released under the MIT
# License: http://www.opensource.org/licenses/MIT
import re
from anima import logger
from anima.ui.base import AnimaDialogBase, ui_caller
from anima.ui.lib import QtCore, QtWidgets
def UI(app_in=N... |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
# File :ICP_Encapsulation.py
# Author :WJ
# Function :
# Time :2021/03/04
# Version :3.0
# Amend :11/16 将原函数拆分为两个函数,以提高代码可移植性:
# (1) ICP负责输出仿射ICP匹配过程中的仿射变换参数;
# (2) 负责用ICP输出的仿射变换参数对点集进行仿射变换。
# 11/24 debug:
# (1)增加新... |
import copy
import pickle
import json
import csv
import argparse
import sys
import torch
import numpy as np
from torch.autograd import Variable
sys.path.append('src/utils/')
from utils import config_parser
from utils.filter_helper import compute_similarity, sample_poles, return_filter_coeffs, extract_eigen_values
fro... |
import torch
from torch import optim
from torchvision.models import alexnet, vgg16
from torchvision import transforms
from dataset import ImageNet
from models import Darknet, MyAlexNet
from utils import (
init_weights,
get_n_classes,
get_accuracy,
print_report,
# mean_average_precision,
# intersection_ov... |
import socketserver
from collections import defaultdict
import struct
import base64
import hashlib
from .utils import prepare_data
from .protocol import *
import random
import threading
import functools
from .logger import get_logger
logger = get_logger(__name__)
class Zwebsocket(socketserver.BaseRequ... |
import sqlite3
from model import face_extract as fe
import cv2
import pickle
import numpy as np
from scipy import spatial
import scipy.misc
import matplotlib.pyplot as plt
import time
import json
import sys
#Returns vector embedding of image, given a path to an image with faces
def get_vec(path):
cap ... |
# Copyright (c) 2019 <NAME>
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publi... |
"""
from https://github.com/sxyu/pixel-nerf/blob/a5a514224272a91e3ec590f215567032e1f1c260/src/data/SRNDataset.py
"""
import os
import torch
import json
import numpy as np
from PIL import Image
from .ray_utils import get_ray_directions, get_rays
from torchvision import transforms
def get_image_to_tensor_balanced(image... |
from math import sqrt
import timeit
from numpy import empty
from heapq import heappush, heappop
"""
#Hypotenuse
def hypo(x, y):
return sqrt(x ** 2 + y ** 2)
"""
# read file
# define
returnPath = []
def readfile(filepath):
Maze =[]
with open(filepath, 'r') as f:
for line in f.readlines():
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author : 陈坤泽
# @Email : <EMAIL>
# @Date : 2021/11/05 09:01
"""
pp是paddlepaddle的缩写
"""
import os
import sys
import logging
from tqdm import tqdm
import numpy as np
import pandas as pd
import humanfriendly
import paddle
import pyxllib.xl
from pyxllib.xl import XlP... |
import os
import pickle
import sys
import matplotlib.pyplot as plt
import numpy as np
from utils.dumpLoaders import RFdataLoader
# sample size
n_sample = 100
n_classes = 1000
exts = ("png", "pdf")
def main(
analysis_root,
rf_root,
model_names,
labels,
key_layer_and_chmax_blockmax=None,
vmin... |
from former import util
from util import mask_
import torch
from torch import nn
import torch.nn.functional as F
import random, math
"""
@kewlcoder - NOTE -
http://peterbloem.nl/blog/transformers
Strongly recommended to go through that blog post before diving into the code.
In the class SelfAttentionWide implement... |
import logging
from datetime import datetime
from bs4 import BeautifulSoup, Tag, Comment
from models import NbaTeam, NbaGame, NbaPlayer
from utilities import game_date, sec_played, team_mappings
logger = logging.getLogger()
class HtmlPage:
def __init__(self, requester, parser):
self.requester = requester
... |
from __future__ import annotations
import dataclasses as dc
import re
from functools import cached_property
from functools import total_ordering
from typing import Any
from chemex.containers.conditions import Conditions
from chemex.nmr.spin_system import Atom
from chemex.nmr.spin_system import Group
from chemex.nmr.s... |
import ply.lex as lex
import logging
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
states = (
('domain', 'exclusive'),
('quote', 'exclusive'),
('comment', 'exclusive'),
)
tokens = (
'FWSP',
'AT',
'DOT',
'COMMA',
'SEMICOLON',
'LANGLE',
'RANGLE',
'ATOM',
... |
#!/usr/bin/env python
# Copyright 2014 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Wrapper around GAE SDK tools to simplify working with multi module apps."""
__version__ = '1.0'
import atexit
import code
impo... |
# GNU MediaGoblin -- federated, autonomous media hosting
# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either versio... |
from rest_framework import serializers
from scholars.users.serializers import UserSerializer
from scholars.utils.dynamic import DynamicFieldsModelSerializer
# from scholars.utils.serializers import ChoicesField
from .models import Course, Slide, get_video_path, Category, CourseMember, SlideReview
class TimezoneSeria... |
"""
Contains all numpy/scipy-dependent code, in case user is unable
to install these packages.
If numpy_error contains [1] there was a problem in loading numpy. This can easily
be detected by the code that imports this file as follows:
if numpy_error:
pass
else:
here is code that needs numpy o... |
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.db.models import Avg, Max, Min, Q
from django.db.models.signals import pre_save
from django.utils import timezone
from django.utils.text import slugify
from vibeon.db.models import PublishStateOptions
from vibeon.db.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script for plotting the recorded C-V measurement curves,
including derived depletion depth and effective charge carrier concentration
(Neff) plots.
@author: <NAME>
@date: March 2019
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import m... |
import argparse
import logging
import librosa
import numpy as np
import torch
def clip_gradient(optimizer, grad_clip):
"""
Clips gradients computed during backpropagation to avoid explosion of gradients.
:param optimizer: optimizer with the gradients to be clipped
:param grad_clip: clip value
"""... |
from app.ctf import blueprint
from flask import render_template,jsonify,request
from flask_login import login_required
from app import db,scheduler,record_return_value_scheduler, get_return_value_scheduler
from app.ctf.models import Target,Script,Task,Flag
import json
import os
import imp
import pip
import uuid
import ... |
import unittest
import unittest.mock
import io
import tempfile
import shutil
import converter
class PgsFileTest(unittest.TestCase):
def test_as_tuples(self):
input_str = io.StringIO("""testpwd -5
asdfasdf 49949""")
self.assertEqual([('testpwd', '-5'), ('asdfasdf', '49949')],
... |
import logging
import os
import sys
from time import time as ts
from typing import Dict, List, Optional, Union
import docker
from docker.models.networks import Network
from . import utils
from .artifacts import ArtifactManager
from .cache import CacheManager
from .config import config
from .container import Container... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This module was on:
[Hilmi 2008: A Random Walk Method for Alleviating the Sparsity Problem in Collaborative Filtering]
"""
from copy import deepcopy
import numpy as np
import pandas as pd
import itertools
from sklearn.metrics.pairwise import cosine_similarity
"""... |
# Clairmeta - (C) <NAME>.
# See LICENSE for more information
import contextlib
import six
import re
@contextlib.contextmanager
def modified_dict(in_dict, *remove, **update):
""" Temporarily updates the ``in_dict`` dictionary in-place.
The ``in_dict`` dictionary is updated in-place so that the modificati... |
import pandas as pd
import os
import sys
import numpy as np
from math import log
from nltk import bigrams, trigrams
from collections import Counter, defaultdict
from scipy.stats import entropy
#from scipy.special import softmax, rel_entr
from datetime import datetime, timedelta
class BigramModel:
def __init__(se... |
"""Tool to pull intraday sleep data from Fitbit.
Register your app as a "personal app" with Fitbit Developers, online at
<https://dev.fitbit.com/apps/new>. Fill out client_secret.json according
to the guidelines in the README. You are then ready to pull your sleep data.
Usage:
fitbit.py
fitbit.py <start date>... |
""" fiber.py
Module containing classes and functions related to processing fiber
information.
"""
import numpy as np
import vtk
from collections import defaultdict
from . import misc
def tree():
"""
Creates tree to store quantitative information.
INPUT:
none
OUTPUT:
none
"""
... |
from itertools import product
# This needs to stay as the first import, it sets up paths.
from .gaetest_common import DummyPostData, fill_authors
from google.cloud import ndb
from wtforms import Form, StringField, IntegerField, BooleanField, \
SelectField, SelectMultipleField, FormField, FieldList
from wtforms_... |
import random
import pandas as pd
from codifyComplexes.codifyProtocols.AbstractProtocol import FEATURES_MISMATH_TOLERANCE
class ComplexCodified(object):
'''
This class contains pairs of amino acids (a,b) such that a belongs
to the ligand of the complex and b to the receptor of the complex.
Each pair of am... |
#!/usr/bin/python2
#
# Copyright 2018 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Tests of data_source_to_dspl module."""
__author__ = '<NAME> <<EMAIL>>'
import unittest
import da... |
from datetime import datetime
from typing import List
from fastapi import APIRouter, Depends
from fastapi import HTTPException
from tracardi.domain.console import Console
from tracardi.service.storage.driver import storage
from tracardi.service.storage.factory import StorageFor, StorageForBulk, storage_manager
from t... |
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import torch.nn as nn
import torch
import math
import torch.utils.model_zoo as model_zoo
from .quant import ClippedReLU, int_conv2d, int_linear
__all__ = ["resnet18_imagenet_quant"]
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.o... |
from basic.types import TP_BAYES, Bow, Configuration, Tuple, Union, elemental
from basic.decorators import type_checker, document
import basic.docfunc as doc
from typing import Sequence
import numpy as np
from numpy import ndarray
import copy
def _rect_inter_inner(x1: ndarray, x2: ndarray) -> Tuple[ndarray]:
n1 =... |
import fcntl
import os
import sys
import signal
import re
import time
from threading import Thread
import codecs
import psutil
try:
from queue import Queue, Empty
except ImportError:
from Queue import Queue, Empty # python 2.x
from subprocess import Popen, PIPE, STDOUT
ON_POSIX = 'posix' in sys.builtin_mod... |
#!/usr/bin/env python3
import os
import sys
# from random
import random
import click
import functions
import downloader
import ioutils
import workflow_animescrapper
import workflow_aria2c
import workflow_server
import workflow_watcher
import workflow_wget
import workflow_ydl
from dto import dto
# - - - - - # - - ... |
"""
Utilities
"""
from collections import defaultdict
import heapq
import json
import logging
from typing import Dict, TypeVar, Tuple, NamedTuple, List, Union, Any, cast
from typing import Sequence, Callable
from .quality_control import QualityControlDecision
T = TypeVar("T")
# Ideally, we would use # the "SimpleOb... |
# -*- coding: utf-8 -*-
from collections import OrderedDict
import string
import re
import numpy as np
from africanus.util.casa_types import STOKES_ID_MAP
class FitsAxes(object):
"""
FitsAxes object, inspired by Tigger's FITSAxes
"""
def __init__(self, header=None):
# Create an zero-dimen... |
import dill
import os
import datetime
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from statistics import mean, stdev
from math import sqrt
import random
sns.set()
weights_loc = './weights.dill'
graph_loc = './weight_graph.png'
# get the data
def get_weight_history():
if os.path.isfil... |
import threading
from sklearn import preprocessing
import settings
import pandas as pd
from bson import ObjectId
import json
import datetime
from constants import MAX_FILE_SIZE
from db.encoding import EncodingHelper
class MongoDataStream(object):
def __init__(self, collection, start_date, end_date, ch... |
"""
This script simulates the beam dynamics when put under hydrodynamic loads using
the FEniCS solver.
It contains three functions:
initialise_results
------------------
This is a way to save the results. Here I decided to save the vectors
of the material frame (t, n, b, ), the displacement w,... |
#!/usr/bin/env python3
# Copyright 2018, OpenSoft Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification, are permitted
# provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of
... |
# Ball Balancing Bot
# Date : 28.09.2017
# Code by : <NAME>
# : <NAME>
#
# Description : This code use OpenCV library to track the color of a ball on frames of a webcam feed and get the co-ordinates
# Then the code will calculate the position where the ball should move and send servo signal... |
from dataclasses import dataclass
from datetime import date, datetime
from glob import glob
from io import BytesIO
from subprocess import PIPE
from typing import Callable, Dict, Iterator, List, TypeVar
from PIL import Image
from pathlib import Path
import cv2
import gc
import joblib
import json
import numpy as np
impor... |
#!/usr/bin/env python
import os
import json
import argparse
import numpy as np
from plantcv import plantcv as pcv
import skimage
from scipy import ndimage as ndi
def options():
parser = argparse.ArgumentParser(description="Camelina PlantCV workflow.")
parser.add_argument("-i", "--image", help="Input image fi... |
import json
from pathlib import Path
import pandas
import glob
import matplotlib.pyplot as plt
import matplotlib.markers as markers
import numpy as np
from math import inf
def get_brats_data():
names = ["cpc", "jigsaw", "rotation", "rpl", "exemplar", "baseline"]
splits = [10, 25, 50, 100]
data = [[0.76, 0.... |
#
# LSST Data Management System
# Copyright 2008, 2009, 2010 LSST Corporation.
#
# This product includes software developed by the
# LSST Project (http://www.lsst.org/).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the ... |
ROOMSIZE = 30
GAPSIZE = 30
rooms = []
selected = []
HELPTEXT = """
Help
----
Click + Drag : Select
X : Deselect
R : Add room
I : Show room info
M : Minimise room info
C : Clean workspace
O : Select all
WASD : Move selected tiles
"""
import tkinter# GUI Stuff
root = tkinter.Tk()
root.title("Sto... |
#!/usr/bin/env python3
"""Oblique self-describing database language.
Oblique is a simple computer language that allows you to define types and data
entries in the same file. It was originally designed to make it possible to
input todo lists, snippets, and planning tasks all in one place, in a format
that is remarkably... |
import argparse
import os, random, pdb, math, sys
import numpy as np
import torch
from torch.utils.data import DataLoader
from torchvision import transforms
import network, my_loss
import lr_schedule, data_list
def image_train(resize_size=256, crop_size=224):
return transforms.Compose([
transforms.Resize(... |
#!/usr/bin/env python
#
# Copyright (c) 2016 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, mer... |
import gym
from enum import IntEnum
import random
import numpy as np
from snake.envs.snake_env import SnakeEnv
from snake.envs.snake_env import Action
class Snake():
def __init__(self, body):
self.body = body
self.direction = random.choice(list(Action))
self.done = False
# died_number is the order i... |
import tensorflow as tf
def pad_border(tensor, filter_size):
rep = filter_size // 2
tensor = tf.concat([tf.tile(tensor[:, :, 0:1, :], (1, 1, rep, 1)), tensor, tf.tile(
tensor[:, :, -1:, :], (1, 1, rep, 1))], axis=2)
tensor = tf.concat([tf.tile(tensor[:, 0:1, :, :], (1, rep, 1, 1)), tensor, tf.t... |
import os # Import OS for cwd, mkdir
import numpy as np
from numpy.core.numeric import NaN
import pandas as pd
import logging
LOG_MSGFORMAT = "%(asctime)s - %(message)s"
LOG_TIMEFORMAT = "%H:%M:%S"
logging.basicConfig(format=LOG_MSGFORMAT, datefmt=LOG_TIMEFORMAT, level=logging.DEBUG)
def getFileListRoot(path: str, ... |
import argparse
import uuid
import os
import cv2
import numpy as np
from constants.ultrasound import (
HSV_COLOR_THRESHOLD,
FRAME_DEFAULT_ROW_CROP_FOR_SCAN_SELECTION,
FRAME_DEFAULT_COL_CROP_FOR_SCAN_SELECTION)
def select_out_curvature_line(
scan_window,
target_slice_percentage=0.025,
target_sl... |
import base64
import json
import logging
import os
from abc import ABC, abstractmethod
from time import sleep
import boto3
from botocore.exceptions import ClientError
from google.auth.exceptions import DefaultCredentialsError
from google.cloud import storage
from ocs_ci.framework import config
from ocs_ci.ocs import ... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
"""
Knows about local and global names for a PositionTree
"""
from tree import PositionTree
import random
from collections import namedtuple
ROOT_NAME = ''
GLOBAL_SEPARATOR = "."
FLATTEN_SEPARATOR = "__"
# Describes position of a flattened tree
NamedElement = namedtuple('NamedElement', 'tree position')
class NodeNa... |
#!/usr/bin/env python3
# set interpreter
import hashlib
import os
from argparse import ArgumentParser
def handle_wel_args():
global rsync, path
rsync = ArgumentParser(prog="rsync",
usage='./rsync.py [OPTIONS] SRC [SRC...] DES')
rsync.add_argument('srcs', nargs="+", help="sourc... |
# Copyright (C) 2019 NTT DATA
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Project: Sift implementation in Python + OpenCL
# https://github.com/silx-kit/silx
#
# Copyright (C) 2013-2017 European Synchrotron Radiation Facility, Grenoble, France
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy... |
import pickle
from datetime import datetime
from typing import Optional, Tuple, Any
from dataclasses import dataclass, field
from pathlib import Path
import jsonpickle.handlers
from triple_agent.classes.missions import Missions
from triple_agent.classes.outcomes import WinType
from triple_agent.classes.venues import V... |
#!/usr/bin/env python
# Modified code from: https://github.com/asrivat1/DeepLearningVideoGames
# Network rates positions:
# Pieces on bad positions will be moved to better positions if possible
# Pieces will be set down on best positions
# Opponent pieces on best positions will be taken
#
# Input: 2... |
# 迷宫基本规则
# 砸墙理解方法:每一个格子理解为一个房间,有四堵墙
# 1. 当隔壁房间没有去过才可以砸墙
# 2. 去到终点后,执行 3
# 3. 当有房间没有去过,在其最近已经去过的房间随机选一个,按照规则 1 开始砸墙,直到不可以砸墙,重复,直到不存在没有去过的房间
import tkinter as tk
import random
import time
HEIGHT = 4
WIDTH = 6
MAZE_IN = [1, 1]
MAZE_OUT = [HEIGHT, WIDTH]
CELL_SIZE = 50
BORDER_SIZE = 20
class GUI:
def __init__(self... |
from sklearn.model_selection import LeaveOneOut
from sklearn.neural_network import MLPClassifier
from load_models import load_model
from utils import load_data, load_vecs, results_to_file, merge_wi_dicts
from utils import to_np_array
import numpy as np
from scipy.sparse import csc_matrix
import sys
from random import s... |
from __future__ import division
#function snippets
def simple1():
return 1
def simple2():
return False
def simple3(i):
c = "Hello, Stars!"
return c[i]
def simple4():
return 3 + simple1()
def simple5(b):
if b:
x = 12
else:
x = 13
return x
def simple6():
simple4()... |
#!/usr/bin/env python3
from argparse import ArgumentParser
from dataclasses import dataclass
import sys
@dataclass
class Section:
start: int
end: int
def __contains__(self, address):
return self.start <= address < self.end
@dataclass
class SrcBinary:
start: int
sections: [Section]
... |
import argparse
import calendar
import os
import sys
import img2pdf
from PyPDF2.pdf import PdfFileWriter, PdfFileReader
import time
# Get the timestamp
ts = calendar.timegm(time.gmtime())
def PdfPassword(filepath, password):
# Check if file exists
checkFile = os.path.isfile(filepath)
if checkFile:
... |
from itertools import permutations
import pytest
from causal_networkx.algorithms import (
discriminating_path,
possibly_d_sep_sets,
uncovered_pd_path,
)
from causal_networkx.cgm import ADMG, PAG
from causal_networkx.ci import Oracle
from causal_networkx.discovery import FCI
def test_possibly_d_separated... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.