text
stringlengths
3.07k
12.6k
#!/usr/bin/python # The MIT License (MIT) # Copyright (c) 2017 "<NAME>"<<EMAIL>> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights ...
import logging import secrets from collections import OrderedDict from typing import MutableMapping, cast import attr from homeassistant.core import (callback, HomeAssistant) from homeassistant.loader import bind_hass from homeassistant.const import ( ATTR_NAME, CONF_CONDITIONS, ) from . import...
# # For licensing see accompanying LICENSE file. # Copyright (C) 2020 Apple Inc. All Rights Reserved. # import argparse from data.sampler import arguments_sampler from options.utils import load_config_file from data.datasets import arguments_dataset from cvnets import arguments_model, arguments_nn_layers, arguments_em...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import getopt import traceback from concurrent import futures from fasttest.version import VERSION from fasttest.project import * def _usage(): print('') print(' usage: fasttest [-h|-v|] [arg] ...') print('') print(' options:') p...
import os import torch import torchvision from torch import nn from d2l import torch as d2l d2l.DATA_HUB['dog_tiny'] = (d2l.DATA_URL + 'kaggle_dog_tiny.zip', '0cb91d09b814ecdc07b50f31f8dcad3e81d6a86d') demo = True if demo: data_dir = d2l.download_extract('dog_tiny') else: data_dir ...
from Node import Node import random as r def accept(currentIteration, iterations): return r.random() < (currentIteration / iterations) class Operation(object): BACK_MUTATION = 0 DELETE_MUTATION = 1 SWITCH_NODES = 2 PRUNE_REGRAFT = 3 NUMBER = 4 def __init__(self, type, node_name_1 = None...
''' Adapted from original predict.py by <NAME> implementation of [DeeperCut](https://github.com/eldar/pose-tensorflow) Source: DeeperCut by <NAME> https://github.com/eldar/pose-tensorflow To do faster inference on videos: "On the inference speed and video-compression robustness of DeepLabCut" <NAME> & <NAME> doi: h...
from kivy.app import App from kivy.lang import Builder from kivy.clock import Clock from kivy.uix.screenmanager import Screen, ScreenManager from kivy.core.window import Window Window.size = [500, 500] from kivy.uix.boxlayout import BoxLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Bu...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys sys.path.insert(0,'..') # -------------------------------------------- import logging class NullHandler(logging.Handler): def emit(self, record): pass logger = logging.getLogger('pyagentx3.main') logger.addHandler(NullHandler()) # -----------------...
import pygame import sys import random class Game: def __init__(self): pygame.init() self.title = "Box Eater" self.icon = "icon.bmp" self.height = 800 self.width = 620 self.quit = 0 self.background = (255, 255, 255) self.not_quit = 1 ...
import random import numpy as np import cv2 import lmdb import torch import torch.utils.data as data import data.util as util import sys import os try: sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from data.util import imresize_np from utils import util as utils except Impor...
import hashlib from slick import model from sqlalchemy import Column, DateTime, Integer, String, ForeignKey, Boolean from sqlalchemy.orm import relationship class Game(model.BaseModel): """Game data model""" __tablename__ = "game" _lookup_attributes = ('name', ) id = Column(Integer, primary_key=True) name = ...
#!/usr/bin/env python # # Copyright 2019, Data61 # Commonwealth Scientific and Industrial Research Organisation (CSIRO) # ABN 41 687 119 230. # # This software may be distributed and modified according to the terms of # the GNU General Public License version 2. Note that NO WARRANTY is provided. # See "LICENSE_GPLv2.tx...
#!/user/bin/env python import time from time import sleep import random import colorsys # HSV to RGB import board # GPIO import neopixel # Set LED values # Colors DARK_RED = (80, 0, 0) RED = (255, 0, 0) ORANGE = (255, 70, 0) YELLOW = (255, 255, 0) DARK_GREEN = (0, 80, 0) GREEN = (0, 255, 0) CYAN = (0, 255, 255) DARK_...
import collections import os import sys import csv import socket def parseFile(fileName): suitesNames = {} with open(os.path.join(fileName, "logs/final_result.csv"), 'rb') as f: csv_read = csv.reader(f) for line in csv_read: for i in range(1, len(line)): if not suite...
#!/usr/bin/env python -O import os import sys import bisect import os.path import ijson import numpy as np from datetime import date, datetime, timedelta from netCDF4 import Dataset ''' Testing Commands: Jerome: python hyperspectral_flux_based_calibration.py "10/15/2016 18:37:44" . ROGER : python hyperspectral_flux_...
import os from pathlib import Path from sys import path from ez_detect import config, hfo_annotate from flask import ( Blueprint, request, send_from_directory, current_app, jsonify ) from flask_api import status from trcio import read_raw_trc from werkzeug.utils import secure_filename from .engine import file...
""" Recursively replace placholder expressions with time and date fields in all files within a directory Config comes from a file, specified as --config argument. Some configuration options (listed below) can also be given at the command line, where they will override the configuration file. See example/template...
# Copyright (c) 2019 UAVCAN Consortium # This software is distributed under the terms of the MIT License. # Author: <NAME> <<EMAIL>> import typing import random import struct import itertools import functools import numpy import pydsdl import pyuavcan.dsdl def expand_service_types( models: typing.Iterable[pyds...
import sys from sim import ( Component, Signal, NotifySignal, Net, Register, SplitRegister, BusConnect, Clock, Ram, Rom, Power, MemDisplay, PagedRamController, ) from .asm import Assembler class Decoder(Component): MASK_OP = 0b011 MASK_REG = 0b100 OP_NOR...
from collections import Counter from operator import itemgetter import os class Beacon(object): def __init__(self, x, y, z): self.coords = ((1, x), (2, y), (3, z)) def __str__(self): return str(self.coords) def get_coords(self): return self.coords def apply_trns(self, coords...
#!/usr/bin/env python # coding: utf-8 # First, let's load the JSON file which describes the human pose task. This is in COCO format, it is the category descriptor pulled from the annotations file. We modify the COCO category slightly, to add a neck keypoint. We will use this task description JSON to create a topolo...
# -*- coding: utf-8 -*- # # Copyright © 2009 <NAME> # Licensed under the terms of the MIT License # (see pydeelib/__init__.py for details) """Qt utilities""" import os.path as osp import webbrowser, imp from PyQt4.QtGui import (QAction, QStyle, QWidget, QIcon, QApplication, QVBox...
from tensorflow.keras.layers import (Conv2D, BatchNormalization, Activation, add) def identity_block(input_tensor, kernel_size, filters, stage, block): filters1, filters2, filters3 = filters ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains default implementation for nested YAML configurations """ from __future__ import print_function, division, absolute_import import os import logging from collections import OrderedDict # To avoid errors when initializing Dcc server try: impor...
import os import sys import shutil import unittest import tensorflow as tf import tensorflow.contrib.slim.nets as nets from tensorflow.contrib import layers import hiddenlayer as hl # Hide GPUs. Not needed for this test. os.environ["CUDA_VISIBLE_DEVICES"] = "" # Create output directory in project root ROOT_DIR = os.p...
# Copyright 2018 Iguazio # # 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, softwa...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # 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 appl...
# coding: utf-8 import time import json from urllib.parse import urlparse from pycurl_session.response import Response from pycurl_session.spider.spider import Spider from pycurl_session.spider.request import Request from pycurl_session.spider.robotstxtparser import RobotFileParser from pycurl_session.spider.exceptio...
# -*- coding: utf-8 -*- import os import platform import tempfile from pathlib import Path from collections import defaultdict import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt from snl_d3d_cec_verify import (MycekStudy, Report, ...
#!/usr/bin/python # -*- coding: utf-8 -*- # # This file is a part of EM Media Handler Testing Module # Copyright (c) 2014-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...
import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import train_test_split from imblearn.over_sampling import RandomOverSampler from sklearn....
#! /usr/bin/python3 '''Read and convert data''' # Needs 12k as input! # One signal at 12kHz is around 28000 "short int" long import os from time import sleep from math import floor import numpy as np import db_sql from arduino_read import weather_inside def convert_data(data_block, rain_overflow): '''Check data ...
from xml.etree import ElementTree import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry from mapswipe_workers.definitions import ( OHSOME_API_LINK, OSM_API_LINK, OSMCHA_API_KEY, OSMCHA_API_LINK, CustomError, logger, ) def remove_trou...
#! /usr/bin/env python import os import sys import select import time import math import getopt import RPi.GPIO as GPIO # Debug flag debug = False def Usage(): print('Usage: stepper.py -d -h -v --debug --help --version degrees timing-in-milliseconds') # Stepper motor operation -- 28BYJ48 5V DC motor # 32 teeth ...
# -*- coding: utf-8 -*- """ * TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-蓝鲸 PaaS 平台(BlueKing-PaaS) available. * Copyright (C) 2017-2021 TH<NAME>, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in complianc...
import logging from os import path from sys import platform from typing import List, Tuple from cv2 import VideoWriter, VideoWriter_fourcc, imwrite from numpy import array from PIL import Image, ImageDraw, ImageFont from skunkbooth.data import constants class IOBase: """ASCII conversion module, subclass for acc...
# Copyright 2019 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 by applicable law or ...
#!/usr/bin/env python3 import unittest from dataclasses import dataclass from typing import List, Optional, Sequence from common import open_fixture def abs(n: int) -> int: if n < 0: return -n return n def in_plane(a: int, b: int, n: int) -> bool: if n < a and n < b: return False i...
#!/usr/bin/env python3 """ This script reads task data in iCalendar format and converts it to Gina Trapani's todo.txt format (see http://todotxt.com/). The task data can be exported from Remember The Milk or Apple's Reminders app on OS X. """ import codecs import re import sys import os USAGE = """ Convert iCalen...
"""xception in pytorch [1] <NAME> Xception: Deep Learning with Depthwise Separable Convolutions https://arxiv.org/abs/1610.02357 """ import torch import torch.nn as nn import torch.nn.functional as F class SeperableConv2d(nn.Module): #***Figure 4. An “extreme” version of our Inception module, #wi...
from aiogram import types from aiogram.dispatcher import FSMContext from tortoise.exceptions import IntegrityError from keyboards import inline from keyboards.inline import back_callback, faculties, delete_callback, create_callback from keyboards.inline.admin import cancel, cancel_or_delete, cancel_or_create fr...
# coding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License...
#!/usr/bin/python # -*- coding:utf-8 -*- # Copyright(C) 2020 Inspur Inc. All Rights Reserved. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' --- module: edit_kvm ...
#-*-coding:utf-8 import os import math import numpy as np import cv2 def get_file_path_list(json_dir, postfix = [".jpg"] ): ''' ''' file_path_list = [] if os.path.exists(json_dir): print (json_dir) else: print ("no exist") for rt, dirs, files in os.walk(json_dir): if len(d...
import tensorflow as tf import numpy as np from preprocess_encode_images import extract_cache_features from train_data_preparation import tokenizer, train_max_length from params import attention_features_shape from config import DIRECTORIES def predict_single(image, models, image_features_dir, tokenizer, ...
""" tracked_object.py defines TrackedObj -> a datatype which tracks on object methods """ import numpy as np import operator import functools import copy import math from collections.abc import Iterable import uuid def reset_array_prov(array, array_id = None): if array_id == None: array_id = uuid.uuid4...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import os import torch import torch.utils.data from opts import opts from MOC_utils.model import create_model, load_model, save_model, load_coco_pretrained_model, load_imagenet_pretrained_model from...
#!/usr/bin/env python """ CEP to coordinates (latitude and longitude). This script receives list of brazilian postal code and returns the latitude and longitude coordinates related to this postal code, based on information provided by Open Street Map (OSM). """ import sys # basic system library import urllib # to o...
#!/usr/bin/env python # -*- coding: utf-8 -*- import dns.resolver import os import socket import sys import time def main(): argv = sys.argv argc = len(argv) if argc < 2: exit_msg(argv[0]) resolvstring = argv[1] if argc < 3: # recordtype = "ANY" # DNS metaqueris a not allowd....
"""Tests for control utility functions. """ import control import numpy as np import kontrol.core.controlutils def test_tfmatrix2tf(): tf1 = control.tf([1, 2], [3, 4, 5]) tf2 = control.tf([6, 7], [8, 9, 10]) tf3 = control.tf([11, 12], [13, 14, 15]) tf4 = control.tf([1], [2, 3]) tf5 = control.tf([...
''' Created on Jun 4, 2021 @author: mballance ''' import cocotb import pybfms from gpio_bfms.GpioBfm import GpioBfm from wishbone_bfms.wb_initiator_bfm import WbInitiatorBfm from riscv_debug_bfms.riscv_debug_bfm import RiscvDebugBfm from spi_bfms.spi_memory_model import SpiMemoryModel from elftools.elf.elffile import...
import _init_paths import os import os.path as osp import caffe from caffe import layers as L, params as P from caffe import tools from caffe.model_libs import * def caffenet_body(net, data, post, is_train): # the net itself net['conv1'+post], net['relu1'+post] = conv_relu(net[data], 11, 96, stride=4, is_t...
import cvxpy as cp import numpy as np def skew_symmetric(V): skew = cp.vstack([cp.hstack([0, -V[2, 0], V[1, 0]]), cp.hstack([V[2, 0], 0, -V[0, 0]]), cp.hstack([-V[1, 0], V[0, 0], 0])]) return skew def skew_symmetric_neg(V): skew = cp.vstack([cp.hstack([0, V[2, 0...
#!/usr/bin/env python import aiohttp import logging import re ARXIV_ABS_URL_BASE = "https://arxiv.org/abs/" ARXIV_PDF_URL_BASE = "https://arxiv.org/pdf/" # poor man's XML parser; group the ID and text title separately FIND_TITLE_REGEX = re.compile("<title>\[(\d*\.\d*)\](.*)</title>") FIND_ID_REGEX = re.compile("\d{4...
import PyQt5.QtWidgets as QW from math import floor, ceil def createHorLayout(widList, stretch=False, spacing=0): """Create horizontal box layout widget containing widgets in widList""" wid = QW.QWidget() wid.setStyleSheet("""QWidget {border: 0px solid gray; border-radius: 0px; ...
import fnmatch import json import re from typing import Any, Callable, Dict, List, Optional, Tuple, Union import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 DEFAULT_ALGORITHM = 'literal' DEFAULT_PRIORITY = 'first_match' def make_regex(pattern: str, algorithm: str) -> str: ...
""" Utilities for determining file locations or names from the configuration specification """ from yaml import YAMLObject IGNORE_LABEL_INDEX = -100 TRAIN_STR = 'train' DEV_STR = 'dev' TEST_STR = 'test' PTB_UNIVERSAL_CONVERSION_STRING = 'ptb_to_upos' WSD_COARSENING_CONVERSION_STRING = 'wsd_coarse' def get_results_ro...
import bson from pymongo import ReturnDocument from pymongo.cursor import Cursor import numpy as np import pandas as pd from config import get_config from logger import get_logger from .db import configdb, metricdb logger = get_logger(__name__, log_level=("ANALYZER", "LOGLEVEL")) config = get_config() app_collect...
""" Functions to construct Transformer based models. """ import tensorflow as tf # pylint: disable=no-name-in-module from tensorflow.keras.layers import Dense, MultiHeadAttention, TimeDistributed from vlne.consts import DEF_MASK from .funcs import ( get_inputs, get_outputs, modify_series_layer, add_hidden_layers...
# Arduino piano # this code reads 7 digit hex values from serial port and plays corresponding notes import os import time import serial from pynput.keyboard import Key, Controller SERIAL_PORT = '/dev/ttyACM0' SERIAL_RATE = 115200 keyboard = Controller() keystate0 = [False] * 12 keystate1 = [False] * 12 keystate2 = ...
# Copyright (c) 2016 Uber Technologies, Inc. # # 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, publ...
""" Helpers for the asset mutations """ from json import dumps from uuid import uuid4 from typing import List, Union from ...helpers import encode_base64, is_url from .queries import (GQL_APPEND_MANY_TO_DATASET, GQL_APPEND_MANY_FRAMES_TO_DATASET) def encode_object_if_not_url(content): """ ...
import SonarDataset import tensorflow as tf import numpy as np def sigmoid(phi): return 1.0/(1.0 + tf.exp(-phi)) def train_network(training_points, training_out, testing_points, testing_out, num_c): in_size = len(data[0]) out_size = 1 num_centroids = num_c inputs = tf.placeholder('float64', [...
import abc import warnings import gym import numpy as np from scipy.spatial.ckdtree import cKDTree from gym_guppy.guppies import Agent, Guppy, GlobalTargetRobot from gym_guppy.tools import Feedback from gym_guppy.tools.math import is_point_left, normalize, rotation class AdaptiveAgent(GlobalTargetRobot): def ac...
#!/usr/bin/env python # vim:fileencoding=utf-8:noet '''Gradients generator ''' from __future__ import division import sys import json from powerline.colorscheme import cterm_to_hex from itertools import groupby import argparse try: from __builtin__ import unicode except ImportError: unicode = str # NOQA def num2(...
#!/usr/bin/env python3 # # record_human_play.py # Script for recording human gameplay and storing # screen images + actions import argparse import time import os import json from video_game_env.connection import Connection # Note on the recording: # Human actions per request are button presses/mouse movements # that...
#!/usr/bin/env python ''' Copyright 2018 <NAME> Created June 28, 2018 Read in mapped reads with STAR assigned to gene with FeatureCounts and produce counts table. ''' import os.path import sys import time import argparse import traceback import errno from subprocess import Popen, PIPE, STDOUT from collections import ...
#!/usr/bin/env python """ Author: <NAME> Last Updated: 2015-03-13 This is a demo of Panda's occluder-culling system. It demonstrates loading occluder from an EGG file and adding them to a CullTraverser. """ # Load PRC data from panda3d.core import loadPrcFileData loadPrcFileData('', 'window-title Occluder Demo') loa...
import os import pdb import sys import time import cv2 import message_filters import numpy as np import ros_numpy import rospy import sensor_msgs.point_cloud2 as pc2 import torch from cv_bridge import CvBridge, CvBridgeError from geometry_msgs.msg import Pose, Vector3 from jsk_recognition_msgs.msg import BoundingBox, ...
import argparse import numpy as np import torch import torchvision import os import time from collections import OrderedDict from torch import nn from torch import optim from torch.autograd import Variable from torchvision import datasets, models, transforms def main(): args = get_arguments() data_dir = args....
import yaml import inspect import scapy.all as scapy_all from typing import Callable, Dict, Any, List, Set, Optional from copy import deepcopy, copy import logging log = logging.getLogger(__name__) def getScapyMethod(method_str: str) -> Any: try: method = getattr(scapy_all, method_str) except Attribu...
import numpy as np from typing import Union, List, Tuple, Optional, Any import pandas as pd import sympy from functools import partial from fastcore.all import partialler from sklearn.utils import resample from torch.tensor import Tensor import torch import torch.nn as nn __all__ = ['to_np', 'to_device', 'to_tensor'...
import inspect import logging import sys from collections import OrderedDict from datetime import datetime from functools import wraps, partial from pathlib import Path from timeit import default_timer as now from typing import Any, Dict, Optional, List LOGGER_FMT = "%(levelname)-8s | %(name)-20s | %(indent)s %(messag...
import logging import os import pathlib import subprocess import sys from glob import glob from time import time from datetime import datetime as dt, timedelta import platform if platform.system() == 'Windows': splitter = '\\' else: splitter = '/' base = splitter.join(__file__.split(splitter)[:-2]) if base not...
# Copyright 2019-present Kensho Technologies, LLC. """Int value conversion. This module is a utility for reasoning about intervals when computing filter selectivities, and generating parameters for pagination. Since integers are the easiest type to deal with in this context, when we encounter a different type we repre...
#!/usr/bin/python import os, re from clint.textui import puts, prompt, validators, progress import requests, feedparser def clear(): os.system('cls' if os.name == 'nt' else 'clear') def geturl(url, dst): if os.path.isfile(dst): halt_exec = prompt.options("A file already exists with that name. Contin...
# Project nlogparser is developed by <NAME> on 10/20/19, 7:12 PM. # # Last modified at 10/20/19, 7:11 PM. # # Github: fahadahammed # Email: <EMAIL> # Location: Dhaka, Bangladesh # # Copyright (c) 2019. All rights reserved. import argparse import datetime import gzip import os import shutil import time import urll...
import random from math import sqrt #Neuron - this is what processes the data and returns an answer class Neuron: def __init__(self,numInputs,learningRate): self.lr = learningRate #The rate at which the weights are adjusted self.weights = [] #A coefficient for a feature - the goal is to determine t...
#!/usr/bin/env python3 from devnet2019.models import Devicedb, DeviceInterface, MonitorInterval from django.shortcuts import render from datetime import datetime, timedelta import numpy as np from django.http import JsonResponse # 获取利用率监控间隔 def get_utilization_monitor_interval(): try: utilization_monitor...
""" CountryCollaborationOperator: Draws a collaboration graph between countries based on the author affiliations. Papers are filtered by their publication year. CountrySimilarityOperator: Finds the similarity between countries based on their abstracts. It averages the abstract vectors of a country to create a country ...
# -*- coding: utf-8 -*- """ Created on Fri May 13 09:48:25 2016 Demonstrate relationship between P/Z and magnitude frequency response in an animation @author: <NAME> see https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/ https://zulko.github.io/blog/2013/09/27/read-and-write-video-...
import logging import math from abc import ABC, abstractmethod from functools import reduce from typing import List, Union, Collection, Callable, Optional, Iterable import simpy logger = logging.getLogger(__name__) _unnamed_power_meters_created = 0 class PowerMeasurement: def __init__(self, dynamic: float, stat...
import os import sys import json import socket import select import logging import argparse logger = logging.getLogger('net_checker') class Daemonizator(object): def __init__(self, working_dir, stdout, stderr): self.working_dir = working_dir self.stdout = stdout self.stderr = stderr ...
import ast import difflib import zipfile import tempfile import sqlite3 import os import logging import threading from shutil import rmtree from django.core.files import File from blousebrothers.confs.models import Speciality from ..models import Card, Tag, AnkiPackage, AnkiImage logger = logging.getLogger(__name__) ...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2016 <NAME> <<EMAIL>> # # 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...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 29 12:31:18 2018 @author: plunder """ import subprocess import fenics as fe from dolfin import Function from fenics import near, between, Function, TestFunction, TrialFunction, grad, div, det, tr, dot from gmsh_interface import GmshInterface def...
#!bin/bash """ Description: This is a python based wrapper for adapter trimming with cutadapt. After running this, run the DADA2 pipeline using the DADA2_notebook.Rmd in this directory. Docs @ github.com/jimbopants/DADA2DADA2_processing Get help by running `python DADA2_prep.py --h` Argparse Options: -h, --help ...
############################################################################### # Core Python Wrapper for RP1210 dlls ############################################################################### from struct import pack, unpack from ctypes import windll, byref, c_char_p, c_int, c_short, c_long, c_void_p, create_str...
from django.shortcuts import render from django.http import HttpResponse, HttpResponseBadRequest from django.core.paginator import Paginator from django.db.models import Count from rest_framework.response import Response from rest_framework.views import APIView from contract.models import Contract from vendor.models ...
import matplotlib.pyplot as plt import pandas as pd import numpy as np def read_entry(entry): path = entry["path"] model_name = entry["model"] try: label = entry["label"] except KeyError: label = path.split("/")[-2] try: ls = entry["linestyle"] except KeyError: ...
from typing import Any, Dict, Tuple, Union import torch from torch.nn.functional import interpolate from torchvision.prototype.datasets.utils import SampleQuery from torchvision.prototype.features import BoundingBox, Image, Label from torchvision.prototype.transforms import Transform class HorizontalFlip(Transform):...
# PyCalc # Simple calculator with python/pygame # Import import pygame pygame.init() # Didnt use dedicated globals.py at the time, so I made a class to avoid using the global keyword class Globals: screen = pygame.display.set_mode((260, 400)) calculator_sheet = pygame.image.load('operator_sheet.png') ico...
import torch import re import random def copy_memory(memory): return ( torch.clone(memory[0]), torch.clone(memory[1]) ) def update_memory(net, memory, int2char, char2int, text): for i in range(len(text)-1): _, memory = generate_character(net, memory, int2char, char2int, text) return memory def ge...
import discord import asyncio import duckduckgo as ddg import json # Bot Info __author__ = 'eye-sigil' __version__ = '0.2.3' # Settings blocked = {} commands = {} safesearch_values = {} # Message Templates html_tags = {"b": "**", "i": "_", "br/": "\n", "u": "__"} ready_msg = '...
#!/usr/bin/env python # coding: utf-8 # # Randomized Image Sampling for Explanations (RISE) import os import argparse from pathlib import Path import numpy as np from matplotlib import pyplot as plt from tqdm import tqdm import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torch.utils.data ...
# import modules import random import argparse import numpy as np import pandas as pd from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from os.path import join, realpath, dirname # variables for performing text preprocessing lemmatizer = WordNetLemmatize...
from configparser import ConfigParser import requests from bs4 import BeautifulSoup import pyttsx3 import paho.mqtt.client as mqtt # First run: pip install paho-mqtt from datetime import datetime import time import json from azure.iot.hub import IoTHubRegistryManager print("\n--------- start cloud app ---------\n") ...
# This file is part of the Etsin service # # Copyright 2017-2018 Ministry of Education and Culture, Finland # # :author: CSC - IT Center for Science Ltd., Espoo Finland <<EMAIL>> # :license: MIT import json import yaml import os import subprocess def get_config_from_file(): with open('/home/etsin-user/app_config...
import sys, os from config import leap_lib, more_leap sys.path.insert(0, leap_lib) sys.path.insert(0, more_leap) import Leap, ctypes, itertools import matplotlib.pyplot as plt import numpy as np def read_frame(filename): Leap.Controller() new_frame = Leap.Frame() with open(os.path.realpath(f...