text stringlengths 1 927k |
|---|
# Copyright 2019 Miguel Angel Abella Gonzalez <miguel.abella@udc.es>
#
# 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 ap... |
from .canvas import DefaultCanvas
from ...cell_fabric.generators import *
from ...cell_fabric.grid import *
import logging
logger = logging.getLogger(__name__)
class MOSGenerator(DefaultCanvas):
def __init__(self, pdk, height, fin, gate, gateDummy, shared_diff, stack, bodyswitch):
super().__init__(pdk)
... |
import torch
import torch.nn as nn
import math
import numpy as np
def weights_init(m):
if type(m) == nn.Linear:
nn.init.xavier_uniform_(m.weight)
def pate(data, teachers, lap_scale, device="cpu"):
"""PATE implementation for GANs.
"""
num_teachers = len(teachers)
labels = torch.Tensor(num... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-24 08:44
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dashboard2', '0004_auto_20170310_1811'),
]
operations = [
migrations.DeleteModel(
... |
"""
Python program to implement Graph
@Author: Archibald
@Date: Sept. 12
"""
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [None] * self.V
def add_directed_edge(self, tail, header):
node = Node(header)
node.next = self.graph[tail]
self.graph... |
from __future__ import print_function
import traceback
try:
import pbundler
pbundler.PBundler.setup()
except:
print("E: Exception in pbundler activation code.")
print("")
print("Please report this to the pbundler developers:")
print(" http://github.com/zeha/pbundler/issues")
print("")
... |
"""
Expression splitting for chunked computation
To evaluate an expression on a large dataset we may need to chunk that dataset
into pieces and evaluate on each of the pieces individually. This module
contains logic to break up an expression-to-be-evaluated-on-the-entire-array
into
1. An expression to be evaluated ... |
import webbrowser
from tornado import ioloop, web
from minotor.api.projection_handler import ProjectionHandler
from minotor.api.data_handler import DataHandler
from minotor.api.training_data_handler import TrainingDataHandler
from minotor.constants import PACKAGE_PATH
# Defining constants
REACT_BUILD_PATH = PACKAGE... |
"""Offer time listening automation rules."""
import logging
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.const import CONF_PLATFORM
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.event import async_track_time_change
# mypy: allow-untyped-d... |
import torch
import matplotlib.pyplot as plt
from torchvision import datasets, transforms
from random import choice
BATCH_SIZE=64
# Load the mnist dataset
train_loader = torch.utils.data.DataLoader(
datasets.MNIST(
"./data",
train=True,
download=True,
transform... |
#########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. 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... |
"""converted from ..\fonts\tvga9000i-2__8x8.bin """
WIDTH = 8
HEIGHT = 8
FIRST = 0x20
LAST = 0x7f
_FONT =\
b'\x00\x00\x00\x00\x00\x00\x00\x00'\
b'\x18\x3c\x3c\x18\x18\x00\x18\x00'\
b'\x6c\x6c\x6c\x00\x00\x00\x00\x00'\
b'\x6c\x6c\xfe\x6c\xfe\x6c\x6c\x00'\
b'\x18\x7e\xc0\x7c\x06\xfc\x18\x00'\
b'\x00\xc6\xcc\x18\x30\x66\x... |
import snap7
from snap7.util import *
from snap7.snap7types import *
import struct
s1500=snap7.client.Client()
s1500.connect('172.16.6.200',rack=0,slot=1)
Real_Value=s1500.read_area(0x84,38,0,1)
print(Real_Value)
order = '00PP000022'
byarray=bytearray(order,encoding='utf-8')
print(byarray)
productNo = '00A03'
produ... |
__all__ = ["EvaluatingInferencer"]
from dataclasses import dataclass
from typing import Sequence
import torch
import torch.utils.data as td
import utils
from datasets import BatchData
from .inferencer import Inferencer
from evaluators import FinegrainedEvaluator
@dataclass
class EvaluatingInferencer(Inferencer):
... |
# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
# Modifications Copyright OpenSearch Contributors. See
# GitHub history for details.
# Licensed to Elasticsearch B.V. under one ... |
# -*- coding=gbk -*-
#-----------------------------------------------------------
# Copyright (c) 2015 by Aixi Wang <aixi.wang@hotmail.com>
#-----------------------------------------------------------
import random, time
import os
import sys
import thread, threading, subprocess
#import mosquitto
import leveldb
RPC_V... |
from .typefire import Switch, Agreement, TypeFire, typefire, composed, typeswitch, likefire |
def main():
print('monthly reset')
if __name__ == '__main__':
main() |
import tensorflow as tf
tfk = tf.keras
from .shaping import move_dim
def move_ch2h(maybe_headed_tensor,
channels_dim=-1, head_dim=1):
if maybe_headed_tensor.shape.rank == 4:
return move_dim(maybe_headed_tensor,
from_dim=channels_dim,
to_dim=he... |
from tkinter import *
root = Tk()
'''
Creating a label widget
'''
mylabel = Label(root, text= 'Hello World')
mylabel.pack()
root.mainloop() |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from .ga import GeneticAlgorithm
from . import objectives as ga_objectives
import deap
import warnings
class AutoGeneS:
PLOT_PARAMS = {
'small': {
'figsize': (10,5),
'all_ms': 8,
'sel_ms': 10
... |
"""
This is taken from "Simple Usage" page in the docs:
http://sanic-jwt.readthedocs.io/en/latest/pages/simpleusage.html
"""
from sanic import Sanic, response
from sanic_jwt import exceptions
from sanic_jwt import Initialize, protected
class User:
def __init__(self, id, username, password):
self.user_id ... |
BRAND_A = ["jablka", "hrusky"]
BRAND_B = ["jablka", "banany"]
BRAND_C = ["banany"]
def search_a(item):
if item in BRAND_A:
return True
else:
return False
def search_b(item):
if item in BRAND_B:
return True
else:
return False
def search_c(item):
if item in BRAND_... |
from collections import OrderedDict
import six
from .base import _cls_init
from .parsing import (
_register_marking, _register_object, _register_observable,
_register_observable_extension,
)
def _get_properties_dict(properties):
try:
return OrderedDict(properties)
except TypeError as e:
... |
from pprint import pprint
from configparser import ConfigParser
from ibc.client import InteractiveBrokersClient
# Initialize the Parser.
config = ConfigParser()
# Read the file.
config.read('config/config.ini')
# Get the specified credentials.
account_number = config.get('interactive_brokers_paper', 'paper_account')... |
# for saving files
from PyQt5 import QtCore, QtGui, QtWidgets
import sys,csv
from measurement_gui import Ui_Measurement
from PyQt5.QtWidgets import QFileDialog
import serial,itertools
class Measurement(QtWidgets.QMainWindow, Ui_Measurement):
def __init__(self,parent = None):
super(Measurement,self).__init_... |
# Copyright (c) 2017, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import pandas as pd
import numpy as np
import random
import tempfile
import unittest
import pytest
from... |
# 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 ... |
import cfenv
env = cfenv.AppEnv()
__all__ = ['env'] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2019 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... |
"""
Django settings for footballnews project.
Generated by 'django-admin startproject' using Django 1.11.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
impo... |
import tensorflow as tf
import time
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
beginTime=time.time()
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
learning_rate = 0.01
training_iterations = 30
batch_size = 100
display_step = 2
x = tf.placeholder("float... |
# Copyright (c) 2021 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 appli... |
from utils.addressing import AddressParser
class Disassembler:
def __init__(self, mpu, address_parser=None):
if address_parser is None:
address_parser = AddressParser()
self._mpu = mpu
self._address_parser = address_parser
self.addrWidth = mpu.ADDR_WIDTH
self.... |
#!c:\users\hp\chat\new\scripts\python.exe
# -*- coding: utf8 -*-
# :Copyright: © 2015 Günter Milde.
# :License: Released under the terms of the `2-Clause BSD license`_, in short:
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the cop... |
# optimizer
optimizer = dict(type='SGD', lr=0.001, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=0.001,
step=[8, 11])
total_epochs = 12 |
"""
Django settings for paymentsapp_project project.
Generated by 'django-admin startproject' using Django 3.0.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
... |
from flask import Flask
# 플라스크를 import한다
#
app = Flask(__name__)# flask객체 생성
# URL /의 GET요청에 대해 뷰 함수를 등록
# @표시는 데코레이터라고 한다
# Flask에서 URL을 처리하는 방법을 URL Dispath라고한다.
# 밑의 코드는 클라이언트가 /를 요청하면 helloworld라는 함수를 실행한다는 것
# route 데코레이터에 추가된 함수를 뷰 함수라고 한다
@app.route("/")
def helloworld():# 뷰 함수
return "Hello world flask"
... |
LOGGER_NAME = "cli"
PLUGIN_PREFIX = "BUILDKITE_PLUGIN_GIT_DIFF_CONDITIONAL" |
"""
Problem Statement:
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
from __future__ import print_function
def solutio... |
import numpy
import scipy.signal
from generate import *
def generate():
def process(factor, x):
out = scipy.signal.decimate(x, factor, n=128 - 1, ftype='fir', zero_phase=False)
return [out.astype(type(x[0]))]
vectors = []
x = random_complex64(256)
vectors.append(TestVector([2], [x], ... |
# SPDX-FileCopyrightText: 2022 Tim Hawes <me@timhawes.com>
#
# SPDX-License-Identifier: MIT
from django.contrib import admin
from .models import ChangeOfAddress, GroupPolicy, MailingList
class GroupPolicyInline(admin.TabularInline):
model = GroupPolicy
fields = ("group", "policy", "prompt")
extra = 0
... |
# -*- coding: utf-8 -*-
"""
This module offers a generic date/time string parser which is able to parse
most known formats to represent a date and/or time.
This module attempts to be forgiving with regards to unlikely input formats,
returning a datetime object even for dates which are ambiguous. If an element
of a dat... |
from scipy.io import loadmat
import numpy as np
import pandas as pd
import sklearn.preprocessing
from sklearn import preprocessing
class kamitani_data_handler():
"""Generate batches for FMRI prediction
frames_back - how many video frames to take before FMRI frame
frames_forward - how many video frames to ... |
#!/usr/bin/env python
#
# Helper Functions.
# file : Functions.py
# author : Tom Regan <noreply.tom.regan@gmail.com>
# since : 2011-07-19
# last modified : 2011-08-04
#!/usr/bin/env python
def binary(number, size=1, extend=False):
"""Improved bin function that can return two's compleme... |
from tempfile import TemporaryDirectory
import numpy as np
from numpy.testing import assert_allclose
from astropy import units as u
from ctapipe.reco.energy_regressor import EnergyRegressor
def test_prepare_model():
cam_id_list = ["FlashCam", "ASTRICam"]
feature_list = {"FlashCam": [[1, 10], [2, 20], [3, 3... |
from django.contrib import admin
# Register your models here.
from notification_service.models import Message
@admin.register(Message)
class MessageAdmin(admin.ModelAdmin):
pass |
# Copyright 2018 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 = [
'recipe_engine/cipd',
'recipe_engine/context',
'recipe_engine/json',
'recipe_engine/path',
'recipe_engine/platform',
'recipe... |
"""
Check lesson files and their contents.
"""
import os
import glob
import re
from argparse import ArgumentParser
from util import (Reporter, read_markdown, load_yaml, check_unwanted_files,
require)
__version__ = '0.3'
# Where to look for source Markdown files.
SOURCE_DIRS = ['', '_episodes', '_... |
import os
import sys
from abc import ABC, abstractmethod
from collections import namedtuple
from dagster import check
from dagster.core.definitions.reconstructable import ReconstructableRepository
from dagster.core.types.loadable_target_origin import LoadableTargetOrigin
from dagster.serdes import create_snapshot_id, ... |
from django.db import models
class AvailabilityTest(models.Model):
primary_key = models.CharField(max_length=20, primary_key=True)
last_access = models.DateTimeField(help_text='Datetime of last access to this model from the celery task') |
from django.apps import AppConfig
class CommentappConfig(AppConfig):
name = 'commentapp' |
import plotly_study
import os
import shutil
import pytest
# Fixtures
# --------
@pytest.fixture()
def setup():
# Reset orca state
plotly_study.io.orca.config.restore_defaults(reset_server=False)
here = os.path.dirname(os.path.abspath(__file__))
# Run setup before every test function in this file
pytestmar... |
import json
import logging
import storage
from defs import DeviceRequest
from device.models import Device, DeviceAddress
from hint.models import HintAuthentication
from hint.procedures.request_library import create_device
LOGGER = logging.getLogger(__name__)
"""
This module specifies the handling of device message... |
class TransactionHooksDatabaseWrapperMixin(object):
"""
A ``DatabaseWrapper`` mixin to implement transaction-committed hooks.
To use, create a package for your custom database backend and place a
``base.py`` module within it. Import whatever ``DatabaseWrapper`` you want
to subclass (under some othe... |
"""
Q647
Palindromic Substrings
Medium
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different
substrings even they consist of same characters.
"""
class Solution:
def countSubstrings(self, s: str... |
# -*- coding: utf-8 -*-
#
# clan documentation build configuration file, created by
# sphinx-quickstart on Fri Apr 15 21:52:09 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All co... |
#!/usr/bin/env python
"""Handles run."""
__author__ = 'pramodg@room77.com (Pramod Gupta)'
__copyright__ = 'Copyright 2012 Room77, Inc.'
import itertools
import json
import os
import re
import sys
import time
from pylib.base.flags import Flags
from pylib.base.exec_utils import ExecUtils
from pylib.base.term_color im... |
#!/usr/bin/env python3
# Copyright (c) 2019-2020 The YieldStakingWallet developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
Covers various scenarios of PoS blocks where the coinstake input is already spent
(either in a ... |
"""Exceptions for pymoney"""
class MoneyError(Exception):
"""Generic Money error"""
class InvalidAmount(MoneyError, ValueError):
"""Raised when the amount of money is invalid"""
class CurrencyMismatch(MoneyError, ValueError):
"""Raised when a operation is performed on money with different
currenci... |
# -*- encoding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
import objc
from GlyphsApp import *
from GlyphsApp.plugins import *
if int(Glyphs.versionNumber) == 3:
from GlyphsApp import GSMouseOverButton, GSScriptingHandler
from AppKit import (
NSButton,
NSMiniControlSize,
... |
# orm/loading.py
# Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""private module containing functions used to convert database
rows into object inst... |
"""
Module for fetching artifacts from Nexus 3.x
.. versionadded:: 2018.3.0
"""
import base64
import http.client
import logging
import os
import urllib.request
from urllib.error import HTTPError, URLError
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
try:
... |
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from modules.utils import plots
from modules.utils import firefox_dataset_p2 as fd
from modules.utils import tokenizers as tok
from modules.utils import aux_functions
from modules.models.lda import LDA... |
import asyncio
from itertools import zip_longest
import os
import os.path
from bs4 import BeautifulSoup
from tqdm import tqdm
import aiohttp
from jinja2 import Environment, PackageLoader
from pubmedasync.fetch import Fetcher
from geneinfo.make_table import make_table
from geneinfo.process import extract_paper_info
... |
""" Pruning a pre-trained model by GSP.
Author: Ruizhe Zhao
Date: 12/02/2019
The work-flow of this script:
- load a pre-trained model (suffixed by 'm')
- compute the mask based on weights
- fine-tune the model
"""
import os
import sys
import argparse
import copy
import time
import shutil
import json
import logging
... |
import os
import subprocess
import csv
from operator import itemgetter
point = { }
with open('scorecard.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
total = 0
if line_count == 0:
line_count += 1
else:
... |
BINARY_DOCKER_COMPOSE_VERSION = '1.29.1'
DEFAULT_DIRECTORY_BASE = '/opt/'
DEFAULT_DIRECTORY_INSTALLATION = '/opt/mayan-edms/'
DEFAULT_DIRECTORY_MEDIA_ROOT = '/opt/mayan-edms/media/'
DEFAULT_DATABASE_NAME = 'mayan'
DEFAULT_DATABASE_PASSWORD = 'mayanuserpass'
DEFAULT_DATABASE_USER = 'mayan'
DEFAULT_OS_GROUP = 'mayan'
DEF... |
from StringIO import StringIO
import copy
import logging
import hashlib
import itertools
from lxml import etree
import os
import re
import json
from collections import defaultdict
from xml.dom.minidom import parseString
from diff_match_patch import diff_match_patch
from django.core.cache import cache
from django.templ... |
# Copyright (c) 2019 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 appli... |
# 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 ... |
# -*- coding: utf-8 -*-
from ccxt.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
class therock (Exchange):
def describe(self):
return self.deep_extend(super(therock, self).describe(), {
'id': 'therock',
'name': 'TheRockTrading',
... |
"""
Check out this website for the entire Unicode characters list:
http://unicode-table.com
"""
import config
# *_PATCHED glyphs exist only in patched fonts (available at:
# https://github.com/Lokaltog/powerline-fonts).
DIVIDER_RIGHT_PATCHED = chr(57520)
DIVIDER_RIGHT_SOFT_PATCHED = chr(57521)
DIVIDER_LEFT_PATCHED = ... |
import datetime
import os
import re
import pandas as pd
import pytest
from ruamel.yaml import YAML
from great_expectations import DataContext
from great_expectations.core import ExpectationSuite
from great_expectations.core.batch import Batch, RuntimeBatchRequest
from great_expectations.data_context import BaseDataCo... |
"""The tests for the demo stt component."""
import pytest
from homeassistant.components import stt
from homeassistant.setup import async_setup_component
@pytest.fixture(autouse=True)
async def setup_comp(hass):
"""Set up demo component."""
assert await async_setup_component(hass, stt.DOMAIN, {"stt": {"platfo... |
#Perform Edge Detection using Roberts Cross Gradient & Sobel Operators over an Image
import cv2
import math
import numpy as np
def robertCrossGradient(image):
#Objective: Performing Robert Cross Gradient Edge Detection over an Image
#Input: Original Image
#Output: Resultant Image
#Robert Cross Operator
# x 0 ... |
# Model Imports
from .models import PollVote, Poll, PollChoice, Post, post_content_types, PostContent
# Util Imports
from .utils import PollVoteUtil
import base64
from django.core.files.base import ContentFile
# Library Imports
from datetime import datetime, timedelta
from django.utils import timezone
from django.fo... |
import torch
import torch.nn as nn
import torch.nn.functional as F
# pretrained BPE Tokenizer
from transformers import BertTokenizer
"""
tokenizer = Tokenizer()
print(tokenizer.get_vocab_size())
print()
print(tokenizer.get_vocab())
50265
"""
class Tokenizer():
def __init__(self, language, max_len):
self.... |
#!/usr/bin/env python3
import argparse
import json
import logging
import multiprocessing
import shutil
import time
from conflation import aggregation, util
from conflation.map_matching import valhalla
from conflation.trace_fetching import mapillary, mapillary_v3, auth_server
def main():
arg_parser = argparse.Arg... |
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
import math
import numpy as np
from scipy import linalg
from os import path as osp
import cv2
import random
import matplotlib.pyplot as plt
import pdb
#0. torch imports
import torch
from torch.utils.data import DataLoader,Dataset
from torch import optim,nn
import tor... |
#!/usr/bin/env python3
#
# linearize-hashes.py: List blocks in a linear, no-fork version of the chain.
#
# Copyright (c) 2013-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from __future__ impo... |
# 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 ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
"""Seasons_Greetings URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
C... |
import nonebot
from nonebot.adapters.cqhttp.message import Message
from nonebot.matcher import Matcher
from nonebot.typing import T_State
from nonebot.plugin import on_command
from nonebot.adapters.cqhttp import Bot, MessageEvent
import userlib
import os
from userlib.wiki import EntryInfoBase, WikiBase
from userlib.... |
import cv2
import mediapipe as mp
import os
def main():
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
drawing_styles = mp.solutions.drawing_styles
# fn = filename; Images in the img folder
IMAGE_FILES = ['img/' + str(fn) for fn in next(os.walk('./img'))[2]]
with mp_ha... |
"""
@author: ksanoo
@updated_at: 12/4/2020
@description: All parameters that are to be swept (specified in sweep_setup files) must have a class definition in
this script. The class name must be the same as the parameter key in loop_param
"""
import global_vars as swp_gbl
from parameter_classes import GenericParam
impo... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
# 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 ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# -*- encoding: utf-8 -*-
__all__ = [ 'NodeInterfaceError' ]
class NodeInterfaceError(BaseException) :
pass |
''' Opening and Reading Files
Syntax to open file.
f = open("Myfile.txt) # assigned to the variable f.
''' |
from discord.ext import commands
from discord.ext.commands import Bot, Context
from models.command import CommandInfo
import config
from util.discord.channel import ChannelUtil
from util.discord.messages import Messages
from util.env import Env
from db.models.favorite import Favorite
from db.models.user import User
fr... |
import pytorch_lightning as pl
from torch.utils.data import DataLoader
class plDataModule(pl.LightningDataModule):
def __init__(
self,
train_dataset,
val_dataset,
test_dataset=None,
num_workers=2,
train_sampler=None,
train_shuffle=True,
train_batch_s... |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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... |
#!/usr/bin/env python2
# coding: utf-8
"""Test immutable registers."""
import unittest
import random
from triton import *
class TestImmutableAArch64Registers(unittest.TestCase):
def setUp(self):
"""Define the arch."""
self.ctx = TritonContext()
self.ctx.setArchitecture(ARCH.AARCH64)
... |
from abc import ABCMeta, abstractmethod
from copy import deepcopy
class Prototype(metaclass=ABCMeta):
@abstractmethod
def clone(self):
pass
class Concrete(Prototype):
def clone(self):
return deepcopy(self)
prototype = Concrete()
foo = prototype.clone()
bar = prototype.clone()
print(... |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... |
# -*- coding: utf-8 -*-
"""The SleuthKit (TSK) file entry implementation."""
import copy
import decimal
from dfdatetime import definitions as dfdatetime_definitions
from dfdatetime import factory as dfdatetime_factory
from dfdatetime import interface as dfdatetime_interface
import pytsk3
from dfvfs.lib import defin... |
import copy
import os
import re
import json
import sys
import warnings
from collections import namedtuple
from datetime import datetime
from enum import Enum, unique
from json import JSONDecodeError
from operator import lt, le, eq, ge, gt
from boto3 import Session
from collections import OrderedDict
from moto.core.ex... |
from __future__ import division
from __future__ import absolute_import
# from __future__ import unicode_literals
from sklearn.feature_extraction.text import strip_accents_ascii, \
strip_accents_unicode
def clean(s, lowercase=True, replace_by_none=r'[^ \-\_A-Za-z0-9]+',
replace_by_whitespace=r'[\-\_]', ... |
"""Tools for summarizing lightcurve data into statistics"""
import numpy as np
import scipy.optimize as spo
from tensorflow.contrib.framework import nest
from justice import lightcurve
from justice import xform
def opt_alignment(
lca: lightcurve._LC,
lcb: lightcurve._LC,
ivals=None,
constraints=None... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.