text stringlengths 3.07k 12.6k |
|---|
# -*- coding: UTF-8 -*-
"""
Capture output (stdout, stderr), logs, etc.
"""
from __future__ import absolute_import
from contextlib import contextmanager
import sys
from six import StringIO, PY2
from behave.log_capture import LoggingCapture
from behave.textutil import text as _text
def add_text_to(value, more_text, se... |
# -*- coding: utf-8 -*-
import unittest
import pandas as pd
from ddt import data, ddt, unpack
from melo.conf import BASE_K_FACTOR
from melo.poc import compute_score, update_matches_outcome
# TODO: Use pytest fixtures for more cases.
def _compute_expected_score(score_1, score_2):
return 1 / (1 + 10 ** ((score... |
import time
import discord
import psutil
import os
import re
import tempfile
from io import BytesIO
from urllib.request import urlopen
from expiringdict import ExpiringDict
from pixivpy3 import AppPixivAPI
from discord.ext import commands
from utils import default
from utils.tweetscrapper import TweetSc... |
#!/usr/bin/env python
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
"""
import sys
import matplotlib.pyplot as plt
import numpy as np
import cupy as cp
import time
import os
import tensorflow as tf
import vedo
######## START GPU SETTINGS ############
########## SET MEMORY GROWTH to True ############
physical_devices = tf.con... |
#!/usr/bin/env python3
import psutil, requests, json, time, socket
import datetime
RIGNAME = 'rig01'
def telegrambot(bot_msg):
data = {
'message': bot_msg
}
url = "YOUR_TELEGRAMBOT_WEBHOOK_URL"
try:
req = requests.post(url, data=data)
except:
pass
def minerDetect():
# EWBF
# CCMINER
# ETHDCRMINER6... |
# Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license.
# See LICENSE in the project root for license information.
from urllib.parse import unquote
from falcon import HTTPError, HTTP_201, HTTPBadRequest, HTTPNotFound
from ujson import dumps as json_dumps
from ...auth import... |
from __future__ import absolute_import, annotations
import gzip
import json
import logging
import os
import re
from xml.etree import cElementTree as ET
import click
import gensim
logger = logging.getLogger("recap")
logger.setLevel(logging.INFO)
"""
Module for converting models from different formats to the ones us... |
from unittest import TestCase, main
from project.folder_reader import KillerFolder, KillerFile, FolderStore, RootDoesNotExist
class KillerFolderTestCase(TestCase):
def setUp(self):
self.folder = KillerFolder('king', 'C:\\user\\main')
self.folder_1 = KillerFolder('queen', 'C:\\user\\main\\queen', ... |
import torch
from torch.utils.data import DataLoader
from torch.autograd import Variable
from voc import VOCDataset
from darknet import DarkNet
from yolo_v1 import YOLOv1
from loss import Loss
import os
import numpy as np
import math
from datetime import datetime
from tensorboardX import SummaryWriter
# Check if G... |
import sys
import os
import re
from collections import deque
day_number = sys.path[0].split('\\')[-1]
if len(sys.argv)==1:
path_to_source = os.path.join("\\".join(sys.path[0].split("\\")[:-2]), f"input\\{day_number}")
else:
path_to_source = os.path.join("\\".join(sys.path[0].split("\\")[:-2]), f"sample\\{day_nu... |
import platform
import textwrap
import unittest
from jinja2 import Template
from parameterized.parameterized import parameterized
from conans.client.build.compiler_flags import architecture_flag, build_type_flags
from conans.client.build.cppstd_flags import cppstd_flag_new
from conans.client.toolchain import MakeTool... |
from torch import nn, optim
import torch
import numpy as np
from torch.utils import data
from styleflow.flow import cnf
from math import log, pi
import os
from tqdm import tqdm
import random
import torchvision.transforms as transforms
from torch.utils.data import Dataset
import torchvision.datasets as dset
import argp... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 21 11:55:50 2021
@author: freeridingeo
"""
import os
from pathlib import Path
import numpy as np
import pandas as pd
import geopandas as gpd
from sentinelhub import BBoxSplitter, CRS
import rasterio
from rasterio.windows import Window, bounds as wind_bounds
from rasteri... |
import pandas as pd
import math
from math import log
# 测试数据集
def create_data():
datasets = [
['青年', '否', '否', '一般', '否'],
['青年', '否', '否', '好', '否'],
['青年', '是', '否', '好', '是'],
['青年', '是', '是', '一般', '是'],
['青年', '否', '否', '一般', '否'],
['中年', '否', '否', '一般', '否'],
... |
#! /usr/bin/env python3
import boto3
import chevron
import click
import coloredlogs
import datetime
import jq
import json
import logging
import os
import re
import requests
import sys
import tempfile
import urllib3
MAX_FILES = 10
INPUTS_FILE_MUSTACHE = 'parliament2_inputs.mustache'
def make_url(host):
'''Return ... |
# -*- coding: utf-8 -*-
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models import Sum, Count
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.hashers import make_password, check_password
# Base
class AbstractBaseModel(models.Model):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
from flask import Blueprint,Response, request, session, redirect, url_for
from flask import json, jsonify, render_template
import pandas as pd
from flask import current_app as app
from webapp import functions as fn
from flask_principal import I... |
import os, sys
import h5py
import PIL
import cv2
import numpy as np
from tqdm import tqdm
from action_to_seg_pl_filename import action_to_seg_pl_filename
# multiprocessing routine
def routine(img_action_path, cam, subj, action, files, save_dir):
img_cam_path = os.path.join(img_action_path, cam)
img_files = []... |
from PyQt5.QtWidgets import QGraphicsView, QGraphicsScene, QDialog, QGridLayout, QComboBox, \
QSpinBox, QPushButton
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QImage, QPixmap, QColor, QPainter, qRgb, qRgba
COLORKEY = (128, 160, 128)
class ImageView(QGraphicsView):
def __init__(self, windo... |
import json
import datetime
import urllib
import os
import argparse
from time import sleep
from Queue import Queue
from threading import Thread
try:
import requests
except ImportError:
print ('Python requests module required, get it from the cheese shop (https://pypi.python.org/pypi/requests/) or run:')
p... |
import discord
import random
import asyncio
from discord.ext import commands
bot_token = '<PASSWORD>_token'
dlt_cnl_id = int('client_id')
Client = commands.Bot(command_prefix='+')
# -----------------------------------------------------
status_play = ("on Devil's Orders", "with Admin's Life", "Tic-Tac-Toe", ... |
from django.db import models
# Create your models here.
class Project_Config(models.Model):
project_repertory_choices = (
('git', 'git'),
('svn', 'svn'),
)
deploy_model_choices = (
('branch', 'branch'),
('tag', 'tag'),
)
project_env = models.CharField(max_length=50,... |
import os.path
import unittest
class Test_parse_named_assetspecs(unittest.TestCase):
def _callFUT(self, *args, **kwargs):
from pyramid_jinja2.settings import parse_named_assetspecs
return parse_named_assetspecs(*args, **kwargs)
def test_it_with_strings(self):
from pyramid.path import... |
import imp
import re
import os
# Some helper functions to get the correct version of a file
def get_src_file(file, env):
return str(File(env.subst('$BASE_DIR') + "/" + file).srcnode().abspath)
def get_build_file(file, env):
return str(File(env.subst('$BASE_DIR') + "/" + file).abspath)
def get_bin_file(file, ... |
"""
Author: Darren
Date: 12/11/2021
Solving https://adventofcode.com/2016/day/23
We need to tweak the Day 12 Monorail Assembunny computer.
Uses same instruction set as Assembunny, but now adds a new instruction: tgl x
This means: toggle the instruction that is x instructions away.
Part 1:
Extend the original Ass... |
# -*- coding: utf-8 -*-
# @Time : 2020/8/7 1:07 下午
# @Author : shiro
# @Software: PyCharm
import asyncio
import hashlib, re, requests
import aiohttp
import saucenao_api
async def CACHE_IMG(url):
async with aiohttp.request("GET", url) as file:
data = await file.read()
with open("cache.jpg", "wb+")... |
import torch
import torch.nn as nn
import numpy as np
from mmcv.cnn import ConvModule
from PIL import Image
from ..builder import HEADS
from .decode_head import BaseDecodeHead
import torch.nn.functional as F
from scipy.ndimage.morphology import distance_transform_edt
###seg to edge
def label_to_onehot(label, num_classe... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import json
import sys
from django.contrib.sessions.middleware import SessionMiddleware
from django.contrib.sites.models import Site
from django.core.exceptions import PermissionDenied
from django.test import TestCase
from django.test.cl... |
from io import BytesIO as BIO
class Bitstream(object):
def __init__(self, buf=None, raw=None, bits=None):
self.bytes = buf or BIO(raw)
self.bits = bits or []
def __len__(self):
curr = self.bytes.tell()
last = self.bytes.seek(0, 2)
self.bytes.seek(curr)
... |
#
# multistagefingerprint.py
#
# Author(s):
# <NAME> <<EMAIL>>
#
# Copyright (c) 2018-2021 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/license... |
# coding=utf-8
import sys
import os
import logging
import urllib
from book_record import BookAnnotation
sys.path.append(os.path.join(os.path.dirname(__file__), "third_party"))
import webapp2
from autocompleter import Autocompleter, BookRecord
import json
from suggest import Suggester, SuggestionsRecord
from google.a... |
import torch
import torch.nn as nn
from torch.nn import functional as F
import matplotlib.pyplot as plt
from tqdm import tqdm
import numpy as np
from scipy.stats import norm
import scipy.io
# Load and prepare training set
img_size = (28, 20)
img_data = scipy.io.loadmat('Data/frey_rawface.mat')["ff"]
img_da... |
# -*- encoding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright © 2021 <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 ... |
def shuffle(cards, cmds):
cards = list(cards)
for cmd in cmds:
if cmd.startswith('cut'):
_, n = cmd.split()
n = int(n)
cards = cards[n:] + cards[:n]
elif cmd.strip() == 'deal into new stack':
cards = cards[::-1]
elif cmd.startswith('deal wi... |
import logging
import re
logger = logging.getLogger(__name__)
def _sanitize(line):
# try to make the metric names, graphite compatible
line = re.sub(r"\s+", "_", line)
line = re.sub(r"\/", "_", line)
line = re.sub(r"^\.", "", line)
line = re.sub(r"[^a-zA-Z_\-0-9\.]", "", line)
return(line)
... |
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import torch
from pathlib import Path
def comp_corr_pred(cm: np.ndarray) -> float:
"""Returns the ratio of true positives over the total.
Estimates how many correct predictions the model did
Args:
cm (np.ndarray): confusion ... |
# This file is a part of GrumpyWidgets.
# The source code contained in this file is licensed under the MIT license.
# See LICENSE.txt in the main project directory, for more information.
import re
from pycerberus.validators import StringValidator
from pythonic_testcase import *
import six
from grumpyforms.fields imp... |
# Written by <NAME>, <EMAIL>
# Last modified 4/01/2021
import h5py
import numpy as np
import pywt
""" Given a coefficient vector and a percentile, this truncates all entries which are below
the vector's percentile in magnitude.
Inputs:
coeffs A set of wavelet coefficients derived from a DWT
percentile ... |
from __future__ import absolute_import, unicode_literals
import functools
import socket
import time
from clay import config
log = config.get_logger('clay.stats')
class StatsConnection(object):
'''
Handles the lifecycle of stats sockets and connections.
'''
def __init__(self):
self.sock = No... |
import pytest
from six import print_
try:
import unittest2 as unittest
except ImportError:
import unittest
from hypothesis import given, settings
import hypothesis.strategies as st
try:
from hypothesis import HealthCheck
HC_PRESENT=True
except ImportError:
HC_PRESENT=False
from .numbertheory import ... |
#!/usr/bin/env python3
'''
calculateGenomeSize.py -- calculate the number of bases in genome(.fa|.fa.gz) file.
Author:
<EMAIL>
Bugs:
Any bugs should be reported to the above E-mail.
Info:
Scale units:
1 kbp (kilo base pairs) = 1,000 bp (base pairs)
1 Mbp (mega base pairs) = 1,000,000 bp
1 Gbp ... |
from firedrake import *
import numpy as np
from firedrake.petsc import PETSc
from firedrake import COMM_WORLD
try:
import matplotlib.pyplot as plt
plt.rcParams["contour.corner_mask"] = False
plt.close("all")
except:
warning("Matplotlib not imported")
nx, ny = 20, 20
Lx, Ly = 1.0, 1.0
quadrilateral = ... |
#!/usr/bin/env python
# coding:utf-8
"Integrated Simpler Web Browser for testing web2py apps"
__author__ = "<NAME> (<EMAIL>)"
__copyright__ = "Copyright (C) 2011 <NAME>"
__license__ = "GPL 3.0"
# Based on wxPython examples (HTML2 using IE on Windows and webkit on Linux)
import os
import sys
import wx
DEFA... |
#!/usr/bin/env python
import argparse
import os
import re
import shutil
import pandas
import pysam
from Bio import SeqIO
def get_sample_name(file_path):
base_file_name = os.path.basename(file_path)
if base_file_name.find(".") > 0:
# Eliminate the extension.
return os.path.splitext(base_file_... |
from rdkit.Chem.Descriptors import MolWt
from .mol_parse import nx_to_mol
from rdkit import Chem
from .utils import *
import copy
from .graph_parse import prepare_dict
def parse_mol_text(text):
fragment_dict = {}
try:
fragment_dict = prepare_dict(text)
except:
fragment_dict["status"] = "Er... |
from __future__ import print_function # In python 2.7
from flask import Flask, session, render_template, make_response, jsonify, request, send_from_directory, g, url_for
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import json
from sklearn.naive_bayes import GaussianNB
import num... |
# -*- coding: utf-8 -*-
"""
Resources below '/<api_base>/token'
"""
from __future__ import print_function, unicode_literals
import logging
from flask import request, g
from flask_jwt_extended import (
jwt_refresh_token_required,
create_access_token,
create_refresh_token,
get_jwt_identity
)
from flasgg... |
"""Helper functions for the ``actions`` package."""
import functools
import importlib
import logging
import re
import sys
from collections import namedtuple
from typing import Any
from typing import Callable
from typing import Dict
from typing import Generator
from typing import List
from typing import Tuple
from .... |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... |
#!/usr/bin/env python3
# -*- indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4; -*-
import cffi
import math
import os
import random
import re
import subprocess
import unittest
src_directory = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
def compile_gf2curve():
"""Compile module bitvec.c"... |
import base64
import logging
import os
from github.ContentFile import ContentFile
import hmac
import hashlib
import yaml
import azure.functions as func
import github
from github.Commit import Commit
from github.PullRequest import PullRequest
from github.Repository import Repository
SUPPORTED_BOTS = {
"dependabot",... |
import math
import statistics
import warnings
import numpy as np
from hmmlearn.hmm import GaussianHMM
from sklearn.model_selection import KFold
from asl_utils import combine_sequences
class ModelSelector(object):
'''
base class for model selection (strategy design pattern)
'''
def __init__(self, all... |
import datetime
import time
from collections import defaultdict, deque
from typing import Dict, List
import numpy as np
from procgen_adventure.algos.base import Algo
from procgen_adventure.algos.ppo.model import Model
from procgen_adventure.algos.ppo.sampler import Sampler
from procgen_adventure.algos.utils import ge... |
from flask import Flask, render_template, request
import pandas as pd
import dao
import json
import plotly
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
app = Flask(__name__)
@app.route('/getData')
def getData():
df = dao.getWinDeltaData()
return df.t... |
from traffic.testing import *
from traffic.utils import *
from traffic.consts import *
from traffic.imports import *
from traffic.logging import *
from traffic.mrcnn import *
def setup_function(function):
MrcnnCategory.clear()
def teardown_function(function):
patch.stopall()
@name(MrcnnCategory.__new__, "... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 19 14:34:01 2018
@author: Harry
Creates "segment level d vector embeddings" compatible with
https://github.com/google/uis-rnn
Edited on Nov 11, 2020
@author: <NAME>
Create dvector embeddings and labels
based on SCOTUS Oyex data (preprocessed)
"... |
from nose.tools import assert_equal, assert_not_equal, \
assert_true, assert_false, raises
from mock import Mock
from .tests_base import TestsBase
from arango import create
from arango.core import Connection, Response, Resultset
from arango.clients import Client
class TestConnectionInit(TestsBase):
def t... |
import importlib
from unittest.mock import MagicMock, patch, PropertyMock
import pytest
from tools.testing import plugin, python_pytest
# this is necessary to fix coverage as these libs are imported before pytest
# is invoked
importlib.reload(python_pytest)
importlib.reload(plugin)
def test_pytest_cov_collect():... |
import logging
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import redirect, render
from django.utils import timezone
from django.views.decorators.http import require_POST
from apps.core.backends import (
... |
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
def plot_margin(X, Y, model, title=''):
"""
Represents the performance of a svm model over data.
Parameters
----------
X: ndarray
data points. (shape:(n_samples, dim))
Y: ndarray
groundtruth labels. (shape:(n_sa... |
from django.core.paginator import Paginator, PageNotAnInteger, InvalidPage, EmptyPage
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.core import serializers
from django.http import JsonResponse
import json
from rest_framework_jwt.utils import jwt_decode_ha... |
import pygame
from math import copysign
WIDTH = 800
HEIGHT = 640
FPS = 60
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Run!!!")
clock = pyg... |
# Copyright (c) 2017 Civic Knowledge. This file is licensed under the terms of the
# MIT, included in this distribution as LICENSE
""" """
from rowgenerators.appurl.file.file import FileUrl
from rowgenerators.exceptions import AppUrlError
class ZipUrlError(AppUrlError):
pass
class ZipUrl(FileUrl):
"""Zip ... |
# Copyright 2019-2020, <NAME>;
# Licensed under the terms of the Apache License, Version 2.0. See the LICENSE file associated with the project for terms.
""":term:`jetsam` utility for annotating exceptions from ``locals()``.
.. doctest::
:hide:
.. Workaround sphinx-doc/sphinx#6590
>>> from graphtik.jetsa... |
from tvm.relay.transform.pattern_manager.target import *
from tvm.collage.optimizer.custom_fusion_pass import CustomFusionPass
from tvm.contrib import graph_executor as runtime
import argparse
from tvm import autotvm
from workloads.torch_workloads import *
from tvm.relay.transform.utility.debug_helper import *
from bac... |
"""Package defining all the IMAP parsing and response classes."""
from __future__ import annotations
from abc import abstractmethod, ABCMeta
from collections.abc import Sequence
from typing import Any, TypeVar, Generic
from .exceptions import NotParseable, UnexpectedType
from .state import ParsingState
from ..bytes ... |
""" scan filesystem
tors_dct: {coordinate name: number of points}
"""
import os
import functools
import autofile
import autoinf
from autodir import par
from autodir import util
from autodir.run import information as _run_information
# path definitions
BASE_DIR_NAME = 'SCANS'
def base_path(prefix):
""" base dir... |
import discord
import re
print("Launching PuppetBot. This may take a second...")
client = discord.Client()
is_ready = False
home_server = None
output = None
token = None
puppet_master_ids = []
ignore_ids = []
prefix = "pb!"
prefix_been_set = False
config_file = open("PuppetConfig.txt", 'r') #todo: make this a cli a... |
import polymath as pm
from collections import OrderedDict
import numpy as np
from tvm.relay.frontend.common import infer_channels, infer_shape
from tvm import relay
@pm.register_pass
class TVMPass(pm.Pass):
def __init__(self):
self.tvm_ir = {}
self.last = None
super(TVMPass, self).__init_... |
# -*- coding: utf-8 -*-
import logging
import sys
import traceback
from contextlib import contextmanager
from enum import EnumMeta
from io import BytesIO
from typing import List, Union
import allure
from PIL import Image
from selenium.common.exceptions import (
ElementClickInterceptedException,
ElementNotInter... |
import os.path
from datetime import datetime, timedelta, date
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.core.files import File
from django.core.management import call_c... |
#!/usr/bin/env python
'''
Generates an AST_L1T-SO2 product
'''
from __future__ import print_function
import os
import json
import urllib3
import dateutil.parser
import requests
import numpy as np
from hysds.celery import app
import run_ratio
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
PROD_S... |
"""
KNAPSACK PROBLEM
--------------------
This problem represents a generalization that can be applied to a wide variety of real-life problems.
Considering a set of 'n' elements, each one has associated a value 'v' and a cost 'c'. The objective of the problem
is to select the subset of elements that maximizes the sum ... |
"""Module containing class `ClipCountsExporter`."""
import csv
import datetime
from vesper.singletons import archive
import vesper.django.app.model_utils as model_utils
import vesper.old_bird.clip_count_utils as clip_count_utils
'''
Clip Count Table preset for Old Bird:
preset_type: Clip Count Table
preset_type_v... |
# Quick and dirty end-to-end integration tests
# Run 'python -m pytest' in the root directory
#
import os
import sys
import pdb
import re
import time
import collections
import argparse
import random
import subprocess
import numpy as np
class STDOUTParserError(Exception):
def __init__(self, message):
se... |
import re
import sys
from bioblend import galaxy
from find_by_tags import find_histories_by_tags
def show_matching_dataset_info(
gi, history_id, dataset_names,
visible=None, types=None, include_invocation_inputs=True
):
name_patterns = [re.compile(name) for name in dataset_names]
history_datasets_inf... |
from __future__ import print_function
import os
import time
from datetime import datetime
import math
import argparse
import logging
import pickle
import yaml
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
f... |
# Example 1: Using Descriptors to Compute Attributes
# Create the display name of an object when it is needed.
class DisplayName:
def __get__(self, instance, owner=None):
parts = []
if instance.salutation:
parts.append(instance.salutation)
if instance.forename:
par... |
# coding: utf-8
# In[ ]:
import pandas as pd
import tensorflow as tf
import io
import requests
# # read data and fix errors
# the data read has some minor errors like string 'false' instead of boolean False
# let's fix them
# In[2]:
#read training data set
def read_train_data():
return pd.read_csv('./tra... |
"""
Contains all application routes
"""
import time
from datetime import datetime
from typing import Tuple
from flask import current_app as app
from flask import g, jsonify, request
from flask_httpauth import HTTPBasicAuth
from jsonschema import ValidationError, validate
from sqlalchemy import asc
from .models import... |
# -*- coding: utf-8 -*-
#
# || ____ _ __
# +------+ / __ )(_) /_______________ _____ ___
# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 2018 Bitcraze AB
#
# Th... |
import sys
sys.path.append("../")
from appJar import gui
from mcpi.minecraft import Minecraft
# put this near the top of your code
BLOCKS={ "AIR":0, "STONE":1, "GRASS":2, "DIRT":3, "COBBLESTONE":4,
"WOOD_PLANKS":5, "SAPLING":6, "BEDROCK":7, "WATER_FLOWING":8, "WATER":8,
"WATER_STATIONARY":9, "LAVA_FLOWING":10... |
#!/usr/bin/env python
"""convert magnet link to torrent file.
Created on Apr 19, 2012 @author: <NAME>
GNU GENERAL PUBLIC LICENSE - Version 3
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Found... |
import contextlib
import logging
import sys
import time
import warnings
from datetime import datetime
from typing import Any, Callable, Iterator, Optional, Tuple, Union, cast
import torch
from torch.optim.lr_scheduler import _LRScheduler as LRScheduler
from torch.optim.optimizer import Optimizer
import pystiche
from ... |
#!/usr/bin/env python3
# file CanVisa.py
import sys, can, time, datetime, string, struct, math, pyvisa
# get object dictionary for the Visa instrument
from Keithley2230 import theTree
# setup for various CAN interfaces
# https://copperhilltech.com/pican2-controller-area-network-can-interface-for-raspberry-pi/
# sud... |
import time
import numpy as np
import torch
from torch import nn
from torch import optim
from config import device, label_names, print_every, hidden_size, encoder_n_layers, dropout, learning_rate, start_epoch, \
epochs
from data_gen import SaDataset
from models import EncoderRNN
from utils import AverageMeter, Ex... |
# 3D PICK AND PLACE SIMULATION
import numpy as np
import logging
from math import *
from matplotlib import pyplot as plt
from utils import init_fonts
from obstacles import Parallelepiped
from objects import Object
from arm import Arm
from arm_state_machine import ArmStateMachine, ArmState
from velocity_control import *... |
# Copyright (c) 2011 OpenStack, LLC.
# 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 requi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Parallel Builder """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ imp... |
from constants.enum import *
class MyInfo(object):
""""信息类"""
# 好友信息表(包括群) remark_name -> user_id //global_friends_list
user_name_to_user_id = dict()
# 聊天信息 chat_id -> chat_info() //global_chat_info
chat_id_to_chat_info = dict()
# 用户ID与聊天ID映射表 user_id -> chat_id // global_name_id_map
us... |
import json
import time
import torch
import torchvision
import cv2
import numpy as np
from flask import Flask, request
from flask_cors import CORS
import traceback
import base64
# __cache_folder__ = 'D:\\mobile-apps\\image_similarity_demo\\server\\cache\\'
__cache_folder__ = 'D:\\github_repo\\mobile-apps\\image_simil... |
"""
This demonstrates a simple skill built with the Amazon Alexa Skills Kit to define the general terms of Machine Learning.
"""
from __future__ import print_function
import json
import boto3
import random
DEF = 'B' # key in the dictionary containing the definition of the term
START_MESSAGE = ' has the following def... |
# -*- coding: utf-8 -*-
import logging
import numpy as np
from math import sqrt, sin, cos, acos
from math import factorial as fact
import rmgpy.constants as constants
from ape.HarmonicBasis import IntXHmHnexp
from ape.FourierBasis import IntXPhimPhin
# fix overflow problem
from decimal import Decimal as D
from decim... |
from flask import Flask, render_template, request, Response
import logging
# import azure.functions as func
import config_cosmos
import pydocumentdb.document_client as document_client
import config_cosmos
import os
import urllib.request
import json
import time
import datetime
import sys
# sys.path.append('/models')
sys... |
import PySimpleGUI as sg
import auto_splitter.variables as variables
from time import sleep
import json
def read_routes_from_file():
try:
with open('routes.json', 'r') as f:
config = json.load(f)
except:
config = {
'routes': [
['Default', []]
... |
"""A collection of function for doing my project."""
from datetime import datetime as dt
# For my_script.py, MUST comment/hide when running test_function.py
from my_module.classes import Manager
# For test_function.py, MUST comment/hide when running my_script.py
#from classes import Manager
import os
def create_tas... |
# $language = "python"
# $interface = "1.0"
import os
import sys
import logging
# Add script directory to the PYTHONPATH so we can import our modules (only if run from SecureCRT)
if 'crt' in globals():
script_dir, script_name = os.path.split(crt.ScriptFullName)
if script_dir not in sys.path:
sys.path.... |
import os
import tensorflow as tf
from tensorflow.python.framework import ops
dir = os.path.dirname(os.path.abspath(__file__))
_lr_module = tf.load_op_library('%s/../../lib/tf_linear_recurrence.so' % dir)
def linear_recurrence(decays, impulses, initial_state=None):
'''
Compute r[i] = decays[i] * r[i - 1] + im... |
''' Evaluation of agent trajectories '''
import json
from collections import defaultdict
import networkx as nx
import numpy as np
import pprint; pp = pprint.PrettyPrinter(indent=4) # NoQA
from env import R2RBatch, ImageFeatures
import utils
from utils import load_datasets, load_nav_graphs
from follower import BaseAg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.