content
stringlengths
5
1.05M
from bibliopixel.animation.matrix import Matrix try: from websocket import create_connection except ImportError: create_connection = None import threading import numpy as np WS_FRAME_WIDTH = 640 WS_FRAME_HEIGHT = 480 WS_FRAME_SIZE = WS_FRAME_WIDTH * WS_FRAME_HEIGHT def clamp(v, _min, _max): ...
import os import json from pathlib import Path import yaml import unittest import click from click.testing import CliRunner os.environ['QA_TESTING'] = 'true' # Missing: # - tests with --share # - tests with CI=ON CI_COMMIT=XXXXXX class TestQaCli(unittest.TestCase): @classmethod def setUpClass(self): self.p...
ASCII_MAZE = """ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ S | | | | | | +-+ + +-+-+ + + + + +-+ + + +-+-+-+ + + + | | | | | | | | | | | | | | | + + +-+ + +-+ + +-+-+ +-+-+ +-+-+ + + + + | | | | | | | | +-+-+-+-+-+ +-+-+ +-+ +-+-+ +-+-+-+-+-+ + | | ...
from Instruments.devGlobalFunctions import devGlobal class CounterClass(devGlobal): # Human readable name for the gui, note: Needs to be unique name = "Counter" def __init__(self, *args): devGlobal.__init__(self, *args) self.func_list = self.func_list + [ self.C...
from . import config from .genome import Genome class Population(): def __init__(self, default=True): self.genomes = [] self.speciesRepresentatives = [] self.species = 0 if default: self.initialize() def initialize(self): for i in range(config.populationSiz...
from __future__ import print_function import setuptools import sys # Convert README.md to reStructuredText. if {'bdist_wheel', 'sdist'}.intersection(sys.argv): try: import pypandoc except ImportError: print('WARNING: You should install `pypandoc` to convert `README.md` ' 'to reSt...
# Module to describe all the potential commands that the Renogy Commander # supports. # # Author: Darin Velarde # # from collections import namedtuple # I typically don't like import * but I actually need every symbol from # conversions. from conversions import * # Register # ** immutable data type ** # Represents ...
# 视觉问答模型 from keras.layers import Conv2D, MaxPooling2D, Flatten from keras.layers import Input, LSTM, Embedding, Dense from keras.models import Model, Sequential import keras # First, let's define a vision model using a Sequential model. # This model will encode an image into a vector. vision_model = Sequential() visi...
# Generated by Django 3.1.3 on 2020-12-07 23:51 from django.db import migrations, models import django.db.models.deletion import django_update_from_dict class Migration(migrations.Migration): initial = True dependencies = [ ('users', '0003_auto_20201206_1634'), ] operations = [ mig...
from django.contrib.auth import logout, authenticate, login from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.paginator import Paginator from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import redirect, get_object_or_40...
from typing import Any # NOQA import optuna from optuna._experimental import experimental from optuna._imports import try_import with try_import() as _imports: from catalyst.dl import Callback if not _imports.is_successful(): Callback = object # NOQA @experimental("2.0.0") class CatalystPruningCallback(...
#!/usr/bin/python """Copyright 2016 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 l...
import pygame from Clock import Clock from Timer import Timer class TileManager(object): # Call constructor def __init__(self, screenWidth, screenHeight, tileWidth, tileHeight, tileImage, tileType): self.tiles = [] self.tileWidth = tileWidth self.tileHeight = tileHeight self.scr...
"""In this module are all SuperCollider Object related classes"""
# Crie um programa que peça um número ao usuário e retorne se antecessor e o seu sucessor. print('=-'*7 'DESAFIO 7' ''=-'*7) n = int(input('Digite um número: ')) print('Analisando o número {}, seu antecessor é {} e seu sucessor é {} '.format(n, n - 1, n + 2))
import pygame from pygame.locals import QUIT, K_ESCAPE, K_a, K_d, K_s, K_SPACE from time import time from os.path import dirname, realpath def main(): running, settings = load() while running: settings = update(settings) draw(settings) running = check_exit(settings) pygame.quit() de...
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
from vplot import GetOutput import subprocess as sub import numpy as np import os cwd = os.path.dirname(os.path.realpath(__file__)) import warnings import h5py import multiprocessing as mp import sys import bigplanet as bp def test_bpstats(): #gets the number of cores on the machine cores = mp.cpu_count() ...
import cv2 import pickle import face_recognition class recognize: def __init__(self): self.data = pickle.loads(open("./encodings.pickle", "rb").read()) self.detector = cv2.CascadeClassifier("./haarcascade_frontalface_default.xml") def recognize_face(self, frame): gray = cv2.cv...
token = 'BOT-TOKEN' initial_extensions = ['cogs.general', 'cogs.groups', 'cogs.lights', 'cogs.scenes'] prefix = '>' owner_only = True owner_id = DISCORD-USER-ID bridge_ip = 'BRIDGE-IP'
# -------------- import numpy as np import pandas as pd import matplotlib.pyplot as plt # code starts here df = pd.read_csv(path) total_length = len(df) print(total_length) fico = 0 for i in df['fico'] > 700: fico += i print(fico) p_a = fico/total_length print(round(p_a, 2)) debt = 0 for i in df['purpose'] ==...
import requests, zipfile import os import pandas as pd def gdpimporter(url, filename=None, filetype='csv'): """Download the zipped file, unzip, rename the unzipped files, and outputs a dataframe along with the title from meta data. This function downloads the zipped data from URL to the local path, un...
from functools import partial from typing import Callable, Union import jax import jax.numpy as np from rbig_jax.transforms.histogram import get_hist_params from rbig_jax.transforms.inversecdf import ( invgausscdf_forward_transform, invgausscdf_inverse_transform, ) from rbig_jax.transforms.kde import get_kde_...
# -*- coding: utf-8 -*- import csv from collections import defaultdict, namedtuple from datetime import datetime, timedelta import pkg_resources import re from zipfile import ZipFile from enum import Enum, unique from io import TextIOWrapper Train = namedtuple("Train", ["name", "kind", "direction", "stops", "service_...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type raise Exception('this code should never execute')
skills = [ { "id" : "0001", "name" : "Liver of Steel", "type" : "Passive", "isPermable" : False, "effects" : { "maximumInebriety" : "+5", }, }, { "id" : "0002", "name" : "Chronic Indigestion", "type" : "Combat", ...
from netmiko import ConnectHandler, file_transfer from getpass import getpass ios_devices = { "host": "cisco3.lasthop.io", "username": "pyclass", "password": "88newclass", "device_type": "cisco_ios", } source_file = "testTofu.txt" dest_file = "testTofuBack.txt" direction = "get" file_...
#!/usr/bin/env python3 # coding: utf-8 from threading import Thread from queue import Queue class TaskQueue(Queue): def __init__(self, num_workers=1): super().__init__() self.num_workers = num_workers self.start_workers() def add_task(self, task, *args, **kwargs): args = args ...
#!/usr/bin/env python import logging import os import shutil import sys import tempfile from io import BytesIO from itertools import groupby from subprocess import Popen,PIPE, check_output import requests from KafNafParserPy import * from lxml import etree from lxml.etree import XMLSyntaxError from .alpino_dependenc...
import os import pytest from packaging import version from unittest import TestCase from unittest.mock import patch from osbot_utils.utils.Dev import pprint from osbot_utils.utils.Files import temp_folder, folder_files, folder_delete_all, folder_create, file_create_bytes, \ file_contents_as_bytes, file_contents, ...
# Generated by Django 3.1.4 on 2021-11-13 12:20 import datetime from django.db import migrations, models from django.utils.timezone import utc import uuid class Migration(migrations.Migration): dependencies = [ ('library_app', '0007_auto_20211113_1319'), ] operations = [ migrations.Alte...
# Original script acquired from https://github.com/adafruit/Adafruit_Python_MCP3008 # Import SPI library (for hardware SPI) and MCP3008 library. import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 import time # Hardware SPI configuration: SPI_PORT = 0 SPI_DEVICE = 0 mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev...
""" This component provides basic support for the Philips Hue system. For more details about this component, please refer to the documentation at https://home-assistant.io/components/hue/ """ import asyncio import json import ipaddress import logging import os import async_timeout import voluptuous as vol from homea...
import re import sys import boa3 from boa3 import neo from boa3.constants import SIZE_OF_INT32, SIZE_OF_INT160, DEFAULT_UINT32 from boa3.neo import cryptography from boa3.neo.utils.serializer import Serializer from boa3.neo.vm.type.Integer import Integer class NefFile: """ The object encapsulates the informa...
""" @author: Skye Cui @file: layers.py @time: 2021/2/22 13:43 @description: """ import tensorflow as tf class ConvAttention(tf.keras.layers.Layer): def __init__(self, l, h, w, c, k): super(ConvAttention, self).__init__() self.reshape = tf.keras.layers.Reshape((l, w * h * c)) self.layer1 =...
start_case_mutation = """\ mutation startCase($case: StartCaseInput!) { startCase(input: $case) { case { id } } }\ """ intervalled_forms_query = """\ query allInterForms { allForms (metaHasKey: "interval") { pageInfo { startCursor endCursor } edges { node { met...
# -*- coding: utf-8 -*- # pylint: disable=no-self-use, too-many-locals, too-many-arguments, too-many-statements, too-many-instance-attributes """Invite""" import string import time import json from configparser import ConfigParser import requests from flask import request from library.couch_database import Co...
from __future__ import annotations from dataclasses import dataclass from dataclasses import field import boto3 from ..ec2api.vpcs import VPCs from ..ec2common.ec2exceptions import * # See vpc notes at the end of this file. @dataclass class VPCAttributes: CidrBlock: str = None DhcpOptionsId: str = None ...
# coding=utf-8 from particles import Particle class RectParticle(Particle): def __init__(self, l): Particle.__init__(self, l) # super(RectParticle, self).__init__(l) rectMode(CENTER) self.rota = PI/3 def display(self): stroke(0, self.lifespan) fill(204...
import pytest from detect_secrets.core.potential_secret import PotentialSecret from testing.factories import potential_secret_factory @pytest.mark.parametrize( 'a, b, is_equal', [ ( potential_secret_factory(line_number=1), potential_secret_factory(line_number=2), T...
""" Basic shared function to read input data for each problem; the data file must be in the subdirectory 'input' and with the name '<prog_name>.txt', where '<prog_name>.py' is the name of the program being run """ import inspect import pathlib def get_input(): """ Get input data for currently running program...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Holds fixtures for the smif package tests """ from __future__ import absolute_import, division, print_function import json import logging import os from copy import deepcopy import numpy as np import pandas as pd from pytest import fixture from smif.data_layer import S...
import os import sys from setuptools import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist bdist_wheel') os.system('python -m twine upload dist/*') sys.exit() setup()
#!/usr/bin/env python3 # Copyright (c) 2020-2022, NVIDIA CORPORATION. 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...
# Based on https://www.geeksforgeeks.org/get-post-requests-using-python/ # importing import requests import time # defining the api-endpoint API_ENDPOINT = "https://api.gfycat.com/v1/gfycats" # your API key here # API_KEY = "XXXXXXXXXXXXXXXXX" # your source code here external_url = input("Please input the externa...
import unittest from datetime import datetime from models import * class Test_UserModel(unittest.TestCase): """ Test the user model class """ def setUp(self): self.model = User() self.model.save() def test_var_initialization(self): self.assertTrue(hasattr(self.model, "ema...
""" Configuration file """ __author__ = 'V. Sudilovsky' __maintainer__ = 'V. Sudilovsky' __copyright__ = 'ADS Copyright 2014, 2015' __version__ = '1.0' __email__ = 'ads@cfa.harvard.edu' __status__ = 'Production' __license__ = 'MIT' SAMPLE_APPLICATION_PARAM = { 'message': 'config params should be prefixed with the...
import asyncio class ClientServerProtocol(asyncio.Protocol): metrics = {} def __init__(self): # self.metrics = {} self.spliter = '_#_' self.ok_message = 'ok\n' self.error_message = 'error\nwrong command\n\n' def connection_made(self, transport): self.transport = t...
__author__ = 'Thomas Rueckstiess, ruecksti@in.tum.de' from scipy import random, asarray, zeros, dot from pybrain.structure.modules.neuronlayer import NeuronLayer from pybrain.tools.functions import expln, explnPrime from pybrain.structure.parametercontainer import ParameterContainer class StateDependentLayer(Neuron...
#!/usr/bin/env python import sys import time from ansible.module_utils.forward import * try: from fwd_api import fwd except: print('Error importing fwd from fwd_api. Check that you ran ' + 'setup (see README).') sys.exit(-1) # Module documentation for ansible-doc. DOCUMENTATION = ''' --- module:...
from django.db.models import ForeignKey from graphene.utils.str_converters import to_camel_case # https://github.com/graphql-python/graphene/issues/348#issuecomment-267717809 def get_selected_names(info): """ Parses a query info into a list of composite field names. For example the following query: ...
"""Constants for integration_blueprint tests.""" from custom_components.arpansa_uv.const import CONF_NAME, CONF_LOCATIONS, CONF_POLL_INTERVAL # Mock config data to be used across multiple tests MOCK_CONFIG = {CONF_NAME: "test_arpansa", CONF_LOCATIONS: ['Brisbane','Sydney','Melbourne','Canberra'], CONF_POLL_INTERVAL: 1...
import json from datetime import datetime, timedelta from email import utils as email_utils import pytest from flask.testing import FlaskClient from sqlalchemy.orm import Session from app.models.exceptions import NotFound from app.models.products import Brand, Category, Product, FEATURED_THRESHOLD def create_basic_...
print('domain.com'.endswith('com'))
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Batch-create ownCloud users """ __author__ = "Constantin Kraft <c@onstant.in>" import sys import argparse import owncloud from owncloud.owncloud import HTTPResponseError import csv API_URL = '' # User needs Admin permissions OC_USER = '' OC_PASS = '' oc = owncloud.C...
from chipclock.display import ModeDisplay from chipclock.modes.clock import ClockMode from chipclock.renderers.time import render_ascii, render_chip from chipclock.renderers.segment import setup_pins, render_segment seconds_pins = [ ['LCD-D5', 'LCD-D11'], ['LCD-D4', 'LCD-D10'], ['LCD-D3', 'LCD-D7'], ['LCD-D20'...
from typing import NoReturn, TypeVar, Type import six from .avrojson import AvroJsonConverter TC = TypeVar('TC', bound='DictWrapper') class DictWrapper(dict): __slots__ = ['_inner_dict'] def __init__(self, inner_dict=None): super(DictWrapper, self).__init__() self._inner_dict = {} if inner_...
"""Functions to simplify interacting with database.""" import datetime as dt from math import ceil from bson.objectid import ObjectId from bson import SON from motor.motor_asyncio import AsyncIOMotorClient from pymongo import WriteConcern, IndexModel, ASCENDING, ReturnDocument def init_db(config, loop): """Initi...
#! /usr/bin/env python # def timestamp ( ): #*****************************************************************************80 # ## TIMESTAMP prints the date as a timestamp. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 06 April 2013 # # Author: # # John Burkardt ...
""" Tests for the :module`regression_tests.parsers.c_parser.module` module. """ import io import re import sys from textwrap import dedent from unittest import mock from regression_tests.utils.list import NamedObjectList from tests.parsers.c_parser import WithModuleTests class ModuleTests(WithModuleTests): ...
import types from operator import add import sys from common.functions import permutations, pick_from COMMON_ENGLISH_WORDS = ['of', 'the', 'he', 'she', 'when', 'if', 'was'] ALPHABET = map(chr, range(ord('a'), ord('z') + 1) + range(ord('A'), ord('Z') + 1)) NUMBERS = set(map(str, range(0, 10))) SPECIAL_CHARACTERS = {'...
# File name: SIM_SolarSys.py # Author: Nawaf Abdullah # Creation Date: 9/October/2018 # Description: numerical simulation of the n-body problem of a solar system from classicalMech.planet import Planet import matplotlib.pyplot as plt # Constants PI = 3.14159 class System: def __init__(self, i_ms, i_pla...
# -*- coding: utf-8 -*- import json from jinja2.ext import Extension from jinja2 import nodes from watson.assets.webpack import exceptions from watson.common.decorators import cached_property __all__ = ['webpack'] class WebpackExtension(Extension): tags = set(['webpack']) cached_stats = None @cached_pr...
#:coding=utf8: import logging from django.test import TestCase as DjangoTestCase from django.conf import settings from jogging.models import Log, jogging_init class DatabaseHandlerTestCase(DjangoTestCase): def setUp(self): from jogging.handlers import DatabaseHandler, MockHandler import logging...
"""Defines preselections. Currently implements 'loose' and 'tight' strategies.""" from __future__ import annotations __all__ = ["preselection_mask", "cut_vars"] from functools import singledispatch import awkward as ak import numpy as np from uproot.behaviors.TTree import TTree def cut_vars(strength: str) -> list[...
from tutils import Any from tutils import Callable from tutils import List from tutils import Tuple from tutils import cast from tutils import concat from tutils import reduce from tutils import lmap from tutils import splitstriplines from tutils import load_and_process_input from tutils import run_tests """ END H...
#!/usr/bin/env python # -*- coding: utf-8 -*- import __future__ import sys print("===" * 30) print("SAMPLE INPUT:") print("===" * 30) print(open("./input14.txt", 'r').read()) sys.stdin = open("./input14.txt", 'r') #print(open("./challenge_sample_input", 'r').read()) #sys.stdin = open("./challenge_sample_input", 'r') ...
# -*- coding: utf-8 -*- import io import time import queue import socket import select import functools from quickgui.framework.quick_base import time_to_die class DisconnectedException(Exception): '''Socket was disconnected''' pass class QueueClient(): ''' TCP client for queue-based communication...
import xml4h import os import re import spacy #doc = xml4h.parse('tests/data/monty_python_films.xml') #https://xml4h.readthedocs.io/en/latest/ class getData: def __init__(self, name, path): self.name = name self.path = path self.files = [] # test self.testfile = None ...
import os import logging """ Provide a common interface for all our components to do logging """ def basic_logging_conf(): """Will set up a basic logging configuration using basicConfig()""" return basic_logging_conf_with_level( logging.DEBUG if "MDBRAIN_DEBUG" in os.environ else logging.INFO) def ...
#!/usr/bin/env python # coding: utf-8 # This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). # # Solution Notebook # ## Problem: Implement a linked list with insert, append, find, delete, length, an...
#!/usr/bin/env python3 import json import os import random random.seed(27) from datetime import datetime import sqlalchemy.ext import traceback import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) import connexion impo...
#!/usr/bin/env python2 """Create GO-Dag plots.""" __copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang. All rights reserved." __author__ = "DV Klopfenstein" import sys sys.path.append("/dfs/scratch2/caruiz/code/goatools/") from goatools.cli.gosubdag_plot import PlotCli def run(): """Create GO-Dag ...
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: ...
import pytest from . import constants from pybible import pybible_load from pybible.classes.bible import Bible from pybible.classes.bible_without_apocrypha import BibleWithoutApocrypha from pybible.classes.book import Book from pybible.classes.chapter import Chapter from pybible.classes.verse import Verse @pytest.fix...
from django.shortcuts import render, redirect from django.template.loader import render_to_string from django.http import JsonResponse, HttpResponse from .models import User, Photo, Followers from .forms import * from django.contrib.auth import authenticate, login, logout as dlogout import json def ajaxsignup(request)...
import numpy from scipy.spatial import distance import matplotlib.pyplot as plt # wspolczynnik uczenia eta = 0.1 # momentum alfa = 0 class NeuralNetwork: def __repr__(self): return "Instance of NeuralNetwork" def __str__(self): # todo: zaktualizuj to_string() if self.is_bias: ...
import torch import matplotlib.pyplot as plt from torchsummary import summary import yaml from pprint import pprint import random import numpy as np import torch.nn as nn from torchvision import datasets, transforms from itertools import product def imshow(img): # functions to show an image fi...
from models.mlm_wrapper import MLMWrapper from transformers import BertForMaskedLM, BertTokenizer class BertWrapper(MLMWrapper): def __init__(self, tokenizer: BertTokenizer, model: BertForMaskedLM, device: int = None): super().__init__(tokenizer, model, device=device)
import csv import clueUtils import guess suspects = clueUtils.suspects weapons = clueUtils.weapons rooms = clueUtils.rooms allCards = clueUtils.allCards playerNames = clueUtils.playerNames numPlayers = clueUtils.numPlayers numSuspects = clueUtils.numSuspects numWeapons = clueUtils.numWeapons numRooms = clueUtils.nu...
# This file is part of the scanning-squid package. # # Copyright (c) 2018 Logan Bishop-Van Horn # # 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 limita...
""" Feb 23 Like net_feb23_1 but with faster affine transform and more filters and DNN (~15s faster) 363 | 0.678831 | 0.869813 | 0.780434 | 74.74% | 69.6s Early stopping. Best valid loss was 0.846821 at epoch 262. Finished training. Took 25459 seconds Accuracy test score is 0.7608 Multicla...
# cat train.info | grep "Test net output #0: accuracy =" | awk '{print $11}' import re import os import matplotlib.pyplot as plt import numpy as np import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--traininfo', type=str, required=True) args = parser.parse_...
''' Perform Object Classification (SGCLS only) Input is the pointcloud of the BOX, its location and heading is known Output the predicted class of the BOX ''' import torch from torch import nn from torch.nn import functional as F from model.modeling.detector.pointnet2.pointnet2_modules import PointnetSAModuleVotes, P...
# Copyright 2016 Intel # # 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, softwar...
#! /usr/bin/env nix-shell #! nix-shell -i python3 -p "python3.withPackages(ps: [ps.numpy ps.psycopg2 ps.requests ps.websockets])" import sys import threading from tenmoTypes import * from tenmoGraph import universe_print_dot import select import time import datetime import pprint import traceback import io import jso...
from django.urls import path from django.contrib.auth import views as auth_views from account import views as account_views urlpatterns = [ path('login', auth_views.LoginView.as_view( template_name='account/login.html', extra_context={ 'title': 'Account login'})...
''' This is based on cnn35_64. This is after the first pilot. Changes: -don't filter out # in the tokenizer, tokenize both together. or save tokenizer https://stackoverflow.com/questions/45735070/keras-text-preprocessing-saving-tokenizer-object-to-file-for-scoring -use 'number' w2v as representation for any digit -shu...
#!/usr/bin/env python import os import sqlite3 import cherrypy from collections import namedtuple import tweepy import random import twitterkeys # setup twitter authentication and api twitter_auth = tweepy.OAuthHandler(twitterkeys.consumer_key, twitterkeys.consumer_secret) twitter_auth.set_access_token(twitterkeys.ac...
#!/usr/bin/env python3 import xml.etree.ElementTree as ET CSPROJ_FILE = 'Uri/Uri.csproj' ENV_VARIABLE_FILE = '.env' ENV_VARIABLE_NAME = 'URI_VERSION' csproj_tree = ET.parse(CSPROJ_FILE) version_tag = csproj_tree.getroot().find('PropertyGroup').find('Version') version_parts = version_tag.text.split('.', 2) version_p...
class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: dic = {} stack = [] for num in nums2: stack.append(num) while len(stack) >= 2: if stack[-1] > stack[-2]: dic[stack[-2]] = stack[-1] ...
# -*- coding: utf-8 -*- import torch import torch.nn as nn from torch.nn import BatchNorm1d from ncc.models import register_model from ncc.models.ncc_model import ( NccEncoder, NccEncoderModel, ) from ncc.modules.base.layers import ( Embedding, Linear, ) class DeepTuneEncoder(NccEncoder): def __...
# MAP WARMPUP # Given the two lists of numbers below, produce a new iterable of their element-wise sums # In this example, that'd be (21, 33, 3, 60...) # Hint: look for a `from operator import ...` one = [1, 2, 3, 40, 5, 66] two = [20, 31, 0, 20, 55, 10] # FILTER WARMPUP # Take the following iterable, and filter o...
""" This is templates for common data structures and algorithms. Frequently used in my leetcode practices. """ """ Binary search """ nums, target left, right = 0, len(nums) - 1 while left + 1 < right: mid = (left + right) // 2 # might need modification to fit the problem. if nums[mid] < target: ...
from __future__ import (absolute_import, division,print_function, unicode_literals) from builtins import * import numpy as np import cv2 import SimpleITK as sitk from builtins import * from scipy.spatial import distance from scipy import stats import sys import time ############### FUNCTIONS ##############...
import tempfile import pickle import os import sys import time import zipfile import inspect import binaryninja as binja from binaryninja.binaryview import BinaryViewType, BinaryView from binaryninja.filemetadata import FileMetadata, SaveSettings from binaryninja.datarender import DataRenderer from binaryninja.function...
#!/bin/python3 import math import os import random import re import sys # Complete the arrayManipulation function below. def arrayManipulation(n, queries): d=[0]*(n+1) max_val=0 for query in queries: d[query[0]-1]+=query[2] d[query[1]]+=query[2]*(-1) max_dif=0 for i in d: ...
from model.model.space.space import Space from model.model.space.space import Space from watchmen.auth.storage.user_group import get_user_group_list_by_ids, update_user_group_storage, USER_GROUPS from watchmen.auth.user_group import UserGroup from watchmen_boot.guid.snowflake import get_surrogate_key from watchmen.co...
from scipy.spatial.distance import pdist, squareform from causality.greedyBuilder.scores import mutual_info_pairwise import networkx as nx class TreeBuilder: def __init__(self, score=None): if score is None: self.score = mutual_info_pairwise else: self.score = score d...
"""Interval set abstract type""" import datetime import collections __version__ = "0.1.5" _InternalInterval = collections.namedtuple("Interval", ["begin", "end"]) class Interval(_InternalInterval): """Represent an immutable interval, with beginning and ending value. To create a new interval: ...