text stringlengths 3.07k 12.6k |
|---|
# MIT License
#
# Copyright (c) 2020 Aruba, a Hewlett Packard Enterprise company
#
# 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 socket
import struct
from threading import Thread
import time
# Copyright (c) 2014, <NAME> <<EMAIL>>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source c... |
import tensorflow as tf
from tensorflow.keras.layers import (
BatchNormalization,
Concatenate,
Conv2D,
Conv2DTranspose,
Dropout,
ELU,
LeakyReLU,
Multiply,
ReLU,
Softmax,
Add,
MaxPooling2D,
)
from tensorflow.compat.v1.keras.initializers import he_uniform
from functools imp... |
from venv import EnvBuilder
from .deps_handler import DepsHandle
import shutil
import os
from subprocess import call
import logging
from simple_term_menu import TerminalMenu
extra_options = ["manually specify", "ignore dependency"]
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m... |
"""
Author : <NAME>
This script allows you to get a complete list of twitter threads replies
so you can have a fast and complete view of complex threads even if you
are not cited in all the tweet branches
= CREDITS =
Based on the initial work made by @gmellini
https://github.com/gmellini/twitter-scraper
"""
im... |
import logging
import jinja2
import os
import json
from networkconfgen import custom_filters
from networkconfgen.constants import ERROR_UNKNOWN, ERROR_INVALID_VLAN_RANGE, ERROR_INVALID_VALUE, ERROR_CODES
logger = logging.getLogger("networkconfgen")
class NetworkConfGenResult(object):
"""
Object, that represe... |
from math import atan2, pi
import matplotlib.pyplot as plt
import matplotlib as mpl
EPS = 0.000001
astmap = """.#..#
.....
#####
....#
...##"""
astmap1 = """......#.#.
#..#.#....
..#######.
.#.#.###..
.#..#.....
..#....#.#
#..#....#.
.##.#..###
##...#..#.
.#....####"""
astmap2 = """.#..#..###
####.###.#
....###.#.
... |
from __future__ import annotations
import json
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib import axes
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
from matplotlib.... |
# Copyright (c) 2015 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
import json
import math
import requests
from urllib.parse import quote
UK_FOOD_BANK_DATA_URL = "https://www.trusselltrust.org/get-help/find-a-foodbank/foodbank-search/?foodbank_s=all&callback=?"
_dataLoaded = False
_ukFoodBanksList = []
_ukFoodBanksByCity = {}
class FoodBankSchedule:
def __init__(self):... |
from pickle import NONE
import torch
import os
from torch import optim
from torch.autograd.grad_mode import F
from torch.nn.modules.container import ModuleList
from torch.utils.data.dataloader_experimental import DataLoader2
import modules
import data_utils
from torch import nn
from torch.utils.data import DataLoader, ... |
from . import locales
from . import messages
from . import rendered
from . import sitemap
from . import static
from grow.common import utils
from werkzeug import routing
import collections
import webob
import werkzeug
class Error(Exception):
pass
class GrowConverter(routing.PathConverter):
pass
class Dupl... |
import argparse
import os
import platform
import re
import shlex
import subprocess
import sys
from Cython.Build import cythonize
from Cython.Compiler.AutoDocTransforms import EmbedSignature
from setuptools import Extension, find_packages, setup
FFMPEG_LIBRARIES = [
"avformat",
"avcodec",
"avdevice",
... |
from typing import List, Sequence, Union, Dict, Any, Callable, Optional, Type, TYPE_CHECKING
import logging
import json
from hashlib import sha1
from ctypes import cast, byref, sizeof, POINTER, c_float, c_double, c_longlong
from .scvars import validate_simvar, validate_units, validate_event
from .scdefs import (
S... |
from django.shortcuts import render
from django.db.models import Count
from .models import Post, PostReaction, SavedPost, Comment, Profile, CommentReply, CommentVote, ForgetPassword as ForgetPasswordModel, ReplyVote
from .serializers import PostSerializer, PostReactionSerializer, SavedPostSerializer, UserSerializer,Com... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Execute various operations (train, test, time, etc.) on a classification model."""
import argparse
import sys
imp... |
"""
@file lane.py
@author <NAME>
@author <NAME>
@author <NAME>
@author <NAME>
@author <NAME>
@date 2011-11-28
@version $Id$
This file contains a Python-representation of a single lane.
SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
Copyright (C) 2011-2017 DLR (http://www.dlr.de/) and contribut... |
import asyncio
import contextlib
import dataclasses
import itertools
import json
import logging
import time
import typing
import asyncpg
from pg_sql import SqlId, SqlNumber, SqlObject, SqlString
from .collection.dict import groups
from .concurrent import to_thread, wait_success
from .concurrent.graph import GraphRunn... |
# Copyright 2002-2011 <NAME>. See LICENSE for licensing information.
# Id: ClientMain.py,v 1.89 2003/06/05 18:41:40 nickm Exp $
"""mixminion.ScheduleUtils
Simple implementation of a block-until-it's-time-to-do-something scheduler.
"""
import time
import threading
__all__ = [ 'ScheduledEvent', 'OneTimeEvent',... |
# -*- coding: utf-8 -*-
# mymodule/models.py
import json
from exts.sqlalchemy import db
from datetime import datetime
from uuid import uuid4
# SQLAlchemy Imports
from sqlalchemy import text, inspect, select, func
from sqlalchemy.orm import relationship
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy... |
# These are a collection of functions that may be useful to include in MinHash.py in future releases
import numpy as np
import os
import screed
import multiprocessing
from itertools import *
def cluster_matrix(A_eps, A_indicies, cluster_eps=.01):
"""
This function clusters the indicies of A_eps such that for a... |
"""
Implementation of mvtec architecture inspired by:
https://github.com/cheapthrillandwine/Improving_Unsupervised_Defect_Segmentation/blob/master/Improving_AutoEncoder_Samples.ipynb
"""
import tensorflow as tf
from tensorflow import keras
import numpy as np
import cv2
import random
import matplotlib.pyplot as plt
# P... |
import math
import utime
import _thread
from m5stack import lcd
from micropyGPS import MicropyGPS
from machine import UART, I2C, Pin
from mpu9250 import MPU9250
target_coords = (35.388127, 139.427293) # replace with where you want to go
current_coord = (0, 0) # lat, lon
timestamp = ("N/A", 0, 0, 0) # date_str, h, m... |
import logging
import os
import sys
import time
from typing import List
from ymir_exc import dataset_reader as dr, env, monitor, result_writer as rw
def start() -> int:
env_config = env.get_current_env()
if env_config.run_training:
_run_training(env_config)
if env_config.run_mining:
_run... |
import discord
import json
import config
from helpers.restrictions import get_user_restrictions
class Logs:
"""
Logs join and leave messages, bans and unbans, and member changes.
"""
def __init__(self, bot):
self.bot = bot
async def on_member_join(self, member):
await self.bot.wa... |
# import argh
import argparse
import os
import csv
import matplotlib.pyplot as plt
from .find_anomalies import separate_test_entry, FIRST_EXAMPLE_LINE, SEPARATOR
UTT_ID_CSV_NAME = 'ID' # Column name of the utterance identifier in the (test) .csv file.
DUR_CSV_NAME = 'duration' # similar as above
TEXT_CSV_NAME = 'wr... |
import json
import brownie
import pytest
from brownie import *
from config.badger_config import badger_config
from dotmap import DotMap
from helpers.constants import *
from helpers.gnosis_safe import GnosisSafe, multisig_success
from helpers.proxy_utils import deploy_proxy, deploy_proxy_uninitialized
from rich.console... |
"""
Python script to control consistency between the CIGAR overlap (from GFA format)
and the overlap of the nodes's sequences involved in the edge
"""
import difflib
import logging
from Bio import SeqIO
GRAPH_LOGGER = logging.getLogger(__name__)
def reverse_and_complement(string):
"""Given a genomic string
... |
# -*- coding: utf-8 -*-
"""
Created on 2018/9/20
@author: gaoan
"""
from tigeropen.common.consts import Language
from tigeropen.common.util.signature_utils import read_private_key
# 老虎证券开放平台网关地址
SERVER_URL = 'https://openapi.itiger.com/gateway'
# 老虎证券开放平台 socket 连接域名端口
SOCKET_HOST_PORT = ('ssl', 'openapi.itiger.com',... |
from matplotlib import cm
import matplotlib.colors as colors
import matplotlib.pyplot as plt
import matplotlib.patheffects as PathEffects
import types
import numpy as np
import scipy.ndimage
from .cmap import ReversedColormap, WrappedColormap, InvertedColormap
__all__ = ['contour_image']
def contour_image(x,y,Z,
... |
#!/usr/bin/env python3
import urllib.request
from pathlib import Path
from dotenv import load_dotenv
import os
import argparse
import requests
from collections import defaultdict
import urllib
import pandas as pd
load_dotenv()
USGS_DOWNLOAD_URL = os.getenv("USGS_DOWNLOAD_URL")
USGS_METADATA_URL = os.getenv("USGS_META... |
# -*- coding: utf-8 -*-
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
"""
Poll based south plugin to retrieve data from w1-gpio devices on a raspberry pi,
based on the following template: https://github.com/foglamp/FogLAMP-Examples/blob/master/south_plugin_poll/python/foglamp/plugins/south/poll_... |
# -*- coding: utf-8 -*-
# Copyright (c) 2012 Jiri "NoxArt" Petruzelka
#
# 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,... |
"""
HTTP request validators
"""
import re
from jasmin.protocols.http.errors import UrlArgsValidationError, CredentialValidationError
from jasmin.protocols.validation import AbstractCredentialValidator
class UrlArgsValidator:
"""Will check for arguments syntax errors"""
def __init__(self, request, fields): ... |
import hashlib
import os
import logging
from functools import reduce
from operator import iadd
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
RANDOM_SEED = 42
DATA_PATH = 'test_data'
def to_csv(df, file_name):
path = os.path.join(DATA_PATH, file_name)
df.to_csv(path, index=Fal... |
# Copyright (c) 2018-2020 Inria
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following... |
import sublime
import sublime_plugin
import re
import logging
import webbrowser
from .terminal import Terminal, CONTINUATION
from .utils import highlight_key
logger = logging.getLogger('Terminus')
rex = re.compile(
r'''(?x)
\b(?:
https?://(?:(?:[a-zA-Z0-9\-_]+(?:\.[a-zA-Z0-9\-._]+)+)|localhost)| # ... |
import errno
import logging
import os
import uuid
import struct
import time
import base64
import socket
from . import exc
from .cliutil import priority
from .conf import CephConf
from . import hosts
from .util import arg_validators, ssh
from .misc import mon_hosts
from .lib.remoto import process
from .connection impor... |
# Copyright 2021 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Test for Kconfig checker"""
import contextlib
import io
import os
import re
import sys
import tempfile
import unittest
import kconfig_check
# Prefix ... |
#!/usr/bin/env python
import logging
import os
import sys
import click
import yaml
import yadage.steering_api as steering_api
import yadage.utils as utils
import yadageschemas
from packtivity.plugins import enable_plugins
from .logutils import LOGFORMAT
log = logging.getLogger(__name__)
RC_FAILED = 1
RC_SUCCEEDED ... |
from django.db import models
from django.contrib.auth.models import User
from django_countries.fields import CountryField
# Create your models here.
class Person(models.Model):
GENDER = (
('M', 'male'),
('F', 'female'),
)
EDU = (
('Primary', 'Primary'),
('Secondary', 'Secondary'),
('C... |
#!/usr/bin/python3
import os
import subprocess
import numpy as np
from threading import Thread, Lock
import time
import unittest
import sys
# Efficienly capture audio into a ringbuffer using arecord
# This will only work for linux based systems
# To minimize CPU usage large chunks are read from alsa
# The audio capt... |
import time
from datetime import datetime
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.test import *
from sqlalchemy.test.profiling import profiled
class Item(object):
def __repr__(self):
return 'Item<#%s "%s">' % (self.id, self.name)
class SubItem(object):
def __repr__(self):... |
#!/usr/bin/env python
"""
Copyright 2016 ARC Centre of Excellence for Climate Systems Science
author: <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/lic... |
from edmtypes import *
from lxml import etree as ET
from pdb import Pdb
debug = Pdb()
ODATA_NAMESPACES = {
'edmx': 'http://docs.oasis-open.org/odata/ns/edmx'
}
BOOLEAN_RANGE = [True, False]
class ComplexType(type):
def __init__(cls, clsname, bases, _dict):
if clsname != 'Base':
valid_bases = filter(lambda x: x... |
import os.path as op
from skbold.core import MvpBetween
from skbold import testdata_path, roidata_path
import os
import pytest
import numpy as np
cmd = 'cp -r %s/run1.feat %s/mock_subjects/sub00%i'
_ = [os.system(cmd % (testdata_path, testdata_path, i+1)) for i in range(9)
if not op.isdir(op.join(testdata_path, ... |
from inspect import getfullargspec
from typing import Optional
from pydantic import BaseModel
def show_plots(schema, files):
"""
This function accepts the schema model and runs it using yt code which returns
a list. This function iterates through the list and displays each output.
Args:
sche... |
##############################################################################
# Copyright 2019 IBM Corp.
#
# 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/LI... |
#!/usr/bin/env python3
import sys
class Grid:
def from_input(input):
lines = input.split('\n')
height = len(lines)
width = len(lines[0])
result = Grid(width, height, 1)
for y, line in enumerate(lines):
for x, char in enumerate(line):
result.set(x... |
from rest_framework import viewsets, mixins, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from rest_framework.response import Response
from core.models import Tag, Character, Series
from series i... |
#!/usr/bin/python3
import argparse
import json
import os
# sys.path.insert(0, "lib")
import discord
from classes.PluginManager import PluginManager
from classes.Logger import Logger
from config import config
from utilities import get_meta
class ConDeBot(discord.Client):
def __init__(self, *args, **kwargs):
... |
import math
import random
from .exceptions import UnableToBreedException
class Gender:
"""
An enum for defining genders.
"""
# NOTE: I really don't care about political correctness for
# this algorithm. Numerical values only serve a logical purpose.
# Undefined only means unspecified.
MA... |
# -*- coding: utf-8 -*-
"""
Classes and methods used to define loading to apply to dynamic systems
"""
from __init__ import __version__ as currentVersion
import numpy
import pandas as pd
import inspect
import scipy
import matplotlib.pyplot as plt
from numpy import sin, pi
class Loading():
"""
Generic loadin... |
# _*_ coding: utf-8 _*_
"""
python_restful_api.py by xianhu
"""
import sqlalchemy
import sqlalchemy.orm
import sqlalchemy.ext.declarative
from flask import Flask, g
from flask_restful import reqparse, Api, Resource
from flask_httpauth import HTTPTokenAuth
# Flask相关变量声明
app = Flask(__name__)
api = Api(app)
# 认证相关
a... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FuncFormatter
np.random.seed(19680801)
X = np.linspace(0.5, 3.5, 100)
Y1 = 3+np.cos(X)
Y2 = 1+np.cos(1+X/0.75)/2
Y3 = np.random.uniform(Y1, Y2, len(X))
fig = plt.figure(figsize=(8, 8))
ax =... |
import torch
import numpy as np
from collections import defaultdict
class Tree(object):
"""
Reused tree object from stanfordnlp/treelstm.
"""
def __init__(self):
self.parent = None
self.num_children = 0
self.children = list()
def add_child(self, child):
child.par... |
import glob
import os
import readline
from ftplib import FTP, all_errors
ftp = FTP('')
pwd = ""
address = "disconnected"
connected = False
def complete(text, state):
"""
generate path from input string and auto complete
:param text: text to complete
:param state: input state
:return: completed t... |
import os
import json
import torch
import torch.nn as nn
import itertools
import argparse
import torchvision
from torchvision import datasets, transforms
import torch.nn.functional as F
from torchvision.utils import save_image
from det_ae import AutoEncoder
from det_vae import VAE
from det_vae import ... |
# Copyright 2017 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 ag... |
import torch
from typing import List
from training.training_loop import spec_to_audio
from PySide2.QtCore import QRunnable, QObject, Signal, Slot
from utils.audio_file import AudioFile
class KGSignals(QObject):
generation_finished = Signal(AudioFile)
status_log = Signal(str)
k_model_name = '... |
from os import system, name as OSname
from getkey import getkey, keys
from threading import Thread
from random import randint
from cursor import hide, show
from sys import stdout
from time import sleep
#--------------configs-------------#
speed = [0.20, 0.20, 0.15, 0.10, 0.08, 0.05]
lives = 3
IMG_body = "🚀"
IMG_obsta... |
import csv,sys
from math import log,exp
if sys.version_info[0]<3: print("Requires Python 3");sys.exit(1)
def getcountrydata(country,thr=0,smoothlevel=0,region="",source="worldometer"):
"""
Returns (dates, totalconfirmed, totaldeaths, recovered (if available), active (if available), newcases, newdeaths)
for the ... |
from discord_slash.utils.manage_components import create_button, create_actionrow
from discord_slash.model import ButtonStyle
programme_roles_dict = {
'cse': 'Computer Science and Engineering',
'ae': 'Aerospace Engineering',
'mech': 'Mechanical Engineering',
'ee': 'Electrical Engineering',
'nb': 'N... |
import asyncio
import collections
import io
from ctypes import addressof, c_uint8
from . import nghttp2
class StreamReader(object):
def __init__(self, loop=None):
self._loop = loop or asyncio.get_event_loop()
self._eof = False
self._buffer = collections.deque()
self._size = 0
... |
# coding: utf-8
# python controller.py (with Picamera)
# python controller.py --use-usb (with USB Webcam)
import argparse
import base64
#import cStringIO as io
import io
import os
import tornado
import tornado.httpserver
import tornado.web
import tornado.websocket
import tornado.ioloop
import webbrowser
from fabolib.ca... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
from PIL import Image, ImageDraw, ImageFont
from dataclasses import dataclass
from inotify_simple import Event, INotify, flags
from pathlib import Path
from typing import Tuple
from waveshare_epd import epd2in13b_V3
import logging
import time
import socket
import subprocess
@d... |
import torch
import numpy as np
import copy
from general_config.anchor_config import default_boxes
from utils.box_computations import wh2corners_numpy, corners_to_wh
from utils.postprocessing import nms
class Model_output_handler():
"""
Class used to bring the raw model outputs to interpretable data
-> b... |
##############################################
# This for AVX2
REGISTER_TYPE="__m256d"
DATA_TYPE="double"
REGISTER_WIDTH = 4
NUMBER_OF_REGISTERS = 16
MASK_IN_REGISTER = 0 # should be 1 ??
#TARGET_ITILE = 4
#TARGET_JTILE = 12
TARGET_ITILE = 3
TARGET_JTILE = 16
TARGET_KTILE = 48
CACHE_SIZE = 8192
MAX_JTILE = 20
MAX_I... |
import flask
from flask import jsonify
from donut.modules.groups import helpers as groups
from donut.modules.account import helpers as account
from donut.modules.core.helpers import get_name_and_email
from donut import auth_utils
import html2text
from . import blueprint, helpers
# Set up converter for html to plain t... |
from abc import ABC, abstractmethod
import threading
import heapq
class SearchDomain(ABC):
# construtor
@abstractmethod
def __init__(self):
pass
# lista de accoes possiveis num estado
@abstractmethod
def actions(self, state):
pass
# resultado de uma accao num estado, ou ... |
import json
import datetime
import re
from functools import wraps
from pyramid.view import view_config
from pyramid.view import view_config, notfound_view_config
from pyramid.response import Response
from pyramid import httpexceptions
LIMIT = 20
ALLOWED_TYPE_DOCS = ['article', 'issue', 'journal', 'website']
REGEX_ISS... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This file is part of Ansible
#
# Ansible 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 Foundation, either version 3 of the License, or
# (at your option) any later version.
... |
import os
import re
import h5py
import math
import numpy as np
import pandas as pd
from pyntcloud import PyntCloud
BASE_DIR = r"G:\Capstone"
# Load ply files with asset reference models
ply_folder = os.listdir(os.path.join(BASE_DIR, "data", "assets", "test"))
# Output h5 file containing ply files
h5_fi... |
import yaml, sys, os
import torch
import argparse
import timeit
import numpy as np
from torch.utils import data
from tqdm import tqdm_notebook as tqdm
from ptsemseg.models import get_model
from ptsemseg.loader import get_loader
from ptsemseg.metrics import runningScore
from ptsemseg.utils import convert_s... |
"""
`scrapd-augmenter-geocoding-geocensus` is an augmenter geocoding the crash locations.
It uses the Geo Census database. The script does not recode entries which already have their geolocation.
Usage examples:
$ scrapd-augmenter-geocoding-geocensus fatalities.json
"""
import argparse
import asyncio
import json
imp... |
#!/usr/bin/env python
from flask import Flask, Blueprint, render_template, redirect, request, g
from flask.ext.login import login_user, logout_user, current_user, login_required
import bbcode, bcrypt, base64, re
from models import Post, User, Draft
from app import app, cache
# PREFIXES ------------------------------... |
import logging
import time
import uuid
import structlog
from flask import current_app
from application.controllers.helper import (is_valid_file_extension, is_valid_file_name_length,
convert_file_object_to_string_base64)
from application.controllers.rabbit_helper import init... |
# -*- coding: utf-8 -*-
"""
Copies media files from file system into database
see parser.description in class Command bellow
"""
import argparse
import importlib
import os
import re
from django.conf import settings # proper settings must be found (search for DJANGO_SETTINGS_MODULE or --settings= in Django d... |
""" Reference implementation of the Shamir Secret Sharing for Mnemonic Phrases (SSSMP) specification.
The implemenation is designed to be minimalistic, and closely resembles the specification.
See also: https://de-centralized-systems.github.io/sssmp/
"""
import hmac
import secrets
from typing import List, Optional, S... |
# Copyright European Organization for Nuclear Research (CERN)
#
# 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
#
# Authors:
# - <NAME>, <<EMAIL>>, 20... |
"""
This rdflib Python script creates a DefinedNamespace Python file from a given RDF file
It is a very simple script: it finds all things defined in the RDF file within a given
namespace:
<thing> a ?x
where ?x is anything and <thing> starts with the given namespace
<NAME>, Dec, 2021
"""
import argparse
imp... |
#!/usr/bin/python3
import oneflow.nn as nn
import oneflow as flow
from modeling import BertForPreTraining
import pickle
import numpy as np
def get_masked_lm_loss(
logit_blob,
masked_lm_positions,
masked_lm_labels,
label_weights,
max_prediction_per_seq=20,
):
# gather valid position indices
... |
from collections import Counter
import json
import time
import logging
import requests
from threading import Thread
from textwrap import dedent
logger = logging.getLogger('flask.app')
def github_topic(owner: str, repo: str) -> list:
"""return topics list
using https://developer.github.com/v3/repos/#list-all-to... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
import argparse
import logging
import os
import subprocess
import sys
if False:
# See https://zulip.readthedocs.io/en/latest/testing/mypy.html#mypy-in-production-scripts
from typing import Callable, Dict, Lis... |
import image, network, rpc, sensor, struct
import time
import micropython
from pyb import Pin
from pyb import LED
# variables that can be changed
save_to_SD = False
# leds are used as an easy way to know if the remote camera has started fine
red_led = LED(1)
green_led = LED(2)
blue_led = LED(3)
ir_led = LED(4)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 12 09:16:20 2021
@author: trondkjekstad
"""
from flask import (
Flask, render_template, request, redirect, flash, url_for, session, g
)
from werkzeug.security import check_password_hash, generate_password_hash
from werkzeug.exceptions import... |
import sys
# attempt to import zabbix runtime if running embedded
try:
import zabbix_runtime
except ImportError:
zabbix_runtime = None
__version__ = "1.0.0"
__python_version_string = "Python %i.%i.%i-%s" % sys.version_info[:4]
__modules = []
__items = []
__routes ... |
"""Support for beets command aliases, not unlike git.
By default, also checks $PATH for beet-* and makes those available as well.
Example:
alias:
from_path: yes # Default
aliases:
singletons: ls singleton:true
external-cmd-test: '!echo'
sh-c-test: '!sh -c "echo foo bar arg1:$1... |
import torch
import torch.utils.data
import torch.nn as nn
import torch.nn.functional as F
import math
from src.nn_utils import *
from src.gauss_interp import *
from src.viewer_utils import *
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from src.point_cloud_data_augmentation import center_res... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 09 15:36:16 2018
@author: cansu.yildiz
"""
from __future__ import print_function
import argparse
import h2o
import findspark
from pyspark import SparkConf, SparkContext
from pysparkling import *
from pyspark.sql import SparkSession
from math import sqrt
... |
from collections import namedtuple
import camus
from unittest import mock
from pytest import raises
IdRecord = namedtuple("IdRecord", "id")
def check_id(i, row):
assert row.id == i
class MockAurora:
def begin_transaction(self, secretArn, resourceArn, database):
return {"transactionId": "transact... |
import logging
from datetime import datetime, timezone
from typing import Optional, Mapping
import aioredis
from aioredis import Redis, ConnectionsPool
from aioredis.util import decode
from lightbus.transports.base import EventMessage
from lightbus.exceptions import LightbusException, TransportIsClosed, LightbusShut... |
import timeit
import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
from sklearn.model_selection import StratifiedKFold
from tabulate import tabulate
def load_dataset(file: str, class_label_column):
dataset = pd.read_csv(file, header=N... |
from tkinter import *
boton = ""
def convBinario(num):
vector=[]
vector2=[]
i=0
j=0
if num==1:
return 1
elif num==0:
return 0
else:
while(int(num/2) != 1):
vector.insert(i,int(num%2))
i=i+1
num=num/2
i=i+1
vector.insert(i,int(num%2... |
from typing import Union
import gym
import numpy as np
from PIL import Image
from gym import Env, ObservationWrapper
from gym.spaces import Box, Discrete
def get_wrapper(env, wrapper_type):
w = next(filter(lambda w: isinstance(w, wrapper_type), list_wrappers(env)), None)
return w
def list_wrappers(env: Uni... |
import numpy as np
import os
import time
import wave
from subprocess import check_call
import pyaudio
import scipy.io.wavfile as wavfile
from scipy.signal import lfilter
import nstdvs
from struct import pack
import alsaaudio
import math
def readHRTF(name):
r = np.fromfile(file(name, 'rb'), np.dtype('>i2'), 256)... |
import json
import multiprocessing
import os
import signal
import sys
import time
from functools import partial
import matplotlib as mpl
import pandas as pd
import psutil
from matplotlib import pyplot as plt
from src.preprocessing import preprocess_sample
from src.utils import matrix2answer, show_sample
from tqdm.no... |
"""
Copyright (c) 2013-2015, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following d... |
import os
from glob import glob
import h5py
import numpy as np
import torch_em
import torch_em.shallow2deep as shallow2deep
from torch_em.model import UNet2d
def prepare_shallow2deep_isbi(args, out_folder):
patch_shape_min = [1, 256, 256]
patch_shape_max = [1, 512, 512]
raw_transform = torch_em.transfor... |
import os
import numpy as np
import datetime as dt
import requests
import polyline
import folium
import time
"""
TO DO
"""
def next_best_date():
"""
Finds the next datetime which is a weekday, with a time of 9am
Returns:
(string): datetime from epoch in seconds as string
"""
date_today ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.