content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
from . import ecode, remove_line_with, remove_new_lines
sign = "Одесский Клуб Рыболовов: "
mark1 = "Ответ в теме "
mark2 = "Перейти к сообщению"
mark3 = " только что ответил в теме, на которую Вы подписались"
mark4 = "но Вы не будете получать уведомления, пока снова не посетите форум."
def st... |
from elm import ELM
import numpy as np
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import pandas as pd
import matplotlib.pyplot as plt
import seaborn a... |
import numpy as np
from model import model
import pickle
class PredictIntent:
def __init__(self):
with open("vocab.pkl", 'rb') as data0:
data = pickle.load(data0) #data is a set
self.intents = {'forward':0,'backward':1,'type':2, 'reload':3, 'down':4,
... |
import os
import pwd
import random
import bagit
from django.test import TransactionTestCase, Client
from django.conf import settings
from bag_transfer.lib.cron import DiscoverTransfers, DeliverTransfers
from bag_transfer.test import helpers
from bag_transfer.test.setup import BAGS_REF, TEST_ORG_COUNT
from bag_transfe... |
import json
import os
import zipfile
config = {
"path_to_zip_files": "/Users/nslobodchuk/Projects/twitter-data/twitter-data-zip_",
"working_directory": "/Users/nslobodchuk/Projects/twitter-data/twitter-data-working-directory"
}
zip_files_names = os.listdir(config["path_to_zip_files"])
output = "#!/bin/bash \n"
for... |
from django.apps import AppConfig
class SwdistribsConfig(AppConfig):
name = 'SWDistribs'
|
# Copyright 2017 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.
import copy
from gae_libs.testcase import TestCase
from waterfall.flake import lookback_algorithm
from waterfall.flake.lookback_algorithm import Normalized... |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name="batching-kafka-consumer",
version="0.0.5",
author="Sentry Team and Contributors",
author_email="hello@getsentry.com",
url="https://github.com/getsentry/batching-kafka-consumer",
description="Kafka Consumer abstracti... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 9 14:35:38 2021
@author: s1253
"""
import numpy as np
import sklearn.preprocessing as preprocessing
from sklearn.model_selection import train_test_split
from util import load_dataframe
from tensorflow.keras.layers import Input, Conv2D, Flatten, Dense, Activation, Batch... |
'''
https://gamedev.stackexchange.com/questions/126353/how-to-rotate-an-image-in-pygame-without-losing-quality-or-increasing-size-or-mo
'''
import math
import pygame
class GameObject(pygame.sprite.Sprite):
def __init__(self, image, rect):
pygame.sprite.Sprite.__init__(self)
self._position = [0, 0]... |
"""
Copyright 2009 Josh Marshall
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, softwar... |
"""Using the higher order function filter(), define a function
filter_long_words() that takes a list of words and an integer n
and returns the list of words that are longer than n."""
def filter_long_words(words, n):
pass
#test
print(filter_long_words(['that', ' was', 'not', 'funny', 'at', 'all'], 3)) |
import logging
import configparser
from src.bot import Bot
import time
if __name__ == "__main__":
# config file parser initialization
config = configparser.ConfigParser()
config.read("config.ini", encoding="utf-8")
# custom logging format
logging.basicConfig(
level=logging.DEBUG
i... |
"""
Advent of code 2021
Day 22: Reactor Reboot
"""
import re
from dataclasses import dataclass
from aoc.loader import LoaderLib
from aoc.utility import lines_to_list
LINE_RE = re.compile(r'(\w+) x=(-?\d+)\.\.(-?\d+),y=(-?\d+)\.\.(-?\d+),z=(-?\d+)\.\.(-?\d+)')
def clipped_range(a: int, b: int):
if a > 50 or b < ... |
# Generated by Django 3.1 on 2020-11-10 09:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('package', '0011_package_package_type'),
]
operations = [
migrations.AddField(
model_name='gaduurpackage',
... |
'''
Write a Python program to add member(s) in a set.
'''
set1 = set([2, 4, 8, 10])
num = [1]
print("Origin set without the new member is: {}".format(set1))
print()
set1.update(num)
print("New set with the new member is: {}".format(set1)) |
from flask import Flask, request, make_response, redirect
from flask_restful import Api, Resource
from math import log10
from os import statvfs
from uptime import boottime
from datetime import datetime
from collections import namedtuple
from time import sleep
import os
import htu21
from ht0740 import HT0740
disk_named... |
for _ in range(int(input())) :
n = int(input())
arr = list(map(int, input().split()))
x = min(arr)
if(arr.count(x)%2 is 0) :
print("Unlucky")
else :
print("Lucky") |
from __future__ import print_function, division
from vec3 import Vec3
from math import sqrt, atan2, asin, pi
from material import Material
from aabb import Aabb
from random import randint
import sys
def getSphereUv(p):
phi = atan2(p.z,p.x)
theta = asin(p.y)
u = 1-(phi + pi)/(2*pi)
v = (theta +pi/2) / pi
retu... |
from bisect import bisect_left, bisect_right
class Result:
def __init__(self, index, value):
self.index = index
self.value = value
class BinarySearch:
def __init__(self):
pass
@staticmethod
def greater_than(num: int, func, size: int = 1):
"""Searches for smallest eleme... |
import os
import shutil
import fnmatch
import filecmp
import sys
import glob
import re
import subprocess
import json
import ciutil
_this_dir = os.path.dirname(os.path.abspath(__file__))
premake_workspace = ciutil.read_text_file(os.path.join(_this_dir,"templates","premake_workspace_template.txt"))
p... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 16:35:59 2020
@author: agarwal.270a
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import tensorflow.keras.layers as layers
#import modules.custom_layers as clayers
from tensorflow.keras import... |
import heapq
from .event import Event
from ..base import BaseSimObj
class EventQueue(BaseSimObj):
""" Queue which stores simulation events.
Args:
events (List[Event]): A list of Event-like objects.
"""
def __init__(self, events=None):
self._queue = []
if events is not None:
... |
from django.db.models import PositiveIntegerField
class PositiveIntegerRangeField(PositiveIntegerField):
"""Field for Integers in a specific, positive range.
This class was based off of <a href="
https://stackoverflow.com/questions/849142/how-to-limit-the-maximum-value-of-a-numeric-field-in-a-django-mode... |
from django.apps import AppConfig
class WagtailHoneypotTestAppConfig(AppConfig):
label = "wagtail_honeypot_test"
name = "wagtail_honeypot.test"
verbose_name = "Wagtail Honeypot tests"
|
import pathlib
import ssl
import aiohttp
import pytest
from aiohttp import web
from aiohttp.test_utils import make_mocked_request
from yarl import URL
from aiohttp_remotes import Secure
from aiohttp_remotes import setup as _setup
@pytest.fixture
def here():
return pathlib.Path(__file__).parent
@pytest.fixture... |
from .LoadJson import LoadJson
|
#_*_coding:utf-8_*_
__author__ = 'jieli'
import datetime
import re
from django import template
from django.utils.safestring import mark_safe
from django.urls import reverse as url_reverse
register = template.Library()
@register.simple_tag
def query_set(table_related_field,query_field,string):
data_set = tab... |
import os
import csv
from flask import jsonify, current_app
# Returns list of models contained within metadata directory
# TODO: filter so that it only returns folders that have a theta.csv or something
def get_models_list():
return os.listdir(current_app.config['METADATA_ROOT'])
# Old versions of Serendip stored... |
# -*- coding: utf-8 -*-
import unittest
import pymongo
from datetime import datetime, timedelta
from mongoengine.queryset import (QuerySet, MultipleObjectsReturned,
DoesNotExist)
from mongoengine import *
class QuerySetTest(unittest.TestCase):
def setUp(self):
connect... |
import numpy as np
def luptitude(mag, depth, m0=22.5):
"""
Convert magnitudes to luptitudes
Parameters
----------
mag: float or array
depth: float
estimate of e.g. 10 sigma depth
m0: float
optional mag zero point (default 22.5)
Returns
-------
lupt: float or... |
# Copyright (C) 2019 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import random
from datetime import datetime
import helper
from locust import task
class SaleTaskSet(helper.BaseBackendTaskSet):
def on_start(self, *args, **kwargs):
super(SaleTaskSet, self).on_sta... |
from django.contrib import admin
from .models import Task
@admin.register(Task)
class TaskAdmin(admin.ModelAdmin):
list_display = ['id', 'title', 'project', 'created', 'estimate', 'is_done']
class Meta:
model = Task
|
from sys import getdefaultencoding
from NERDA.models import NERDA
from NERDA.datasets import get_dane_data
from hyperopt import fmin, hp, tpe, space_eval
from hyperopt.pyll import scope
import numpy as np
def objective(params):
print(params)
model = NERDA(dataset_training = get_dane_data('train', 20),
... |
import pytest
from virt_backup.domains import (
search_domains_regex,
get_domain_disks_of,
get_domain_incompatible_disks_of,
)
from virt_backup.exceptions import DiskNotFoundError
from helper.virt_backup import MockDomain
def test_get_domain_disks_of(build_mock_domain):
domain = build_mock_domain
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import pickle
import numpy as np
from mmdet.core import multiclass_nms
from mmcv.runner import force_fp32
from .convfc_bbox_head import Shared2FCBBoxHead
from mmdet.models.builder import HEADS, build_loss
@HEADS.register_module()
class GSBBoxHeadWith... |
import json
import sys
import logging
from panos.firewall import Firewall
from prtg.sensor.result import CustomSensorResult
from prtg.sensor.units import ValueUnit
import lxml.etree as ET
logging.basicConfig(filename="Power_supply_sensor_debug.log",
filemode='a',
... |
#! usr/bin/env python3
#Arnas Steponavicius
#Program header function
def header():
"""Header for program"""
print("|===========================|")
print("| Graph Theory |")
print("| Arnas Steponavicius |")
print("| G00361891 |")
print("|=======================... |
result = 0 > 0.0
result2 = 0 < 0.0
result3 = 0.0 > 0
result4 = 0.0 < 0 |
import hail as hl
S = 500
V = 2000
mt = hl.balding_nichols_model(1, S, V, 500)
mt = mt.annotate_cols(n_called = hl.agg.filter(hl.is_defined(mt.GT), hl.agg.count()))
mt = mt.filter_cols(mt.n_called > 0).count()
|
"""An example of a test command with an argument."""
import lldb
from lldb_script_utils import debugger_utils
from lldb_script_utils import lldb_commands
def __lldb_init_module(debugger: lldb.SBDebugger, _: dict) -> None:
# pylint: disable=invalid-name
TestCommand1.lldb_init_class(debugger)
class TestComm... |
from flask_wtf import FlaskForm
from flask_wtf.file import FileRequired, FileAllowed
from flask_uploads import UploadSet, IMAGES
from wtforms import FileField, SubmitField
from wtforms.validators import DataRequired
images = UploadSet('images', IMAGES)
class UploadImage(FlaskForm):
img = FileField('Add Image',
... |
import contextlib
from io import StringIO
from twisted.trial import unittest
from lbrynet.extras.cli import normalize_value, main
from lbrynet.extras.system_info import get_platform
class CLITest(unittest.TestCase):
def test_guess_type(self):
self.assertEqual('0.3.8', normalize_value('0.3.8'))
s... |
from kivy.uix.screenmanager import Screen
class HomeScreen(Screen):
"""
The Welcome Screen
"""
def __init__(self, BippyApp, **kwargs):
super(HomeScreen, self).__init__(**kwargs)
self.BippyApp = BippyApp
return
|
#pylint: disable=C0114, C0116, W0311, W0212, E0110
import pytest
from SnowieCaster import abstract
@pytest.mark.asyncio
async def test_subscription_updater():
abstract.SubscriptionUpdater.__abstractmethods__ = set()
updater = abstract.SubscriptionUpdater()
updater.get_request_delay()
await updater._update_subscrip... |
import discord
from discord.ext import commands
import mysql.connector
class ModerationCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=["mute"])
@commands.has_permissions(manage_messages=True)
async def gulag(self, ctx):
gulag_file = discord.File('gul... |
import json
from server import config
from server.storage.models import SlackUserSubscription
def subscription_modal(state_option=None, district_option=None, age_option=None):
blocks = [
{
"type": "actions",
"elements": [
{
"type": "external_sel... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import ElementClickInterceptedException, StaleElementReferenceException
import time
from random import randint
SEARCH = "_ACCOUNT_YOU_WANT_TO_GET_FOLLOWERS_FROM_"
WEB_PAGE = "https://www.instagram.com/account... |
from rest_framework import serializers
from rest_framework.serializers import (
ModelSerializer,
)
from create_app.models import Post
class CreateSerializer(ModelSerializer):
class Meta:
model = Post
fields = [
'title',
'text',
]
|
# Generated by Django 3.1.12 on 2021-06-03 16:17
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("lti_consumer", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="lticonsumer",
... |
"""
Status: Jim is currently rewriting
https://stackoverflow.com/questions/40450591/converting-json-to-sql-table
DB
- create table
- add entries to table
- 1) for now, overwrite local
- 2) eventually, if any dirty, then fail (handle later)
"""
import math
import os
# Third party imports
... |
notice = """
Hello sideways text Earth Demo
-----------------------------------
| Copyright 2022 by Joel C. Alcarez |
| [joelalcarez1975@gmail.com] |
|-----------------------------------|
| We make absolutely no warranty |
| of any kind, expressed or implied |
|-----------------------------------|
... |
from .multithreading import *
import warnings
warnings.simplefilter('always', DeprecationWarning)
warnings.warn("The 'ubcs_auxiliary.threading' class was renamed to 'ubcs_auxiliary.multithreading' to make room for 'multithreading' and 'multiprocessing'", DeprecationWarning )
|
# coding: utf-8
from flask import Blueprint
from flask import render_template
from ..helpers import require_user
from ..models import Node, Topic, fill_topics
bp = Blueprint('front', __name__)
@bp.route('/')
def home():
"""The homepage of the site."""
topics = Topic.query.order_by(Topic.id.desc()).limit(16... |
from .api import run |
from steem import Steem
s = Steem()
for v in s.get_active_votes('awarenessraiser', 'vlog-13-introduced-high-level-music-ceo-to-steemit-luxury-clips-inside'):
print(v)
'''
python3 get_active_votes.py
{'voter': 'berkah', 'weight': 1084, 'rshares': '9097363023', 'percent': 100, 'reputation': '59326661645', 'time': '... |
from typing import Tuple
import torch.utils.data as data
import numpy as np
from core.config import cfg
from torch.utils.data.dataloader import default_collate
import cv2
import torch
def get_minibatch_blob_names(is_training=True):
"""Return blob names in the order in which they are read by the data loader.
""... |
import clr
# Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to ... |
# -*- coding: utf-8 -*-
# python-holidays
# ---------------
# A fast, efficient Python library for generating country, province and state
# specific sets of holidays on the fly. It aims to make determining whether a
# specific date is a holiday as fast and flexible as possible.
#
# Author: ryanss <ryanssdev@icl... |
from machine import Pin
import _onewire
def init(pin):
Pin(pin, Pin.OPEN_DRAIN, Pin.PULL_UP)
def convert(pin):
_onewire.reset(Pin(pin))
_onewire.writebyte(Pin(pin), 0xcc)
_onewire.writebyte(Pin(pin), 0x44)
def read(pin):
_onewire.reset(Pin(pin))
_onewire.writebyte(Pin(pin), 0xcc)
_onewire.writebyte(P... |
# =============================================================================
# TexGen: Geometric textile modeller.
# Copyright (C) 2015 Louise Brown
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Found... |
#!/usr/bin/env python
'''
@author jstober
'''
import pdb
import sys
import numpy as np
import numpy.linalg as la
import functools
import os
from utils import scatter3d, create_norm_colors, save_many, scatter
from gridworld.gridworld8 import SparseGridworld8 as Gridworld
from gridworld.gridworld8 import SparseRBFGridwo... |
# Module for setting global variables for use in designSets.py and designSetsClasses.py
import sys
def setParameters(descriptor):
global params_descriptor
global is_directional
global RT_rxn_temp
global DNAPOL_rxn_temp
global monovalent_salt_conc
global divalent_salt_conc
global dntp_co... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=C0321,C0103,C0301,E1101,C0303,E1004,C0330,R0915,R0914,W0703,C0326
# Disable many annoying pylint messages, warning me about variable naming for example.
# yes, in my Solr code I'm caught between two worlds of snake_case and camelCase.
__author__ = "N... |
#!/usr/bin/env python3
# Import the value of pi from the math library
from math import pi
def rectangle_area(length, width):
"""
Calculates the area of a rectangle.
:param length: The length of the rectangle.
:param width: The width of the rectangle.
:return: The area of the rectangle.
"""
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author : 陈坤泽
# @Email : 877362867@qq.com
# @Date : 2020/06/02 11:09
from collections import defaultdict, Counter
import sys
import pandas as pd
from pyxllib.prog.newbie import typename
from pyxllib.text.pupil import shorten, east_asian_shorten
from pyxllib.algo.pu... |
import os
root_path = os.path.dirname(os.path.abspath('__file__'))
import sys
sys.path.append(root_path)
from tools.plot_utils import plot_pacf
plot_pacf(
file_path=root_path+'/Xianyang_modwt/data/db10-2/PACF.csv',
save_path=root_path+'/Xianyang_modwt/graph/',
) |
import os as _os
from pathlib import Path as _Path
_version_file = _Path(_os.path.realpath(__file__)).parent / 'VERSION'
__version__ = _version_file.read_text().strip()
|
from click.testing import CliRunner
from tzc.main import cli
from pathlib import Path
def test_conversion(shared_datadir):
INPUT_LINE = '2021-01-01 01:01:02.345678+00:00 test2'
OUTPUT_LINE = '2020-12-31 19:01:02.345678-06:00 test2'
_test(shared_datadir, INPUT_LINE, OUTPUT_LINE, ['-o', 'US/Central'])
def ... |
def moveTower(height,fromPole, toPole, withPole):
if height >= 1:
print " " * (3-height),"moving tower :", height, fromPole,toPole
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole, height)
moveTower(height-1,withPole,toPole,fromPole)
def moveDisk(fp,tp, heigh... |
import os.path as osp
import os
import json as js
import numpy as np
from shutil import copyfile
from PIL import Image
my_labels = ['coach', 'graygirl', 'bluegirl', 'blackgirl', 'blackboy', 'claretgirl', 'orangeboy']
class DataChange:
def __init__(self, rootpath, source_json_path, source_img_path, use... |
import datetime
import json
from datetime import datetime
from django.conf import settings
from django.http import (HttpResponse,
HttpResponseBadRequest,
HttpResponseNotFound)
from django.template.defaultfilters import capfirst, floatformat
from django.utils.translatio... |
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
tracker = cv2.Tracker_create("MIL")
ret, frame = cap.read()
box = (287, 23, 86, 320)
tracker.init(frame,box)
while(1):
ret, frame = cap.read()
ret, box = tracker.update(frame)
if ret:
p1 = (int(box[0]), int(box[1]))
p2 = (int(box... |
from providers import OnLineDataProvider
from agents.data_agent import *
from agents.stock_agent import *
from data_util import *
from providers import *
from cache_providers import *
from sklearn.metrics import *
from collections import Counter
def add_hot_load(minutes,
win,
total,
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 3 19:52:10 2018
@author: weixw
"""
import myTrees as mt
import treePlotter as tp
#测试
dataSet, labels = mt.createDataSet()
#copy函数:新开辟一块内存,然后将list的所有值复制到新开辟的内存中
labels1 = labels.copy()
#createTree函数中将labels1的值改变了,所以在分类测试时不能用labels1
myTree = mt.createTree(dataSet,labels1)
... |
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
stack = root and [root]
va... |
import importlib
from exporter import base
def save(data: dict) -> bool:
module = importlib.import_module('exporter.' + data['name'])
class_ = getattr(module, data['name'].title())
exporter = class_()
success = False
if isinstance(exporter, base.Export):
exporter.execute(data=data)
... |
import logging
from aiogram import Bot, Dispatcher
bot = Bot(token="")
dp = Dispatcher(bot)
logging.basicConfig(level=logging.INFO) |
from django.apps import AppConfig
class JeelizglassesConfig(AppConfig):
name = 'jeelizGlasses'
|
# -*- coding: utf-8 -*-
class BasePermissionChecker(object):
def __init__(self, *checkers):
self._checkers = list(checkers)
super(BasePermissionChecker, self).__init__()
def fill_cache(self, obj, sender):
cache = {}
for c in set(self.get_atomical_checkers()):
cach... |
import argparse
import cv2
# Construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument('-i', '--image', required=True, help = 'Path to the image')
ap.add_argument('-o', '--output', required=True, help = 'Path to saving the image')
args = vars(ap.parse_args())
# load the imag... |
# Generated by Django 2.1.5 on 2019-05-09 10:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rankings', '0038_auto_20190508_1943'),
]
operations = [
migrations.RemoveField(
model_name='competition',
name='impo... |
from mootdx import config
from mootdx.consts import EX_HOSTS
from mootdx.consts import GP_HOSTS
from mootdx.consts import HQ_HOSTS
from mootdx.server import Server
from mootdx.utils import get_config_path
__version__ = '0.7.21'
__author__ = 'bopo.wang<ibopo@126.com>'
|
# %% [markdown]
# <div class="center-wrapper"><div class="video-wrapper"><iframe src="https://www.youtube.com/embed/4UyBxlJChfc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div></div>
# Let's sta... |
from django.shortcuts import render, HttpResponse
from .mlmodel import model_path, label_path, detect
from .models import Roads
from .serializers import RoadSerializer, PostRoadSerializer
from rest_framework import viewsets
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from... |
# coding=utf-8
from rest_framework import viewsets
from pagelink.api.serializers import PageLinkSerializer
from pagelink.api.serializers import PageLinkTrackSerializer
from pagelink.models import PageLink
from pagelink.models import PageLinkTracker
class PageLinkViewSet(viewsets.ReadOnlyModelViewSet):
"""
Ret... |
import torch
from gpytorch.utils.toeplitz import toeplitz_matmul, \
sym_toeplitz_derivative_quadratic_form, index_coef_to_sparse
def kronecker_product(matrices):
"""
Performs Kronecker product of a list of matrices.
Args:
- matrices (a list of matrices)
Returns:
- matrix - the resu... |
from pyhive import hive
connection = hive.Connection(host='hiveserverIp', port=hiveserverPort, username='hive', database='default', auth='KERBEROS', kerberos_service_name="hive", krbhost='hadoop.hadoop.com')
cursor = connection.cursor()
cursor.execute('show tables')
for result in cursor.fetchall():
print(result) |
from zope.interface import implementer
from sqlalchemy import (
Column,
String,
Unicode,
Integer,
Float,
Boolean,
ForeignKey,
UniqueConstraint,
)
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.ext.hybrid import hybrid... |
from gym_numberworld.envs.numberworld_env import NumberWorldEnv |
from django.urls import path
from .views import BotCreateView, BotDetailView, BotListView, BotUpdateView
app_name = 'choices'
urlpatterns = [
path('<int:pk>/edit/', BotUpdateView.as_view(), name='bot_update'),
path('<int:pk>/', BotDetailView.as_view(), name='bot_detail'),
path('add/', BotCreateView.as_v... |
import logging
from typing import Optional
from functools import partial
from qcodes.utils.helpers import create_on_off_val_mapping as on_off_map
from .visa_types import (
ViString, ViAttr, ViSession, ViReal64, ViBoolean
)
from .dll_wrapper import AttributeWrapper, NamedArgType
from .ni_dll_instrument... |
"""Exceptions"""
import os
class ImageSizeNotEqual(Exception):
"""Image size not equal exception"""
def __str__(self):
return "Image sizes must be equal"
@staticmethod
def validate(image_a, image_b):
"""
Validate standard exception condition.
Raises exception if valida... |
from users.api.serializers import UserSerializer
from users.models import User
def test_user_serializer_no_personal_account():
"""
A regression test for issue https://github.com/stencila/hub/issues/813.
"""
user = User()
data = UserSerializer(user).data
assert data == dict(
display_nam... |
# 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 ma... |
from typing import Union, overload
from contextvars import ContextVar
from test_pkg.overload.typing import T_Type
@overload
def func(arg: ContextVar[int]) -> T_Type:
"""
docstring overload 1.
Args:
arg: the context var of type int.
Returns:
T_Type: str or none.
"""
...
@ov... |
import importlib
class PluginEntry(object):
"""A Plugin entry point
The entry-point is not loaded/imported on creation.
Use the method `get()` to import the module and get the attribute.
"""
class Sentinel(object):
pass
# indicate the entry-point object is not loaded yet
NOT_LOAD... |
from pprint import pprint # for debugging
from core_marketing.models import UnilevelNetwork
from accounts.models import CoreLevelPlans, Affilate
# import sys
# sys.setrecursionlimit(10000)
class MlmNetworkManager(object):
def __init__(self, plan):
self.plan = self.get_plan_obj(plan)
self.all_nets... |
"""
page object model
Using the poium Library
https://github.com/SeldomQA/poium
```
> pip install poum
```
"""
import seldom
from seldom import Seldom
from poium import Page, PageElement
class BaiduPage(Page):
"""baidu page"""
search_input = PageElement(id_="kw")
search_button = PageElement(id_="su")
cl... |
from . import base, types
class If(base.RegexBase):
type = types.RegexType.Group
cond = if_true = if_false = None
def __init__(self, cond, if_true, if_false=None):
super(If, self).__init__()
self.cond = cond
self.if_true = if_true
self.if_false = if_false
self.c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.