content stringlengths 5 1.05M |
|---|
import re
def count_smileys(arr):
faces = ''.join(arr)
smiley = re.findall('[:;][-~]?[D)]', faces)
return len(smiley)
def count_smileys2(arr):
smileys = [":)", ";)", ":~)", ";~)", ":-)", ";-)", ":D", ";D", ":~D", ";~D", ":-D", ";-D"]
faces = 0
if not arr:
return 0
for face in arr:
... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
def vol_plot(x):
import os #TO control directories
import nibabel as nib # read and save medical images
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import plotly
import plotly.express as px
from ipywidgets import interact, interactive,... |
# Generated by Django 3.0.7 on 2020-07-05 01:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0014_auto_20200705_0118'),
]
operations = [
migrations.DeleteModel(
name='Family',
),
]
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from django import forms
from django.conf import settings
try:
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
except ImportError:
from django.contrib.contenttypes.generic import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from ... |
import string
from pywebapp import http_helper
from pywebapp.errors import PyWebAppResponseHeadersAlreadySentError
class WebResponse(object):
def __init__(self, start_fn, request=None):
self._start_fn = start_fn
self.request = request
self.status_code = http_helper.status['OK']
self.headers = {'Cont... |
from getch import getch
import os
class TextUI:
def displayWelcome(self):
print """ ::: === === :::==== :::====
::: === === ::: === ::: ===
=== === === ======== =======
=========== === === === ===
==== ==== === === === ===
"""
def promptForPlayers(self):
num = 0
... |
# ../managers/operatorsSignaling/reconstructer.py
import efel
#from quantities import mV
class Reconstructer(object):
"""
**Available methods:**
+-------------------------------------------------+--------------------+
| Method name | Method type |
+------... |
# coding: utf-8
# /*##########################################################################
# Copyright (C) 2016-2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to dea... |
from . import (
secp256k1,
sha256,
utils,
merkle_part,
iavl_merkle_path,
multi_store,
tm_signature
)
|
# Inference code for the CVAE driver sensor model. Code is adapted from: https://github.com/sisl/EvidentialSparsification.
import os
import time
seed = 123
import numpy as np
np.random.seed(seed)
from matplotlib import pyplot as plt
import torch
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cud... |
#!/usr/bin/env python3
"""
Library providing convenient classes and methods for writing data to files.
"""
import sys
import json
import pickle
try:
import yaml
except ImportError:
yaml = None
class Serializer(object):
ext = ""
woptions = ""
roptions = ""
@classmethod
def marshal(cls, in... |
import os
import shutil
def ensure_directory(directory):
if not os.path.exists(directory):
os.makedirs(directory)
def ensure_directory_hard(directory):
if os.path.exists(directory):
shutil.rmtree(directory)
os.mkdir(directory)
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import six
import hashlib
import pyscrypt
import base58
import hashlib
#from Crypto.Hash import RIPEMD
import libnacl.public
import libnacl.secret
# The public key used for verifying peer tokens which are the id... |
import pytest
xfail = pytest.mark.xfail(strict=True)
import numpy as np
from skroute.datasets import load_barcelona
from skroute.metaheuristics.som._utils_som import *
from skroute.metaheuristics.som import SOM
from skroute._utils._utils import _cost
from skroute.preprocessing import dfcolumn_to_dict
df_barcelona = ... |
import datetime
from itertools import count
import random
import string
import time
import names
from .. import models
__all__ = ['fixture_random']
ORDINARY_USERID = "42"
ADMIN_USERID = "666"
def date_to_timestamp(d) :
return int(time.mktime(d.timetuple()))
def random_text(n=100):
return ''.join(random.ch... |
""" Holds all statistics for some question and manages them.
One question might have multiple statistics (for example time, correctness...).
"""
from typing import Dict
from .abstract_statistics import AbstractStatistcs
from .statistics_builder import StatisticsBuilder
class StatisticsHolder:
def __init__(se... |
import json
import pytest
from aizynthfinder.chem import TreeMolecule, Molecule, Reaction
from aizynthfinder.analysis import TreeAnalysis, ReactionTree, RouteCollection
@pytest.fixture
def setup_complete_tree(fresh_tree, mocker, mock_stock):
tree = fresh_tree
state1 = mocker.MagicMock()
state1.mols = [... |
n = int(input())
X = list(map(int, input().split()))
F = list(map(int, input().split()))
S = [x for i, x in enumerate(X) for f in range(F[i])]
S.sort()
n = len(S)
assert sum(F) == n, "The number of elements must equal the total frequency."
def median(n, X):
if n % 2 == 0:
numerator = float(X[int(n /... |
# Generated by Django 3.2.5 on 2021-07-31 15:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('church', '0012_introduction_copywrite'),
]
operations = [
migrations.CreateModel(
name='YoutubeMass',
fields=[
... |
#!/usr/bin/env python
import time, sys, random
def single_loading():
print("Loading...")
for i in range(0, 100):
time.sleep(0.01)
width = (i + 1) // 4
bar = "[" + "#" * width + " " * (25 - width) + "]"
sys.stdout.write(u"\u001b[1000D" + bar)
sys.stdout.flush()
prin... |
from __future__ import print_function
import tweepy
import json
import pprint
FIRSTJAN2017 = 1483209000
# Using twitter account hd_irrigation01
# Using keys from app https://apps.twitter.com/app/13837356/keys
# Email for account hrishikesh.date+hd_irrigation01@gmail.com
with open('./twitterconfig.json', 'r') as file:... |
class Person:
# constructor
def __init__(self, real_name):
self.real_name = real_name
def report(self):
print("I'm {}".format(self.real_name))
class Agent(Person): # Agent inherits Person class
# class object attribute
planet = "Earth"
def __init__(self, real_name, eye_color... |
'''
Description: Maps exercise logs to exercise/feeling values using embeddings.
Author: Mandy korpusik
Date: 8/5/2020
'''
import json
import nnets
import numpy as np
from nltk.stem import PorterStemmer
from sklearn.metrics.pairwise import cosine_similarity
def get_x_y(data):
'''Loads exercise/feeling tokens an... |
import os
import requests
import xml.etree.ElementTree as ET
import webbrowser
# EDGAR_BASE_URL = "https://www.sec.gov"
# EDGAR_BROWSE_URL = "/cgi-bin/browse-edgar?action=getcompany"
# EDGAR_ARCHIVE_URL = "/Archives/edgar/data/"
# EDGAR_API_BASE = "https://data.sec.gov/"
class edgarFiler():
"""Accesses data from... |
from .utils.data_processing import DataProcessing
from .network.network_architecture import ModelArchitecture
from .core.test_worker import TestWorker
from .core.train_worker import TrainWorker
from .utils.helpers.io_helper import IOHelper
from .utils.helpers.json_helper import JsonHelper |
import json
from datetime import datetime
from inflection import tableize
from ..builder import QueryBuilder
from ..collection import Collection
from ..connections import ConnectionFactory
from ..grammar import MySQLGrammar
class BoolCast:
def get(self, value):
return bool(value)
class JsonCast:
d... |
#!/usr/bin/env python
'''
Created on Sep 2, 2020
@author: gsnyder
Parse the Synopsys Detect log to get the status.json file emitted and use status.json to monitor
the scans (codelocations) and wait for the scan processing to complete
'''
import argparse
import arrow
import json
import logging
import re
import sys
i... |
from time import sleep
print('==== CALCULANDO O VALOR DAS VIAGENS ====')
km = float(input('Digite em KM a distancia da viagem: '))
print('CALCULANDO O VALOR COM BASE NA DISTANCIA ....')
sleep(2)
if km <= 200:
print('O valor da viagem é de R$ {:.2f}'.format(km*0.50))
else:
print('O valor da viagem é de R$ {:.2f... |
from django.apps import AppConfig
class ButtonsConfig(AppConfig):
name = 'apps.buttons'
verbose_name = 'Клавиши'
|
import FWCore.ParameterSet.Config as cms
#
# This cfi should be included to parse the muon standalone XML geometry.
#
XMLIdealGeometryESSource = cms.ESSource("XMLIdealGeometryESSource",
geomXMLFiles = cms.vstring('Geometry/CMSCommonData/data/normal/cmsextent.xml',
'Geometry/CMSCommonData/data/cms.xml',
... |
#!/usr/bin/env python
# -*- coding=utf-8 -*-
from keras import Input
from keras.layers import LSTM, Dense, Dropout, Embedding
from keras.layers.merge import add
from keras.models import Model
from keras.preprocessing.sequence import pad_sequences
from gen_train_captions import EOS_TOKEN, SOS_TOKEN
import numpy as np
... |
import os
import json
import sap.lambda_ as lambda_
import sap.sns as sns
from aws_cdk import core
class CdkSAPBlogSAPStack(core.Stack):
account = None
region = None
thing_name = None
def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)... |
"""
Usage: cache_aws_security_data.py [options]
Options:
--profile PROFILE profile to use for AWS access
--loglevel LEVEL logging level
[default: INFO]
"""
import batch
from db_models import ProjectModel
import importlib.util
import importlib
import platform
import urllib3
import ... |
"""HTML shenanigans.
Format:
!x:word1|word2
"""
s = input('?:')
ts = []
for t in s.split(' '):
if t[0] == '!':
x, ws = t.split(':')
x = float(x[1:])
w0, w1 = ws.split('|')
# Format
ts.append('<span class="wordswap" word1="%s" word2="%s" threshold="%f"></span>' % (w0, w1, ... |
class Solution:
def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int:
return ceil(log(buckets) / log(minutesToTest // minutesToDie + 1))
|
# Imports python modules
import torch
from torchvision import models
def get_arch(arch: str):
if arch == 'resnet18':
model = models.resnet18(pretrained=True)
if arch == 'alexnet':
model = models.alexnet(pretrained=True)
if arch == 'vgg13':
model = models.vgg13(pretrained=True)
... |
#!/usr/bin/env python3
# Copyright 2022 Canonical Ltd.
# See LICENSE file for licensing details.
"""Deploy and manage the Cinder CSI plugin for K8s on OpenStack."""
import logging
from pathlib import Path
from charms.openstack_cloud_controller_operator.v0.cloud_config import (
CloudConfigRequires,
)
from charms.o... |
from dataclasses import dataclass
@dataclass
class Result:
"""
Result of a trace
"""
# True if an error occurred during the execution of a function, false otherwise
error: bool
# Error type, e.g TypeError, ZeroDivisionError...
error_type: str
# True if an TimeOutError occurred during ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
http.manage
~~~~~~~~~~~
Production management script of HTTP Request & Response service
:copyright: (c) 2011 - 2013 by Alexandr Lispython (alex@obout.ru).
:license: BSD, see LICENSE for more details.
:github: http://github.com/Lispython/httphq
"""
import time
impor... |
"""
-- ASDL's 5 builtin types are:
-- identifier, int, string, object, constant
module Python
{
mod = Module(stmt* body, type_ignore *type_ignores)
| Interactive(stmt* body)
| Expression(expr body)
| FunctionType(expr* argtypes, expr returns)
-- not really an actual node but useful... |
"""
GravMag: Generate synthetic gravity data on an irregular grid
"""
import fatiando as ft
from fatiando import logger, mesher, gridder, gravmag
from fatiando.vis import mpl
log = logger.get()
log.info(logger.header())
log.info(__doc__)
prisms = [mesher.Prism(-2000, 2000, -2000, 2000, 0, 2000, {'density':1000})]
xp,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
main
----------------------------------
An entry point to using the ingestion package
"""
import sys
import getopt
import os
from ingestion.conversion_factory import ConversionFactory
CSV_CONVERSION = 'CSVConversion'
PROJECT_ROOT = os.path.abspath(os.path.dirname(_... |
import numpy as np
import matplotlib.pyplot as py
class svm():
def __init__(self):
self.w=[]
self.b=[]
starting_w=1
starting_b=10
self.w=[starting_w,starting_w,starting_b] #some implementations have rolled bias together to simplify calculations.
self.C = 1.0
def fit (self,data,labels... |
from scipy.special import gammaln
from numpy import log, exp, sqrt
import numpy as np
import scipy.stats
class GrowthRateConversion(object):
def __init__(self):
self.lam, self.k = self.get_params(5.0, 1.9)
def get_params(self, mu, sigma):
# we know that mu = lambda * Gamma(1+1/k)
# and... |
import collections.abc
import weakref
import teek
from teek._structures import ConfigDict
from teek._tcl_calls import make_thread_safe
from teek._widgets.base import ChildMixin, Widget
class TabConfigDict(ConfigDict):
def __init__(self, tab):
self._tab = tab
super().__init__()
self._type... |
# coding=utf-8
# ----------------
# author: weiyu
# create_time : 5/2/2021
# description :
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# 如果根节点和p,q的差相乘是正数,说明这两个差值要么都是正数要么都是负数,也就是说
# 他们肯定都位于根节点的同一侧,就继续往下找
while (root.val - p.... |
import sys
sys.path.append('')
from src.parser.queryParser import Parser
from src.engine.label import Label
from src.engine.property import Property
from src.engine.property_type import PropertyType
from src.engine.graph_engine import GraphEngine
from src.parser.relationCreator import RelationCreator
from src.config im... |
#!/usr/bin/env python
#
# Author: Prem Karat (pkarat@mvista.com)
# License: MIT
# (C) Copyright MontaVista Software, LLC 2016-2019. All rights reserved.
from apis.utils import check_kernel_configs
from apis.utils import run_cmd
import re
import sys
import glob
def pytest_configure(config):
"""Provide additional... |
import click
import sys
from obs.libs import auth
from obs.cli.storage import bucket
from obs.cli.storage import gmt
from obs.libs import utils
from obs.libs import config
def warn_inexsit_config():
msg = (
f"Configuration file not available.\n"
f"Consider running 'obs --configure' to create one"... |
from .message import Message
from .notify import QueueNotify
from http.server import HTTPServer,BaseHTTPRequestHandler
from threading import Thread
from queue import Queue
from time import sleep
class cServerHandler(BaseHTTPRequestHandler, QueueNotify):
def rename_page(self):
res = """
<script... |
# We will need the following module to generate randomized lost packets
import random
from socket import *
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket
serverSocket.bind(('', 12000))
while True:
... |
""""""
# -*- coding: utf-8 -*-
# date: 2021
# author: AllChooseC
import os
import numpy as np
from tensorboardX import SummaryWriter
import torch
from tqdm import tqdm
from utils import EarlyStopping, class_penalty
class_distribution = [59.68, 8.68, 28.55, 3.08]
# 2017
class_distribution = [59.22, 8.65, 28.80, 3.3... |
from detoxify import Detoxify
detox_model = None
def generate_model():
global detox_model
detox_model = Detoxify('original')
def predict(inputmessage):
if detox_model is None:
generate_model()
results = detox_model.predict(inputmessage)
return results
if __name__ == '__main__':
... |
from ._base import Plugin, get_implementation # noqa
|
import numpy as np
import pytest
import treetensor.numpy as tnp
# noinspection DuplicatedCode
@pytest.mark.unittest
class TestNumpyFuncs:
_DEMO_1 = tnp.ndarray({
'a': np.array([[1, 2, 3], [5, 6, 7]]),
'b': np.array([1, 3, 5, 7]),
'x': {
'c': np.array([3, 5, 7]),
'd... |
# Lexical Addressing "X", because as of yet, we only do a very particular kind of addressing. Namely: we refer to a
# scope by "frames up", but we do not address within the scope (e.g.: memory-offset, or var-count-offset)
from utils import pmts
from dsn.form_analysis.free_variables import free_variables
from dsn.form... |
#You are given the following information, but you may prefer to do some research for yourself.
#1 Jan 1900 was a Monday.
#Thirty days has September,
#April, June and November.
#All the rest have thirty-one,
#Saving February alone,
#Which has twenty-eight, rain or shine.
#And on leap years, twenty-nine.
#A leap year oc... |
import urllib.parse
import socket
import re
from selectors import *
seen_urls = set('/')
urls_todo = set('/')
selector = DefaultSelector()
stopped = False
class Fetcher():
def __init__(self,url):
self.url = url
self.response = b''
self.sock = None
def fetch(self):
self.sock... |
# Copyright 2019,2020,2021 Sony Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
import re
from routersploit import (
exploits,
print_success,
print_error,
print_table,
sanitize_url,
http_request,
mute,
)
class Exploit(exploits.Exploit):
"""
Exploit implementation for DSL-2750B Information Disclosure vulnerability.
If the target is vulnerable it allows to ... |
from django.db import models
# Create your models here.
class User(models.Model):
SEX = (
('M','男性'),
('F','女性'),
('S','保密'),
)
nickname = models.CharField(max_length=32,unique=True)
password = models.CharField(max_length=128)
age = models.IntegerField(default=18)
sex... |
for i in range(5):
with open('file.txt', 'a') as file:
file.write('input\n') |
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from core import views
from rest_framework_simplejwt import views as jwt_views
urlpatterns = [
path('teams/', views.TeamList.as_view()),
path('teams/<int:pk>/', views.TeamDetail.as_view()),
path('token/', jwt_views.T... |
import tensorflow as tf
# Define model as a policy network
class DynamicsModel():
def __init__(self):
def train(self):
|
import logging
import os
config_text = 'site_name: My Docs\n'
index_text = """
#LARGE(This is STATICGENNAN layout)
#MEDI(Created by Nandha, Ali, Abishekh)
#NORM(Aim to build a energy efficient website)
"""
log = logging.getLogger(__name__)
def new(output_dir):
docs_dir = os.path.join(output_dir, 'd... |
# coding: utf-8
"""
.. module:: fler_core.training_df.py
basic class for a training database
"""
__author__ = "Axel Marchand"
# standard
import asyncio
from typing import Union, List, Dict
import pandas as pd
import os
import numpy as np
import logzero
from sklearn.externals import joblib
# custom
from fler_utils.com... |
import os
import numpy as np
from flopy.utils.lgrutil import Lgr
def test_lgrutil():
nlayp = 5
nrowp = 5
ncolp = 5
delrp = 100.0
delcp = 100.0
topp = 100.0
botmp = [-100, -200, -300, -400, -500]
idomainp = np.ones((nlayp, nrowp, ncolp), dtype=int)
idomainp[0:2, 1:4, 1:4] = 0
nc... |
import sys
import logging
import traceback
import multiprocessing as mp
import atexit
class ExceptionWrapper(object):
r"""Wraps an exception plus traceback to communicate across threads"""
def __init__(self, exc_info):
self.exc_type = exc_info[0]
self.exc_msg = "".join(traceback.format_except... |
"""Auto-generated file, do not edit by hand. JM metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_JM = PhoneMetadata(id='JM', country_code=1, international_prefix='011',
general_desc=PhoneNumberDesc(national_number_pattern='(?:[58]\\d\\d|658|900)\\d{7}', possible_l... |
# https://stackoverflow.com/questions/34518656/how-to-interpret-loss-and-accuracy-for-a-machine-learning-model
from additional_models.data import read_csv_data, get_samples
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Flatten, Lambda
from keras.layers import ELU
from keras.layers.c... |
def headleft():
i01.setHeadSpeed(1.0,1.0)
i01.head.rothead.attach()
i01.head.rothead.moveTo(180)
sleep(1)
i01.head.rothead.detach()
|
#!/usr/bin/python
######################################################
# ****************************************
# Neural Network Color Classification \
# Using Yocto & Numpy /
# Running KnNN Network \
# /
# Alejandro Enedino Herna... |
"""
Creates a MobileNetV2 Model as defined in:
Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen. (2018).
MobileNetV2: Inverted Residuals and Linear Bottlenecks
arXiv preprint arXiv:1801.04381.
import from https://github.com/tonylins/pytorch-mobilenet-v2
"""
import torch.nn as nn
import ma... |
import csv, json, requests, datetime, sys
try:
import input
key = input.key
org_name = input.org_name
net_name = input.net_name
except ImportError:
print('Looks like there was an error inputting your variables. Please enter the correct information now: ')
key = str(raw_input('Enter your Meraki ... |
import logging
import sys
import time
import tkinter as tk
import traceback
from tkinter import PhotoImage, ttk
from multiprocessing import Queue
from modlunky2.constants import BASE_DIR, IS_EXE
from modlunky2.updater import self_update
from modlunky2.version import current_version, latest_version
from modlunky2.confi... |
# Import required libraries
import pygame
import os
from os.path import dirname, abspath
from Game import Game
imgs_path = dirname(dirname(abspath(__file__)))
GROUND_ASSET = pygame.transform.scale2x(pygame.image.load(os.path.join(imgs_path, "imgs", "ground.png"))) # Load in required images and double their size
# A... |
import pytest
import unittest
class MyTest(unittest.TestCase):
@pytest.fixture(autouse=True)
def initdir(self, tmpdir):
tmpdir.chdir() # change to pytest-provided temporary directory
tmpdir.join("samplefile.ini").write("# testdata")
def test_method(self):
with open("samplefile.ini") as f:
s = f.read()
... |
""" Cisco_IOS_XR_tunnel_nve_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR tunnel\-nve package operational data.
This module contains definitions
for the following management objects\:
nve\: NVE operational data
Copyright (c) 2013\-2016 by Cisco Systems, Inc.
All rights reserved.
""... |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os.path as osp
import mmcv
import torch
from mmcv.runner import CheckpointLoader
def convert_stdc(ckpt, stdc_type):
new_state_dict = {}
if stdc_type == 'STDC1':
stage_lst = ['0', '1', '2.0', '2.1', '3.0', '3.1', '4.0', '4.1']
... |
class Test:
desc = "this is a test class"
def __init__(self, name):
self.name = name
def show(self):
print self.name
if (__name__ == "__main__"):
t = Test("test name")
print t
print t.desc
t.show()
|
# Copyright (c) 2016 PaddlePaddle Authors. 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 applic... |
"""
Copyright (C) 2019-2020 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
This module provides the base class for every Tool. A tool is anything that a Recipe
might depend on from the system environment.
The base class provides the logic for detecting tools.
There is work-in-progress logic to [opt... |
from .client import Client # noqa: F401
from . import log # noqa: F401
from . import broker # noqa: F401
from . import codec # noqa: F401
from . import protocol # noqa: F401
from . import throttle # noqa: F401
from . import sequence # noqa: F401
from . import correlater # noqa: F401
from . import ratelimiter ... |
from .asistplanningagents import *
from .preemptive import *
from .selectivetriage import *
from .mixedtimestrategy import *
from .mixedproxstrategy import *
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# df.iloc[:,-8:]
def idx_to_case_xy(idx):
x=((idx/100).astype(int)/100*5).astype(int)
y=((idx-100*(idx/100).astype(int))/100*5).astype(int)
return x,y
# df['Answer.selected_idx']
# df['Input.ref_idx']
X=np.lo... |
import kopf
def test_nothing(invoke, real_run):
result = invoke(['run'])
assert result.exit_code == 0
registry = kopf.get_default_registry()
assert len(registry.resources) == 0
def test_one_file(invoke, real_run):
result = invoke(['run', 'handler1.py'])
assert result.exit_code == 0
reg... |
import re
class TxtParser(object):
"""
Class to apply Czech typography rules to input text.
Most of regular expressions are from Texy!
http://github.com/dg/texy/blob/master/Texy/modules/TexyTypographyModule.php
"""
text = ''
positions = {}
extracted = {}
def __init__(self, text... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import math
from .blocks import ConvBnActivation3D, DecoderBlock3D, EncoderBlock3D, init_weights
class UNet(nn.Module):
def __init__(self, filters: list, in_channels: int = 1, n_classes: int = 13, residual: bool = True, bn: bool ... |
#UNION
n_english = int(input())
english_student = input().split()
n_french = int (input())
french_student = input().split()
set_english = set(english_student)
set_french = set(french_student)
one_sub = set_english.union(set_french)
output = len(one_sub)
print (output) |
import numpy as np
from scipy.interpolate import splprep, splev
import matplotlib.pyplot as plt
class paths:
def __init__(self,points = None):
self.spline = None
self.resolution = 100
if points != None:
self.set_points(points)
def set_points(self,points):
self.point_array = points
self.spline, u = spl... |
#!/usr/bin/env python
# Copyright (c) 2010 Rosen Diankov (rosen.diankov@gmail.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... |
#winVersion.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2006-2013 NV Access Limited
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
import sys
import winUser
winVersion=sys.getwindowsversion()
winVersionText="{v.major}.{v.minor}.{v.build}".fo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 26 14:56:33 2019
@author: JoeCalverley
"""
import numpy as np
import math
import scipy.stats as sk
import matplotlib.pyplot as plt
def choose_b(J_est):
# Input is the array of current estimates of means
b = J_est.index(min(J_est))
#Fun... |
'''
Created on 8 de set de 2020
@author: michel
'''
from pymongo.mongo_client import MongoClient
from helpers import conf_reader
class mongo_con:
def connect_db(self):
c_reader = conf_reader.conf_reader('../configuration.cfg')
host = c_reader.getConf('general', 'host')
method = c_reader.... |
# Copyright (c) 2015 OpenStack Foundation
# 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 ... |
from telethon.errors import (UserIdInvalidError, UserAdminInvalidError,
ChatAdminRequiredError, BadRequestError)
from telethon.tl.functions.channels import EditBannedRequest
from ..help import add_help_item
from userbot import BOTLOG, BOTLOG_CHATID, is_mongo_alive, is_redis_alive
from user... |
# coding: utf-8
from enum import Enum
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
from bitmovin_api_sdk.models.h264_per_title_configuration import H264PerTitleConfiguration
from bitmovin_api_sdk.models.h265_per_title_configuration import H265PerTitleConfiguration... |
"""
Common resource for bladder annotation terms.
"""
# convention: preferred name, preferred id, followed by any other ids and alternative names
bladder_terms = [
("urinary bladder", "FMA:15900", "UBERON:0001255"),
("neck of urinary bladder", "FMA:15912", "UBERON:0001258"),
("Dome of the Bladder", "ILX:07... |
import os
import subprocess
import unittest
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
class CodeStyleTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
if hasattr(cls, 'root_path'):
return
try:
root_path = os.p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.