content stringlengths 5 1.05M |
|---|
# --depends-on config
# --depends-on format_activity
from src import ModuleManager, utils
from src.Logging import Logger as log
@utils.export("botset", utils.BoolSetting("print-motd", "Set whether I print /motd"))
@utils.export(
"botset",
utils.BoolSetting("pretty-activity", "Whether or not to pretty print a... |
import numpy as np
import dask.array as da
from napari.components import ViewerModel
from napari.util import colormaps
base_colormaps = colormaps.CYMRGB
two_colormaps = colormaps.MAGENTA_GREEN
def test_multichannel():
"""Test adding multichannel image."""
viewer = ViewerModel()
np.random.seed(0)
data... |
import argparse
import collections
import datetime
import os
import shutil
import time
import dataset
import mlconfig
import toolbox
import torch
import util
import madrys
import numpy as np
from evaluator import Evaluator
from tqdm import tqdm
from trainer import Trainer
mlconfig.register(madrys.MadrysLoss)
# General... |
"""
"""
from jax import numpy as jnp
from jax import jit as jjit
@jjit
def _calc_weights(x, x_table):
n_table = x_table.size
lgt_interp = jnp.interp(x, x_table, jnp.arange(0, n_table))
it_lo = jnp.floor(lgt_interp).astype("i4")
it_hi = it_lo + 1
weight_hi = lgt_interp - it_lo
weight_lo = 1 - w... |
import os
DEBUG = True
SECRET_KEY = os.getenv("APP_SECRET_KEY")
MYSQL_USERNAME = os.getenv("MYSQL_USERNAME")
MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD")
MYSQL_PORT = 3306
MYSQL_DB = os.getenv("MYSQL_DB")
LOGGING_LEVEL = "DEBUG"
LOGGIN_FILE = "activity.log"
LOGGING_BACKUPS = 2
LOGGING_MAXBYTES = 1024
TIMEZONE = "... |
#
# PySNMP MIB module HP-ICF-OOBM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-OOBM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:34:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
"""
MARL environment for google football
"""
import numpy as np
import gym
import gfootball.env.football_env as football_env
from gfootball.env import _process_representation_wrappers
from gfootball.env import _process_reward_wrappers
from gfootball.env import config
from gfootball.env import wrappers
class Goog... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""This mo... |
# -*- coding: utf-8 -*-
"""
Bottle is a fast and simple micro-framework for small web applications. It
offers request dispatching (Routes) with url parameter support, templates,
a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and
template engines - all in a single file and with no dependencies... |
#!/usr/bin/env python
def getinput(): return open('day23.input.txt').read()
### PART 1
import re
def solve(program, a=0, hack=False):
instrs = [l.split() + [''] for l in program.strip().splitlines()]
tgl = { 'cpy': 'jnz', 'inc': 'dec', 'dec': 'inc', 'jnz': 'cpy', 'tgl': 'inc' }
ip, regs = 0, { 'a': a, ... |
"""
二维数组
"""
# use numpy
import numpy as np
import pandas as pd
sdarry = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
])
# different way to get element
print(sdarry[1, 2])
print(sdarry[:, 2])
print(sdarry[2, :])
# get a row or a column mean of data
# axis=1 is row
# axis=0 is column
print(sdar... |
from .confirm import ShutdownConfirmationDialog
def load(manager, params):
"""Launch shutdown confirmation manager"""
pos = (100, 100)
if params and len(params) > 0:
pos = params[0]
ShutdownConfirmationDialog(pos, manager)
|
from handlers.chord import ChordHandler
from handlers.base import IndexHandler
url_patterns = [
(r"/index/", IndexHandler),
]
|
"""
Pytools
Server module
Run server
>> (base) C:\\Users\\ginanjar\\AppData\\Roaming\\Sublime Text 3\\Packages\\pythontools>python core\\server\\pytools
""" |
import unittest
from operator import itemgetter
import tonos_ts4.ts4 as ts4
from utils.wallet import create_wallet, DEFAULT_WALLET_BALANCE
from utils.nft_root import create_nft_root, mint_nft, get_nft_addr, DEFAULT_NFT_ROOT_BALANCE
from utils.nft import restore_nft_by_addr, get_nft_info
from random import randint
un... |
__author__ = 'akshay'
import socket
import time
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
# create a socket and bind socket to the host
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('10.42.0.1', 8001))
buffe=1024
def measure():
"""
measure distance
"""
... |
"""
Function for matching delimiters in an arithmetic expression
"""
from ArrayStack import *
def is_matched(expr):
"""
Return True if all delimiters are properly match; False otherwise
"""
lefty = '({['
righty = ')}]'
S = ArrayStack()
for c in expr:
if c ... |
"""
File: caesar.py
Name: Max Chang
------------------------------
This program demonstrates the idea of caesar cipher.
Users will be asked to input a number to produce shifted
ALPHABET as the cipher table. After that, any strings typed
in will be encrypted.
"""
# This constant shows the original order of alphabetic ... |
from django.db import models
from django.contrib.auth.models import AbstractUser
class StudentUser(AbstractUser):
matric_no = models.CharField(max_length=14, unique=True)
mac_add = models.CharField(max_length=17, unique=True)
|
from typing import Any, Dict
import attr
from targets.config import is_in_memory_cache_target_value
@attr.s(frozen=True)
class TargetCacheKey(object):
target = attr.ib(converter=str)
value_type = attr.ib(converter=str)
class TargetCache(object):
def __init__(self, cache=None):
self._cache = ca... |
import datetime
from Module.MainThread_Socket_Client import MainThread_Socket_Client
from Module.SocketServer_Client import SocketServer_Client
class Socket_Client_Core():
def __init__(self):
try:
self.MainThread_Socket_Client=MainThread_Socket_Client
self.SocketServer_C... |
from tqdm import tqdm
from src.reranker.lambdamart import LambdaMart
from src.interface.corpus import Corpus
from src.interface.iohandler import InputOutputHandler
from src.interface.features import FeatureEngineer
# import src.evaluation.validate_run as validate
OUT = f"./evaluation/fairRuns/submission_lambdamart-fu... |
# coding: utf-8
import time
i=0
while(i<20):
print('-----------main--------[',i,']')
i+=1
time.sleep(1)
print("ok man yeaaaaahh!")
#send block --> input IP and message
#message='abcedf'
#IP='127.0.0.1'
#send_len=client.sendto(message.encode('utf-8'),(IP,recieve_port))
#recieve block -->None
#rx_message,... |
#main.py
# set up track structure
# this one loops over alpha and epsilon
import numpy as np
from placerg.funcs import *
from placerg.funcsrg import *
from placerg.objects import *
from placerg.runfunc import *
N0 = 2048 # number of cells
nstim = 10 # number of nonplace stimuli
percell= 1.0 # probability that eac... |
#Created by Oli MacPherson and Ben O'Sullivan!
#For use with only Python 2 at the moment cause i cant be bothered changing all the raw_inputs.
import sys, os, random
import time
intro_phrases = ["The world is changing. \n",
"Humanity's voracious appetite for and consumption of electricity born of bu... |
HW_SOURCE_FILE = __file__
def num_eights(x):
"""Returns the number of times 8 appears as a digit of x.
>>> num_eights(3)
0
>>> num_eights(8)
1
>>> num_eights(88888888)
8
>>> num_eights(2638)
1
>>> num_eights(86380)
2
>>> num_eights(12345)
0
>>> from construct_c... |
from cacahuate.auth.base import BaseHierarchyProvider
class BackrefHierarchyProvider(BaseHierarchyProvider):
def find_users(self, **params):
return [
(params.get('identifier'), {
'identifier': params.get('identifier'),
'email': params.get('identifier'),
... |
# coding: utf-8
# # Categorical VAE with Gumbel-Softmax
#
# Partial implementation of the paper [Categorical Reparameterization with Gumbel-Softmax](https://arxiv.org/abs/1611.01144)
# A categorical VAE with discrete latent variables. Tensorflow version is 0.10.0.
# # 1. Imports and Helper Functions
# In[1]:
i... |
#!/usr/bin/env python3
""" Checks if a new ts3 version is available """
import re
import smtplib
import json
import sys
from email.mime.text import MIMEText
from email import utils
import argparse
import requests
"""
CONFIG = {}
CONFIG['CHANGELOG'] = ''
CONFIG['URL'] = 'https://www.teamspeak.com/versions/server.jso... |
import bsddb3
import struct
import json
import flask
import time
from threading import Thread
from Queue import Queue
from StringIO import StringIO
from sqlalchemy import text
from sqlalchemy.sql.elements import TextClause
from table_pb2 import *
from itertools import product, chain, combinations
from dct import *
de... |
from collections import deque
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
res = 0
def diameterOfBinaryTree(self, root: TreeNode) -> int:
... |
def f(<caret>x):
return 42 |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import scriptcontext as sc
import compas_fofin
__commandname__ = "FoFin_init"
def RunCommand(is_interactive):
sc.sticky["FoFin"] = {
'cablenet' : None,
'settings' : {
'scale... |
import pytest
from geocodr.keys import APIKeys
from werkzeug.test import EnvironBuilder
from werkzeug.wrappers import Request
@pytest.fixture()
def key_file(tmpdir):
key_file = tmpdir.join("keys.csv")
key_file.write(
'key,domains\n'
'wildcard,\n'
'# comment,with,commas,\n'
'mu... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Header
from humanoid_league_msgs.msg import BallRelative, ObstaclesRelative, ObstacleRelative, Strategy, GameState, RobotControlState
from geometry_msgs.msg import Point, PoseWithCovarianceStamped, Pose2D
import math
import yaml
import rospkg
import os
impo... |
import os
import sys
sys.path.append('../')
import numpy as np
import convert_weights
import tensorflow as tf
############## REPRODUCIBILITY ############
tf.set_random_seed(0)
np.random.seed(0)
###########################################
from keras.models import load_model
from keras.models import Sequential, Model
f... |
from django.contrib import admin
# DJANGAE
from djangae.contrib.gauth.sql.models import GaeUser
admin.site.register(GaeUser)
|
from .handler import handler
|
"""OVK learning, unit tests.
The :mod:`sklearn.tests.test_learningrate` tests the different learning rates.
"""
import operalib as ovk
def test_constant():
"""Test whether constant learning rate."""
eta = ovk.Constant(1)
assert eta(10) == 1
def test_invscaling():
"""Test whether inverse scaling le... |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Discovery
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
... |
# coding: utf-8
from common.db import write_session_scope
from mall_spider.common.enums import TaobaoPageType, TaobaoTaskType
from mall_spider.dao.stream_handle_task_dao import get_stream_handle_task_dao
from mall_spider.dao.stream_opt_data_dao import get_stream_opt_data_dao
from mall_spider.dao.stream_unhandle_task_d... |
from qtpy import QtCore, QtGui
class DataTreeModel(QtCore.QAbstractItemModel):
def __init__(self, data_node, parent=None):
super(DataTreeModel, self).__init__(parent)
self.data_node = data_node
self.rootItem = DataTreeItem(self.data_node)
data_node.changed.connect(self.on_node_chan... |
import math
style_normal = "\033[0m"
style_great_success = "\033[1;32m"
style_success = "\033[32m"
style_error = "\033[31m"
style_warning = "\033[33m"
style_info = "\033[0m"
style_stealthy = "\033[1;37m"
def __generic_style(c):
def _x(s):
return c + s + style_normal
return _x
success = __generic_style(style... |
# pip install feedparser
# pip install notify2
# [Python Desktop News Notifier in 20 lines](http://geeksforgeeks.org/python-desktop-news-notifier-in-20-lines/)
# [Desktop Notifier in Python](https://www.geeksforgeeks.org/desktop-notifier-python/)
import feedparser
import notify2
import os
import time
# https://www.es... |
import requests
from sniplink.utils import *
from sniplink.api import API
from sniplink.objects import ShortLinkData
class Client:
"""
The Backend Client
Sniplink-Py is powered by a back-end client/runner, this system is responsible for ensuring safety among API access.
Once you've registered a clien... |
class AbilityChangeEvent:
"""Event that indicates an ability change"""
def __init__(self, data, type) -> None:
"""Init event"""
self.data = data
self.type = type
@property
def sphere_id(self) -> str:
return self.data['sphere']['id']
@property
def cloud_id(self)... |
from tkinter import messagebox
import pandas as pd
import matplotlib.pyplot as plt
import tkinter as tk
import os
def get_chart_user(date):
if os.path.exists("re/drowsiness_files/"+date+".csv"):
data=pd.read_csv("re/drowsiness_files/"+date+".csv")
data.fillna("Unknown",inplace=True)
gb=data... |
"""User memberships in teams."""
import dataclasses
import kaptos.db
import roax.schema as s
from roax.resource import operation
@dataclasses.dataclass
class Member:
"""User membership in team."""
id: s.uuid(description="Identifies the membership.")
team_id: s.uuid(description="Identifies the team.")
... |
#
# Copyright (c) 2016, deepsense.io
#
# 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 w... |
#!/usr/bin/env python
# coding=utf-8
from setuptools import setup
# setup configuration is in `setup.cfg`
setup()
|
import hashlib
import requests
# import uuid
import os
import tempfile
def get_file(logger, storage_root, doc_uuid, image_url):
# local_path = "%s/%s/images/tmp/%s.%s" % (storage_root, doc_uuid, uuid.uuid4(), image_url["extension"])
try:
r = requests.get(image_url["url"])
temp = tempfile.Named... |
import socket
import sys
import pickle
import time
from tkinter import *
from tkinter import ttk
from tkinter import messagebox, BooleanVar
from tkinter import font
from PIL import Image
import glob
import os
from PIL import Image, ImageTk
import argparse
import pprint
import random
import numpy as np
import struct
i... |
import sys
import collections
Record = collections.namedtuple('Record', ['timestamp', 'action', 'km'])
class Car:
def __init__(self, plate):
self.plate = plate
self.records = []
def add_record(self, record):
record[2] = int(record[2])
self.records.append(Record(*record))
... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import glob
class Efivar(MakefilePackage):
"""Tools and libraries to work with EFI variables"""
... |
# Copyright (c) 2019 Sony Corporation. 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 applicabl... |
import os
import subprocess
import shutil
import datetime
import pandas as pd
SNAPSHOT_FOLDER = "big_test_snapshots_diarios"
RETROACTIVE_FOLDER = "retroactive_data"
def daterange(start_date, end_date, step=None):
for n in range(0,int((end_date - start_date).days),step):
yield start_date + datetime.timedelta(day... |
import os
import numpy as np
import mdtraj as md
from simtk import unit
from simtk.openmm import LangevinIntegrator
from simtk.openmm.app import Simulation
from simtk.openmm.app.pdbfile import PDBFile
from cg_openmm.cg_model.cgmodel import CGModel
from cg_openmm.utilities.iotools import write_pdbfile_without_to... |
#!/usr/bin/env python
import asyncio
import sys
import logging
import unittest
import conf
from os.path import join, realpath
from hummingbot.market.bitcoin_com.bitcoin_com_websocket import BitcoinComWebsocket
from hummingbot.market.bitcoin_com.bitcoin_com_auth import BitcoinComAuth
sys.path.insert(0, realpath(join(_... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 13:57:29 2020
@author: lentzye
"""
import mykeys
|
from IBM_diffprivlib import diffprivlib_single_query
from smartnoise import smartnoise_single_query
from openmined_pydp import openmind_pydp_single_query
library_name = 'smartnoise' # libraries: 'difforivlib', 'smartnoise', additive_noise', 'openmined_pydp'
dataset_folder_path = 'E:\\MS_Thesis\\publication_stuff\\c... |
N = int(input())
A = []
for ii in range(N):
A.append(int(input()))
s = set()
for ii in range(len(A)):
s.add(A[ii])
print(len(s)) |
# -*- coding: UTF-8 -*-
"""
This module provides the abstract base classes and core concepts
for the model elements in behave.
"""
import os.path
import sys
import six
from behave.capture import Captured
from behave.textutil import text as _text
from enum import Enum
PLATFORM_WIN = sys.platform.startswith("win")
def... |
#!/usr/bin/env python3
from pybf import BloomFilter
def test_bf_int(num_items=1000000, error=0.01):
"""Test the BloomFilter with parameters 'num_items' & `error`"""
print(f"Bloom filter test for integer keys")
bf = BloomFilter(num_items, error)
sz = len(bf)
print(f'size: {sz}')
# checking
... |
# -*- coding: utf-8 -*-
"""
"""
from __future__ import absolute_import
import mock
import pytest
import easy_acl.rule as rule
__copyright__ = "Copyright (c) 2015-2019 Ing. Petr Jindra. All Rights Reserved."
def test_init_without_wildcard():
definition = "foo.bar.foo-bar"
parts = ("foo", "bar", "foo-bar")... |
import socket
import re
try:
url = input('Enter - ') # http://data.pr4e.org/romeo.txt
HOST = re.findall(r'http[s]?://([\S\d.]*)/.*?', url)
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((HOST[0], 80))
cmd = 'GET ' + url + ' HTTP/1.0\r\n\r\n'
cmd = cmd.encode()
my... |
"""Tests for envs module.
Need rework.
"""
from __future__ import absolute_import
# import unittest
# from numpy.testing import *
import inspect
from functools import partial
import SafeRLBench.envs as envs
import numpy as np
import gym
gym.undo_logger_setup()
from mock import Mock
class TestEnvironments(object... |
'''
Tipo String
Em Python, um dado é considerado do tipo string sempre que:
- Estiver entre aspas simples -> 'uma string', '234', 'a', 'True', '42.3'
- Estiver entre aspas duplas -> "uma string", "234", "a", "True", "42.3"
- Estiver entre aspas simples triplas;
- Estiver entre aspas simples duplas.
nome = 'Geek Univ... |
# -*- coding: utf-8 -*-
__version__ = '1.0.3'
from .fixedrec import RecordFile, RecordFileError
|
import json
import os
import time
from abc import ABC
import numpy as np
import torch
from agent0.common.utils import set_random_seed
from agent0.ddpg.agent import Agent
from agent0.ddpg.config import Config
from ray import tune
from ray.tune.trial import ExportFormat
class Trainer(tune.Trainable, ABC):
def __in... |
"""Bay Bridge simulation."""
import os
import urllib.request
from flow.core.params import SumoParams, EnvParams, NetParams, InitialConfig, \
SumoCarFollowingParams, SumoLaneChangeParams, InFlows
from flow.core.params import VehicleParams
from flow.core.params import TrafficLightParams
from flow.core.experiment i... |
import logging
from queue import Queue
from common.configuration import ConfigurationService
from common.reddit import get_relevat_subreddits
from common.settings import Setting
from common.storage import StorageService
from functools import wraps
from telegram import Bot, ChatAction, Update
from telegram.ext import C... |
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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, publish,
... |
import bz2
import re
import sys
from collections import namedtuple
from pathlib import Path
from xml.etree import cElementTree as ElementTree
from urllib.parse import urljoin
from urllib.error import URLError
import mwparserfromhell
import numpy
import pycountry
from sklearn.feature_extraction.text import CountVectori... |
#! /usr/bin/env python3
###
# KINOVA (R) KORTEX (TM)
#
# Copyright (c) 2018 Kinova inc. All rights reserved.
#
# This software may be modified and distributed
# under the terms of the BSD 3-Clause license.
#
# Refer to the LICENSE file for details.
#
###
import sys
import os
from kortex_api.RouterClient import Route... |
class Gif:
pass
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
"""
from setuptools import setup, find_packages
from Cython.Build import cythonize
import pysam
setup(
name='svtk',
version='0.1',
description='Structural variation toolkit',
author='Matthew Stone',
author_email='mstone5@mgh.harvard.edu',
p... |
from colour import Color
from utils.animation_maker import *
import numpy as np
from time import time
song = 1
in_file = f'./Songs/Song0{song}.wav'
c1, c2 = Color('#fceaa8'), Color('#00e5ff')
#c1, c2 = Color('#000000'), Color('#00fffb')
c3, c4 = Color('#000000'), Color('#000000')
gradient_mode = 'hsl'
n_points = 100
a... |
import argparse
import asyncio
import rlp
from typing import Any, cast, Dict
from quarkchain.p2p import auth
from quarkchain.p2p import ecies
from quarkchain.p2p.exceptions import (
HandshakeFailure,
HandshakeDisconnectedFailure,
UnreachablePeer,
MalformedMessage,
)
from quarkchain.p2p.kademlia import ... |
"""redux_field_creator URL Configuration"""
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^fields/', include('fields.urls')),
]
|
# echo_04_io_multiplexing.py
import socket
import selectors
sel = selectors.DefaultSelector()
def setup_listening_socket(host='127.0.0.1', port=55555):
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen()
sel.register(sock, sele... |
import json
import sys
import getopt
from os import system
sys.path.insert(0, '/requests')
import requests
def getBridgeIP():
r = requests.get('http://www.meethue.com/api/nupnp')
bridges = r.json()
if not bridges:
bridge_ip = 0
else:
bridge_ip = bridges[0]['internalipaddress']
r... |
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@bazel_skylib//lib:structs.bzl", "structs")
load("//ocaml/_functions:utils.bzl", "capitalize_initial_char")
load("//ocaml/_functions:module_naming.bzl",
"normalize_module_label",
"normalize_module_name")
load("//ocaml/_rules:impl_common.bzl", "module_sep")... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
#
# Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.
#
# OpenArkCompiler is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#
# http://licens... |
from os import listdir
from os.path import isfile, join
import pandas as pd
import pickle
def get_latest_file(filename_str_contains, datapath='../data/', filetype='parquet'):
"""
Method to get the latest file to given a certain string value.
Parameters
----------
filename_str_contains :... |
class SymbolTableError(Exception):
"""Exception raised for errors with the symbol table.
Attributes:
message -- explanation of the error
"""
def __init__(self, message):
self.message = message |
# Created by woochanghwang at 12/07/2021
import toolbox.drugbank_handler_postgres as drug_pg
import pandas as pd
def get_DDI_of_a_drug(drug):
# drug_a = row['DrugA_ID']
# drug_b = row['DrugB_ID']
sql = "SELECT * from structured_drug_interactions where subject_drug_drugbank_id = \'{}\' " \
"or ... |
import unittest
from machinetranslation import translator
from translator import englishToFrench
from translator import frenchToEnglish
class TestTranslator(unittest.TestCase):
# test function
def test_englishToFrench(self):
self.assertIsNotNone(englishToFrench('Hello'),'Bonjour')
self.assertE... |
import tkinter as tk
import tkinter.ttk as ttk
from ..elements import TreeList
from ...head.database import Database as db
from ...globals import SURVEY_TYPES
from .templates import ListFrameTemplate
class SurveysListFrame(ListFrameTemplate):
def __init__(self, top):
super().__init__(top)
self.dat... |
import unittest
import os
import plexcleaner.database as database
from plexcleaner.media import Library, Movie
__author__ = 'Jean-Bernard Ratte - jean.bernard.ratte@unary.ca'
# flake8: noqa
class TestMediaLibrary(unittest.TestCase):
_nb_movie = 98
_effective_size = 100275991932
def test_init(self):
... |
#coding=utf-8
import os
import jieba
import shutil
dirs = []
for d in os.listdir(os.getcwd()):
if os.path.isfile(d):
continue
dirs.append(d)
imgs = []
with open("data.txt",'w') as fw , open("imgs.txt","w") as fi:
for d in dirs:
for f in os.listdir(os.path.join(d)):
... |
from urllib.parse import parse_qsl
from establishment.socialaccount.providers.base import Provider
class OAuth2Provider(Provider):
def get_auth_params(self, request, action):
settings = self.get_settings()
ret = settings.get("AUTH_PARAMS", {})
dynamic_auth_params = request.GET.get("auth_p... |
# coding: utf-8
from __future__ import annotations
from datetime import date, datetime # noqa: F401
import re # noqa: F401
from typing import Any, Dict, List, Optional # noqa: F401
from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401
from acapy_wrapper.models.credential_offer import Credentia... |
from pyilluminate import Illuminate
import numpy as np
import pytest
pytestmark = pytest.mark.device
@pytest.fixture(scope='module')
def light():
with Illuminate() as light:
yield light
def test_single_led_command(light):
light.color = 1
# setting led with an integer
light.led = 30
def te... |
"""Tests for deletion of assemblies."""
import os
import unittest
from hicognition.test_helpers import LoginTestCase, TempDirTestCase
# add path to import app
# import sys
# sys.path.append("./")
from app import db
from app.models import (
Dataset,
Assembly,
)
class TestDeleteAssembly(LoginTestCase, TempDirT... |
import ccxt
def build_exchange(name):
exchange = getattr(ccxt, name)
return exchange({
'enableRateLimit': True
})
def timestamps_to_seconds(data):
for datum in data:
datum[0] = datum[0] // 1000
def secs_to_millis(datum):
return datum * 1000
|
# TODO: add more filetypes
paste_file_types = [
["All supprted files", ""],
("All files", "*"),
("Plain text", "*.txt"),
("Bash script", "*.sh"),
("Batch script", "*.bat"),
("C file", "*.c"),
("C++ file", "*.cpp"),
("Python file", "*.py"),
("R script file", "*.R")
]
for _, extension ... |
'Faça um script de menu que mostra na tela, com o título de "Menu Principal" e mais três opções:'
# 1. FIM
# 2. CADASTRO
# 3. CONSULTA
"O programa recebe um input do teclado a opção desejada e mostra uma mensagem confirmando a opção escolhida."
# Caso a opção escolhida seja inválida, mostrar uma mensagem de erro "Opç... |
from django.http import HttpResponse, JsonResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from tasks.models import Task
from tasks.... |
from math import sqrt
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils import data as data
from torchvision import transforms as transforms
from data.datasets import MNIST_truncated, FEMNIST, FashionMNIST_truncated, SVHN_custom, CIFAR10_truncated, Generated
... |
class Solution(object):
def maxDistance(self, nums):
"""
:type arrays: List[List[int]]
:rtype: int
"""
low = float('inf')
high = float('-inf')
res = 0
for num in nums:
# We can use num[0] && num[-1] only because these lists are sorted
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.