content stringlengths 5 1.05M |
|---|
# Copyright 2020 Daniel J. Tait
#
# 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 writin... |
def part1(input) -> int:
dic = {}
for line in input:
line = line.split()
line.pop(1)
key = line[0]
value = line[1]
if key == "mask":
mask = {}
for i in range(len(value)):
if value[i] != "X":
mask[i] = value[i]
... |
import os
from .planner import *
from .user import *
from .tokens import *
from .yaml_validator import *
from .request_handler import set_dry
set_dry(False)
validation = yaml_init()
#Logging/Register the user
#
if validation == "set_user" or validation == "register":
if validation == "set_user":
dry_res... |
from grab import Grab
"""Скрипт, используя логин и пароль, авторизовывается в github, после выводит
информацию о пользователе.
"""
__author__ = 'ipetrash'
if __name__ == '__main__':
login = input("Логин: ")
password = input("Пароль: ")
g = Grab()
# Переходим на страницу входа
print("...Перехо... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import requests
from lxml import etree
import re
from maoyan_font import MaoyanFontParser
from movie_spider.site.base_site import BaseSite
from movie_spider.utils.time_util import get_today
today = get_today()
class MaoYan(BaseSite):
site = '猫眼'
... |
# By @kirito6969 for PepeBot
# Don't edit credits Madafaka
"""
This module can search images in danbooru and send in to the chat!
──「 **Danbooru Search** 」──
-> `animu`(search string) or `aninsfw`(search nsfw string)
Search images from Danbooru.
"""
import requests
from asyncio import sleep
from uniborg.util import a... |
#Given an array of integers, write a method that will pack neighbouring numbers that are the same into the string X:N, where X is the integer value and N is the sequence length.
#For example, this
#packNumbers([5, 5, 5, 7, 7, 3, 4, 7])
#should return
#['5:3', '7:2', 3, 4, 7]
#Please use the ... |
from plugins.adversary.app.commands import systeminfo
from plugins.adversary.app.operation.operation import Step, OPUser, OPDomain, OPCredential, OPHost, OPRat, OPVar, OPOSVersion
class SysteminfoRemote(Step):
"""
Description:
This step enumerates a target machine located remotely on a network.
Re... |
# Copyright (C) 2013-2016 GRNET S.A. 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 ... |
from django.db.backends.base.introspection import BaseDatabaseIntrospection, TableInfo
class DatabaseIntrospection(BaseDatabaseIntrospection):
def get_table_list(self, cursor):
"Returns a list of table names in the current database."
cursor.execute("SHOW TABLES")
return [TableInfo(row[0], ... |
import pandas as pd
import robin_stocks.robinhood as rs
import pyotp
import numpy as np
import os
_float = float
def float(str_num):
if str_num is not None:
return _float(str_num)
else:
return None
class RH_Portfolio():
def __init__(self, uname=None, pword=None, _2fa=None, using_env_vars =... |
import json
from confluent_kafka.cimpl import KafkaException, KafkaError
from pytest import raises
from pytest_mock import MockerFixture
from transport.kafka_transport import KafkaTransportPublisher, KafkaTransportSync
def test_kafka_transport_publisher(mocker: MockerFixture):
mocker.patch('transport.kafka_trans... |
import logging
from unittest.mock import Mock
import grpc
import numpy
import numpy.random
import pytest
from google.protobuf import any_pb2
from google.rpc import error_details_pb2, status_pb2, code_pb2
from grpc_status import rpc_status
from grpc4bmi.bmi_grpc_server import BmiServer
from grpc4bmi.bmi_grpc_client im... |
from setuptools import setup, find_packages
setup_args=dict(
name="PySCli",
version="1.0",
author="Sancho Godinho",
description="A Simple Module to Get User Terminal Commands...\nSee https://github.com/sancho1952007/PySCLI",
packages=['pyscli'],
keywords=['cli()']
)
install_requires... |
from dataclasses import dataclass
from enum import Enum
from dataclasses_tensor import dataclass_tensor
import numpy as np
class Movie(Enum):
THE_MATRIX = 0
THE_DARK_KNIGHT = 1
INTERSTELLAR = 2
@dataclass_tensor
@dataclass
class Watch:
next_movie: Movie
def test_numpy_dtype_argument():
s1 = Watc... |
from __future__ import absolute_import
# for localized messages
from . import _
#from Plugins.Plugin import PluginDescriptor
from .MPHelp import MPHelp
from collections import Callable
helpList = []
class PluginHelp(object):
def __init__(self, getNameFunc, getPagesFunc, additionalSkin=""):
if not isinstance(get... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# Скачивание файла
import requests
rs = requests.get('https://cloclo18.datacloudmail.ru/weblink/view/emCb/gXFkchRJ2?etag=7706DA739680EAC4A5B9044E9767047365988F54&key=a91762c6f1d8a559f6d780934b2509c728b33df4')
# Получение текста, разделение его п... |
import requests
import json
from .models import CarDealer, DealerReview
from requests.auth import HTTPBasicAuth
# from ibm_watson import NaturalLanguageUnderstandingV1
# from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
# from ibm_watson.natural_language_understanding_v1 import Features, SentimentOptions
... |
""" 回测基本模块 """
from .md_api import LooperMe
from .td_api import LooperYou
__all__ = [LooperYou, LooperMe]
|
# ZUS REACTION PICTURES
ZUS_PIC_SHOCKED = 'https://media.discordapp.net/attachments/872435741270097940/872439835967758356/shocked.png'
ZUS_PIC_NOT_AMUSED = 'https://media.discordapp.net/attachments/872435741270097940/872439831848972318/not_amused.jpg'
ZUS_PIC_BORED = 'https://media.discordapp.net/attachments/8724357412... |
"""
User Interface [Omission]
"""
# This is needed to force use of SDL2 for audio, needed for Windows and
# for Snapcraft.
import os
os.environ['KIVY_AUDIO'] = 'sdl2'
# Workaround for https://github.com/kivy/kivy/issues/3576
from kivy.config import Config
Config.set('graphics', 'multisamples', '0')
#pylint: disable=... |
""" AVIA protocol implementations
Base Class AVIaParser
contains shared functions
Inherited Classes
AVIaSerial
Serial-specific implementation details
AVIaTCP
TCP-specific implementation details
"""
import os
import serial
import copy
from struct import unpack
from common_packets.avia_pack... |
class DelimiterProcessor():
"""
A basic processor to split field values based on delimiters.
The core process() method accepts a dictionary representing a CSV row. It will split configured
fields on configured delimiters, replacing the field values for the split fields with lists.
This del... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
import pandas as pd
import random
import cv2
import os
# ### 1. Preparing training and test csv files
# In[5]:
root_dir = r'D:\Trainings-2019\custom_data_generator\flowers_recognition' #The r means that the string is to be treated as a raw str... |
def setup():
size(600,600)
smooth()
noStroke()
rectMode(CENTER)
def draw():
background(255)
fill(6458774563)
rect(mouseX, mouseY, 50,50)
|
import pandas as pd
import datetime
import random
random.seed = 6
def trace_philly_process(dir, date_range):
start = '2017-10-01 00:00:00'
df = pd.read_csv(dir+'/cluster_log.csv', parse_dates=['submit_time'], usecols=['user', 'vc', 'jobname', 'gpu_num',
... |
import functools
import itertools
import os
import time
from twisted.internet import defer
from twisted.spread import pb
from myutils.testhelpers import run_cmd, kill_with_children
from myutils.twisted_utils import sleep
WITH_PIPENV = run_cmd(['which', 'pipenv']) == 0
DOTENV_SCRIPT = os.path.join(os.path.dirname(os.p... |
import os
import sys
from glob import glob
from config.path_config import CONFIG_PATH_GROBID, DATA_PATH
def run_grobid(config_path, data_path, GrobidClient):
client = GrobidClient(config_path=config_path)
client.process("processFulltextDocument", data_path, output=data_path, consolidate_citations=True, tei_coo... |
from conservancy.apps.supporters.models import Supporter
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
|
import os
import unittest
from monitor.writer import DBConnection
from monitor.writer import MetricsWriter
def test_db_connection():
with DBConnection() as db_connection:
db_connection.cursor.execute("SELECT 1 = 1;")
assert db_connection.cursor.fetchone() == (True,)
@unittest.skipIf(os.environ... |
import matplotlib.pyplot as plt
import numpy as np
from tensorboardX import SummaryWriter
import torch.nn.functional as F
from matplotlib import colors
plt.switch_backend('agg')
import torch
from SOS.moments import generateMoments
from SOS.moments import Q
from scipy.special import comb
def visualize_instance_on_tenso... |
import torch
import itertools
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
class GenerativeCycleGANModel(BaseModel):
"""
This class implements the CycleGAN model, for learning image-to-image translation without paired data.
The model training requires '--... |
import vtk
import vtk.test.Testing
tree_data = "((((((((ahli:0.1308887296,allogus:0.1308887296):0.109078899,rubribarbus:0.2399676286):0.3477240729,imias:0.5876917015):0.1279779191,((((sagrei:0.2576204042,(bremeri:0.1097436524,quadriocellifer:0.1097436524):0.1478767518):0.06150599843,ophiolepis:0.3191264027):0.08721... |
# coding=utf-8
from __future__ import unicode_literals
import os
import platform
import mock
from decimal import Decimal
import pytest
try:
import setproctitle
except ImportError:
setproctitle = None
from pgcli.main import (
obfuscate_process_password, format_output, PGCli, OutputSettings
)
from utils imp... |
import asyncio
import time
import os
import _thread
from apps.Config.config import config
from apps.PiCam.piCam import piCam
from apps.PiCam.simulation.piCam import piCam as simulatedCamera
class Timelapse:
def __init__(self):
self.status = "Down"
self.loop_flag = True
self.camera = piCam
... |
from datetime import date
import coreschema
from coreapi.document import Field
from django.conf import settings
from django.contrib.gis.db.models import Collect
from django.db.models.query_utils import Q
from django.utils.translation import gettext as _
from rest_framework.filters import BaseFilterBackend
from rest_fr... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-05-08 09:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('reason', '0001_initial'),
('strea... |
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.timezone import timedelta
def md5(user):
import hashlib
import time
ctime = str(time.time())
m = hashlib.md5(bytes(user, encoding='utf-8'))
m.update(bytes(ctime, encoding='utf-8'... |
import argparse
import random
import pathlib
import sys
sys.path.append('../PyPipes')
from src.core.PartType import PartType, random_part_type, random_pipe_type
from src.graph_creator.core.PipelineGraph import PipelineGraph
from src.classifier.trainer.TrainingModel import create_training_model
from src.graph_creator.... |
from collections import deque
from pathlib import Path
from unittest.mock import patch
import h5py
import numpy as np
import pytest
from click.testing import CliRunner
from pandablocks import cli
from tests.conftest import STATE_RESPONSES, STATE_SAVEFILE, DummyServer
def test_writing_fast_hdf(dummy_server_in_thread... |
import os
import pickle
import threading
import numpy as np
from torch.utils import data
from tqdm import tqdm
from load_audio import load_wav
from load_video import load_mp4
from utils import colorize
class DemoDataset(data.Dataset):
def __init__(self, video_path, resize, fps, sample_rate):
self.resi... |
from khayyam import JalaliDate, JalaliDatetime
from datetime import timedelta, datetime, date, time
from typing import Union, List
# todo: type hints
from avishan.misc.translation import AvishanTranslatable
class BchDatetime(object):
def __init__(self, year: Union[int, datetime, date, JalaliDatetime, dict, 'BchD... |
#import pdftotext
import os
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import BytesIO
import json
import gensim
import csv
import pandas as pd
class Data(object):
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 03 11:27:05 2015
@author: Jak
"""
import math
import sys
import os
sys.path.append(".." + os.sep)
print(os.getcwd())
import bpy
#Load stewart configuration
from configuration import *
#default units is mm
thickness = height/10
def makeRigidBody... |
#------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
#-----------------------------------------------------... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-06-09 09:39
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('drugshare', '0018_auto_20160609_0754'),
]
operation... |
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.conf import settings
from . import registry
from .compat import reverse
from .settings import import_setting
class Run(models.Model):
user = models.F... |
""" Tests for overall io sub-package
"""
from dipy import io
from nose.tools import assert_false
def test_imports():
# Make sure io has not pulled in setup_module from dpy
assert_false(hasattr(io, 'setup_module'))
|
#!/usr/bin/python3
#running command: python ArpSpoofing2.py victimIP
import sys #for command line argument
import time
import os
import shutil
import tempfile
from random import randint
from scapy.all import *
from scapy.layers.inet import *
import scapy
import socket
def get_ip():
s = socket.socket(socket.AF_... |
from ..filter import Filter, Stream, Sequence, Any, Mapping
from typing import Callable
class MathFilter(Filter):
'''
Performs a give operation on keys of an item.
Inputs:
Single stream.
Outputs:
Single stream.
'''
def __init__(self, inputs: str, outputs: str, keys_operations... |
import sys
from task_list.console import Console
from task_list.app import TaskList
def main():
task_list = TaskList(Console(sys.stdin, sys.stdout))
task_list.run()
if __name__ == "__main__":
main()
|
import boto3
import decimal
import json
bucket = "dev-image-repo-bucket"
s3 = boto3.client("s3")
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return int(obj)
return super(DecimalEncoder, self).default(obj)
def list_obj(event, c... |
__all__ = ['NullHealther']
class NullHealther:
def ping(self):
pass
def cleanup(self):
pass
def healthy(self, key, ttl=60):
pass
def unhealthy(self, key):
pass
|
import multiprocessing
import requests
import bs4
import os
from .extractor.bing import BingExtractor
from .extractor.konachan import KonachanExtractor
from .extractor.wallpapercraft import WallpaperCraftExtractor
from .dowanloader.http import HttpDownloader
from .processor.common import Processor
processor = Process... |
import logging
from multiprocessing import Pool
from typing import Dict, List
from morpheus.api.endpoints.project_routes import ProjectsRoute, CommitsRoute
from morpheus.api.endpoints.methods_routes import MethodsInProjectRoute
from morpheus.api.endpoints.tests_routes import TestMethodsInCommitRoute
from morpheus.api.e... |
# MIT License
#
# Copyright (c) 2020 Gcom
#
# 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... |
# -*- coding: utf-8 -*-
# This file is part of Kaleidoscope.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... |
"""
.. See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
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.... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GAPS - A GPU Accelerated Parallel Sampler based on the affine invariant
ensemble sampler by Goodman & Weare. The pure Python equivalent is
`emcee` by Dan Foreman-Mackey and is available at http://dfm.io/emcee.
@author: Sebastian M. Gaebel
@email: sebastian.gaebel@lig... |
from decimal import InvalidOperation
from django import forms
from django.utils.translation import ugettext as _
from django_google_maps.widgets import GoogleMapsAddressWidget
from locations.models import Location, LocationCategory
class LocationSearchForm(forms.Form):
"""
A form to collect and validate loc... |
#! /usr/bin/env python
"""
.. module:: bug0
:platform: Unix
:synopsis: Python module for implementing the bug0 path planning algorithm
.. moduleauthor:: Omotoye Adekoya adekoyaomotoye@gmail.com
This node implements the bug0 path planning algorithm for moving a robot from its current
position to some target ... |
from typing import List
def minsubsequence(nums: List[int]) -> List[int]:
if len(nums) < 2:
return nums
nums = sorted(nums)
ans = []
for _ in range(len(nums)):
ans.append(nums.pop())
if sum(ans) > sum(nums):
return ans
if __name__ == '__main__':
... |
"""本モジュールの説明
画像処理に使用する種々の関数群
"""
import cv2
import numpy as np
import os.path
import sys
import time
from sklearn import preprocessing
from tqdm import tqdm
# グローバル変数
drawing = False
complete_region = False
ix, iy, box_width, box_height = -1, -1, 0, 0
box = [ix, iy, box_width, box_height]
def lo... |
import getpass
import logging
import requests
logger = logging.getLogger("zd_d_verifier")
FORMAT = '[%(asctime)s] %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)
ZENDESK_SITE = 'https://mangohealth.zendesk.com'
TICKET_STATUSES = ['open', 'solved', 'closed']
ROLES = ['end-user', 'agent', 'admin']
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class NSGeneratorLoss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, fake_p):
return F.binary_cross_entropy_with_logits(
fake_p, torch.ones_like(fake_p))
class DiscriminatorLoss(nn.Module):
... |
from fiber.condition.fact.fact import _FactCondition
from fiber.database.table import (
d_pers,
fact,
fd_diag,
)
class Diagnosis(_FactCondition):
"""
Diagnosis are parts of the building-blocks of FIBER. In order to define
Cohorts, Diagnosis fetch patients that were diagnosed as having 'X'.
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('farms', '0018_copy_waterregister_date_to_datetime'),
]
operations = [
... |
from pathlib import Path
import time
from mindmap.model.Note import Note
from mindmap.utils import Utils
from mindmap.utils.NoteEditor import NoteEditor
from mindmap.utils.ScopeManager import ScopeManager
from mindmap.utils.Utils import logger
DEFAULT_HOME = f"{Path.home()}/mindmap/" # todo
class Mindmap(object):... |
#%%
import random
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.keras as keras
import seaborn as sns
import timeit
import numpy as np
import pickle
from sklearn.model_selection import StratifiedKFold
from math import log2, ceil
import sys
sys.path.append("../src_mapping_3/")
from lifelon... |
"""Custom errors."""
class ConfigurationError(Exception):
"""
This exception is raised if the user hasn't properly configured
Flask-Simple.
"""
pass
|
# $Id: helpers.py 081917d30609 2010-03-05 mtnyogi $
# coding=utf-8
#
# Copyright © 2007-2008 Bruce Frederiksen
#
# 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, includi... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
SQL_DATABASE_URL = "mysql+pymysql://test:Test123456!@127.0.0.1:3306/pollings"
engine = create_engine(SQL_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=F... |
import math
import time
import cPickle
import argparse
import matplotlib.pyplot as plt
import numpy as np
def check_prime(N):
sqrtN = math.sqrt(N)
Nf = float(N)
for i in xrange(2, int(sqrtN) + 1):
if (Nf / i).is_integer():
return False
return True
if __name__ == "__main__":
p... |
# Copyright (C) 2019 Project AGI
#
# 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 writi... |
"""Tests for module utils for timing and parallel computation """
# Author: Remi Flamary <remi.flamary@unice.fr>
#
# License: MIT License
import ot
import numpy as np
import sys
import pytest
def test_proj_simplex(nx):
n = 10
rng = np.random.RandomState(0)
# test on matrix when projection is done on ax... |
import sys
sys.path.append('../python_packages_static')
import pandas as pd
import os
import numpy as np
import flopy as fp
import flopy.utils as fu
# define a MF6 capable T calculation function (thanks Andy!)
def get_transmissivities(heads, hk, top, botm,
r=None, c=None, x=None, y=None, model... |
import json
import config
from source.requestUtil import requestGet
from source.readable import createReadableDict
from source.replicas import createDict, findExactReplicas, findSimilar
from source.fileWriter import writeToJSONFile, writeToTXT
def driver():
# Perform the GET operation on the link
# and recei... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
first = raw_input()
second = raw_input()
dist = np.empty(shape=(len(first) + 1, len(second) + 1), dtype=np.int32)
dist[:, 0] = range(0, dist.shape[0])
dist[0, :] = range(0, dist.shape[1])
for j in range(1, dist.shape[1]):
for i in range(1, dist.s... |
import json
from common.logger import get_logger
from common.utils import generate_lambda_response, validate_dict
from payments.application.dapp_order_manager import OrderManager
from common.constant import StatusCode
logger = get_logger(__name__)
def initiate(event, context):
logger.info("Received request for ... |
#!/usr/bin/env python
###############################################################################
# Copyright (C) 1994 - 2007, Performance Dynamics Company #
# #
# This software is licensed as described in the file ... |
import requests
from Services.ApiAddressService import ApiAddressService
from Services.StorageCookieService import StorageCookieService
class FriendShipApiService(object):
def __init__(self):
self.apiaddress = ApiAddressService()
self.storagecookie = StorageCookieService()
def Mine(self):
... |
import sys
import os
import json
import csv
from django.core.management.base import BaseCommand, CommandError
from django.contrib.gis.utils import LayerMapping
from django.contrib.gis.gdal import DataSource
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.geos import MultiPolygon, Point
from dja... |
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
from index import app
if __name__ == "__main__":
app.run()
|
"""
@file
@brief Command line about validation of prediction runtime.
"""
import os
from logging import getLogger
import warnings
from multiprocessing import Pool
from pandas import DataFrame
from sklearn.exceptions import ConvergenceWarning
def validate_runtime(verbose=1, opset_min=9, opset_max="",
... |
from secret import flag
def nk2n(nk):
l = len(nk)
if l==1:
return nk[0]
elif l==2:
i,j = nk
return ((i+j)*(i+j+1))//2 +j
return nk2n([nk2n(nk[:l-l//2]), nk2n(nk[l-l//2:])])
print(nk2n(flag))
#25977495199845200181935389149727440287807670673732106338434418929108307497492776311825... |
"""
The MIT License (MIT)
Copyright (c) 2021 an-dyy
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, merg... |
from app.libs.enums import PendingStatus
from flask_login import current_user
class DriftCollection(object):
def __init__(self, drifts, current_user_id):
self.data = []
self.__parse(drifts, current_user_id)
def __parse(self, drifts, current_user_id):
for drift in drifts:
tem... |
# from flask import current_app
from datetime import datetime
from flask_restful import fields, marshal
from flask import current_app
from werkzeug.security import generate_password_hash, check_password_hash
# local import
from app.database_config import connection
class Users():
""" user class """
def __... |
#!/usr/bin/env python
from __future__ import with_statement
from __future__ import print_function
import os
import cgitb
import json
import redis
from common import authorize
import urlparse
from common import CloudCredentials
from common.constants import get_cloudsim_config
cgitb.enable()
def log(msg):
red =... |
#python file
import argparse
import nltk
from nltk import ne_chunk
from nltk.corpus import stopwords
from nltk.corpus import wordnet
from nltk.tokenize import sent_tokenize,word_tokenize
from nltk import flatten
import os
import re
import ntpath
import ssl
import glob
nltk.download('averaged_perceptron_tagger')
nltk.d... |
import json, logging, pytest
from cryptoadvance.specter.specter import get_rpc, Specter
from cryptoadvance.specter.helpers import alias
from cryptoadvance.specter.rpc import BitcoinRPC
def test_alias():
assert alias("wurst 1") == "wurst_1"
assert alias("wurst_1") == "wurst_1"
assert alias("Wurst$ 1") == "... |
# import BluetoothSocket as bs
import bluetooth
import ConnectionAutomatize
import os
import OBD2Port
import bluetoothWatchDog
if os.system("hciconfig hci0 piscan") == -1:
print("Run it as root!")
exit
def serverConnection():
server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
# port = bluetooth.... |
import SUDP
import time
sock = SUDP.sUDPsocket()
sock.bind (('192.168.0.183',9090))
while True:
msg , address = sock.recvfrom(1024)
sock.retimeout = 1 #any timeout
print(sock.sendto(("lol").encode("utf-8"), address)) |
import os
import sys
import qm3.mol
import qm3.problem
import qm3.engines.lio
import qm3.maths.matrix
try:
import cStringIO as io
except:
import io
os.environ["LIOHOME"] = "./bin/slio"
os.environ["OMP_NUM_THREADS"] = "2"
os.environ["QM3_LIBLIO"] = "./bin/lio.so"
class my_eng( qm3.problem.template ):
def __... |
# Coded by Sebastian Gonzalez Ramirez
# email to software@sgonzalezr.com
from selenium import webdriver
import time
import sys
import os
import sys
import inspect
import random
import botconfig as cfg
class SpotifyBot():
def __init__(self):
print("Starting SpotifyBot.")
print("Remember, to cance... |
special.pbvv(v,x) |
"""
Copyright 2017-present, Airbnb Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, sof... |
#!/usr/local/bin/python
x = [100, 8, 6, -3, 8, -87, 12, 67, -3, 0, -7, -29]
print(''.join([chr(x) for x in [i+100 for i in [0, 8, 14, 11, 19, -68, -56, 11, 8, 8, 1, -28]][::-1]]))
|
from setuptools import setup
import re
with open('stickybar.py') as f:
version = next(filter(None, map(re.compile("^version = '([a-zA-Z0-9.]+)'$").match, f))).group(1)
tests_require = ['pyte']
setup(
name = 'stickybar',
version = version,
description = 'Stdout wrapper that prints a status bar below the curso... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.