text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/python
import argparse
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
def exit_and_explain(msg):
logging.critical(msg)
sys.exit(msg)
def cleanup_before_exit(tmp_dir):
if tmp_dir and os.path.exists(tmp_dir):
shutil.rmtree(tmp_dir)
def get_... |
import pycocotools.coco as coco
from pycocotools.cocoeval import COCOeval
import sys
import cv2
import numpy as np
import pickle
IMG_PATH = '/kaggle/input/coco-2017-dataset/coco2017/val2017/'
ANN_PATH = '/kaggle/input/coco-2017-dataset/coco2017/annotations/instances_val2017.json'
DEBUG = True
import matplotlib.pyplot a... |
import re
import sys
import itertools
import pygraphviz as pgv
import logging
logging.basicConfig(
filename="parse.log",
level=logging.DEBUG,
format="%(levelname)s:%(message)s",
filemode="w",
)
if len(sys.argv) != 2:
print("You have given too many arguments")
sys.exit(1)
G = pgv.AGraph(direct... |
import pygame
import random
import pickle
import constants
class World:
def __init__(self, bg_colour):
self.bg_colour = bg_colour
self.sprite_list = []
self.car_sprite = ""
self.road_sprite = ""
self.ended = False
self.end_world_crashed = ""
self.end_world_e... |
"""Examples to be used in tests."""
import ast
import contextlib
import inspect
import itertools
import sys
import typing as t
import numpy as np
import static_typing as st
import typed_ast.ast3
AST_MODULES = (ast, typed_ast.ast3)
def function_a1():
"""function with built-in types"""
a = 0
b = 0.0 # t... |
"""Sementic module."""
from collections import OrderedDict
from gibica import builtins
from gibica.ast import NodeVisitor, AST, FunctionDeclaration
from gibica.exceptions import SementicError
from gibica.types import Function
#
# <NAME>
#
class Symbol(object):
"""Container of a symbol."""
def __init__(se... |
from PIL import Image
import numpy as np
from jax import numpy as jnp
from util.image import gradient, gradient_to_img, laplace, laplacian_to_img
from abc import ABC, abstractmethod
def get_data_loader_cls_by_type(type):
if type == "normal":
return NormalImageLoader
elif type == "gradient":
re... |
import torch
from tensorboardX import SummaryWriter
import numpy as np
import os
from datetime import datetime
from multiprocessing import cpu_count
import gc
import random
import sys
os.chdir("style_transfer")
sys.path.append("./../models")
sys.path.append("./../general_modules")
from st_argument_parser_helper impo... |
# Copyright 2018 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... |
# coding: utf-8
import time
import torch.optim
from collections import OrderedDict
from attrdict import AttrDict
import pandas as pd
try:
import cPickle as pickle
except ImportError:
import pickle
import json
import pdb
from src.args import build_parser
from src.train_and_evaluate import *
from src.component... |
import requests
from optparse import OptionParser
import sys
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
parser = OptionParser()
parser.add_option("-u", "--url", dest="url",
help="Enter your desired action", default='NotDefined')
parser.add_option("-c", "--cookie... |
import os
import pathlib
import time
import numpy as np
import tensorflow as tf
# from backgammon.agents.human_agent import HumanAgent
from tqdm import tqdm
import backgammon.game as bg
from backgammon.agents import RandomAgent
from backgammon.agents_old.tf_agent import TfAgent
# helper to initialize a weight and b... |
"""MIPhy class that performs the clustering and stability analysis.
"""
import os
import numpy as np
from miphy_resources.miphy_common import MiphyValidationError, MiphyRuntimeError
from miphy_resources import phylo
class Clusterer(object):
def __init__(self, gene_tree, species_tree_data, species_map, use_coords... |
# -*- coding: utf-8 -*-
# (C) Copyright 2019 Hewlett Packard Enterprise Development LP.
# 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... |
#!/usr/bin/env python
import numpy as np
import datetime as dt
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm, ListedColormap,BoundaryNorm
from scipy.ndimage.filters import gaussian_filter
from scipy.stats import pearsonr
import os
import pickle as pickle
... |
from slm_lab.agent.algorithm import policy_util
from slm_lab.lib import logger, util
import os
import pydash as ps
import torch
import torch.nn as nn
import torch.nn.functional as F
NN_LOWCASE_LOOKUP = {nn_name.lower(): nn_name for nn_name in nn.__dict__}
logger = logger.get_logger(__name__)
def build_sequential(di... |
#!/usr/bin/env python3
# type: ignore
import time
import math
import atexit
import numpy as np
import threading
import random
import cereal.messaging as messaging
import argparse
from common.params import Params
from common.realtime import Ratekeeper
from lib.helpers import FakeSteeringWheel
STEER_RATIO = 25.
parser ... |
from math import inf
import numpy as np
from .rq.hand import GraspMode, Hand, Position
from . import rq
from .ur.arm import Arm, Tool, Joints
from . import ur
from . import server
from .sim.simscene import SimScene
from .ur import UR_DEFAULT_FORCE_LOW_BOUND, UR_DEFAULT_FORCE_HIGH_BOUND, UR_DEFAULT_MAX_SPEED, UR_DEFAULT... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
@author: rz
@email:
"""
#%% imports
import itertools, time, copy
from tqdm import tqdm
import numpy as np
import pandas as pd
import torch
from torch.autograd import Variable
import Levenshtein as Lev
from sklearn import metrics
from .etdata import ETData
from .u... |
import os
import numpy as np
import pickle
from utils import absolute_file_paths, round_down, standardize
def chunks(arr, batch_size, num_gpus, step, window, trim=True):
"""Chunks a 4D numpy array into smaller 4D arrays."""
new = []
coords = []
shape = arr.shape
z_max = shape[0] - window[0]
... |
# -*- coding: utf-8 -*-
import numpy
import six
import os
import pvl
import collections
from .image import PlanetaryImage
from .decoders import BandSequentialDecoder
class Pointer(collections.namedtuple('Pointer', ['filename', 'bytes'])):
@staticmethod
def _parse_bytes(value, record_bytes):
if isinst... |
import time
from django.urls import reverse
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from wkz import configuration as cfg
from wkz import models
def test_awards_page__complete(import_demo_da... |
# -*- coding: utf-8 -*-
"""
:mod:`orion.algo.robo.rbayes -- TODO
============================================
.. module:: robo
:platform: Unix
:synopsis: TODO
TODO: Write long description
"""
import george
import numpy
from robo.acquisition_functions.ei import EI
from robo.acquisition_functions.lcb import LC... |
#pylint: disable=bare-except, too-many-locals, too-many-statements, too-many-branches, wrong-import-order, too-many-arguments
"""
Read and write quicknxs reduced files
"""
from __future__ import absolute_import, division, print_function
import sys
import os
import time
import copy
import math
import logging
import ... |
import numpy as np
from math import sqrt, log
from Bandit import Bandit
#from maze import Sets
'''
def get_nearby_set_to_ban(set_index_list, bandit_index, ban_to_set_dict):
sets = ban_to_set_dict[str(bandit_index)]
min_index = set_index_list[0]
min = abs(sets[0]-min_index)
for i in set_... |
from __future__ import annotations
from typing import Union
from pathlib import Path
from dataclasses import dataclass, field
import math
import uuid
# useful geometric constants
TWO_PI = 2 * math.pi
PI_OVER_TWO = math.pi / 2
THREE_PI_OVER_TWO = 3 * math.pi / 2
def get_oriented_distance(p0: Point, p1: Point, p2: Poi... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import json
import frappe
from frappe import _, throw
from frappe.desk.form.assign_to import clear, close_all_assignments
from frappe.model.mapper imp... |
import copy
import itertools
import multiprocessing as mp
import pickle
import numpy as np
from qiskit import QuantumCircuit
from qiskit import quantum_info as qi
from qml import layers
class QcnnStruct:
"""
The base class which our QCNN will inherit core functionality from.
"""
Layers = {layers.le... |
""" IOS-XE Quad service implementations. """
from time import sleep, time
from collections import namedtuple
from unicon.eal.dialogs import Dialog
from unicon.core.errors import SubCommandFailure
from unicon.bases.routers.services import BaseService
from unicon.plugins.generic.statements import custom_auth_statements... |
import argparse
import gzip
from pathlib import Path
import re
import sys
from datetime import datetime
'''
Script for cooking ORCHID corpus
- word-level
- characteristics
'''
# ORCHID delimiters
LINE_DELIM = '\n' # Line
EOS_DELIM = '//' # End of sentenc... |
"""
Application utility module
"""
# Copyright 2021 Silicon Laboratories Inc. www.silabs.com
#
# SPDX-License-Identifier: Zlib
#
# The licensor of this software is Silicon Laboratories Inc.
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for... |
#!/usr/bin/env python3
"""
Pipeline for running wmgx and wmgx_vis bioBakery workflows.
"""
import argparse
import traceback
import os
import re
import csv
from collections import namedtuple
import sh
from nephele2.pipelines.pipebase import PipeBase
from nephele2.pipelines import pipeline_error
class BiobakeryPipe(... |
# Copyright 2021 Alibaba Group Holding Limited. 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 ... |
## Copyright 2017 <NAME> <<EMAIL>>
## Copyright 2017 <NAME> <<EMAIL>>
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless req... |
# -*- coding: utf-8 -*-
"""Tests for class `Original`."""
import warnings
from collections import namedtuple
from os.path import expanduser
import pandas as pd
from nose.tools import assert_equal, assert_true
from sosia.classes import Original
warnings.filterwarnings("ignore")
test_cache = expanduser("~/.sosia/tes... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 8 16:07:04 2020
@author: holmeschang
"""
import datetime
import numpy as np
import os
from six.moves import cPickle
import requests
from bs4 import BeautifulSoup
import json
from scipy.interpolate import UnivariateSpline
import matplotlib.pyplot as pl... |
import pyttsx3
import datetime
import time
import speech_recognition as sr
import os
import wikipedia
import webbrowser
import pyjokes
import subprocess
import tkinter
from bs4 import BeautifulSoup
import psutil
import pyautogui
from playsound import playsound
import random
import json
import requests
... |
#!/usr/bin/env python
# encoding: utf-8
# Author: guoxudong
import time
from datetime import datetime
from bottle import (Bottle, HTTPResponse, request, response, run, json_dumps as dumps)
from getData import getDataSync, getShDataSync
app = Bottle()
@app.hook('after_request')
def enable_cors():
print("after_r... |
# Copyright 2021 eprbell
#
# 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, soft... |
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.utils import timezone
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from ...serializers.workflows.c... |
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
__all__ = ['Elaborator', 'ElaboratorError']
from yaml.error import MarkedYAMLError
from yaml.events import (StreamStartEvent, StreamEndEvent,
DocumentStartEvent, DocumentEndEv... |
import os, sys
import time
import subprocess
import hashlib
from flask import session, flash, request, jsonify
from pantry.config import ConfigParser, read_config_file
from marshmallow import Schema, fields, pprint
def format_release(output):
if 'NAME' in output.decode():
release = {}
for line in ... |
import click
import requests
from eth_account.messages import defunct_hash_message
from eth_account.account import Account
from eth_abi import is_encodable
from eth_abi.packed import encode_abi_packed, encode_single_packed
import json
from dynaconf import settings
import eth_utils
CONTEXT_SETTINGS = dict(
help_op... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 24 22:01:01 2020
@author: SW274998
"""
import click
import numpy as np
from nseta.common.commons import *
from nseta.common.log import tracelog, default_logger
from nseta.live.liveurls import quote_eq_url, futures_chain_url, holiday_list_url
import json
from bs4 import B... |
from __future__ import print_function
"""This module contains classes that are specialized for opening specific types of files.
They also retrieve and store the file properties (e.g. compression, extension) for further reference.
"""
import logging
import os
# PORT: pathlib2 is for python version 2.7, use pathlib in ... |
from matplotlib import pylab as plt
import numpy as np
import datetime
import pathlib
from sklearn.metrics import roc_curve, auc, confusion_matrix
import matplotlib.dates as mdates
from matplotlib.collections import PolyCollection
from collections import OrderedDict
import io
import base64
from urllib.parse import quo... |
from enum import Enum
from cronex import CronExpression
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import Session, validates
from sqlalchemy import UniqueConstraint, event
db = SQLAlchemy()
class Environment(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(... |
import modwrap, yaml, copy
'''
The main goal of this over testmaker.py is
parse task/whatever.yaml into a Test object
description: string
solution: string that can be exec'd
func: function name or None for module test
imports: list of permitted module names
recursive... |
import pandas as pd
from math import isnan, nan
from fractions import Fraction as frac
systems = ["aetherling_copies", "halide_to_hardware", "spatial"]
def get_latex_from_results_str(results_file):
results = pd.read_csv(results_file)
results['Clock Rate'] = nan
results_tex_str = ""
applications = ["map... |
# -*- coding: utf-8 -*-
import os
import itertools
import codecs
import re
import datetime
import cairocffi as cairo
import editdistance
import numpy as np
from scipy import ndimage
import pylab
from keras import backend as K
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.layers import Input, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import sys
import getopt
import logging
import random
import string
import json
import copy
class JaggedMatrixGenerator(object):
"""Generate a Jagged Matrix and fill it with random characters as defined by available string sequences.
"""
SEQUENCE = ["ascii... |
from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Sequential as Seq, Linear, ReLU
from abc import ABC, abstractmethod
def maxpool2x2(input, ksize=2, stride=2):
"""2x2 max pooling"""
return nn.MaxPool2d(ksize, stride... |
import copy
import pandas as pd
import numpy as np
import networkx as nx
from networkx.convert_matrix import from_pandas_edgelist
## -- Parameters -- ##
HH_LABELS = ['Family Member',
'Family member',
'Daughter - Mother',
'Father - Son',
'Husband - Wife',
'Clo... |
# MIT License
# Copyright (c) 2019 Churchland laboratory
# 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,... |
from abc import ABC, abstractmethod, abstractproperty
import torch
from torch.nn import Module, Parameter
from abc import abstractmethod
from fireworks.utils.exceptions import ParameterizationError
from .message import Message
from .junction import Junction, PyTorch_Junction
from .component_map import Component_Map, Py... |
from typing import List, Tuple, Union
import numpy as np
from games.game import Game
from games.level import Level
from games.mario.java_runner import java_astar_number_of_things_in_open_set
from games.mario.mario_game import MarioGame
from games.maze.maze_game import MazeGame
from metrics.metric import Metric
from me... |
from __future__ import absolute_import
import os
from contextlib import contextmanager
from celery.fixups.django import (
_maybe_close_fd,
fixup,
DjangoFixup,
DjangoWorkerFixup,
)
from celery.tests.case import (
AppCase, Mock, patch, patch_many, patch_modules, mask_modules,
)
class FixupCase(A... |
# This file is part of Moksha.
# Copyright (C) 2008-2010 Red Hat, 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 b... |
"""
owtf.managers.url
~~~~~~~~~~~~~~~~~
The DB stores HTTP transactions, unique URLs and more.
"""
from owtf.db.session import get_count, get_scoped_session
from owtf.lib.exceptions import InvalidParameterType
from owtf.managers.target import is_url_in_scope, target_required
from owtf.models.url import Url
from owtf.ut... |
import unittest
import numpy as np
from brainbox.plot_base import (DefaultPlot, ImagePlot, ScatterPlot, ProbePlot, LinePlot,
scatter_xyc_plot, arrange_channels2banks)
class TestPlotBase(unittest.TestCase):
def setUp(self):
"""
Test Basic functionality... |
# <NAME>
# Reference: With modification from http://inventwithpython.com/chapter10.html.
import random
import sys
NUMBER_SPACES = 10
PLAYER_LETTER = ''
COMPUTER_LETTER = ''
NEXT_MOVE = 0
VERBOSE = False
BORDER = False
# !! Board Functionality
def drawBoard(board):
"""This function prints out the board that it w... |
from typing import Callable, List, Tuple
from tvm import tir
from tvm._ffi.runtime_ctypes import DataType
from tzer.tir import util
from tzer.tir.mutate.generate.generator import Generator
from tzer.tir.semantic.constraint import PrimExprConstraint, satisfies
from tzer.tir.visit.size import MemoizedGetSize
from .mutato... |
import torch
import nussl
from nussl.datasets import transforms
from nussl import ml
import pytest
import numpy as np
import librosa
import itertools
def test_register_module():
class ExampleModule(torch.nn.Module):
def forward(self, data):
data = data * 2
return data
assert E... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.utils.spectral_norm as spectral_norm
import numpy as np
from torch.autograd import Function
from model.base_network import BaseNetwork, AdaptiveInstanceNorm
# GradReverse.apply(inp, lambd)
class GradReverse(Function):
@staticmethod
... |
# LoRaWAN Security Framework - lafProcessData
# Copyright (c) 2019 IOActive Inc. All rights reserved.
import argparse, sys, time, logging, os
from auditing.analyzers.printer import LafPrinter
from auditing.analyzers.bruteforcer import LafBruteforcer
from auditing.analyzers.dataanalysis import LafPacketAnalysis
from a... |
import os
import math
import datetime
from dateutil.relativedelta import relativedelta
import dataflows as DF
from sqlalchemy import or_
from anyway.db_views import VIEWS
from anyway.models import AccidentMarker, Involved, Vehicle, ProviderCode
from ..db import session_decorator
from .config import (
CBS_YEARLY_... |
from pandas import DataFrame
from multiprocessing import Pool
from sklearn.ensemble import IsolationForest
from sklearn.metrics import f1_score
import random
from numpy import arange, isnan, array
import threading
from multiprocessing import cpu_count
from functions import *
from configs import conf
from data_access i... |
import MoleculeDrawer
from wxPython.wx import *
class wxMixin(wxScrolledWindow):
def _init(self, parent, height=None, width=None):
self.x0 = 0
self.y0 = 0
self.name = ""
if height is None and width is None:
size = parent.GetClientSize()
else:
size = (... |
"""
Set of functions to export the database to the ftp directory
"""
import csv
import gzip
import os
from flask import current_app
from sqlalchemy.orm import joinedload, noload
from conekt import create_app, db
from conekt.models.expression.coexpression_clusters import CoexpressionClusteringMethod
from conekt.models... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 17 20:21:08 2018
@author: crazydemo
"""
import tensorflow as tf
import tensorflow.python.layers.layers
REGULARIZATION_RATE = 0.001
regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)
def max_pool(x, kheight, kwidth, stridex, strid... |
import os
import sys
from os.path import exists
from os.path import join
import cv2
import numpy as np
def get_file_list_recursively(top_directory):
"""
Get list of full paths of all files found under root directory "top_directory".
If a list of allowed file extensions is provided, files are filtered acc... |
import ops
import iopc
TARBALL_FILE="harfbuzz-1.7.6.tar.bz2"
TARBALL_DIR="harfbuzz-1.7.6"
INSTALL_DIR="harfbuzz-bin"
pkg_path = ""
output_dir = ""
tarball_pkg = ""
tarball_dir = ""
install_dir = ""
install_tmp_dir = ""
cc_host = ""
tmp_include_dir = ""
dst_include_dir = ""
dst_lib_dir = ""
def set_global(args):
g... |
from __future__ import unicode_literals
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import ColorConverter
import matplotlib.transforms as transforms
from colorsys import rgb_to_hls, hls_to_rgb
from .calc_funcs import map_aggarwal_ratio, rescale_limit
from . import legend_entries as... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2020 Fetch.AI Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the ... |
import wx
from wx.lib.scrolledpanel import ScrolledPanel
# Class LegendDialog:
# generic dialog used to add legends to graphs.
class LegendDialog(wx.Dialog):
def __init__(self, parent, txt):
# inherits the wx.Dialog class, set the ID, name, size of dialog
wx.Dialog.__init__(self, parent, wx.ID_AN... |
"""Set up a temporary postgres DB"""
import itertools
import os
import sys
import atexit
import shutil
import subprocess
import tempfile
import time
import pwd
from contextlib import contextmanager
import shlex
import warnings
# Module level TempDB singleton
temp_db = None
# Module constants
DEFAULT_DOCKER_EXE = 'd... |
"""This module contains inherited classes for defining, manipulating and training a Gaussian Process.
"""
import numpy as np
import scipy as sp
import pymc3 as pm
import theano as th
import theano.tensor as tt
import theano.tensor.slinalg as tsl
import theano.tensor.nlinalg as tnl
from scipy import stats
from thea... |
#######################################################################
##### #####
##### <NAME> #####
##### <EMAIL> #####
##### 02/04/2019 ... |
import paddle
import paddle.nn as nn
from paddle.nn.initializer import Assign, Constant, Normal
class Identity(nn.Layer):
def __init__(self):
super(Identity, self).__init__()
def forward(self, inputs):
return inputs
class QuickGELU(nn.Layer):
def forward(self, x):
return x * nn.... |
import csv
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as sci
import seaborn as sns
import sensorprocessor as sp
import signalfilters as mf
csv_missed = '/Users/philliphartin/TAUT/SensorRecordings/3802/6/3802_1409230847_Accelerometer.csv'
csv_acknowledged = '/Users/philliphartin/TAUT/Senso... |
# Main function of the "maquette"
# Print debug messages
debug = True
debug_sockets = False
debug_threads = False
import threading
import time
from collections import deque
import speech_recognition as sr
import pyttsx3
import json
actionQueue = deque()
# Stop semaphores
stop = dict()
for ps in ['FGFS','API','SR','... |
import logging
import os
import joblib
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader
from sklearn.preprocessing import StandardScaler
from nas_bench_x11.utils import utils
from nas_bench_x11.surro... |
# coding: utf-8
import ui
import os
from objc_util import ObjCInstance, ObjCClass
from operator import attrgetter
import time
import threading
import functools
import ftplib
import re
# http://stackoverflow.com/a/6547474
def human_size(size_bytes):
'''Helper function for formatting human-readable file sizes'''
if si... |
#!/usr/bin/env python
from __future__ import print_function
from optparse import OptionParser
import sys
import h5py
import numpy.random as npr
import numpy as np
import subprocess
from utils import dna_io
import split_ttv
################################################################################
# seq_hdf5.p... |
import json
from pytest import raises
from enhanced_versioning.base_version import VersionError
from enhanced_versioning.nonsemantic_version import NonSemanticVersion
def test_nonsemantic_versions():
"""Test revisions
Test handling nonsemantic versions. Ensure that regenerating the version
strings work... |
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
def get_edges_df_from_obabel(obabel_edges_df, structures_df):
"""
Given obabel edge data, convert it to format of edges_df so that all other code remains the same.
"""
obabel_edges_df = obabel_edges_df[[
'mo... |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license.
# code modified from https://github.com/waldeland/CNN-for-ASI
from __future__ import print_function
from os.path import isfile, join
import segyio
from os import listdir
import numpy as np
import scipy.misc
def read_segy(filename):
... |
import json
from torch.autograd import Variable
import torch
from load_data import ParaphraseDataset
import argparse
import logging
import time
import os.path
from scipy.spatial.distance import cosine
from statistics import mean
train, test = 'train', 'test'
combined, cls, pool = 'combined', 'cls', 'cls_pool'
module_... |
import re
from datetime import timedelta
from pathlib import Path
from typing import Any, Callable, Optional, Tuple, Union, cast, overload
from .bases import CNumerical, Converter
from .validators import (VBool, VFloat, VInt, VNumber, VPath, VString, VTimedelta)
class CBool(VBool, Converter):
"""VBoo... |
import json
from datetime import datetime
import yaml
from .exceptions import context
from .utils import format_list, ensure_unicode, datetime_to_millis
def typename(cls):
if cls is str:
return 'string'
elif cls is int:
return 'integer'
return cls.__name__
# constants used to detect no... |
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import numpy as np
from utils.misc import get_paths_in_dir, decompose_labels_batchs, decompose_labels
import glob
from pathlib import Path
import imageio
import gc
from typing import List, Tuple, Optional
class CroppedImageDataGenerator(ImageDataGener... |
#!/usr/bin/env python
# ------------------------------------------------------------------------------------------------------%
# Created by "Thieu" at 14:05, 28/01/2021 %
# ... |
import argparse
from collections import defaultdict
import os
import intcode
import my_collections
from position import Position
class Maze: # pylint: disable=C0115
CLEAR_SCREEN = lambda: os.system('cls' if os.name == 'nt' else 'clear')
UNKNOWN = 0
OPEN = 1
WALL = 2
OXYGEN_SYSTEM = 3
TILES = {
UNKNO... |
#!/usr/bin/env python3
"""update_device_record.py
Update device inventory information with a csv input file and the Kandji API.
"""
###################################################################################################
# Created by <NAME> | Senior Solutions Engineer | Kandji, Inc | Solutions | <EMAIL>
##... |
## -*- coding: utf-8 -*-
'''
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 distribute... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Functions for use with the GEOS-Chem chemical transport model (CTM).
Use help(<name of function>) to get details on a particular function.
"""
# - Required modules:
# I/O / Low level
import os
import sys
#import csv
import glob
import pandas as pd
import xarray as xr
impo... |
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
sys.path.append(os.path.join('..', '..'))
from dataloader import Synthesizer
from problems.ranking import BasicFasSolver, IlpSolver, AC, IL, SP, DF
from problems.ranking.fassolver.embedding import get_sym_embs
from weights import RidgeRegressor, ... |
import logging
import os
import random
import socket
import time
import re
import pdPythonLib
from .wrapper import wrap
__all__ = ['connect', 'PDApp']
logger = logging.getLogger(__name__)
testpat = re.compile(r""".*""", re.X | re.M | re.S)
retmsgpat = re.compile(r"""
\ARETVAL:(?P<body>.*)\n\x00\Z""", re.X |... |
import streamlit as st
import pandas as pd
import requests
import matplotlib.pyplot as plt
from bs4 import BeautifulSoup
import json
import base64
import cufflinks as cf
import yfinance as yf
import datetime
st.set_page_config(layout="wide")
st.sidebar.title('Options')
option = st.sidebar.selectbox("Selec... |
from datetime import datetime
import json
import unittest
from httmock import urlmatch, HTTMock
import requests
from myria.connection import MyriaConnection
from myria.schema import MyriaSchema
from myria.relation import MyriaRelation
from myria.query import MyriaQuery
from test_connection_query import query_status
QU... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.