text stringlengths 2 999k |
|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .base import GenericModelTestBase
from computedfields.models import ComputedFieldsModelType
from computedfields.graph import CycleNodeException
from django.core.management import call_command
from django.utils.six.moves import cStringIO
from django.ut... |
"""Emoji
Available Commands:
.support
"""
from telethon import events
import asyncio
from userbot.utils import admin_cmd
@borg.on(admin_cmd("secktor"))
async def _(event):
if event.fwd_from:
return
animation_interval = 0.1
animation_ttl = range(0,36)
#input_str = event.pattern_match.group(1)... |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(name='CryptoPlus',
version='1.0',
description='PyCrypto Cipher extension',
author='Christophe Oosterlynck',
author_email='tiftof@gmail.com',
packages = find_packages('src'),
install_requires = ['pycryptodome'],... |
import torch
from weakvtg.loss import loss_orthogonal_box_class_count_scaled
def test_loss_orthogonal_box_class_count_scaled():
X = torch.tensor([1, -1, 1, -1, 0, 0, .236, -.751], dtype=torch.float), torch.tensor([3, 1, 1, 1, 0, 1, 1, 0])
y = torch.tensor([1, -1, -1, 1, -1, 1, -1, 1], dtype=torch.fl... |
from setuptools import setup, find_packages
import pathlib
directory = pathlib.Path(__file__).parent
README = (directory / "README.md").read_text()
setup(
name="qsurface",
version="0.1.5",
description="Open library from surface code simulations and visualizations",
long_description=README,
long... |
from flask import Flask, request, jsonify
from td4a.controllers.config import api_config
from td4a.controllers.hosts import api_hosts
from td4a.controllers.inventory import api_inventory
from td4a.controllers.link import api_link
from td4a.controllers.render import api_render
from td4a.controllers.retrieve import api_r... |
# 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 may ... |
from __future__ import absolute_import
from __future__ import print_function
import veriloggen
import simulation_simulator_verilator
from veriloggen import *
expected_rslt = """\
LED: 0 count: 0
LED: 0 count: 1
LED: 0 count: 2
LED: 0 count: 3
LED: 0 count: 4
LED: 0 count: ... |
import json
import time
from urllib2 import urlopen
from sys import argv
albumID = argv[1]
urlpath = urlopen('https://itunes.apple.com/lookup?id=' + albumID)
result = json.loads(urlpath.read())
print (result['resultCount'])
count = 0
while result['resultCount'] == 0:
urlpath = urlopen('https://itunes.apple.co... |
# SPDX-License-Identifier: Apache-2.0
# Copyright 2020 Contributors to OpenLEADR
# 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 re... |
import pandas as pd
def load_report(mr, params) -> pd.DataFrame:
return normalize_report(mr.get('report'), params)
def normalize_report(df, params):
df = df.copy()
df.R0 = df.R0.apply(lambda x: round(complex(x).real, 1))
df_temp = df.drop(['Time', 'R0', 'latentRate', 'removalRate', 'hospRate', 'deat... |
# Generated by Django 3.1.4 on 2020-12-08 05:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('alog', '0003_answer_author'),
]
operations = [
migrations.AddField(
model_name='answer',
name='modify_date',
... |
from django import forms
from Hostel.models import *
class Hostel_DetailsForm(forms.ModelForm):
class Meta:
model = Hostel_Details
fields = '__all__'
class Hostel_RoomForm(forms.ModelForm):
class Meta:
model = Hostel_Room
fields = '__all__'
class Hostel_RegisterForm(forms.ModelForm):
class Meta:
model... |
#!/usr/bin/python
#
# Send a value to change the opening of the Robotiq gripper using an action
#
import argparse
import rospy
import copy
import geometry_msgs.msg
from std_msgs.msg import Header, ColorRGBA
from geometry_msgs.msg import PoseStamped, Vector3, Pose, Quaternion
from visualization_msgs.msg import Marker, ... |
import logging
import datetime
from google.appengine.ext import webapp
import util
_SE_MONTH_NAMES = {
1: "januari", 2: "februari", 3: "mars", 4: "april", 5: "maj", 6: "juni",
7: "juli", 8: "augusti", 9: "september", 10: "oktober", 11: "november",
12: "december"
}
register = webapp.template.create_templ... |
# -*- coding: utf-8 -*-
import unittest
from blo.BloArticle import BloArticle
class TestBloArticle(unittest.TestCase):
def setUp(self):
self.blo_article = BloArticle('./templates')
self.base_file_path_1 = "./test_article_1.md"
self.base_file_path_2 = "./test_article_2.md"
def test_fai... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import List, Optional, Dict, Any, Tuple, TYPE_CHECKING
from mephisto.abstractions.blueprint import AgentStat... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import curses
from collections import OrderedDict
import pytest
from tuir.page import PageStack
from tuir.submission_page import SubmissionPage
from tuir.docs import FOOTER_SUBMISSION
try:
from unittest import mock
except ImportError:
import mo... |
# coding=utf-8
import configobj
import os
import sys
import logging
import inspect
import traceback
import pkg_resources
from diamond.util import load_class_from_name
from diamond.collector import Collector
from diamond.handler.Handler import Handler
logger = logging.getLogger('diamond')
def load_include_path(path... |
"""This module contains the general information for DupeScope ManagedObject."""
import sys, os
from ...ucsmo import ManagedObject
from ...ucscoremeta import UcsVersion, MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class DupeScopeConsts():
IS_SYSTEM_FALSE = "false"
IS_SYSTEM_NO = "no"
IS_SYST... |
"""
m2g.utils.reg_utils
~~~~~~~~~~~~~~~~~~~~
Contains small-scale registration utilities.
"""
# standard library imports
import os
import subprocess
# package imports
import nibabel as nib
import numpy as np
import nilearn.image as nl
from dipy.align.imaffine import MutualInformationMetric
from dipy.align.imaffine ... |
import os
import socket
import sys
import threading
import queue
import time
os.system("cls"),
os.system("mode con lines=22 cols=38"),
os.system("rem IPV4_DOWNED"),
os.system("title PORT SCANNER"),
os.system("rem REMADE by @IPV4_DOWNED"),
common_ports = {
"21": "FTP",
"22": "SSH",
"23": "Tel... |
from fastapi import FastAPI
from config.settings import settings
from config.middleware import register_middleware
from config.tortoise import register_tortoise
from config.exception import register_exception
from config.routes import register_routes
from core.helpers.responses import responses
def create_app():
ap... |
import matplotlib.pyplot as plt
#from matplotlib import rc
from matplotlib import rcParams
from MCPM.cpmfitsource import CpmFitSource
def plot_tpf_data(ra, dec, channel, campaign, file_out, half_size=2,
stars_subtract=[], adjust=None, xlabel=None, ylabel=None, **kwargs):
"""
Plot TPF data f... |
def extractKnokkroTranslations(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Eternal Life' in item['tags']:
return buildReleaseMessageWithType(item, 'Eternal Life', vol, chp, frag=frag, postfi... |
from active_work.miscellaneous import RTPring
from active_work.plot import list_colormap
from active_work.init import get_env
import matplotlib.pyplot as plt
try: plt.style.use('paper')
except: print('Matplotlib stylesheet \'paper\' does not exist.')
from matplotlib.lines import Line2D
import numpy as np
r = RTPring... |
"""
Tests core functionality of naming workers when there are multiple processes.
See https://pytorch.org/tutorials/intermediate/ddp_tutorial.html to decide
how we want to support DistributedDataParallel with limited user configuration.
The key methods are
torch.distributed.get_rank() - when manually spawning proc... |
import logging
logging.addLevelName(5, 'SILLY')
# max(map(len, [logging.getLevelName(level) for level in range(0, 60, 10)])) == 8
# %(asctime)14s
logging.basicConfig(format='%(levelname)-8s (%(name)s): %(message)s')
class Logger(logging.Logger):
def silly(self, msg, *args, **kwargs):
level = logging.get... |
""" Initialization script for Minos. """
from minos.app import create_app
from minos.database import db
# Create the app and push the context
app = create_app(init=True)
app.app_context().push()
app.config.from_envvar('FLASK_SETTINGS')
# Create all tables and stuff.
db.create_all()
|
from typing import List, Optional
from prompt_toolkit.formatted_text import AnyFormattedText
from prompt_toolkit.layout.containers import (
AnyContainer,
HSplit,
VSplit,
Window,
WindowAlign,
)
from prompt_toolkit.layout.controls import FormattedTextControl
from prompt_toolkit.layout.dime... |
from .basegamestate import BaseGameState
class GameStateIntro(BaseGameState):
def on_enter(self):
self.game.r_int.fade = True
# self.logo_engine = self.game.m_res.get_splash("ulix_logo_small")
self.logo_framework = "splash/dexflow_logo_small"
self.game.r_int.load_sprite(self.logo_... |
#!/usr/bin/env python
import sys
import string
from subprocess import *
import re
import time
from optparse import OptionParser
from util_ap import *
from GenericSampler import GenericSampler
from UdpJsonTransmitter import UdpJsonTransmitter
#import pymongo
#from pymongo.errors import AutoReconnect
class ChUtilSampler... |
from django.contrib import admin
# <HINT> Import any new Models here
from .models import Course, Lesson, Instructor, Learner, Question, Choice
# <HINT> Register QuestionInline and ChoiceInline classes here
class QuestionInline(admin.StackedInline):
model = Question
list_display = ('question', 'grade')
class ... |
# ---------------------------------------------------------------------
# Zyxel.MSAN.get_inventory
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Python... |
# (C) StackState 2020
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import pytest
@pytest.fixture(scope='session')
def sts_environment():
# This conf instance is used when running `checksdev env start mycheck myenv`.
# The start command places this as a `conf.yaml` in the `... |
import random
from command import *
from consume import *
from util import *
_MIN_PLAYERS = 5
_MAX_PLAYERS = 10
_GOOD_COUNT = [3, 4, 4, 5, 6, 6]
_GOOD_CHARS = ["Merlin", "Percival"]
_EVIL_CHARS = ["Mordred", "Morgana", "Oberon"]
_DESCRIPTIONS = {
"Merlin": "Knows all evil players except Mordred",
"Percival": ... |
# -*- coding: utf-8 -*-
# File: eval.py
import tqdm
import os
from collections import namedtuple, defaultdict
from contextlib import ExitStack
import numpy as np
import cv2
import json
from tensorpack.utils.utils import get_tqdm_kwargs
from models.rcnn.common import CustomResize, clip_boxes
from models.rcnn.config i... |
from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
'''A form for the Comment model'''
class Meta:
'''Nested class that specifies the form fields'''
model = Comment
fields = ['body']
labels = {'body': ''}
widgets = {
'b... |
# Copyright 2018 Google LLC
#
# 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, ... |
"/mnt/nfs/A.mp3"#! /usr/bin/python
# -*- coding: utf-8 -*-
# Python ctypes bindings for VLC
#
# Copyright (C) 2009-2012 the VideoLAN team
# $Id: $
#
# Authors: Olivier Aubert <contact at olivieraubert.net>
# Jean Brouwers <MrJean1 at gmail.com>
# Geoff Salmon <geoff.salmon at gmail.com>
#
# This libr... |
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""), ... |
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
# Hiding the window title
self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
# Will not be displayed
self.setWindowTitle('-- Light_Manager_v0.01 --... |
# Copyright (c) 2017- Salas Lin (leVirve)
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import grad
import onegan
def adversarial_ce_loss(x, value: float):
''' x: output tensor of ... |
from collections.abc import Hashable
from copy import deepcopy
from itertools import chain, product
from functools import partial
import warnings
import numpy as np
from numpy import ma
import pandas as pd
from pandas.api.types import is_categorical_dtype
import pytest
from scipy import sparse
from boltons.iterutils i... |
from logging import root
import os, cv2
import numpy as np
class Loader:
def __init__(self, root_path) -> None:
self.root_path = root_path
def get_alpha_data(self, file_path):
if (self.root_path):
file_path = os.path.join(self.root_path, file_path)
class VideoMatte240KLoader(... |
#!/usr/bin/env python
import time
print "This demo will build 4 stacks of 40 cubes in the scene. Watch out!"
#print "\x1b!0|"
for x in range(0,1):
for y in range(0,40):
print "\x1b!1;{}.0;{}.0;-1.2;0.1;0.1;0.1|".format(x,y)
print "Done."
|
class TicTacToe():
def __init__(self):
# Initialising the game board to empty strings
self.board = {
'1': ' ', '2': ' ', '3': ' ',
'4': ' ', '5': ' ', '6': ' ',
'7': ' ', '8': ' ', '9': ' '
}
# The x for the left and right columns
... |
# Copyright (c) 2021, Xu Chen, FUNLab, Xiamen University
# All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
class EncoderDecoder(nn.Module):
def __init__(self, n_in_chs, n_out_chs, ):
super(EncoderDecoder, self).__init__()
self.n_in_chs = n_in_chs
se... |
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always all... |
"""
Re-add triggers to update history.update_time when contents are changed.
"""
import logging
from sqlalchemy import MetaData
from galaxy.model.triggers import (
drop_timestamp_triggers,
install_timestamp_triggers,
)
log = logging.getLogger(__name__)
metadata = MetaData()
def upgrade(migrate_engine):
... |
from app import db
class Product(db.Model):
id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
plu = db.Column(db.BigInteger)
name = db.Column(db.String(128))
buying_price = db.Column(db.Float, nullable=True)
selling_price = db.Column(db.Float, nullable=True)
discount = db.Col... |
import math
import torch
import torch.nn as nn
def rgb_to_hls(image: torch.Tensor) -> torch.Tensor:
r"""Convert a RGB image to HLS.
The image data is assumed to be in the range of (0, 1).
Args:
image (torch.Tensor): RGB image to be converted to HLS with shape :math:`(*, 3, H, W)`.
Returns:... |
# -*- coding: utf-8 -*-
"""DNA Center Get Sync Result for Virtual Account data model.
Copyright (c) 2019 Cisco and/or its affiliates.
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 restr... |
# Moves a servo based on the accelerations of the Y axis
from Adafruit_I2C import Adafruit_I2C
from time import sleep
import Adafruit_BBIO.PWM as PWM
# initializes the i2c library and wakes up the IMU (MPU6050)
i2caddr = 0x68
i2c = Adafruit_I2C(i2caddr)
i2c.write8(0x6B, 0)
# sets up servo - from Adafruit tutorial
s... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.10.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re... |
#!/usr/bin/env python
from __future__ import print_function
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import codecs
import os
import sys
import re
here = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
# intentionally *not* adding an encoding ... |
from io import BytesIO
from base64 import b64encode
from PIL import Image
import requests
from ebedke.utils import http
from ebedke import settings
VISION_API_ROOT = "https://vision.googleapis.com/v1/images:annotate"
def load_img(url: str) -> Image:
image = http.get_bytes(url)
return Image.open(BytesIO(imag... |
try:
frozenset
except NameError:
# Import from the sets module for python 2.3
from sets import Set as set
from sets import ImmutableSet as frozenset
try:
from collections import deque
except ImportError:
from utils import deque
from constants import contentModelFlags, spaceCharacters
from c... |
import numpy as np
import torch
import torchvision
import matplotlib.pyplot as plt
import pickle
from scipy.stats import norm
import re
import json
import os
from layers import Linear, Conv2d
from networks import FFNN, ConvMedBig, MyResnet, myNet, EfficientNet
from itertools import combinations
from PIL import Image
... |
# 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
# d... |
# Generated by Django 2.1.15 on 2020-09-16 20:20
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
... |
## INFO ########################################################################
## ##
## COUBLET ##
## ======= ... |
#To get current date and time we need to use the datetime library
from datetime import datetime
# The now function returns current date and time
today = datetime.now()
# use day, month, year, hour, minute, second functions
# to display only part of the date
# All these functions return integers
# Convert them to stri... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Generator(nn.Module):
def __init__ (self, noise_size=201, cube_resolution=32):
super(Generator, self).__init__()
self.noise_size = noise_size
self.cube_resolution = cube_resolution
self.gen_co... |
from datetime import datetime
from io import BytesIO
from io import TextIOWrapper
import os
from pathlib import Path
import sys
import tarfile
from typing import Dict
from typing import Iterable
from typing import Optional
from typing import Union
import zipfile
import yaml
class Archiver:
def __init__(self, fil... |
import _plotly_utils.basevalidators
class XValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="x", parent_name="scattermapbox.marker.colorbar", **kwargs
):
super(XValidator, self).__init__(
plotly_name=plotly_name,
parent_name=paren... |
from mosaic.simulation.parameter import Parameter
from mosaic.simulation.scenario import WorkflowListTask
def get_configuration_DummyClassifier():
DummyClassifier = WorkflowListTask(is_ordered=False, name="DummyClassifier",
tasks=["DummyClassifier__strategy"])
sampler = ... |
import csv
import requests
df = open("bridgeData3.csv",'r').readlines()
fin = open('final.csv','r').readlines()
finCsv = fin[1:]
# url = https://b2ptc.herokuapp.com/bridges
finalCsv = df[1:]
obj = {}
for i in finalCsv:
x = i.split(',')
obj[x[1]] = {'bridge_name':x[0],'proj_code':x[1],'before_img':x[2],'after_im... |
#!/usr/bin/env python
"""RandDisc.py: Randomize a playlist to a collection of folders."""
# Author: Jeroen Lodder (https://github.com/Jeroen6/randdisc)
# License: Public domain
# Version: 0.1
#
# How does it work?
#
# 0. Note: it moves files. (see simulate)
#
# 1. Set "source", "destination", "tracks" and "discs" as... |
from __future__ import absolute_import, unicode_literals
from celery import Celery
from django.conf import settings
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sending_scheduler.settings')
app = Celery('sending_scheduler')
app.config_from_object(settings, namespace='CELERY')
# # Load tas... |
from flask_mail import Message
from flask import render_template
from . import mail
def mail_message(subject,template,to,**kwargs):
sender_email = '10silvianjoki@gmail.com'
email = Message(subject, sender=sender_email, recipients=[to])
email.body= render_template(template + ".txt",**kwargs)
email.htm... |
## 1. Lists ##
row_2 = ['Instagram', 0.0, 'USD', 2161558, 4.5]
row_3 = ['Clash of Clans', 0.0, 'USD', 2130805, 4.5]
## 2. Indexing ##
row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5]
row_2 = ['Instagram', 0.0, 'USD', 2161558, 4.5]
row_3 = ['Clash of Clans', 0.0, 'USD', 2130805, 4.5]
# get individual ratings
ratings_1... |
# -*- coding: utf-8 -*-
# File: trainers.py
import sys
import os
import tensorflow as tf
import multiprocessing as mp
from ..callbacks import RunOp, CallbackFactory
from ..tfutils.sesscreate import NewSessionCreator
from ..utils import logger
from ..utils.argtools import map_arg
from ..utils.develop import HIDE_DOC,... |
from django.contrib import admin
# Register your models here.
from .models import Event, Location, Schedule, Slot, Booking
admin.site.register(Event)
admin.site.register(Location)
admin.site.register(Schedule)
admin.site.register(Slot)
admin.site.register(Booking)
|
import subprocess
import collections
import glob
import inspect
import os
import random
import re
import shutil
import tempfile
import time
from contextlib import contextmanager
from getpass import getpass
import sys
import psutil
import requests
from pathlib import Path
from cloudmesh.common.console import Console
imp... |
#!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
"""This is a simple cloud program running docker containers. The program provides
an API to view and monitor services running in the cloud.
Core components:
- User-defined Docker bridge network
- Service registry (consul) container
- Service discovery container (regist... |
# 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... |
#!/usr/bin/env python
############################################################################
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The A... |
import panel as pn
from bokeh.document import Document
from holoviews import opts
from panel.pane import HoloViews, Markdown
from panel.template.fast.list import FastListDarkTheme, FastListTemplate
from panel.tests.template.fast.test_fast_grid_template import (
INFO, _create_hvplot, _fast_button_card, _sidebar_it... |
import uuid
from copy import deepcopy
from datetime import date, timedelta
from decimal import Decimal
from unittest import mock
from unittest.mock import ANY, MagicMock, Mock, call, patch
import graphene
import pytest
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ValidationEr... |
from league_api.api import ApiType
from typing import List, Mapping
class Summoner(ApiType):
profileIconId: int = None # ID of the summoner icon associated with the summoner.
name: str = None # Summoner name.
puuid: str = None # Encrypted PUUID. Exact length of 78 characters.
summonerLevel: int = ... |
import os
from wikipedia import summary, DisambiguationError, PageError
from ..help import add_help_item
from userbot import BOTLOG, BOTLOG_CHATID
from userbot.events import register
@register(outgoing=True, pattern=r"^\.wiki (.*)")
async def wiki(wiki_q):
""" For .google command, fetch content from Wikipedia. ... |
from opentrons import robot, containers, instruments
robot.head_speed(x=18000, y=18000, z=5000, a=700, b=700)
#Deck setup
tiprack_1000 = containers.load("tiprack-1000ul-H", "B3")
source_row = containers.load("FluidX_24_5ml", "A1", "acid")
source_col = containers.load("FluidX_24_5ml", "A2", "amine")
source_trough4row... |
import argparse
import numpy as np
import pickle
import os
import random
from torch.utils.data import DataLoader
import torch
from transformers import BertConfig
from model import MidiBert
from finetune_trainer import FinetuneTrainer
from finetune_dataset import FinetuneDataset
from matplotlib import pyplot as plt
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-11 14:44
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ubigeo', '0007_ubigeocontinente_continente_id'),
]
operations = [
migrations.RenameF... |
import _plotly_utils.basevalidators
class SizeValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name='size', parent_name='pie.hoverlabel.font', **kwargs
):
super(SizeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=paren... |
# Generated by Django 2.2.24 on 2021-11-19 10:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('collect', '0015_auto_20211109_1123'),
]
operations = [
migrations.RenameField(
model_name='collectactivity',
old_name='type... |
"""
Operations for a ``Number`` class
"""
import cake
import operator
operator.divmod = divmod
# Add divmod function to operator interface
def evaluate(N, O, *, return_class = None, func: str = 'add'):
"""
Evaluate 2 tokens, if implementing in custom class, N will be self/current value
Parameters
--... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'depot_tools/bot_update',
'depot_tools/gclient',
'depot_tools/git',
'recipe_engine/path',
'recipe_engine/properties',
'recipe_engine/py... |
from .import db
from flask_login import UserMixin
from . import login_manager
from werkzeug.security import generate_password_hash,check_password_hash
from datetime import datetime
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(UserMixin,db.Model):
''' class ... |
#!/usr/bin/env python
from __future__ import print_function
import numpy as np
import cv2
import tensorflow as tf
import threading
import sys
import time
import os
def MakeDir(path):
try:
os.makedirs(path)
except:
pass
lab = False
load_model = False
train = True
test_display = True
test_writ... |
class APIEndPoints:
__GET_GEOLOCATION_API = 'https://api.weather.com/v3/location/search?apiKey=d522aa97197fd864d36b418f39ebb323&format=json&language=en-IN&locationType=locale&query={name_of_place}'
__GET_WEATHER_DATA = 'https://api.weather.com/v2/turbo/vt1dailyForecast?apiKey=d522aa97197fd864d36b418f39ebb... |
# plots.py
"""Volume 1A: QR 2 (Least Squares and Computing Eigenvalues). Plotting file."""
from __future__ import print_function
import matplotlib
matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc')
from matplotlib import pyplot as plt
from functools import wraps
from sys import stdout
import os... |
import os
import tensorflow as tf
from nets import nets_factory
import time
from dl.step1_cnn import Step1CNN
from dl.step2_cnn import Step2CNN
from dl.util import get_labels_to_names
import GPUtil as GPU
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings")
django.setup()
from goods.models im... |
import base64
import hashlib
import hmac
import json
import typing as t
from datetime import datetime, timedelta, timezone
def hmac_data(key: bytes, data: bytes) -> bytes:
return hmac.new(key, data, hashlib.sha256).digest()
class WebhookVerificationError(Exception):
pass
class Webhook:
_whsecret: byte... |
"""
Usage:
# Create train data:
python xml_to_csv.py -i [PATH_TO_IMAGES_FOLDER]/train -o [PATH_TO_ANNOTATIONS_FOLDER]/train_labels.csv
# Create test data:
python xml_to_csv.py -i [PATH_TO_IMAGES_FOLDER]/test -o [PATH_TO_ANNOTATIONS_FOLDER]/test_labels.csv
"""
import os
import glob
import pandas as pd
import argparse
... |
# Generated by Django 2.0.7 on 2018-07-31 11:52
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DeviceInfo',
fields=[
('devid', models.Auto... |
"""Anonymous functions - lambda."""
#lambda [arg1 [,arg2,.....argn]]:expression
#!/usr/bin/python
# Function definition
# sum1 = lambda a, b: a + b
#
# # Sum as a function
# print("sum1 : ", sum(10, 20))
# print("sum1 : ", sum(20, 20))
def key1(x):
return x[1]
a = [(1, 2), (3, 1), (5, 10), (11, -3)]
a.sort(key... |
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import csv
import io
import json
import os
import re
from ast import literal_eval
import requests
import semver
from ..utils import dir_exists, file_exists, read_file, write_file
from .config import load... |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
return len_of_longest_substring_no_repeat(s)
def len_of_longest_substring_no_repeat(s):
n = len(s)
res = 0
sub_str = set()
l = 0
r = 0
while r < n:
if s[r] not in sub_str:
sub_str.add(s[r])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.