content
stringlengths
5
1.05M
import subprocess from typing import List, Union, Tuple from pathlib import Path, PosixPath import Bio.PDB import numba as nb import numpy as np import prody as pd def secondary_to_array(secondary): return np.array(secondary, dtype="S1").view(np.int8) @nb.njit def get_common_positions(aln_array_1, aln_array_2):...
from PyPowerStore.tests.unit_tests.base_test import TestBase from PyPowerStore.utils.exception import PowerStoreException class TestRole(TestBase): def test_get_roles(self): role_list = self.configuration.get_roles() self.assertListEqual(role_list, self.data.role_list) def test_get_role_deta...
def is_sorted(list): return all(list[i] <= list[i+1] for i in range(len(list)-1)) def thanos_sort(list): while not is_sorted(list): list = list[::2] return list
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import unittest from os.path import join, dirname from indra.statements import * from indra.sources.hume.api import * # Path to the HUME test files path_this = os.path.dirname(os.path.abspath(__file__)) test_file_...
# Author: Alexandre Bovet <alexandre.bovet@gmail.com> # License: BSD 3 clause from sklearn.externals import joblib from TwClassifier import TweetClassifier import pickle import time import numpy as np import sqlite3 import pandas as pd from datetime import datetime import time import numpy as np from baseModule imp...
# Copyright 2015-2017 FUJITSU LIMITED # # 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...
from random import random import pytest from tabulate import tabulate from pytest_harvest import saved_fixture # ---------- The function to test ------- def my_algorithm(param, data): # let's return a random accuracy ! return random() # ---------- Tests @pytest.fixture(params=['A', 'B', 'C']) @saved_fixtu...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2018-02-14 21:05 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [migrations.swappa...
#!/usr/bin/python # -*- coding:utf8 -*- import urllib import urllib.request import urllib.parse import os.path import sys import re import time from .util import sec2time, parse_argv #default_encoding = sys.getfilesystemencoding() #if default_encoding.lower() == 'ascii': # default_encoding = 'utf-8' # the old fun...
import setuptools setuptools.setup( name="kite-airflow-dags", # Replace with your own username version="0.0.1", author="Kite Team", description="Kite Airflow codes.", packages=setuptools.find_packages(), python_requires='>=3.6', include_package_data = True, entry_points = { 'ai...
#from IPython.core.display import HTML #from IPython.display import display import copy import os from os.path import expanduser import numpy as np from collections import OrderedDict import pickle from collections import OrderedDict import pprint try: from PyQt4.QtGui import QFileDialog from PyQt4.QtCore impo...
from multiprocessing.connection import Listener from wasap.wasap import Wasap import click import string import random @click.command() @click.option("--hostname", "-h", default="localhost", help="Hostname / Network Interface to use for binding") @click.option("--port", "-h", default=9292, help="Port number to use fo...
# from here: https://stackoverflow.com/questions/36620766/rotating-a-square-on-tkinter-canvas from tkinter import * import math WIDTH = 400 HEIGHT = 400 CANVAS_MID_X = WIDTH/2 CANVAS_MID_Y = HEIGHT/2 SIDE = WIDTH/4 root = Tk() canvas = Canvas(root, bg="black", height=HEIGHT, width=WIDTH) canvas.pack() vertices = [ ...
#!/usr/bin/env python # # This program shows how to use mpi_comm_split # import numpy from numpy import * from mpi4py import MPI import sys def myquit(mes): MPI.Finalize() print(mes) sys.exit() comm=MPI.COMM_WORLD myid=comm.Get_rank() numprocs=comm.Get_size() print("hello from ",myid," of ",...
# pylint:disable=missing-docstring,invalid-name from __future__ import print_function import sys import os import re # By default, test cases are expected to switch and emit warnings if there was none # If a test is found in this list, it's expected not to switch. no_switch_tests = '''test_patched_select.SelectTestCas...
# -*- coding: utf-8 -*- """ Created on Tue Sep 7 12:04:37 2021 @author: yoonseok """ import os import pandas as pd from tqdm import tqdm # 1. 작업 폴더로 변경 os.chdir("C:\data\stockinfo\\") # 작업 폴더로 변경 def GenerateDataFrame(year): df = pd.read_csv('stockPrice_' + str(year) + '.csv', dtype=str) df = df.rename(co...
# Copyright 2021 cms.rendner (Daniel Schmidt) # # 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...
from __code.wave_front_dynamics.algorithms import ListAlgorithm MAX_BIN_SIZE = 100 INIT_BIN_SIZE = 50 algorithms_colors = {ListAlgorithm.sliding_average: 'red', ListAlgorithm.change_point: 'green', ListAlgorithm.error_function: 'blue'} algorithms_symbol = {ListAlgorithm.slid...
from django.shortcuts import render, get_object_or_404, redirect, reverse, HttpResponseRedirect from .models import Post from .forms import PostForm from django.http import JsonResponse from django.core.paginator import Paginator # Create your views here. def index(request): return render(request, 'post/sections...
type = 'Detectron' config = '/home/linkinpark213/Source/online-mot-by-detection/configs/detect/detectron2/bdd100k_faster_rcnn_x_101_32x8d_fpn_2x_crop.yaml' checkpoint = '/home/linkinpark213/Source/online-mot-by-detection/models/detect/detectron2/bdd100k_faster_rcnn_x_101_32x8d_fpn_2x_crop.pth' conf_threshold = 0.3
from django.core.files import File from faker import Faker from softhub.models.Application import Application from softhub.models.Developer import Developer from softhub.models.Category import Category import os import random def create_applications(path): """ This method search inside a given path for icon fil...
import sys import os import docassemble.base.config from docassemble.base.config import daconfig if __name__ == "__main__": docassemble.base.config.load(arguments=sys.argv) def main(): from docassemble.base.config import daconfig container_role = ':' + os.environ.get('CONTAINERROLE', '') + ':' if ':al...
import sys, os import argparse import numpy as np import subprocess from tqdm import tqdm from preprocess.generic import load_wav_snf, stft, save_wav, \ revert_power_db_to_wav, uttid2wav, load_wav, save_wav_snf, extract_adv_mat_frm_grads def main(args): keys, mat_list = extract_adv_mat_frm_grads(args.grads, arg...
import torch import torch.nn as nn from kipoi.model import BaseModel # Simple CNN, taking SeqVec embeddings for a given protein as input. # Returns predictions for 3-state and 8-state secondary structure # as well as for disorder for each residue in the given protein. class CNN( nn.Module ): def __init__( self )...
import os.path from os import path import re from utilities.Exceptions import PlayersFileNotFound, PlayersFileIsEmpty from entity.Player import Player from utilities.Globals import Globals class FileUtils: @staticmethod def read_players_file(filename): if not path.exists(filename): ...
# -*- coding:utf-8 -*- from cmdb.types.base import BaseType class ChartField(BaseType): """ 字符类型 """ def validate(self, data): # 1. 处理值 # 1-1:默认值处理 default = self.option.get('default') if default and not data: data = default # 1-2: 把值变成字符 i...
""" Copyright 2020 LeMaRiva|Tech (Mauro Riva) info@lemariva.com 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 ...
import re class LexerTool: DELIM_AS_PREFIX = "P" DELIM_AS_SUFFIX = "S" DELIM_EXCLUDED = "X" @classmethod def is_token_escaped(cls, token_list_DELIM, tt_list_ESCAPE): if not token_list_DELIM: return False count_ESCAPE = next((i for i,tok_PREV in enumerate(reversed(token_list_DE...
from dados import produtos # Pego todo o dicionário, e dele quando referente a coluna "valor" eu multiplico os valores por 1.21 e depois arredondo o valor obtido até a segunda casa decimal. Por fim, eu retorno todo o dicionário. def aumentador_de_valores(x): x['valor'] = round(x['valor'] * 1.21, 2) return x #...
import random from time import sleep #Used to create the cards with the Card class suits = ('Hearts', 'Diamonds', 'Clubs', 'Spades') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Ei...
from version import __version__ import logging from argparse import ArgumentParser from bioCanon.version import __version__ LOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' def init_console_logger(lvl): logging_levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG] ...
# Copyright 2012-2017 The Meson development team # 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 agree...
# # COPYRIGHT (C) 2012-2013 TCS Ltd # """ .. module:: complement :platform: Unix, Windows, MacOSX :synopsis: Nucleic Acid Complement .. moduleauthor:: Kunal Kundu (kunal.kundu@tcs.com); modified by changjin.hong@gmail.com The module exports one dictionary *COMPLEMENT*, whose keys are the nucleic acid and the v...
from __future__ import absolute_import from .utils import FileInfo, unpack, read_chunk from .consts import * from .mfs_proxy import ProxyConn from dpark.util import get_logger from .fs import MooseFS, PosixFS import os logger = get_logger(__name__) class FileManager(object): def __init__(self): self.fs_l...
import unittest from click.testing import CliRunner from competition import generate # FOR SOME REASONS THOSE TESTS WORK ONLY IF WE START ONE AFTER THE OTHER MANUALLY # I SUSPECT THE TEST DO NOT WAY FOR THE runner TO FINISH class CommandLineCombinationTest(unittest.TestCase): def test_fail_when_model_is_missing(...
#!/usr/bin/env python import sys import os import datetime from subprocess import Popen, PIPE class Mon_sender(): def __init__(self, args, sender_data): '''Set item name pattern, etc''' os.umask(int('137', base=8)) self.args = args self.sender_data = sender_data self.user_...
""" Generalized vs Standard Lomb-Scargle ------------------------------------ Figure 10.16 A comparison of the standard and generalized Lomb-Scargle periodograms for a signal y(t) = 10 + sin(2pi t/P) with P = 0.3, corresponding to omega_0 ~ 21. This example is, in some sense, a worst-case scenario for the standard Lom...
#!/usr/bin/env python3 # Copyright 2016-2021 Arm Limited. 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 r...
import os # from dotenv import load_dotenv basedir = os.path.abspath(os.path.dirname(__file__)) # load_dotenv() class Config(object): # Database config DATABASE_HOST = os.environ.get('SQL_HOST') DATABASE_USERNAME = os.environ.get('POSTGRES_USER') DATABASE_PORT = os.environ.get('SQL_PORT') DATABAS...
from .connect4 import Connect4 from .tictactoe import TicTacToe
from tkinter import CASCADE from django.db import models from django.contrib.auth.models import User # Create your models here. class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=255, null=True, blank=True) ...
from .xpath_utils import XPathUtils from .models import *
import mongoengine def global_init(): mongoengine.register_connection(alias='core', name='demo_dealership')
"""Factory to produce data readers based on the data format.""" from .BaseDataReader import BaseDataReader from .ConllDataReader import ConllDataReader from ..constants import CONLL def create_data_reader(format=CONLL): """ Create a data reader based the provided format. Raises an exception if no data re...
# noinspection PyUnresolvedReferences from Game2 import *
# -*- coding: utf-8 -*- # Copyright 2014, 2015 Metaswitch Networks # # 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 ap...
from annotypes import Anno, Any from malcolm.core import Part, snake_to_camel, BooleanMeta, VMeta, PartRegistrar from malcolm.modules.pandablocks.pandablocksclient import PandABlocksClient with Anno("Client for setting and getting field"): AClient = PandABlocksClient with Anno("Meta object to create attribute fr...
import psycopg2 import configparser from pathlib import Path from queries import create_business_schema, create_business_table config = configparser.ConfigParser() config.read_file(open(f"{Path(__file__).parents[0]}/config.cfg")) class DatabaseDriver: def __init__(self): self._conn = psycopg2.connect("ho...
from typing import List class Solution: """ BFS """ def canReach_1(self, arr: List[int], start: int) -> bool: """ Recursively. """ seen = set() def helper(pos): if not 0 <= pos < len(arr) or pos in seen: return False ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'log_dialog_ui.ui' # # Created: Fri Nov 18 22:58:33 2016 # by: pyside2-uic running on PySide2 2.0.0~alpha0 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): ...
# # # Copyright (C) 2006, 2007, 2008, 2010, 2011, 2012 Google 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, ...
#!/usr/bin/env python ############################################################################ # # Copyright (C) 2016 The Qt Company Ltd. # Contact: https://www.qt.io/licensing/ # # Commercial License Usage # Licensees holding valid commercial Qt licenses may use this file in # accordance with the commercial licen...
''' Having learned how to append Series, you'll now learn how to achieve the same result by concatenating Series instead. You'll continue to work with the sales data you've seen previously. This time, the DataFrames jan, feb, and mar have been pre-loaded. Your job is to use pd.concat() with a list of Series to achieve...
from __future__ import unicode_literals import unittest from datetime import date from infi.clickhouse_orm.database import Database from infi.clickhouse_orm.models import Model, NO_VALUE from infi.clickhouse_orm.fields import * from infi.clickhouse_orm.engines import * from infi.clickhouse_orm.funcs import F ...
import cv2 import audioread import logging import os import random import time import warnings import librosa import numpy as np import pandas as pd import soundfile as sf import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data from contextlib import contextmanager from pat...
import komand from .schema import CreateCaseInput, CreateCaseOutput, Component # Custom imports below import requests from thehive4py.models import Case, CaseTask class CreateCase(komand.Action): def __init__(self): super(self.__class__, self).__init__( name='create_case', ...
""" This module deals with representing the data in an OpSim output (to the extent we will care about it). A description of the OpSim output can be found at (opsim description)[https://www.lsst.org/scientists/simulations/opsim/summary-table-column-descriptions-v335] In brief, we will use two tables from the OpSim outp...
from twx.botapi import TelegramBot from finder import Finder import env """ Send a message to user """ def notify(title, link): bot = TelegramBot(env.TELEGRAM_API_TOKEN) user_id = int(env.USER_ID) bot.send_message( user_id, "Senhor, existe uma nova chamada no Conab: \n\n%s \n\n%s" % (titl...
##### # # This class is part of the Programming the Internet of Things project. # # It is provided as a simple shell to guide the student and assist with # implementation for the Programming the Internet of Things exercises, # and designed to be modified by the student as needed. # import logging import random from...
# -*- coding: utf-8 -*- """ ------------------------------------------------------------------------------ WARPNet Transport - Unicast Ethernet UDP Python Socket Implementation ------------------------------------------------------------------------------ Authors: Chris Hunter (chunter [at] mangocomm.com) ...
import cv2 import numpy as np cam = cv2.VideoCapture(0) detector=cv2.CascadeClassifier('Classifiers/face.xml') i=0 offset=50 name_person = input('Enter registration number of person : ') with open("id_count.txt", "r") as file: name = file.read() with open("id_count.txt", "w") as file: file.write(str(int(name...
#!/usr/bin/env python # # Copyright 2014 tigmi # # 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 agre...
#!/bin/env python """from toc.tex generated by easychair, extract metadata necessary for toc generation: title, authors""" import sys toc = [x.strip() for x in open(sys.argv[1]).readlines()] index = {} for line in toc: if line.startswith("\\tocTitle{"): #print line title = "}".join(line.split("}...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2018-2021 Accenture Technology # # 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 #...
import os import re import requests import yaml from clint.textui import progress from project.generation import generate_build_files, rebuild_marker_append from utils import env from utils.templates import Templates from utils.yaml_template_object import YamlTemplateObject class ContainerTemplate(YamlTemplateObjec...
from collections import Mapping import gevent from raiden.raiden_service import RaidenService from raiden.transfer.architecture import Event, StateChange from raiden.utils.typing import Any, Dict, List, Optional NOVALUE = object() def check_dict_nested_attrs(item: Dict, dict_data: Dict) -> bool: """ Checks the...
# -*- coding: utf-8 -*- # --------------------------------------------------------------- # wxalarm.py # # Copyright (c) 2019 sanderiana https://github.com/sanderiana # # This software is released under the MIT License. # http://opensource.org/licenses/mit-license.php # ------------------------------------------------...
from PIL import Image, ImageDraw from datetime import datetime from random import randint from color import NamedColor import hashlib import io import xkcd def random_color(*, name='Random color'): """ Returns a random color. :return: color.NamedColor """ return NamedColor(name=name, color=(rand...
import argparse import sys from pathlib import Path from optconvert import Converter, Messages, Model def parse_args(args): supported_formats = Model.supported_out_formats parser = argparse.ArgumentParser(prog='optconvert', description='optconvert converts files of (stoch...
# -*- coding: utf-8 -*- # Generated by Django 1.11.26 on 2019-12-24 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('icds_reports', '0156_auto_20191217_0932'), ] operations = [ migrations.RunSQL('A...
import zmq from multiprocessing import Process import sys DATA_SERVER_PATH = "tcp://127.0.0.1:40188" class DataServer(object): def __init__(self): self.context = zmq.Context() self.socket = self.context.socket(zmq.REP) self.socket.bind(DATA_SERVER_PATH) self.store = dict() de...
#Instalando o PyDrive wrapper & importando bibliotecas. !pip install -U -q PyDrive from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials # Autenticação e criação do PyDrive client. auth.authenticate_user() gauth = Googl...
import streamlit as st import time import numpy as np import pandas as pd st.title('My first app') st.write("Here's our first attempt at using data to create a table:") st.write(pd.DataFrame({ 'first column': [1, 2, 3, 4], 'second column': [10, 20, 30, 40] })) chart_data = pd.DataFrame( ...
import logging from vk_api import bot_longpoll from os import path, mkdir from Bot.Plugins import BasePlug from random import choice class MiddlewarePlug(BasePlug): keywords = [] listen_all = True # middleware? def __init__(self, bot): super().__init__(bot) self.res_dir = path.join(s...
# tests for autocompletion impo sys not_exist.  not_exist  x = '123' 1, x.isdi () i = str i.lowe ('ABC') j = None j. 
import sqlite3 import os # Connect to the database conn = sqlite3.connect('perfdata.db') # Get a transaction object c = conn.cursor() # Run some small queries first c.execute("SELECT * FROM `Programs`;") print("All programs:\n" + str(c.fetchall())) c.execute("SELECT * FROM `Runs`;") print("All Runs:\n" + str(c.fetc...
# # Copyright (c) 2022 Airbyte, Inc., all rights reserved. # from unittest.mock import MagicMock from airbyte_cdk.models import SyncMode from airbyte_cdk.sources.declarative.declarative_stream import DeclarativeStream def test(): name = "stream" primary_key = "pk" cursor_field = ["created_at"] sche...
from tensorflow.python.framework import ops from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_shape from tensorflow.python.keras import activations from tensorflow.python.keras import constraints from tensorflow.python.keras import initializers from tensorflow.python.keras im...
from utils import * from user_product_matrix import * from recommender import * def get_recall(rec, tru): """Recommendation recall: |{R & P}|/|P| (R - recommended products, P - relevant products)""" return len(rec & tru)/len(tru) if len(tru) != 0 else 0 def get_precision(rec, tru): """Recommendation p...
SHIFT = 0x100 ALT_GR = 0x200 keymap_azerty_fr = [ 0x00, # NUL 0x00, # SOH 0x00, # STX 0x00, # ETX 0x00, # EOT 0x00, # ENQ 0x00, # ACK 0x00, # BEL 0x2a, # BS Backspace 0x2b, # TAB Tab 0x28, ...
import json from pathlib import Path import pytest from ape import networks from ape.api.explorers import ExplorerAPI from requests import Response from ape_etherscan import NETWORKS ADDRESS = "https://etherscan.io/address/0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B" TRANSACTION = "0x0da22730986e96aaaf5cedd5082fea9fd...
start = None # Estrutura do node class Node: def __init__(self, data): self.data = data self.next = None self.prev = None # Função para inserir no fim def insertEnd(value) : global start # Se a lista estiver vazia, crie um # circular de node unico e uma lista if (start == None) : new_node = Node(0) ...
import workaround.api as api class Client: def __init__(self, api_key=None): if not api_key: raise "api_key must be provided to Client" self.api_key = api_key def test_connection(self): api.set_base_url(self.api_key) assert(api.test_connection()['success']) def...
''' 정점(node)와 간선(edge)로 각 정점들의 관계를 나타낸 것을 그래프 파이썬에서는 그래프를 딕셔너리를 이용해서 표현 그래프의 key는 node를, value는 key와 연결이 된 정점을 나타낸다 ex : graph = {1 : [2,3,4], 2 : [5], 3 : [5], 4 : [], 5 : [6, 7], 6 : [], 7 : [3]} ''' # 알고리즘 문제의 경우 두 정점의 연결관계를 입력을 여러줄로 입력 받음 # 입력받은 값을 리스트로 만들 때는 아래와 같은 방법을 사용 # 먼저 노드의 갯수 n, 간선의 갯수 m을 입력 n,m = map(i...
# Generated by Django 2.2.9 on 2020-04-16 17:25 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('account', '0008_auto_20200415_1840'), ] operations = [ migrations.CreateModel( ...
#!/usr/bin/env python3 # # Copyright 2015 by Raytheon BBN Technologies Corp. All Rights Reserved. import ast import os import sys from copy import deepcopy # Find the directory that this executable lives in; # munge the path to look within the parent module # if __name__ == '__main__': DIRNAME = os.path.normpat...
#coding:utf8 ''' @author: sxmad ''' import socket address=("localhost",1101) m_socket=socket.socket() m_socket.bind(address) m_socket.listen(1024) while True: _socket,addr=m_socket.accept() while True: _data=_socket.recv(2048) if len(_data)>0: print str(len(_data)) prin...
import tempfile import unittest import torch from tests.test_modeling_common import ids_tensor from transformers import AutoAdapterModel, AutoConfig from transformers.adapters.heads import ClassificationHead, PredictionHead from transformers.testing_utils import require_torch, torch_device class CustomHead(Predicti...
from django.shortcuts import get_object_or_404 from net.filters import ConnectionFilterSet from net.forms import ConnectionBulkEditForm, ConnectionFilterForm, ConnectionForm from net.models import Connection from net.tables import ConnectionTable from utils.views import ( AddOrEditView, BulkDeleteView, Bul...
def msg(username, passwd, message, number): import urllib2 import cookielib from getpass import getpass import sys message = "+".join(message.split(' ')) #Logging into the SMS Site url = 'http://way2sms.com/Login1.action?' data = 'username='+username+'&password='+passwd+'&Submit=Sign+i...
from fastai.text import * import html import fire from imdb_scripts.create_toks import make_csv_from_dir, copy_subset_of_files, create_toks from imdb_scripts.predict_with_classifier import run_tta_experiment from imdb_scripts.train_clas import train_clas from imdb_scripts.eval_clas import eval_clas from imdb_scripts.t...
import configparser import serial import serial.tools.list_ports import sys import logging from time import time cp = configparser.ConfigParser() cp.read(sys.argv[1]) logging.basicConfig(filename=cp['path']['log'] + str(int(time())) + ".txt", level=logging.INFO, format='%(ascti...
import asyncio import json import logging import math from datetime import datetime, timezone, timedelta from operator import itemgetter import dateutil import dateutil.parser import pytz from binance_chain.environment import BinanceEnvironment from binance_chain.http import AsyncHttpApiClient from binance_chain.messa...
import math a = float(input("Digite o valor de a: ")) b = float(input("Digite o valor de b: ")) c = float(input("Digite o valor de c: ")) delta = (b**2 - 4*a*c) if (delta < 0): print ("esta equação não possui raízes reais") else: if (delta > 0): x1= (-b + math.sqrt(delta))/(2*a) x2= (-b - math.sqrt(delta))/(...
# SPDX-FileCopyrightText: 20211015 CS for CSigns # SPDX-License-Identifier: MIT import os import gc import adafruit_logging as logging from collections import namedtuple import microcontroller import terminalio import time import board import busio from digitalio import DigitalInOut import adafruit_reques...
# -*- coding: utf-8 -*- # Convert the html tables to csv file format import pandas as pd import os import htmlTablesExtractor as ht def convert_to_csv(**tables): """ Create an output folder if not exists, Browse through the dictionary of tables which is pass him, get the couple (key, value) browse eac...
# -*- coding: utf-8 -*- # @Time : 2019/9/18:10:17 # @Author : xuqiang class TFRecordKeys(): image_encode = "image/encoded" image_filename = "image/filename" image_format = "image/format" image_height = "image/height" image_width = "image/width" object_bbox_xmax = "image/object/bbox/xmax" ...
from __future__ import absolute_import import numpy as np import scipy.signal from .common import PeakFinder, _filter_peaks class Wavelet(PeakFinder): def __init__(self, max_peaks=None, width_min=1, width_max=9): self._max_peaks = max_peaks self._widths = np.arange(width_min, width_max+1) def _fit_one(s...
""" These are all of the signatures related to running a shell command """ from signatures.abstracts import Signature class RunsShell(Signature): def __init__(self): super().__init__( heuristic_id=3, name="runs_shell", description="JavaScript runs code via sh...
#!/usr/bin/env python """ Classic Load Balancer to Network Load Balancer copy utility version 1.0.0 2016 Authors: Long Ren, Dan Lindow, Max Clements, Tipu Qureshi This script uses the configuration of the specified Classic Load Balancer to create an Network Load Balancer in a "best effort" manner. Optionally, it can r...