content stringlengths 5 1.05M |
|---|
from django import forms
from django.contrib.auth import authenticate
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField()
def login(self):
user = authenticate(username=self.cleaned_data['username'], password=self.cleaned_data['password'])
return user
|
#
# 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
# ... |
print('Hello World')
print('Evyerthing is beautiful')
print('from master')
print('gums are perfection')
|
import os
import argparse
parser = argparse.ArgumentParser(
description="Resubmitting jobs with different statuses."
)
statuses = [
"ERROR_V",
"ERROR_E",
"ERROR_IB",
"ERROR_SV",
"ERROR_RE",
"EXPIRED",
"ZOMBIE",
"ERROR_SPLT",
]
parser.add_argument(
"-i",
metavar="--error-ind... |
import json
import os
import csv
messages_location = '../data/facebook/messages/inbox'
with open(messages_location + '/../messages_flat.csv','w') as file:
writer = csv.writer(file)
writer.writerow(['title','sender_name','timestamp_ms','content','type'])
for root,dirs,files in os.walk(messages_location):
for... |
# Generated by Django 3.2.4 on 2021-06-10 07:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('wagtailcore', '0062_comment_models_and_pagesubscription'),
]
operations = [
migrations.... |
# -*- coding: utf-8 -*-
# @Author: Tim Reese
# @Date: 2021-02-20
import numpy as np
import torch
import torch.nn as nn
import os
torch.set_default_tensor_type(torch.DoubleTensor)
def one_hot_embedding(labels, num_classes):
"""Embedding labels to one-hot form.
Args:
labels: (LongTensor... |
import json
import logging
import pytest
from rest_api import create_app
from rest_api.db import init_db
logging.basicConfig(level=logging.INFO)
REQUEST_HEADERS = {'content-type': 'application/json', 'accept': 'application/json'}
@pytest.fixture
def app():
"""Create and configure a new app instance for each tes... |
from unittest import TestCase
import numpy as np
import tensorflow as tf
import core.interaction_mapper as um
import core.network as nw
import core.trainer as tn
from core.config import Config
dim = 3
cf = Config('./resources', continue_previous_run=False)
cf.embedding_size = dim
interaction_map = um.InteractionMapp... |
class printables:
"""Class implementation for the printable items"""
def __init__(self) -> None:
pass
def menu_message(self):
"""Screen print for the welcome MENU items"""
print('MENU FOR DEPOSITS')
print('n -- deposit a nickel')
print('d -- deposit a dime')
... |
""" OOP max likelihood classifier """
""" To Do: change likelihood code to process whole array of training data (not half). i.e.
Training/Test data needs to be set before hand by user.
Also, change code so that it isn't just training/test. Maybe add 'update' likelihoods,
to take previous posterior as new likelihood?... |
import numpy as np
def read_network(path):
import pickle
with open(path, 'rb') as f:
data = pickle.load(f)
return data
def link_prediction(edge_list_file, sg_output_path, pickle_file, ground_truth_file_path, layer_num, tmp_path,
ebd_output_path, node_num, K1, mu, K2, t, tsne=F... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Fraunhofer FKIE/US, Alexander Tiderko
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code mus... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2013, Open Source Robotics Foundation, 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:
#
# * Redistributions of source code mus... |
# Copyright 2019 The TensorFlow 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 applica... |
# Beispielprogramm für das Buch "Python Challenge"
#
# Copyright 2020 by Michael Inden
# Helpers
from ch06_arrays.intro.intro import print_array
def solve_sudoku(board):
return __solve_sudoku_helper(board, 0, 0)
def __solve_sudoku_helper(board, start_row, start_col):
# 1) Bereits alle Zeilen bearbeitet?
... |
#!/usr/bin/env python3
import re
import unicodedata
from morphgnt.utils import load_yaml, sorted_items
from citation_form_data import CITATION_FORMS
lexemes = load_yaml("../../lexemes.yaml")
ACUTE = u"\u0301"
GRAVE = u"\u0300"
CIRCUMFLEX = u"\u0342"
def strip_accents(w):
return "".join(
unicodedata.n... |
import os
UNITTESTS = '../UnitTests/'
CORE = 'CoreUnitTest.exe'
MATH = 'MathUnitTest.exe'
totalNumFailed = 0
#-----------------------------------------------------
def unittest( testname ):
global totalNumFailed
numFailed = os.spawnl( os.P_WAIT, testname, testname )
totalNumFailed += numFailed
print '%s: %d' % (... |
import threading
class MarkerDataSet:
""" Base class for collecting the detected marker pose.
"""
def __init__(self, markerDic={}):
self._marker_dic = markerDic
self.locker = threading.Lock()
def saveitem(self, id, obs, x, y):
"""Save a new position in the marker pose in the ... |
from django.db import models
from django.conf import settings
from .settings import *
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from cms.models import CMSPlugin
from photologue.models import Gallery, Photo, PhotoSize
import random
PHOTO_TEMPLATES = getatt... |
#Autor Manuela Garcia Monsalve
# 28 septiembre 2018
#Clase main donde se crearan los objetos y sus instancias
from Moto import *
from Carro import *
from Avion import *
from Barco import *
from ArchivosMan import *
class Herencia():
carro = Carro('Renaul','Gris','Logan','Terreste')
text = ReadAndWrite()
... |
# -*- coding: utf-8 -*-
"""Api views."""
import datetime
import os
from time import sleep
from json import dumps, loads
from merge_template_lib import template_factory
from cms10.api_bp.merge_data_extractor import MergeDataExtractor
from cms10.initdb import db
from cms10.models import Contact
from cms10.models import ... |
import feedparser
import json
from dateutil.parser import parse
from pprint import pprint
from markdownify import markdownify
urls = []
with open('./urls.json') as url_file:
urls = json.load(url_file)
feeds = [feedparser.parse(url)["entries"] for url in urls]
simplified_feeds = []
for index, feed in enumerate(f... |
# aproksymacja danych wielomianem dowolnego stopnia
import numpy as np
import matplotlib.pyplot as plt
X = np.array([(1, 2, 3, 4, 5)])
Y = np.array([(52, 5, -5, -40, 10)])
def approx(X, Y, m):
if len(X[0,:]) != len(Y[0,:]):
print("Sizes of X[0,:] and Y[0,:] should be the same!")
return
m = m ... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt, cstr, fmt_money
import unittest
class TestFmtMoney(unittest.TestCase):
def test_standard(self):
frappe.db.set_... |
from tkinter import Tk, Button, messagebox
def prikaziObavijest(vrijednost):
messagebox.showinfo("HELLO", "Pritisnuli ste tipku 'HELLO'"+str(vrijednost))
glavni = Tk()
tipka = Button(glavni, text="Hello", command=lambda:prikaziObavijest(4))
tipka.pack()
glavni.mainloop() |
""" Callbacks module define callbacks for training
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.python import keras as k
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.callbacks i... |
# -*- coding: utf-8 -*-
import json
import sys
import os
import os.path
import inspect
import copy
from functools import wraps
from ctypes import WinDLL, c_ulong, c_char_p, create_string_buffer, WINFUNCTYPE
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('WeChatManager')
def is_64... |
import requests
import json, sys, os, string
import math
from imgutils import randomSaturatedColor
class HiddenPrints:
def __enter__(self):
self._original_stdout = sys.stdout
sys.stdout = open(os.devnull, "w")
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
s... |
"""Python code to solve problem 2 on the projecteuler.net website, available
at:
https://projecteuler.net/problem=2
For your convinience:
----------------------------------------------------------------------------
Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with... |
try: from .analysis import Analyzer
except: from analysis import Analyzer
from dotenv import load_dotenv
import os
import time
load_dotenv()
def run_analysis(all_tracks_cleaned):
# timer
START = time.time()
print(f"-----> Starting.")
print(f"-----> Total tracks: {len(all_tracks_cleaned)}")
start ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" AWS auth method module """
import logging
import json
from base64 import b64encode
from hvac import exceptions, aws_utils
from hvac.api.vault_api_base import VaultApiBase
from hvac.constants.aws import ALLOWED_IAM_ALIAS_TYPES, ALLOWED_EC2_ALIAS_TYPES
from hvac.constants.aw... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Print a list of all the commands.
These are the commands available after running: 'python generate_commands.py'.
"""
# Copyright (C) 2018-2020 Håkon Austlid Taskén <hakon.tasken@gmail.com>
# Licenced under the MIT License.
import os
import fnmatch
import argparse
impo... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('welcome', '0006_auto_20170411_1606'),
]
operations = [
migrations.AlterField(
model_name='article',
... |
""" tagger using mecab """
import traceback
import MeCab
from ..models import WordNode
from .base import Tagger
class MeCabNode(WordNode):
"""
Parsed word node by MeCab
Attributes
----------
surface : str
Surface of word
part : str
Part of the word
part_detail1 : str
... |
# coding: utf-8
# TODO: Add examples, tables and best practice links to command
# TODO: Examples of truevalue, falsevalue
# TODO: Test param extra_file
# Things dropped from schema_template.md (still documented inside schema).
# - request_parameter_translation
from __future__ import print_function
import sys
from lx... |
# Generated by Django 4.0.2 on 2022-03-15 14:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0202_carburenotification_and_more'),
]
operations = [
migrations.AlterField(
model_name='carburenotification',
... |
import logging
import pytest
from toolz import get_in
import sdk_fault_domain
import sdk_install
import sdk_utils
from tests import config
log = logging.getLogger(__name__)
@pytest.mark.sanity
@pytest.mark.dcos_min_version("1.11")
@sdk_utils.dcos_ee_only
def test_zones_not_referenced_in_placement_constraints():
... |
"""Treadmill docker authz plugins for different Docker APIs
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import re
_LOGGER = logging.getLogger(__name__)
DEFAULT_ALLOW_MSG = 'Allowed'
class No... |
for c in range(0,8,2):
print(c)
print("fim")
|
#
# Copyright (c) 2019-2020
#
# @author: Daniel Bankmann
# @company: Technische Universität Berlin
#
# This file is part of the python package pymloc
# (see https://gitlab.tubit.tu-berlin.de/bankmann91/python-mloc )
#
# License: 3-clause BSD, see https://opensource.org/licenses/BSD-3-Clause
#
from typing import Callabl... |
# Copyright (c) 2021 CloudZero, Inc. All rights reserved.
# Licensed under the BSD License. See LICENSE file in the project root for full license information.
# Direct all questions to support@cloudzero.com
import csv
import gzip
import os
import pathlib
import sys
import simplejson as json
import botocore
from uca.c... |
import urllib.parse
import httpx
from .fmtypes import SearchType
class YearFilter:
t1920s = "tag:1920s"
t1930s = "tag:1930s"
t1940s = "tag:1940s"
t1950s = "tag:1950s"
t1960s = "tag:1960s"
t1970s = "tag:1970s"
t1980s = "tag:1980s"
t1990s = "tag:1990s"
t2000s = "tag:2000s"
t201... |
import pathlib as pl
class Config:
# Directory to Darknet ml model
DARKNET_PATH = pl.Path("MLService/ml-model/darknet").absolute()
# Directory to DenseDepth ml model
DENSE_PATH = pl.Path("MLService/ml-model/densedepth").absolute()
|
#!/usr/bin/python
from ROOT import *
TMVA.Tools.Instance()
### Visualising the results
##############################
TMVA.TMVAGUI("trainingBDT.root")
#TMVA.TMVAGUI("/vols/lhcb/bd1316/B2ppKgamma/TMVA/trainingBDT_MCcorrectedMOCK.root")
###Keep GUI alive
gApplication.Run()
|
pkgname = "Test-Deep"
|
import numpy as np
import MITgcmutils as mit
import matplotlib.pyplot as plt
import xarray as xr
from scipy.interpolate import griddata
print("-- Make the bathymetry --")
#-- directories --
dir_grd = '/glade/p/univ/ufsu0011/initial_data/grid/'
dir_grd50 = '/glade/p/univ/ufsu0011/runs/chao50/gridMIT/'
dir_out = '/gl... |
'''
The best plugin.
Provides the best command, which provides bad pickuplines.
'''
import fortune
from tombot.registry import Command
from .fortune_plugin import SPECIALS
@Command(['lars', 'loveyou', 'pickup', 'date'], 'fortune')
def lars_cb(bot, message, *args, **kwargs):
'''
Send a (bad) genderless pickup... |
from torch import optim
import torch
from src import signal_functions, metrics
from src.model_management import models
from src.model_management.hyperparameter_optimization import optimization_objective
from src.trade_utils import ParallelTrader, Trader
optimization_objective({
'test_split': 0.2,
'valid_split'... |
"""
pytkdocs package.
Load Python objects documentation.
"""
from typing import List
__all__: List[str] = [] # noqa: WPS410 (the only __variable__ we use)
|
from datetime import datetime
from flask import Flask, render_template,request, redirect, session, url_for
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.config['SECRET_KEY'] = 'this is secret'
app.config['SQLALCHEMY_DATABASE... |
from .name_message import NameMessage
class RemovePersonMessage(NameMessage):
pass
|
#!/usr/bin/env python
# -*- python -*-
#BEGIN_LEGAL
#
#Copyright (c) 2016 Intel 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-... |
"""Authentification helpers."""
import hashlib
import string
from random import SystemRandom
CLIENT_ID = "636F70653E"
SERVER_ID = "736F70653E"
def _digit_to_hex(string_of_digit):
"""Convert string of digits to string of hex."""
return "".join(
[
hex(int(i))[2:]
for i in [
... |
#!/usr/bin/python3
from functools import lru_cache
def Z_S(n, f, k):
"""
The cycle index of the symmetric group has recurrence
Z(S_n, f(x)) = 1/n \sum_{i=1}^n f(x^i) Z(S_{n-i}, f(x)).
This function finds the coefficient of x^k in Z(S_n, f(x))
"""
# Special case to avoid division by zero
... |
from tkinter import *
import math
# ---------------------------- CONSTANTS ------------------------------- #
PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
FONT_NAME = "Courier"
WORK_MIN = 25
SHORT_BREAK_MIN = 5
LONG_BREAK_MIN = 20
reps = 0
timer = None
# ---------------------------- TIMER RESE... |
import subprocess
import glob
import os
import time
import psutil
from workflow.utilities import PrepTemporalCytoscapeTPS
from requests.exceptions import ConnectionError
from requests.exceptions import HTTPError
from json.decoder import JSONDecodeError
from py2cytoscape.data.cyrest_client import CyRestClient
from py2cy... |
from dataclasses import dataclass
from pdip.cqrs import IQuery
from pdi.application.connection.GetConnectionList.GetConnectionListRequest import GetConnectionListRequest
from pdi.application.connection.GetConnectionList.GetConnectionListResponse import GetConnectionListResponse
@dataclass
class GetConnectionListQuer... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-10-17 18:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('salt', '0004_auto_20181017_1318'),
]
operations = [
migrations.AlterField(
... |
import sys
import tarfile
import gzip
import shutil
import os
from ftplib import FTP
if not os.path.exists('./metadata'):
os.makedirs('metadata')
for filename in os.listdir('./metadata'):
if filename.endswith('.tar'):
print 'Removing ' + filename
os.remove('./metadata/' + filename)
ftp = FTP('... |
# NOTE This module is not added to `builtins.__init__` bczit is only for dsl internal logics not for making blueprints
# Below helpers are used in both `calm/dsl/cli/` and `calm/dsl/builtins/`
# Import its helpers using `from calm.dsl.builtins.models.metadata_payload import *`
from .metadata import Metadat... |
'''
笨阶乘
通常,正整数 n 的阶乘是所有小于或等于 n 的正整数的乘积。例如,factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1。
相反,我们设计了一个笨阶乘 clumsy:在整数的递减序列中,我们以一个固定顺序的操作符序列来依次替换原有的乘法操作符:
乘法(*),除法(/),加法(+)和减法(-)。
例如,clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1。然而,这些运算仍然使用通常的算术运算顺序:
我们在任何加、减步骤之前执行所有的乘法和除法步骤,并且按从左到右处理乘法和除法步骤。
另外,我们使用的除法是地板... |
word='Racecar'
sortetword = ''.join(sorted(word))
print(sortetword)
def isAlphabetic(string):
sortedstring = ''.join(sorted(string))
if sortedstring == string:
results = True
else:
results = False
return results
Given a sting
When
T
then
The string is in alpahbetical... |
from collections import OrderedDict
TRAINER_DEFAULTS = OrderedDict({
'default_root_dir': None,
'gradient_clip_val': 0,
'process_position': 0,
'num_nodes': 1,
'num_processes': 1,
'gpus': None,
'auto_select_gpus': False,
'tpu_cores': None,
'log_gpu_memory': None,
'progress_bar_ref... |
"""
Binary search is a very important algorithm which enables the user to search for a specific item
by incrementally chopping the dataset in half. The search happens in O(logn) time and O(1) space.
The requirement is that the problem set has to be in a sorted order.
"""
import unittest
from typing import List
def bi... |
import numpy as np
class ParticleDipoleRegularize(object):
"""
L2 regularizer for charges
"""
def __init__(self, coeff_lambda=0.0, zeta=8.0):
self.coeff_lambda = coeff_lambda
self.zeta = zeta
self.n = 1
def cost(self, particle_input, layers):
# c = 0.0
# ... |
from datetime import datetime
DATE_FORMAT = '%Y-%m-%dT%H:%M:%S.%f%Z'
def to_msbpay_string(dt: datetime) -> str:
return datetime.strftime(dt, DATE_FORMAT)
def from_msbpay_string(dt: str) -> datetime:
return datetime.strptime(dt, DATE_FORMAT)
|
from quotes.models import Quote
from rest_framework import serializers
class QuoteSerializer(serializers.ModelSerializer):
class Meta:
model = Quote
fields = '__all__'
|
"""
REDUNDANT
"""
#!/usr/bin/env python
#stars, times, xyzuvw, xyzuvw_cov = pickle.load(open('results/bp_TGAS2_traceback_save.pkl'))
from __future__ import print_function, division
import numpy as np
import chronostar.retired.fit_group as fit_group
import pickle # for reading in .pkl files... |
# Copyright Peter Gagarinov.
#
# 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, ... |
import multiprocessing as mp
from concurrent.futures import ThreadPoolExecutor
import time
import numpy as np
class Benchmark:
shutdown:bool = False
def __init__(self,fps:float, time_scaler:float=1.0):
assert fps > 0.0
assert time_scaler > 0.0
self.fps = fps * time_scaler
self.... |
from imageai.Prediction import ImagePrediction
import os
import requests
import json
import boto3
from PIL import Image
from http.server import HTTPServer, BaseHTTPRequestHandler
from boto3.dynamodb.conditions import Key, Attr
'''
This code runs on the EC2 to serve predictions
On a post it serves a prediction on th... |
import os
import sys
from pathlib import Path
from argparse import Namespace
import importlib
import shutil
import pytest
from clldutils.path import sys_path
from pycldf import Dataset
from cldfbench.catalogs import CachingConcepticonAPI, CachingGlottologAPI, CLTSAPI
from cldfcatalog.repository import get_test_repo
... |
import os
import argparse
import pyrender
import torch
import trimesh
import numpy as np
from leap import LEAPBodyModel
def sample_points(mesh_vert, n_points=15000):
vert = mesh_vert.detach().cpu().numpy().reshape((-1, 3))
bb_min, bb_max = np.min(vert, axis=0), np.max(vert, axis=0)
loc = np.array([(bb_m... |
import random
import string
from random import randint
numQueries = 200
numDistinct = 8
List = []
file = open("test cases.txt", "w")
class Patient:
def __init__(self,name,eLevel):
self.name = name
self.eLevel = eLevel
def actionZero():
name = "".join(random.choice(string.asci... |
"""
Support for zeptrion_air_api.button_action_listener.
For more details about this Class, please refer to the documentation at
https://github.com/swissglider/zeptrionAirApi
"""
import time
import json
import asyncio
import websockets
class ButtonActionListenerHandler():
"""
This is the Button Action Liste... |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <michael.aivazis@para-sim.com>
# (c) 1998-2021 all rights reserved
# attempt to
try:
# the journal bindings
from . import journal as libjournal
# if something goes wrong
except ImportError:
# mark; the rest of the package will adjust
libjournal = None
... |
from campy.graphics.gimage import GImage
from campy.gui.events.mouse import onmouseclicked
from campy.graphics.gwindow import GWindow
window = GWindow(width=640, height=480)
def main():
onmouseclicked(event)
img = GImage('Goku.jpg')
window.add(img)
def event(mouse):
print(mouse.x, m... |
# Python Essential Libraries by Joe Marini course example
# Example file for Requests library
import requests
# TODO: work with status codes
# TODO: examine response encoding
# TODO: To read JSON content, use the json() function
|
n, m = map(int, input().split())
if m >= n:
print(1)
elif n % 2 == 0 and m >= n // 2:
print(2)
else:
print(-1)
|
from dataclasses import dataclass, field
from typing import List
from modela.Configuration import Configuration
from modela.common import StatusError, Time, ConditionStatus, SecretReference, ObjectReference
from modela.infra.common import ProviderName, ConnectionConditionType, ConnectionCategory
dataclass()
@datacla... |
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.header import Header
from email import encoders
import time
from HttpTesting.library import scripts
from HttpTesting.globalVar import gl
import yaml,os,base64
class Email... |
import os, sys, math, argparse
import torch
import torch.optim as optim
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from copy import copy
import numpy as np
import matplotlib.pyplot as plt
from metaopt.opt... |
import pytest
from pytest_factoryboy import register
from rest_framework.test import APIClient
from .factories import (
ApproachFactory,
ChallengeFactory,
SubmissionFactory,
TaskFactory,
TeamFactory,
UserFactory,
)
@pytest.fixture
def api_client() -> APIClient:
return APIClient()
@pytes... |
# Code is generated: DO NOT EDIT
# Copyright 2019 Machine Zone, Inc. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from kubespec import context
from kubespec import types
from kubespec.k8s import base
from kubespec.k8s import v1 as k8sv1
fr... |
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views.generic import FormView
from web.forms import LoginForm, RegistrationForm
__all__ = ["in... |
day_plan = ['eat','walk','study','sleep']
plan_len = len(day_plan)
i = 0 # s4et4ik
while i < plan_len:
action = input('Vvedite plan deistviya:')
if action in day_plan:
act_index = day_plan.index(action) # nahodim index nashego deistviya
if act_index == 0: # deistvie v preoritete
day_... |
# _
# /\ | |
# / \ _ __ ___| |__ ___ _ __ _ _
# / /\ \ | '__/ __| '_ \ / _ \ '__| | | |
# / ____ \| | | (__| | | | __/ | | |_| |
# /_/ \_\_| \___|_| |_|\___|_| \__, |
# __/ |
# |___/
# Copyright (C) 20... |
def madlib():
time_of_day = input("Time of Day: ")
body_part_plural = input("Body Part (plural): ")
color = input("Color: ")
verb_past_tense = input("Verb (past tense): ")
food = input("Food: ")
noun1 = input("Noun: ")
noun_plural_1 = input("Noun (plural): ")
adj1 = input("Adjective: ")
... |
import boto3
from moto import mock_ecs
from moto.core import ACCOUNT_ID
@mock_ecs
def test_create_capacity_provider():
client = boto3.client("ecs", region_name="us-west-1")
resp = client.create_capacity_provider(
name="my_provider",
autoScalingGroupProvider={
"autoScalingGroupArn"... |
# Generated by Django 3.2.8 on 2021-10-29 21:02
import apps.base.services
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('oauth', '0001_initial'),
]
operations =... |
import os
import cv2
import torch
import torchvision.transforms as transforms
from PyQt5.QtCore import Qt, QRunnable, QThreadPool
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import QLabel
from networks import ResnetGeneratorUGATIT
from utils import tensor2im
class ProcessRunnable(QRunnable):
de... |
"""
This modules carries the smtp logging logic
"""
import logging
from logging.handlers import SMTPHandler
from smtplib import SMTP
from datetime import datetime
from email.message import EmailMessage
import platform
import atexit
from bioflow.configs.main_configs import smtp_logging_parameters, smtp_logging
if not ... |
"""
Base-Common behaviour for all Meross-LAN entities
actual HA custom platform entities will be derived like this:
MerossLanSwitch(_MerossToggle, SwitchEntity)
"""
from __future__ import annotations
from homeassistant.helpers.typing import StateType
from homeassistant.helpers import device_registry as dr
from hom... |
# (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved.
# -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
"""Function implementation
test with: resilient-circuits selftest -l fn_mcafee_tie
"""
import logging
from fn_mcafee_tie.lib.mcafee_tie_common import get_mcafee_client, get_tie_cl... |
from flask import Flask
from flask_restful import Api, request
from flask.json import jsonify
app = Flask(__name__)
api = Api(app)
from tagger import NaiveTagger
from recommendations import Recommendation
@app.route('/get_tags', methods=['GET', 'POST'])
def get_tags():
name = request.args.get('name', '')
d... |
import pprint,os,json,requests,string
from bs4 import BeautifulSoup
from task4 import scrape_movie_details
with open("position_wise_movies.json") as naik:
top_movies=json.load(naik)
movies_list_all_details=[]
def get_movie_list_details(movies_list):
for movie in movies_list:
movie_name=movie['name']
each_movie_... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
header = ListNode(999)
header.next = head
cur = header
for i in range(m):
if i == m - ... |
from .__about__ import *
from .api import *
from .exceptions import *
from .formats import *
from .models import *
__all__ = [
*__about__.__all__,
*api.__all__,
*exceptions.__all__,
*formats.__all__,
*models.__all__,
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.