content stringlengths 5 1.05M |
|---|
import datetime
from weunion.models import User, Town
from news.models import News
from petitions.models import Petitions
from defects.models import Issues
from polls.models import Poll
def city_stats():
users = []
for town in Town.objects.all():
count = User.objects.filter(towns=town).count()
... |
# -*- coding: utf-8 -*-
"""
tests.test_api
~~~~~~~~~~~~~~
Test API
:author: Dave Caraway
:copyright: © 2014-2015, Fog Mine, LLC
templated from https://github.com/ryanolson/cookiecutter-webapp
"""
import pytest
from flask import url_for
from flask_jwt import generate_token
from tests.factories... |
#coding:utf-8
#
# id: bugs.core_0198
# title: wrong order by in table join storedproc
# decription:
# tracker_id: CORE-0198
# min_versions: ['2.5.0']
# versions: 2.5
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
# version: 2.5
# resources: None
subs... |
#print the following lines
print "Mary had a little lamb."
print "Its fleece was white as %s." % 'snow'
print "And Everywhere that Mary went."
#print 10 times the '.' character
print "." * 10 #What'd that do?
#Variable assignment to each letter of the word Cheeseburger
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 ... |
from ...models.user import User
from ...models.role import Role
from werkzeug.security import generate_password_hash
import random
import string
import smtplib
from email.message import EmailMessage
from os import getenv
def user_found(email: str = None, password: str = None) -> bool:
user_exist = User().check_cre... |
#! python3
import re
from math import sqrt
from typing import Union, Optional
import language_check
import constants
lt: language_check.LanguageTool = language_check.LanguageTool('en-US')
def grammar_check(text: str) -> Union[str, bool]:
text = language_check.correct(text, lt.check(text))
if len(lt.check(... |
import numpy as np
import math
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
import pickle
from lib.model import *
from lib.zfilter import ZFilter
from lib.util import *
from lib.ppo import ppo_step
from lib.data import *
def gail_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-02-25 16:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tests', '0003_IBAN'),
]
operations = [
migrations.RemoveField(
m... |
# BSD 3-Clause License
#
# Copyright (c) 2021., Redis Labs Modules
# All rights reserved.
#
import argparse
import os
from redis_benchmarks_specification.__cli__.args import spec_cli_args
from redis_benchmarks_specification.__cli__.cli import cli_command_logic
def test_run_local_command_logic_oss_cluster():
#... |
import sys
from distutils.version import LooseVersion
from os.path import exists
from datetime import datetime
# pylint: disable=no-name-in-module
from Foundation import NSDate
# pylint: enable=no-name-in-module
from .helpers import (nudgelog,
download_apple_updates,
pendi... |
import glob
import json
import logging
import os
import sys
import time
import urllib
import click
import coloredlogs
import pandas as pd
from requests.exceptions import RequestException
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriv... |
# !/usr/bin/env python
# -- coding: utf-8 --
# @Author zengxiaohui
# Datatime:6/22/2021 12:51 PM
# @File:init_weight
import math
import torch
from torch import nn
def _init_weight(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_chan... |
#!/usr/bin/env python3
import re
import sys
# Parses a common style of defining enums in c, printing each with their hex value.
# With small modifications, this could be used to generate a function to convert status codes to strings.
#
# To parse the statuses in this repo
# cat src/include/com/amazonaws/kinesis/video... |
# -*-coding:utf-8-*-
import turtle
if __name__ == "__main__":
turtle.pensize(5)
turtle.speed(10)
turtle.fillcolor("red")
turtle.begin_fill()
turtle.circle(10,180)
turtle.circle(25,110)
turtle.left(50)
turtle.circle(60,45)
turtle.circle(20,170)
turtle.right(24)
turtle.fd(30)
... |
from .main import build_url, pandize, url_storage_function
wug_urls_book = pickle.load(open(os.path.join(mydir, 'cities_urls'), 'rb')) |
import matplotlib
# matplotlib.use('Qt5Agg')
from matplotlib import pyplot as plt
from matplotlib.dates import date2num, DateFormatter
import pandas as pd
import datetime as dt
# load data
file_loc = r'C:\Users\Ayush Jain\Documents\MSL\1255 - Assemblie 2 (MARSIM-2)\Data\1255-GLUEDASSEMBLIES-P3.xlsx'
df = pd.read_exc... |
print("Hello Alejandro! I was first") |
from collections import OrderedDict
from itertools import combinations
from cached_property import cached_property
from devito.exceptions import InvalidOperator
from devito.logger import warning
from devito.symbolics import retrieve_function_carriers, uxreplace
from devito.tools import (Bunch, DefaultOrderedDict, as_... |
import torch.nn as nn
import torch.optim as optim
import argparse
from Data.utils import read_data,get_structure,get_index,get_question_set,get_word_embeddings,get_prediction,get_f1,get_exact_match
from Data.dataloader import DataLoader
from Model.model import Model
def train(model,dataloader,lossFunction,optimizer... |
__version__ = "0.1.0"
from .grids import get_distances, get_metrics, get_coords, get_grid
from .utils import *
from . import pnplot
from . import utils
|
from knigavuhe import Client
cl = Client()
r = cl.search_books('Агата Кристи')
print(r)
print(r[0])
|
#!/usr/bin/env python
"""
Tool for combining and converting paths within catalog files
"""
import sys
import json
import argparse
from glob import glob
from pathlib import Path
def fail(message):
print(message)
sys.exit(1)
def build_catalog():
catalog_paths = []
for source_glob in CLI_ARGS.sources:... |
import RPi.GPIO as GPIO
import time
import threading
GPIO.setmode(GPIO.BOARD)
BB = 35
GPIO.setup(BB,GPIO.OUT)
def Scan():
time.sleep(1)
GPIO.output(BB,True)
time.sleep(1)
GPIO.output(BB,False)
code = input()
time.sleep(0.1)
return code
#def GetCode():
# code = input("Code:")
... |
# vim: set filencoding=utf8
"""
SnakePlan Project Models
@author: Mike Crute (mcrute@gmail.com)
@date: July 09, 2010
"""
# 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.apa... |
import logging
from eventlet.zipkin import api
__original_handle__ = logging.Logger.handle
def _patched_handle(self, record):
__original_handle__(self, record)
api.put_annotation(record.getMessage())
def patch():
logging.Logger.handle = _patched_handle
def unpatch():
logging.Logger.handle = __o... |
import os
import unittest
from persistence import Persistence
class TestPersistence(unittest.TestCase):
def setUp(self) -> None:
self.path = os.path.dirname(os.path.realpath(__file__))
self.name = "test_file"
self.persistence = Persistence(self.path, self.name)
def tearDown(self) -> ... |
import ftplib
from colorama import Fore, init # for fancy colors, nothing else
# init the console for colors (for Windows)
init()
# hostname or IP address of the FTP server
host = "192.168.1.113"
# username of the FTP server, root as default for linux
user = "test"
# port of FTP, aka 21
port = 21
def is_correct(passw... |
#!/usr/bin/env python
#
# Copyright 2018 Alexandru Catrina
#
# 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, modif... |
#
# Class Enhancement
from scipy.signal import lfilter
from spectrum import pmtm
from Universal import *
from VAD import *
class Enhancement:
def simplesubspec(self, signal, wlen, inc, NIS, a, b):
"""
simple spectrum subtraction
:param signal: noisy speech
:param wlen: window length
:param inc: frame shi... |
from bs4 import BeautifulSoup as web
from basic_parser import Parser
class Kommersant_parser(Parser):
def __init__(self):
super().__init__("http://www.kommersant.ru/RSS/news.xml")
self.encoding = "windows-1251"
self.site_encoding = "windows-1251"
def grab(self, url):
content =... |
#!/usr/bin/env python2
from argparse import ArgumentParser
from markovmusic.player import Player
parser = ArgumentParser()
parser.add_argument('--input',
default='input/bach', metavar='PATH',
help='MIDI input, either a single file or a directory')
parser.add_argument('--chain-l... |
import numpy as np
import pandas as pd
from .utils_complexity_embedding import complexity_embedding
def fisher_information(signal, delay=1, dimension=2):
"""**Fisher Information (FI)**
The Fisher information was introduced by R. A. Fisher in 1925, as a measure of "intrinsic
accuracy" in statistical esti... |
'''
黄金矿工
你要开发一座金矿,地质勘测学家已经探明了这座金矿中的资源分布,并用大小为 m * n 的网格 grid 进行了标注。
每个单元格中的整数就表示这一单元格中的黄金数量;如果该单元格是空的,那么就是 0。
为了使收益最大化,矿工需要按以下规则来开采黄金:
每当矿工进入一个单元,就会收集该单元格中的所有黄金。
矿工每次可以从当前位置向上下左右四个方向走。
每个单元格只能被开采(进入)一次。
不得开采(进入)黄金数目为 0 的单元格。
矿工可以从网格中 任意一个 有黄金的单元格出发或者是停止。
示例 1:
输入:grid = [[0,6,0],[5,8,7],[0,9,0]]
输出:24
解释:
[[0,6,... |
# Copyright 2020 Forschungszentrum Jülich GmbH and Aix-Marseille Université
# "Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; and to You under the Apache License, Version 2.0. "
import numpy as np
from mpi4py import MPI
import os
import time
import sys
def simulate... |
import os
os.system("pip3 install proxyscrape")
os.system("cp proxygrab.py proxygrab")
os.system("chmod+x proxygrab")
os.system("mv proxygrab /usr/local/bin/")
print("file copied")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from core_backend import context
from core_backend.service import handler
from core_backend.libs import token as tk
from core_backend.libs.exception import Error
from server.domain.models impor... |
from datetime import datetime, timedelta
from pytz.tzinfo import StaticTzInfo
class OffsetTime(StaticTzInfo):
"""
A dumb timezone based on offset such as +0530, -0600, etc.
"""
def __init__(self, offset):
hours = int(offset[:3])
minutes = int(offset[0] + offset[3:])
self._utco... |
"""Main module."""
import os
from datetime import datetime
import numpy as np
from scipy.optimize import least_squares
import click
import matplotlib.pyplot as plt
from geometric_calibration.reader import (
read_img_label_file,
read_projection_hnc,
read_projection_raw,
)
from geometric_calibration.utils ... |
from flask import request, make_response
import time
import datetime
import calendar
from user_agents import parse
import random
import string
import pymysql
import json
from ast import literal_eval
from secrets import secrets
sql_host = secrets['sql']['host']
sql_port = secrets['sql']['port']
sql_username = secrets[... |
# -*- coding: utf-8 -*-
import json
import scrapy
from locations.items import GeojsonPointItem
class SuperdrugSpider(scrapy.Spider):
name = "superdrug"
item_attributes = {"brand": "Superdrug", "brand_wikidata": "Q7643261"}
allowed_domains = ["superdrug.com"]
download_delay = 0.5
start_urls = ["... |
import numpy as np
from pandas import DataFrame, Series, period_range
import pandas._testing as tm
class TestAsFreq:
# TODO: de-duplicate/parametrize or move DataFrame test
def test_asfreq_ts(self):
index = period_range(freq="A", start="1/1/2001", end="12/31/2010")
ts = Series(np.random.randn... |
import os
import logging
import tempfile
import pytest
from nondjango.storages import utils, files, storages
logging.getLogger('boto3').setLevel(logging.ERROR)
logging.getLogger('botocore').setLevel(logging.ERROR)
logging.getLogger('s3transfer').setLevel(logging.ERROR)
def test_prepare_empty_path():
utils.prep... |
import json
import random
import requests
from config import DataSets
from locust import HttpUser, SequentialTaskSet, task, between, TaskSet
from locust.clients import HttpSession
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import server.tests.decode_fbs as decode_fbs
requests.packages.ur... |
#!/usr/bin/python
# -------------------------------------
# Description:
# Arguments:
# Author: Victor Marot (University of Bristol)
# -------------------------------------
import os
import traceback
import sys
import pandas as pd
import numpy as np
import re
import argparse
import tkinter |
# Copyright 2012-2020 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... |
import unittest
from timeseries.timeseries import TimeSeries
import numpy as np
class MyTest(unittest.TestCase):
def test_median(self):
self.assertEqual(TimeSeries([1,2,3],[2,2,2]).median(),2)
self.assertEqual(TimeSeries([1,2,3],[0,2,0]).median(),0)
self.assertEqual(TimeSeries([1,2,3,4],[0... |
# this is a file full with problems
# but ignored with:
# checker_ignore_this_file
import os
def doit():
foo = bar
def with_tab():
print "there's a tab"
|
import numpy as np
import pandas as pd
import pickle
import sys
import tensorflow as tf
import random
import math
import os
import statistics
import time
from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score, roc_auc_score, brier_score_loss, auc, precision_recall_curve, roc_curve
from sk... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import argparse
import gym
import torch
from pbrl.algorithms.td3 import TD3, Policy, Runner
from pbrl.env import DummyVecEnv
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--env', type=str, default='HalfCheetah-v3')
parser.add_argument('--filename', type=str, required=True)
parse... |
"""
Request context class.
A request context provides everything required by handlers and other parts
of the system to process a message.
"""
from typing import Mapping, Optional, Type
from ..core.profile import Profile, ProfileSession
from ..config.injector import Injector, InjectType
from ..config.injection_contex... |
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
import os.path as path
from .native_package_base import native_package_base
from bes.common.string_util import string_util
from bes.common.string_list_util import string_list_util
from bes.system.execute import execute
# FIXME:... |
# Copyright 2015 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 law or ag... |
#This file is part of numword. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
'''
numword for EU
'''
from .numword_base import NumWordBase
class NumWordEU(NumWordBase):
'''
NumWord EU
'''
def _set_high_numwords(self, high):
'''... |
from .meter import Meter
class Monitor(Meter):
def __init__(self, *args, **kwargs):
super(Monitor, self).__init__(*args, **kwargs)
def monitor(self, rms):
"""Extra monitor actions with RMS values
Custom trigger conditions and actions can be written here as long as
`action=No... |
# 2.6 last digit of sum of fibonacci
n = int(input())
if n <= 1:
print(n)
quit()
lesser = (n + 2) % 60
if lesser == 1:
print(0)
quit()
elif lesser == 0:
print(9)
quit()
def fibo(n):
a, b = 0, 1
for i in range(2, lesser + 1):
c = a + b
c = c % 10
... |
from uuid import uuid4
from django.utils.text import camel_case_to_spaces
from git_orm.models.fields import TextField, CreatedAtField, UpdatedAtField
from django.db.models.options import Options as DjangoOptions
class Options(DjangoOptions):
def __init__(self, meta, app_label=None):
super(Options, self... |
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
class MyForm(FlaskForm):
name = StringField('Enter Text:', validators=[DataRequired()]) |
#!/usr/bin/env python
__author__ = 'broecker'
import rospy
from sensor_msgs.msg import Joy
from geometry_msgs.msg import Twist
from std_srvs.srv import Empty
from sl_crazyflie_srvs.srv import ChangeTargetPose, ChangeTargetPoseRequest, StartWanding
import math
RATE = 50
TIME_OUT = 0.5
CONTROLLER_RP_THRESH = 0.2
UP = 12... |
"""
Modified by Hang Le
The original copyright is appended below
--
Copyright 2019 Kyoto University (Hirofumi Inaguma)
Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""
"""Transformer model for joint ASR and multilingual ST"""
import logging
import math
import numpy as np
import six
import time
from argpa... |
from . import check, v
assert v # Silence pyflakes.
def test_old_format_string(v):
v.scan("'%(a)s, %(b)d' % locals()")
check(v.used_names, ['a', 'b', 'locals'])
def test_new_format_string(v):
v.scan("'{a}, {b:0d} {c:<30} {d:.2%}'.format(**locals())")
check(v.used_names, ['a', 'b', 'c', 'd', 'locals... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
启动系统服务器
默认参数保存在 settings.py 中,也可以通过命令行指定(--help 查看所有的命令行参数)。
如果要使用 80 等端口,可能需要 "sudo ./run.py --port=80"。
"""
import threading
from datetime import datetime
from pprint import pprint
from optparse import OptionParser, OptionGroup
from tornad... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def convertBiNode(self, root: TreeNode) -> TreeNode:
self.root = self.leaf = TreeNode()
self.inorderTraverse(ro... |
import pytest
from flaskbb.plugins.manager import FlaskBBPluginManager
@pytest.fixture
def plugin_manager():
return FlaskBBPluginManager("flaskbb")
|
"""Test agent"""
import unittest
# from aries.core.grid.agent import Agent, Battery, ElectricalVehicle, PVPanel, WaterTank, WindGenerator
import aries.core.grid.agent as agent
# Agent constants
AGENT_NAME = "agent1"
VOLTAGE_RATING = 230
POWER_RATING = 1900
POWER_FACTOR = 0.95
INCOMING_POWER = 1234
REQUEST_INJECT_POWE... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import solver
mu = -0.8645
def homoclinic (S, t):
x, y = S
return (np.array([y,
mu * y + x - np.square(x) + x * y]))
def numInt (Ttrans, Teval, dt, X0):
s = solver.ODE_Solver()
time, sol = s.solveODE(homoc... |
import click
import time
from flask.cli import AppGroup
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
db_cli = AppGroup('db')
# TODO: Add support for schema migrations
@db_cli.command('init')
def init_db():
"""
Create schema
"""
db.create_all()
@db_cli.command('wait')
def wait_db():
... |
# PARTE 1
# Para el ejercicio del primer capítulo, hay que utilizar lo que sigue:
# import random
# numero = random.randint(0, 100)
# Para resaltar el segundo capítulo, hay que utilizar lo que sigue:
print("Introduzca el número a adivinar")
while True:
# Entramos en un bucle infinito
# Pedimos introducir un ... |
import sys
import smtplib
import requests
import bs4
import os
import re
import json
from email.mime.text import MIMEText
# adapter
with open('/Users/axellaborieux/watchArxiv_perso/watchAuthors.json', 'r') as f:
args = json.loads(f.read())
old_total = args['total']
names = args['names']
surnames = args... |
from bolsonaro.models.omp_forest import OmpForest, SingleOmpForest
from bolsonaro.utils import binarize_class_data, omp_premature_warning
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import OrthogonalMatchingPursuit
import warnings
class OmpForestBinaryClassifier(S... |
import re
from .tree import Tree
from .tree_node import TreeNode
SON = "Son"
DAUGHTER = "Daughter"
SIBLINGS = "Siblings"
PATERNAL = "Paternal"
MATERNAL = "Maternal"
UNCLE = "Uncle"
AUNT = "Aunt"
BROTHER = "Brother"
SISTER = "Sister"
IN_LAW = "In-Law"
class RelationshipTree(Tree):
"""
Family tree that suppor... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'L4_gui.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
... |
def rev(n):
return int(str(n)[::-1])
def check_pallindrome(n):
return n == rev(n)
def res(n):
reverse = rev(n)
n += reverse
return n if check_pallindrome(n) else res(n)
if __name__ == '__main__':
n = int(input())
print(res(n))
'''Calculate the pallindrome no from given no by adding reve... |
## 1) Make a user to enter a type of food among 'Korean', 'Chinese', and 'Japanese'.
## 2) Recommend a restuarant randomly.
import secrets
# PROBLEM : How to continue the loop until a user enters a correct value?!
def recommend_cuisine():
try:
korean_food = ['Bibimbap', 'Kimbap', 'Galbi']
italian_food = ['... |
from dotenv import load_dotenv, find_dotenv
import os
from sqlalchemy import create_engine, update
load_dotenv(find_dotenv())
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Connect to MySQL
engine = create_engine("mysql+pymysql://"
+os.environ.get("mysql_user")
+":"+os.environ.get("mysql_pas... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright European Organization for Nuclear Research (CERN) since 2012
#
# 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... |
# -*- coding: utf-8 -*-
import numpy as np
def is_empty(val):
return np.isnan(val) if isinstance(val, float) else not val
|
import os
from io import BytesIO
from urllib.request import urlopen
from django.conf import settings
from django.test import LiveServerTestCase, Client
class Exercise3Test(LiveServerTestCase):
def test_media_example_upload(self):
"""
Test the upload functionality to the media_example view. Check ... |
from re import S
import socket
import sys
command = sys.argv[1]
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect((host, port))
s.send(command.encode())
s.close() |
import os
import sys
import traceback
import logging
def log_exception(level):
exc_type, exc_value, exc_traceback = sys.exc_info()
for i in traceback.extract_tb(exc_traceback):
# line = (os.path.basename(i[0]), i[1], i[2])
line = (i[0], i[1], i[2])
logging.log(level, 'File "%s", line %d... |
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# --------------------------------------------... |
# Copyright 2014 Julia Eskew
# 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... |
from typing import Optional, Tuple
DEFAULT_NAMESPACE = "vernacular-ai"
DEFAULT_PROJECT_TEMPLATE = "dialogy-template-simple-transformers"
def canonicalize_project_name(
template: Optional[str] = None, namespace: Optional[str] = None
) -> Tuple[str, str]:
"""
:param template: Scaffolding will be generated ... |
'''
Copyright 2022 Airbus SAS
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
dis... |
'''
Created on May 21, 2018
@author: helrewaidy
'''
# sub-parts of the U-Net model
import torch
import torch.nn as nn
import torch.nn.functional as F
class double_conv(nn.Module):
'''(conv => ReLU => BN) * 2'''
def __init__(self, in_ch, out_ch):
super(double_conv, self).__init__()
self.conv... |
import os, json, shutil, glob, calendar, codecs, fnmatch, re, unicodedata, errno
from abc import ABCMeta, abstractmethod
from datetime import datetime
from threading import Thread
from collections import Iterable
from stat import *
from inspect import isclass, getmembers
from sys import modules
# Include the Dropbox S... |
import logging
import numpy as np
from openeye import oechem, oegraphsim
from sklearn.cluster import DBSCAN
logger = logging.getLogger(__name__)
def cluster_similar_molecules(
smiles, fingerprint_type=oegraphsim.OEFPType_Tree, eps=0.5, min_samples=2
):
"""The method attempts to cluster a sets of molecules b... |
n = int(input('Digite um número: '))
print('TABUADA')
for c in range (1, 11):
print(f'{n} x {c} = {n*c}') |
import typing
from fiepipelib.gitaspect.routines.config import GitAspectConfigurationRoutines
from fiepipelib.rootaspect.data.config import RootAsepctConfiguration
TR = typing.TypeVar("TR", bound=RootAsepctConfiguration)
class RootAspectConfigurationRoutines(GitAspectConfigurationRoutines[TR], typing.Generic[TR]):
... |
# Matt Grimm
# USAFA
# Wireless nRF24L01+ Wireless Communication
# 7 November 2016
import RPi.GPIO as GPIO
import time
import sys,signal
import spidev
GPIO.setmode(GPIO.BCM)
GPIO.setup(11,GPIO.IN)
rx_buf = [8]
int_step = 0
def signal_handler(signal,frame):
print("\nprogram exiting")
GPIO.cleanup()
sys.ex... |
# step 1: imports
from typing import Generic, TypeVar
# step 2: define generic types to be specified later
T1 = TypeVar("T1")
T2 = TypeVar("T2")
# step 3: define generic class
class MyGenericClass(Generic[T1, T2]):
def do_something(self, value1: T1, value2: T2):
print(f"doing something with {value1} and ... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.20.7
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # ... |
import logging
import re
import subprocess
from collections import OrderedDict
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple
import pandas as pd
from effectiveness.code_analysis.get_commit import get_last_commit_id
from effectiveness.code_analysis.pom_module import CutPair, PomModule
fro... |
"""Useful functions."""
import logging
import os
import sys
from configparser import ConfigParser, RawConfigParser
from datetime import datetime
from json import loads
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
logger = logging.getLogger("Token ma... |
#################################################################################
## Project : AuShadha
## Description : Provides the UI app for AuShadha. The Core UI and its elements.
## Date : 15-10-2013
##
## This code is generously borrowed from Django's own admin app
##
## See django.contrib.admin.__i... |
from pathlib import Path
import torch
import numpy as np
import argparse
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from mpl_toolkits.mplot3d import Axes3D # https://stackoverflow.com/a/56222305
from scipy.spatial.transform import Rotation as R
from post.plots import get_figa
from mvn.mini ... |
#!/usr/bin/env python3
"""
Author : qianying
Date : 2019-04-03
Purpose: Rock the Casbah
"""
import argparse
import sys
import re
# --------------------------------------------------
def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Argparse Python script... |
import pygame
class Action:
packet_name = None
network_command = False
data_required = True
def __init__(self, data=None, target_id=None):
# target_id is the id of the player to send this packet to
if not self.packet_name:
raise TypeError("packet_name not initialized")
... |
#####################################
# Fast spectral decomposition and Laplacian Eigenmaps
# Author: Davi Sidarta-Oliveira
# School of Medical Sciences,University of Campinas,Brazil
# contact: davisidarta[at]gmail.com
######################################
import numpy as np
import pandas as pd
from scipy import spar... |
import frappe, base64
from frappe.utils import cint
from one_fm.legal.doctype.penalty_issuance.penalty_issuance import get_filtered_employees
from one_fm.legal.doctype.penalty.penalty import send_email_to_legal, upload_image
from one_fm.one_fm.page.face_recognition.face_recognition import recognize_face
from frappe imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.