text stringlengths 3.07k 12.6k |
|---|
from losses import SeparableMTLoss
from regularizations import Regularization
from . import Fit, ConvergenceError
import numpy as np
import pandas as pd
from time import time
from joblib import Parallel, delayed
def _ridge(loss, rho, beta, d, b, tr):
return loss.ridge(1. / rho, beta - d, b, threshold=tr)
class Con... |
#coding=utf8
import os, json, pickle, time
from tqdm import tqdm
import fcntl
from .common_utils import Preprocessor
from .align_tables import align_tables_by_dataset_name
def process_tables(processor, tables_list, output_path=None):
tables = {}
for idx, each in tqdm(enumerate(tables_list)):
tables[e... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#############################################################################
# _____ __________ ___ __ #
# / ___// ____/ __ \/ | / / #
# \__ \/ / / /_/ / /| | / / ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 EPFL.
#
# 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 ... |
#!/usr/bin/env python3
import matplotlib
matplotlib.use('pdf')
import scrublet as scr
import scipy.io
import scipy.sparse
import numpy
import numpy.ma
from PIL import Image, ImageDraw, ImageFont
import os
import sys
import re
import warnings
import traceback
import argparse
#
# Notes:
# o apply umi_cutoff in filte... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule
from ove.utils.modeling import Sequential
from ove.utils.arch import make_layer
def warp(
x, flow,
interpolation='bicubic',
padding_mode='zeros',
align_corners=True
):
if x.size()[-2:... |
#!/usr/bin/env python3
""" Load reads in data files before staging and loading them in snowflake"""
import snowflake.connector
import glob
import os
import time
def get_listings():
"""Generator of city names, scrape date and file path"""
# os.chdir(os.path.dirname(os.path.abspath(__file__)))
# os.chdir(... |
#!/usr/bin/python3
import subprocess
import re
import os, sys
import time
import pipes
import argparse
TIMEOUT="15m"
patternP=re.compile("^(P.+)$")
CPUS=[15,16,17,18,19,30,31,32,33,34,35,36,37,38,39]
NEXTCPU=0
def run(model, prop, const, minprob, arguments, num_arg, scriptname, logname):
global NEXTCPU
globa... |
import os.path
import re
import sys
import re
from docutils import nodes, statemachine, utils
from docutils.utils.error_reporting import ErrorString
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive
import fett
import yaml
if sys.version_info.major >= 3:
basestring = str
# Map... |
# Copyright (c) 2017, DjaoDjin Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and t... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import platform
import re
import unittest
import beanmachine.graph as graph
import beanmachine.ppl as bm
import beanmachine.ppl.compiler.pe... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import unittest
import frappe
from frappe.utils import cint
from frappe.test_runner import make_test_records
import erpnext
from erpnext.stock.doctype... |
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from data_loader import DataLoader
from pgnn import PhysicsGuidedNeuralNetwork
from pgnn_config import *
from poisson_equation import PoissonEquation
tf.set_random_seed(SEED)
def save_results(ranges, dim, solution, nn_solution):
"""
... |
# encoding:utf-8
# 参考文献:贝叶斯优化调参 笔记前面这些链接,代码来自http://36kr.com/p/5114423.html
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# mpl.rc('font', family='Times New Roman')
mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = 'SimSun,Times New Roman'
def polyfit(x, y, de... |
import numpy as np
from matplotlib import pyplot as plt
ABS_THRESH = 3
REL_THRESH = 0.05
def get_error_maps(sf, gt):
gtmask = gt[:, :, 2] > 0
flow_error = np.linalg.norm(sf[:, :, 0:2] * np.tile(np.expand_dims(gtmask, axis=2), [1, 1, 2]) - gt[:, :, 0:2] * np.tile(np.expand_dims(gtmask, axis=2), [1, 1, 2]), axi... |
""" """
import os
import random
random.seed(int(os.getenv("SEED"), 16))
from prjxray import util
from prjxray.db import Database
def find_phasers_for_pll(grid, loc):
gridinfo = grid.gridinfo_at_loc((loc[0], loc[1] + 13))
phasers = {
'IN': [],
'OUT': [],
}
for site_name, site_type in ... |
import sublime
import sublime_plugin
import datetime
import re
import os
import logging
import getpass
import OrgExtended.asettings as sets
import OrgExtended.pymitter as evt
import OrgExtended.orgextension as ext
import OrgExtended.orgparse.date as orgdate
log = logging.getLogger(__name__)
# I think I will model thi... |
'''
Commands for querying code review objects on a Gerrit Site
Specifically, the Query command encapsulates the 'query' command line
utility.
Some common queries are provided in the form of functions which return
a prepared Query object. For example, `open_reviews` reviews a Query
prepared to return a complete list o... |
# <NAME> | Kormi001
# Based on the EchoServerPlusHead.py example provided by:
# <NAME>, <NAME>, <NAME>,
# <NAME>, <NAME>, and <NAME>
#
# Calendar in: calendar.html
# Form in: form.html
# Addition Info URL Name: urlinfo
'''
TODO
----
OPTIONS
POST
Response for 406 Error Conditions
'''
import socket
import os
import st... |
from mongolia import ID_KEY
from backend.admin_portal.survey_builder_helpers import choices_append
from utils.time import datetime
from constants.database import ANSWER_VALUE
from database.backbone.schedules import (Schedule, Question, Conditional)
from database.backbone.cohorts import Cohort
from database.tracking.us... |
# Copyright 2021, <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-3-Clause
import os
import hmac
import random
import binascii
import asyncio
import subprocess
import atexit
from socket import AF_UNIX
from dataclasses import dataclass, field
from pathlib import Path
from cryptography.hazmat.primitives.ciphers.aead im... |
import numpy as np
from input import parameters as para
if para.Target=="CPU": import numpy as ncp
from lib import boundary as BC
import h5py as hp
from lib.PoissonSolver import multigrid3D
from lib import grid as gd
from lib.glob import *
if para.Target=="GPU":
import cupy as ncp
ncp.cuda.Device(para.device... |
from .vecenv import DummyVecEnv, VecNormalize, VecFrameStack
from collections import defaultdict
import gym
try:
import robosuite as robst
except Exception as e:
"Could not find package robosuite. All relevant environments cannot be used."
import multiprocessing
import re
from .atariwrapper import ma... |
import pandas as pd
### Helpers
class GraphistryHelpers:
@staticmethod
def apply_dict(df, col, dictionary):
return df[col].apply(lambda v: dictionary[v])
@staticmethod
def color_nodes_by_dict(g, col, dictionary):
node_colors_s = GraphistryHelpers.apply_dict(g._nodes, col, dictionary)
... |
import sys
import time
import torch
from copy import deepcopy
from datetime import datetime
class Timer():
def __init__(self, n_last=0):
self.times = None
self.last = None
self.n_last = n_last
def start(self):
self.last = time.time()
self.start_time = self.last
... |
import argparse
from argparse import ArgumentParser
from . import template
from . import feedback as fdback
from . import github
from .quickstart import create_dir_struct
from .clone import clone_student_repos
from .roster import create_roster
def quickstart():
parser = ArgumentParser(description=create_dir_st... |
"""
Lambert's problem solver using the method proposed by <NAME> in 2008.
This module holds the implementation of the algorithm devised by Avanzini, which
appeared for the first time in his article [1]. The solver takes advantage of
the conservation of the eccentricity projection along the chord direction, so it
itera... |
import json
import os
import shutil
import subprocess
import sys
dcn_cmd = "cd /DCNv2; sh make.sh"
subprocess.run(dcn_cmd, shell=True)
def copy_files(src, dest):
src_files = os.listdir(src)
for file in src_files:
path = os.path.join(src, file)
if os.path.isfile(path):
shutil.copy(p... |
from pyspark import SparkConf,SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.types import *
from operator import add
import pyspark
import sys
import requests
from pprint import pprint
import pandas as pd
import numpy as np
from timescaleplot import graph
from datetime import datetime
# mapper that ... |
import numpy as np
from scipy.io import wavfile
from scipy.signal import firwin, filtfilt, hamming, resample
default_nyquist = 22050.0
def slurp_wav(path, start=0, end=(44100 * 10)):
"""Read samples from the 0th channel of a WAV file specified by
*path*."""
(fs, signal) = wavfile.read(path)
nyq = fs ... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
import os
import sys
os.environ["TF_KERAS"] = '1'
sys.path.append(os.environ['d'])
from tensorflow_addons.shared import *
class LM_layer(Layer): # input: [None, seq_len, max_len] * 2 output: [None, seq_len, hidden_dim]
def __init__(self, seq_len, max_len, hidden_dim, embedding_dim, vocab_size, **kwargs):
... |
from flask import Flask, request, render_template, make_response
import subprocess
import pathlib
from shlex import quote
from banco_teste import BancoTeste
"""
ATENÇÃO: Este código é propositalmente vulnerável,
para fins de estudo de programação segura
--------------------------------------------------
TCC CyberSecur... |
from ._bmdb import get_bookmark, check_bookmark, get_bookmarks, set_bookmark, remove_bookmark
from ._config import ec
import discord
from discord.ext import commands
from discord.commands import message_command
import datetime, calendar
def get_unix(date: datetime.datetime):
u = calendar.timegm(date.utctimetuple()... |
# -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
from yolo_v3 import _conv2d_fixed_padding, _fixed_padding, _get_size, \
_detection_layer, _upsample
slim = tf.contrib.slim
_BATCH_NORM_DECAY = 0.9
_BATCH_NORM_EPSILON = 1e-05
_LEAKY_RELU = 0.1
# 8, 15, 14, 26, 24, 42, 43, 70, 81,124, 162,218
... |
"""Crypto Utility
"""
from functools import reduce
from math import ceil, gcd, lcm
from operator import mul
import gmpy2
def XOR(*array: tuple[bytes]):
"""XOR strings
Calculate `A XOR B`.
Args:
A (bytes): The first string.
B (bytes): The second string.
Returns:
bytes: The re... |
import json
from DB import SQLite as sql
from gems import gemsItems as GI, gemsFonctions as GF
from datetime import date, datetime
from apscheduler.schedulers.background import BackgroundScheduler
import math
def load_dates():
"""
Charge les dates des saisons et leur nombre total
Return :
dict => 5 c... |
# Adopted from https://github.com/fchollet/keras/blob/master/examples/conv_filter_visualization.py
from __future__ import print_function
from scipy.misc import imsave
import numpy as np
import argparse
import time
from math import ceil, sqrt
from keras.models import load_model
from keras import backend as K
from keras... |
"""Containers for information regarding licenses."""
class License:
"""Container for license information with utility methods."""
uri_template = "https://opensource.org/licenses/%s"
def __init__(self, identifier, name, uri=None, scheme=None):
"""Create a new license.
:param identifier: ... |
graph = {
"Arad": {"Zerind": 75, "Timisoara": 118, "Sibiu": 140},
"Zerind": {"Arad": 75, "Oradea": 71},
"Oradea": {"Zerind": 71, "Sibiu": 151},
"Timisoara": {"Arad": 118, "Lugoj": 111},
"Lugoj": {"Timisoara": 111, "Mehadia": 70},
"Mehadia": {"Lugoj": 70, "Dobreta": 75},
"Dobreta": {"M... |
import urllib.request
import urllib.error
import urllib.parse
import socket
import json
import os.path
from .ly_types import CSSRule
from .errors import LyError
QUERY_TIMEOUT = 2
VENDOR_JSON_FILE = 'vendor-data.json'
VENDOR_JSON_URL = 'https://raw.github.com/Fyrd/caniuse/master/data.json'
DEFAULT_TARGETS = 'ie=10;fi... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Turku University (2019) Department of Future Technologies
# Course Virtualization / Website
# uWSGI entry point
#
# application.py - <NAME> <<EMAIL>>
#
# 0.1.0 2019-12-07 Initial version.
# 0.2.0 2019-12-23 Add SSO object creation and .update()
# ... |
from flask import Flask, Response, jsonify, request
from conftest import uuids, make_tarfile
import json
import os
import time
import typing
app = Flask(__name__)
def generate_sleep_intervals(num_exceptions: int = 6) -> int:
"""Generator to return sleep times for the first num_exceptions"""
count = 0
wh... |
from django.contrib.auth.mixins import (
LoginRequiredMixin,
PermissionRequiredMixin,
)
from django import forms
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic import TemplateView
from django.views.generic.list import ListView
from django.forms.utils import Er... |
from itertools import chain
from django import forms
from django.forms import widgets
from django.forms.utils import flatatt
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from ..common.dice import DICE_COUNT
from ..game.models impo... |
# -*- coding: utf-8 -*-
u"""create sirepo configuration
:copyright: Copyright (c) 2017 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern.pkcollections import PKDict
from pykern.pkdebug import p... |
import os
import glob
import shutil
from pathlib import Path
class USGSLib7():
"""
The "USGSLib7" class encodes the files into the USGS Spectral Library Version 7 Data. Each original file contains spectra measured with laboratory, field, and airborne spectrometers. In parallel, each encoded file merges the wav... |
import pytest
import numpy as np
import astropy.units as u
from astropy.tests.helper import remote_data
from .. import *
try:
import scipy
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
class TestSun:
def test___repr__(self):
with default_sun.set('E490_2014LR'):
assert rep... |
import os
import sys
from os import path
from calendar import getDate, getDateMANUAL, OPTIONS_DATE
from config import configGet
from helpers import printOptions
BASEPATH = "assignments"
OPTIONS_FILE = {1: "homework", 2: "labs", 3: "case study"}
SUBFOLDERS = tuple(OPTIONS_FILE.values())
#A function ask the user to cr... |
from flask import render_template, redirect, request, url_for, flash
from flask.ext.login import login_user, logout_user, login_required,current_user
from . import auth
from ..models import User
from .forms import LoginForm,RegisterationForm,ChangePasswordForm,ResetRequestForm,ResetPasswordForm,ChangeEmailForm
from .. ... |
# -*- coding: utf-8 -*-
import io
import inspect
import os
THISDIR = os.path.dirname(__file__)
class GuppyDoc:
def __init__(self, mod, str):
self.mod = mod
if str is None:
str = '???'
str = self._substitute(str)
self.str = str
def __getitem__(self, idx):
... |
# -*- coding: utf-8 -*-
import codecs
import os
import sys
import traceback
unknown_word = 'UNK'
def create_sm_txt(path, name=""):
pass
def get_sm(path):
"""
Creates and returns a StringMap. The mapping is loaded from the file given by `path`.
Args:
path: path to text file, should conta... |
# Copyright <NAME> (c) 2019
#
# 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 t... |
import unittest
import numpy
import math
gravity = numpy.array([0, 0, -9.80665])
class LinkBuilder():
"""
For building up a robotic object for gravity compensation calculations
used like:
b = LinkBuilder()
b.addLink(Link(1, 2, 3, 4, (1,1,1), 1))
b.addLink(Link(2, 3, 4, 5, ... |
from __future__ import print_function
import argparse
import csv
import os
import pytsk3
import pyewf
import sys
"""
MIT License
Copyright (c) 2017 <NAME>, <NAME>
Please share comments and questions at:
https://github.com/PythonForensics/PythonForensicsCookbook
or email <EMAIL>
Permission is hereby granted,... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
main.py - The main module of the project
========================================
This module contains the config for the experiment in the "config" function.
Running this module invokes the :func:`main` function, which then performs the experiment and saves its results
to... |
import random
import hikari
import requests
import cmdtools
from cmdtools.callback.option import OptionModifier
from cmdtools.callback import Callback, ErrorCallback
from bs4 import BeautifulSoup
from lib import command
group = command.BaseGroup("Fun")
PREFIX = "f+"
@group.command()
class Dice(command.BaseCommand):... |
import numpy as np
import pytest
import copy
from ctapipe.utils import get_dataset_path
from ctapipe.io.simteleventsource import SimTelEventSource
from ctapipe.io.hessioeventsource import HESSIOEventSource
from itertools import zip_longest
gamma_test_large_path = get_dataset_path("gamma_test_large.simtel.gz")
gamma_te... |
# -*- coding: utf-8 -*-
# Get N-grams of dependency relations from COW-DOM.
import os.path
import sys
import glob
import re
from lxml import etree as ET
from subtree import SubtreeBuilder
from anytree import Node, RenderTree, find, AnyNode, findall
import operator
stb = SubtreeBuilder(depindpos=0, dephdpos=2, depre... |
# Copyright 2020 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 by applicable law or agreed ... |
import openpyxl
import win32print
import kivy
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.checkbox import CheckBox
kivy.require("1.10.1")
wb = openpyxl.load_work... |
# -*-coding:utf-8-*-
"""
@FileName: QZone_Spider_stable.py
@Author:<EMAIL>
@Create date: 2019/05/09
@Modified date: 2021/05/21
@description: A script to get messages from qzone.com; single-processed version, more stable.
"""
#-------------------initialize----------------------
import os.path
import json
import re
from... |
import os
import sys
import pickle
import pandas as pd
import numpy as np
import word2vec as wv
from tqdm import tqdm
from scripts.create_feature_files import create_sentence_df, pre_process_word_idx, fix_sentence_df
def create_no_class_sentence_df(df):
df['action_class'] = df.apply(lambda x: '{}_{}'.format(x.ve... |
import os
import utils
import cipher_utils
import serializer_utils
import client_exceptions
import general_exceptions
import stoneredis
import warnings
try:
import ujson as json
except:
import json
try:
from bson.objectid import ObjectId
except ImportError:
from pymongo.objectid import Ob... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script Name: Plt.py
Author: <NAME>/Jimmy - 3D artist.
Description:
This script is master file of Pipeline Tool
"""
# -------------------------------------------------------------------------------------------------------------
""" Import """
# Python
# PyQt5
fr... |
"""Helper functions for fetching data from Jenkins.
The main exported symbol here is the get_client_via_*(), which returns
a JenkinsFetcher object that other modules can use to fetch data from
Jenkins.
This module also has support for various methods of fetching the secret key
used to access Jenkins.
"""
import base6... |
# Copyright (c) 2018, Palo Alto Networks
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : hpool_xch_withdraw.py
@Desc : 当前支持`oathtool`获取Google Authenticator验证码,获取token完成自动提现.使用telegram bot发送消息通知.
@Time : 2021/11/01 16:11:55
@Author : Chaos
@Version : 1.3
'''
# here put the import lib
import requests
import re
import ... |
# My Godzilla Hat Code - @alt_bier
from adafruit_circuitplayground.express import cpx
import random
#cpx.pixels.brightness = 0.5 # 50 pct
cpx.pixels.fill((0, 0, 0)) # Turn off the NeoPixels if they're on!
# Function to give us a nice color swirl on the built in NeoPixel (R,G,B)
def wheeln(pos, sft):
if (pos + sf... |
# -*- coding: utf-8 -*-
"""
@Time : 2018/3/23 18:42
@Author : Elvis
cub.py
watch --color -n1 gpustat -cpu
CUDA_VISIBLE_DEVICES=3 python zsl_animals.py
"""
import torch
from torch import nn
from torch import optim
from torch.backends import cudnn
from torch.autograd import Variable
import os
import argparse
from ... |
import numpy as np
import Levenshtein
import spacy
import pickle as pkl
import nltk
import os
from os import path
from tqdm import tqdm
from .util import readpickle, writepickle
def characterRatio(src,ref):
if len(src) == 0:
print('>>> character ratio: zero-exception')
return 0
srcScore = 0
refScore = 0
for ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#------------------------------------------------------
# @ File : train_old.py
# @ Description:
# @ Author : <NAME>
# @ Contact : <EMAIL>
# @ License : Copyright (c) 2017-2018
# @ Time : 2021/2/3 下午4:25
# @ Software : PyCharm
#----------------------... |
import sys
# Copyright 2012 <NAME>, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
from __future__ import print_function, division, absolute_import
from concurrent.futures import CancelledError
from datetime import timedelta
from operator import add
from time import sleep, time
from dask import delayed
import pytest
from toolz import concat, sliding_window
from distributed import Executor, wait, N... |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2020 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pub... |
"""
Defines two convolutional residual neural networks for AlphaZero and MuZero to play generic boardgames.
"""
import sys
from keras.layers import Dense, Input, Concatenate, Reshape, Flatten, BatchNormalization, Conv2D, Lambda
from keras.models import Model
from tensorflow.keras.optimizers import Adam
from utils.ne... |
"""
Collect crash stats.
"""
import healthreportutils
from datetime import date, datetime, timedelta
import os, shutil, csv
import sys, codecs
import traceback
import mrjob
from mrjob.job import MRJob
import tempfile
from collections import defaultdict
try:
import simplejson as json
except ImportError:
impo... |
#!/usr/bin/python3
class Source:
def __init__(self):
self._s = {}
def __call__(self, op):
path = op['contract']
if path not in self._s:
self._s[path] = open(path, encoding="utf-8").read()
return self._s[path][op['start']:op['stop']]
def get_coverage_map(compi... |
#
# Create different sounds with a buzzer
#
# Credit for star wars song: https://gist.github.com/mandyRae/459ae289cdfcf6d98a6b
import time
import numpy as np
import RPi.GPIO as GPIO
sound_pin = 12
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(sound_pin, GPIO.OUT)
GPIO.output(sound_pin, 0)
tone1 = GPIO... |
"""
pywin32 Excel wrappers that are less ugly and cumbersome
>>> import os
>>>
>>> wb = workbook_load(os.path.abspath("testdata/Test.xlsx"))
>>>
>>> list(workbook_list_sheets(wb))
['Jan 17', 'Feb 17', 'Mar 17', 'Apr 17', 'May 17', 'Jun 17', 'Jul 17', 'Aug 17', 'Sep 17', 'Oct 17']
>>>
>>> sheet = worksheet_load(wb, "Ja... |
"""
The SimplifiedLinacParser reads the input xml data file and creates LinacStructureTree
that consists of sequences (class LinacStructureSeq) which in turn consist of nodes
(class LinacStuctureNode). These objects have limited functionality. They are just
containers of dictionaries. Later the LinacStructureTree will... |
#E-Posta Servisi Uygulaması
from datetime import datetime
import os,time
class EPostaServisi():
def __init__(self,isim):
self.__isim= isim
self.__üyeler= [("Tarık","Demir","<EMAIL>","<PASSWORD>")]
self.__gönderilmiş_mailler= []
def __str__(self):
return self.__isim + " servisine hoş geldini... |
import gzip
import PIL
import numpy as np
import torch
import torch.utils.data
from PIL import Image
from torch.utils.data import Dataset
from torchvision import datasets, transforms
def load_data(data_file):
"""loads the data from the gzip pickled files, and converts to numpy arrays"""
print('loading data .... |
import carla
import random
import time
import pygame
from abc import ABC,abstractmethod, abstractproperty
from RouteHandler import RouteHandler
from PIDHandler import PIDHandler
from BehaviourAgent import BaseVehicleAgent, BasicVehicleAgent
from StateHandler import VehicleStateHandler, RSUStateHandler
from Container ... |
import os
import glob
import platform
import subprocess
import fnmatch
from tempfile import mkstemp
from shutil import move
from ftplib import FTP
from spiceypy import spiceypy
# SOME CONSTANTS, consider move it to a config file
SERVER_HOST_NAME = "spiops.n1data.lan"
SERVER_HOST_USER = "esaspice"
SERVER_HOST_FTP_PATH ... |
import os
import sys
import socket
import threading
import json
import time
import click
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
FORMAT = "utf-8"
SIZE = 1024
def watchFolder(conn):
# Keep watching the folder for any change
patterns = "*"
ignore_patte... |
import uuid
import sys
from shutil import copy2
from wand.color import Color
from wand.font import Font
from wand.image import Image
from PIL import Image as pil_Image
def resize_and_overwrite(filename, new_width, new_height):
with Image(filename=filename) as img:
# First rotate image for correct orienta... |
from flask import Flask, render_template, request, send_file, g
from utils import *
from Items import *
import glob
# Global variables
func = {"add" : "New Income/Expense",
"show_history" : "Show History",}
# User friendly inputs and default values for query strings
types = {
"All" : "type",
"Income" : "'Income'... |
# Copyright 2018 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... |
# -*- coding: utf-8 -*-
# @__ramraj__
from __future__ import division, print_function, absolute_import
import tensorflow as tf
import params
import os
import math
FLAGS = tf.app.flags.FLAGS
def distorted_inputs(record_file, batch_size=FLAGS.batch_size, do_test=True):
feature = {'train/image': tf.FixedLenFeat... |
# General ResNet code
import torch.nn as nn
import torch
# ResNet18, ResNet 34
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_channel, out_channel, stride=1, downsample=None, **kwargs):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels=in_chann... |
"""
Create more map-related json files from existing raw map files
to allow quick access for particular information
Prerequisite:
raw map-related json files have been created at the "map_raw" folder
"map_of_comments_for_post.json" at the "map_raw" folder have been cleaned and is most-updated
Effect:
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 17 18:15:38 2021
@author: johan
"""
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tifffile as tf
from scipy import ndimage
from skimage.measure import regionprops, label
import napari
# Use GPU for processing
import pyclespera... |
import torch
import torch.nn as nn
from torch.nn.modules.conv import _ConvNd
from torch.nn.modules.utils import _pair
import torch.nn.functional as F
from network.device import get_device
# import encoding
device = get_device()
class DoubleConv(nn.Module):
def __init__(self, in_ch, out_ch):
super(DoubleCo... |
from typing import Dict, List, Union
import numpy as np
from grl.algos.p2sro.payoff_table import PayoffTable
from grl.utils.strategy_spec import StrategySpec
class PolicySpecDistribution(object):
def __init__(self, payoff_table: PayoffTable, player: int,
policy_selection_probs_indexed_by_polic... |
# Source: http://www.metroid2002.com/retromodding/wiki/Scriptable_Layers_(Metroid_Prime_2)
import dataclasses
import struct
from util import unpack_ascii, pack_ascii
__all__ = ("Connection", "Property", "PropertyStruct", "ScriptObject")
@dataclasses.dataclass(frozen=True)
class Connection:
_struct = struct.Str... |
import os
import enum
import subprocess
import docker
import shutil
import logging
from collections import Mapping
from pathlib import Path
from typing import Any, Union, Optional, Dict
from docker.errors import ContainerError
from runner.error import UnsupportedLangError, InvalidPathError, PathTooLongError, Timeou... |
from telethon import Button
from telethon.errors import ChatAdminRequiredError
from telethon.tl.types import InputMessagePinned
from neko import OWNER_ID, tbot
from neko.utils import Cbot, Cinline
from .. import tbot
from . import button_parser, can_pin_messages, cb_is_owner, is_owner
@Cbot(pattern="^/pinned$")
asy... |
"""
Module: DMS Parallel Keys manager
Project: Adlibre DMS
Copyright: Adlibre Pty Ltd 2013
License: See LICENSE for license information
Author: <NAME>
"""
import logging
import json
log = logging.getLogger('core.parallel_keys')
from mdt_manager import MetaDataTemplateManager
from dmscouch.models import CouchDocument
... |
# coding: utf-8
"""
Description:
Contains helper functions to assist you when working with database translations
Functions:
all_instances_as_translated_dict: Applies 'instance_as_translated_dict' to the iterable of instances
get_current_language: Returns the current active language. Will set a default langu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.