content stringlengths 5 1.05M |
|---|
import numpy as np;
minE=0.5;
def f(frame):
data=frame['data'];
E = (np.sqrt(data['ux']**2+data['uy']**2+data['uz']**2+1)-1)*0.511;
return E>minE;
|
#!/bin/python3
import math
import os
import random
import re
import sys
'''
Max Min
https://www.hackerrank.com/challenges/angry-children/problem
'''
# Complete the maxMin function below.
def maxMin(k, arr):
arr=sorted(arr)
if len(arr)<=k:
return arr[-1]-arr[0]
unfairness=arr[k-1]-arr[0]
print... |
class Source:
'''
Source class to define source objects
'''
def __init__(self,id,name,url,description):
self.id = id
self.name = name
self.url = url
self.description = description |
# Generated by Django 2.0.8 on 2018-10-02 20:25
from django.db import migrations
import imagekit.models.fields
class Migration(migrations.Migration):
dependencies = [
('fishing_equipment', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='product',
... |
from tuyaha.devices.base import TuyaDevice
class TuyaSwitch(TuyaDevice):
def turn_on(self):
if self._control_device("turnOnOff", {"value": "1"}):
self._update_data("state", True)
def turn_off(self):
if self._control_device("turnOnOff", {"value": "0"}):
self._update_d... |
# Copyright (c) 2020, Manfred Moitzi
# License: MIT License
from typing import TYPE_CHECKING, List, cast
from itertools import chain
from ezdxf.entities import factory
from ezdxf.math import Vec3, OCS
import logging
if TYPE_CHECKING:
from ezdxf.entities import MLine, DXFGraphic, Hatch, LWPolyline
__all__ = ['vi... |
from django.contrib import admin
from .models import Post, Comment
# Register your models here.
admin.site.register([Post, Comment])
|
import matplotlib.pyplot as plt
import numpy as np
import random
import math
from skimage import io
def cart2sph(x,y,z):
XsqPlusYsq = x**2 + y**2
r = math.sqrt(XsqPlusYsq + z**2) # r
elev = math.atan2(z, math.sqrt(XsqPlusYsq)) # theta
az = math.atan2(y, x) #... |
# coding: utf-8
"""
JourneyApi.py
Copyright 2016 SmartBear Software
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 b... |
from time import time
t0=time()
f = open('test_100k.tsv')
total = 0
for line in f:
rec = line.split('\t')
rec[-1] = rec[-1].rstrip()
rec = list(map(int,rec))
for x in rec:
total += x
print(total)
print(time()-t0)
|
import os
from logger import logger
def write_tmf_trace(tmf_file, pdb_path, trace):
"""
Write a single trace information into the given TMF file.
"""
tmf_file.write('// PDB: ' + os.path.basename(pdb_path) + '\n')
# Real TMFs also contain a `// last updated time`
# Write general info
tmf_... |
from components.company.Company import Company
from libs.Json_db import Json_db
class Me(object):
def __init__(self, db_file):
self._me = Json_db(db_file)
self._company = Company('ME')
self._company.imports(self._me.get('ME'))
def get_company(self):
return self._company
d... |
from pydantic import BaseModel, Field
from ROAR.control_module.controller import Controller
from ROAR.utilities_module.vehicle_models import VehicleControl, Vehicle
from ROAR.utilities_module.data_structures_models import Transform, Location
from collections import deque
import numpy as np
import math
import logging
... |
from context import Instagram # pylint: disable=no-name-in-module
instagram = Instagram()
instagram.with_credentials('username', 'password', 'path/to/cache/folder')
instagram.login()
# Location id from facebook
location = instagram.get_location_by_id(1)
print(location)
|
"""ScatterPlot object for storing X,Y coordinates."""
from luna.db.base import Base, DB_DELIM
from sqlalchemy import Column, Integer, String
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.types import Enum
import enum
class ScatterPlotType(enum.Enum):
"""ScatterPlot Type... |
from jd.api.base import RestApi
class ServicePromotionPidGetPidRequest(RestApi):
def __init__(self,domain='gw.api.360buy.com',port=80):
RestApi.__init__(self,domain, port)
self.positionName = None
self.promotionType = None
self.unionId = None
self.sonUnionId = None
self.mediaName = None
def geta... |
mport torch as tf
|
# -*- coding: utf-8 -*-
# @Date : 2015-05-28
from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from db import engine
Base = declarative_base()
class Eat(Base):
__tablename__ = 'eat'
day = Column(String(50), nullable=True,primary_key=True)
... |
# https://programmers.co.kr/learn/courses/30/lessons/77485
def solution(rows: int, columns: int, queries: list) -> list:
answer = []
matrix = [[0 for col in range(columns+1)] for row in range(rows+1)]
cnt = 1
for R in range(1, rows+1):
for C in range(1, columns+1):
matrix[R][C] = ... |
import importlib.util
import os
from importlib import import_module
def get_format(format_="default"):
""" Find format schema in $FORMAT_PATH or nerium/schema
NOTE: if `format_` is not found, this falls back to "default"
"""
# Load format from builtin schema if exists
try:
format_mod =... |
#
# This file is part of Orchid and related technologies.
#
# Copyright (c) 2017-2022 Reveal Energy Services. All Rights Reserved.
#
# LEGAL NOTICE:
# Orchid contains trade secrets and otherwise confidential information
# owned by Reveal Energy Services. Access to and use of this information is
# strictly limited and... |
# Copyright 2019 Google LLC. 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 applicable law or a... |
import pytest
import justobjects as jo
from tests.models import Role
def test_validate_dict() -> None:
role = {"name": "Simons"}
with pytest.raises(jo.ValidationException) as v:
jo.validate(Role, role)
assert len(v.value.errors) == 1
err = v.value.errors[0]
assert err.message == f"'race'... |
from .model_utils import collate_fn
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@brief Retrieve and display pixel data from ADNS-3050 sensor.
@file Uno_ADNS_3050_Test/ser-mon-adns-3050.py
@see MultiWii_2_4/MultiWii
@author drtrigon
...
consider using miniterm or arduino ide serial monitor
"""
import serial
import matplotlib.pyplot as plt
import n... |
#
# context.py
# Build up some descriptive context for automatic commit to git
import sys
import os
import os.path
import string
import random
import logging
def buildmessagefile(config):
""" Build a commit message that uses the provided ControlConfig object and
return a reference to the resulting file.... |
import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_Run2_2017_cff import Run2_2017
from Configuration.Eras.Modifier_ppRef_2017_cff import ppRef_2017
Run2_2017_ppRef = cms.ModifierChain(Run2_2017, ppRef_2017)
|
#!/usr/bin/python
from __future__ import division
import numpy as np #--- To handle math processing
#import scipy.integrate as sci
import scipy.ndimage as ndi
from skimage import exposure
from scipy import linalg as LA
#from scipy.ndimage.interpolation import zoom
#import mahotas #--- to handle image manipulation <nump... |
# -*- coding: utf-8 -*-
import bag
lib_name = 'serdes_templates'
prj = bag.BagProject()
print('importing library: %s' % lib_name)
prj.import_design_library(lib_name)
print('finish importing library %s.' % lib_name)
|
import FWCore.ParameterSet.Config as cms
#
# module to make the MaxSumPtWMass jet combination
#
findTtSemiLepJetCombMaxSumPtWMass = cms.EDProducer("TtSemiLepJetCombMaxSumPtWMass",
## jet input
jets = cms.InputTag("selectedPatJets"),
## lepton input
leps = cms.InputTag("selectedPatMuons"),
## ma... |
# Copyright (c) 2021, 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
from coremltools.converters.mil.mil.passes.pass_registry import register_pass
from coremltools.conver... |
import torch
from pytorch_lightning.metrics import TensorMetric
from typing import Any, Optional
from losses.supervised_losses import *
from losses.unsupervised_losses import *
from losses.common_losses import *
class EPE3D(TensorMetric):
def forward(self, pc_source: torch.Tensor, pc_target: torch.Tensor, pred_fl... |
import os
import json
from functools import reduce
import numpy as np
import pandas as pd
import geopandas as gpd
from dsed.ow import DynamicSednetCatchment, FINE_SEDIMENT, COARSE_SEDIMENT
from dsed.const import *
import openwater.nodes as node_types
from openwater.examples import from_source
from openwater import d... |
# Generated by Django 4.0.4 on 2022-05-18 03:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('agents', '0050_remove_agent_plat_release'),
]
operations = [
migrations.AlterField(
model_name='agent',
name='plat',... |
from urllib.request import urlopen
from django.conf import settings
from .cases import SeleniumTestCase
class TestNews(SeleniumTestCase):
def setUp(self):
super().setUp()
self.selenium.get("%s%s" % (self.live_server_url, "/aktuality/"))
def test_server_available(self):
req = urlopen(... |
"""API router.
"""
from django.conf.urls import url
from django.urls import include, path
from drf_yasg2 import openapi
from drf_yasg2.views import get_schema_view
from rest_framework import permissions
from rest_framework.routers import DefaultRouter
from vision_on_edge.azure_part_detections.api import views as part... |
import os
import unittest
from scripts import train
cuda_on = 1
class TestsMiniImagenet(unittest.TestCase):
def test_1_shot_5_way_with_restore(self):
config = {
'data.dataset': 'mini-imagenet',
'data.dataset_path': 'data/mini-imagenet',
'data.split': 'ravi',
... |
from canvas_sdk import client, utils
def list_accounts(request_ctx, per_page=None, as_user_id=None, **request_kwargs):
"""
List accounts that the current user can view or manage. Typically,
students and even teachers will get an empty list in response, only
account admins can view the accounts that th... |
# 비트단위로 NOT 하여 출력하기
print(~int(input())) |
"""
Scanner aka lexer.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any, Dict, Iterable
from as3.enums import TokenType
from as3.exceptions import ASSyntaxError
# Group names must match `TokenType` members.
specification = re.compile(r'''
# Special tokens... |
import torch
from torch.autograd import Variable
from torch import nn
from torch.nn import functional as F
from .basic_layers import sort_batch, ConvNorm, LinearNorm, Attention, tile
from .utils import get_mask_from_lengths
from .beam import Beam, GNMTGlobalScorer
class SpeakerClassifier(nn.Module):
'''
... |
class Quote:
symbol: str
current: float
high: float
low: float
open_: float
previousClose: float
timestamp: int
def __init__(self, s, c, h, l , o, pc, t):
self.symbol = s
self.current = c
self.high = h
self.low = l
self.open = o
self.previ... |
#!/usr/bin/env python3
# 2021 - jtm.gg
# Version 0.9
import argparse
import base64
import binascii
import itertools
import math
import os
import random
import sys
from enum import Enum
parser = argparse.ArgumentParser()
parser.add_argument('save_path', help='Filepath to save, used for reading and writing (good idea ... |
from collections import Counter
import pytest
from fastapi.testclient import TestClient
from jsonschema import validate
from semesterstat.reciepts import DepartmentReciept
from semesterstat.reports import DepartmentReport
@pytest.mark.parametrize(
["dept", "rescode"],
[
("CS", 200),
("XX", 4... |
def extractTsukigomori(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag):
return False
if 'Our Glamorous Time' in item['tags']:
return buildReleaseMessageWithType(item, 'Our Glamorous Time', vol, chp, frag=frag, postfix=postfix)
if 'Same Plac... |
import shutil
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
import django
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.admin import site as default_admin_site
from django import VERSION
if VERSION[0] < 2:
fro... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^signup/$', views.home, name="signup",),
url(r'^login/$', views.home, name="login"),
url(r'^logout/$', views.home, name="logout"),
url(r'^$', views.home, name='home'),
url(r'^search/$', views.search, name='search'),
url(... |
filter_list为QTableWidget类型
#得到总行数
rows = self.filter_list.rowCount()
for rows_index in range(rows):
#print items[item_index].text()
print self.filter_list.item(rows_index,0).text()
tableWidget.currentRow() ##可以获取一行的行号
QModelIndexList QTableView::selectedIndexes
// QTableWidget选中所有单元格及取消选中所有单元格
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
fields = ['nums', 'val', 'expect', 'new_nums']
rows = [
([3, 2, 2, 3], 3, 2, [2, 2]),
([0, 1, 2, 2, 3, 0, 4, 2], 2, 5, [0, 1, 3, 0, 4]),
([1, 1, 1, 1], 1, 0, []),
([1, 1, 1, 1], 2, 4, [1, 1, 1, 1]),
([1, 2, 3, 4], 2, 3, [1, 3, 4]),
]
if __name__ == '__m... |
"""
Translate JADN to JSON Schema
"""
import json
import re
from datetime import datetime
from typing import Callable, Optional, Union
from ..definitions import (
TypeName, BaseType, TypeOptions, TypeDesc, Fields, ItemID, ItemValue, ItemDesc, FieldID, FieldName, FieldType,
FieldOptions, FieldDesc, OPTION_ID, i... |
import socket
import numpy as np
import io
import cv2
import zstandard
import atexit
from netutils import *
import sys
import platform
class Client:
def __init__(self, **kwargs):
#self.os=platform.system()
self.verbose = kwargs.get("verbose", False)
self.promoteErrors=kwargs.get("promot... |
#!/usr/bin/env python3
import pytest
from ruamel.yaml import YAML
from verifiers import reference_validation
from pprint import pprint
def get_ref_val_config():
config_yaml = """
tag-prefix: "ref"
error-texts:
reference-not-found: "The field '{}' ... |
import logging
from django.views.generic import TemplateView
logger = logging.getLogger(__name__)
class SamlIDPErrorView(TemplateView):
""" Default error view when a 'known' error
occurs in the saml2 authentication views.
"""
template_name = 'error.html'
status = 403
def get_contex... |
"""
Helper functions for use across syncing related functionality.
"""
import uuid
import json
import factory
import mock
from django.test.testcases import LiveServerTestCase
from django.core.serializers.json import DjangoJSONEncoder
from django.utils import timezone
from facility_profile.models import Facility
from f... |
from enum import Enum
from typing import Optional
from pydantic import BaseModel, Field
from app.airtable.response import AirtableResponse, ListAirtableResponse
class FieldCategoryType(str, Enum):
race_ethnicity = "Race & Ethnicity"
gender = "Gender"
income_background = "Income Background As Child"
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import tensorflow.keras.layers as tfkl
from tensorflow.python.keras import activations
from tensorflow.python.keras import constraints
from tensorflow.python.keras import initializers
fr... |
# -*- coding: utf-8 -*-
'''
Descripttion:
version:
Author: 32353
Date: 2021-05-06 09:14:46
LastEditors: 32353
LastEditTime: 2021-05-06 22:20:13
'''
from MF.utils import ModelManager
from MF.utils import LogTime
from MF.LFM import LFM
from MF.dataset import DataSet
from usercf import UserBasedCF
from itemcf import I... |
'''
Notification Application Permissions
notification/permissions.py
@author Teerapat Kraisrisirikul (810Teams)
'''
from rest_framework import permissions
from notification.models import Notification
class IsNotificationOwner(permissions.BasePermission):
''' Notification owner permission '''
def... |
"""
doorbell_script.py
Part of code for HackHer413
Sents request code to play a door bell sound;
split and storge the audio file that is paused during the door bell soung,
to allow easy playback after the pause.
Author: Kunjal Panchal
Date: 02-09-2020
"""
import requests # for making http calls
import xml.do... |
"""Rule definition for a failure to load a file."""
from ansiblelint.rules import AnsibleLintRule
class LoadingFailureRule(AnsibleLintRule):
"""File loading failure."""
id = '901'
shortdesc = 'Failed to load or parse file'
description = 'Linter failed to process a YAML file, possible not an Ansible ... |
from . import FixtureTest
class IntermittentWater(FixtureTest):
def test_river(self):
# Arizona Canal Diversion Channel (ACDC)
self.load_fixtures(['http://www.openstreetmap.org/way/107817218'])
self.assert_has_feature(
16, 12353, 26272, 'water',
{'kind': 'river', '... |
class OrganicCompoundsParser(object):
name: str
radicals = ["meth", "eth", "prop", "but", "pent", "hex", "hept", "oct", "non", "dec", "undec",
"dodec", "tridec", "tetradec", "pentadec", "hexadec", "heptadec", "octadec", "nonadec"]
mutlipliers = ["di", "tri", "tetra", "penta"... |
"""Flfiles_dir module."""
import os
import hashlib
from typing import List
from PyQt6 import QtXml # type: ignore[import]
from pineboolib.core.utils import logging, utils_base
LOGGER = logging.get_logger(__name__)
class FlFiles(object):
"""FlFiles class."""
_root_dir: str
_areas: List[List[str]]
... |
# recipe.py (lciafmt)
# !/usr/bin/env python3
# coding=utf-8
"""
This module contains functions needed to compile LCIA methods from the
ReCiPe model
"""
import pandas as pd
import xlrd
import lciafmt.cache as cache
import lciafmt.df as dataframe
import lciafmt.xls as xls
from .util import datapath, aggregate_factors_... |
# Weichao Qiu @ 2018
# Visualize arm dataset
import unreal.virtual_db as vdb
import imageio as io
import matplotlib.pyplot as plt
import numpy as np
joint_name = vdb.meta.arm_skel
def fov2f(fov, width):
# fov = 2 * arctan(w / 2f)
fov = fov * np.pi / 180
return width / (2 * np.tan(fov / 2))
def f2fov(f, ... |
from typing import Any, Dict, List
import logging
from collections.abc import Iterable, Mapping, ByteString, Set
import numbers
import decimal
logger = logging.getLogger(__file__)
CONTEXT = decimal.Context(
Emin=-128,
Emax=126,
# rounding=None,
prec=38,
traps=[decimal.Clamped, decimal.Overflow, de... |
import os
from solid.auth import Auth
IDP = os.getenv('SOLID_IDP')
USERNAME = os.getenv('SOLID_USERNAME')
PASSWORD = os.getenv('SOLID_PASSWORD')
def test_login():
auth = Auth()
assert not auth.is_login
auth.login(IDP, USERNAME, PASSWORD)
assert auth.is_login
|
{
'targets': [
{
'target_name': 'temporalio-workflow-isolate-extension',
'include_dirs': [
"<!(node -e \"require('nan').include\")",
'<!(node -e "require(\'isolated-vm/include\')")',
],
# see: https://github.com/nodejs/node-gyp/issues/17#issuecomment-3917672
'cflags!'... |
from trame_simput.core.domains import PropertyDomain, register_property_domain
from . import paraview, decorators
from .const import PANEL_WIDGETS, WIDGETS, DOMAIN_TYPES, DOMAIN_TYPE_DEFAULT
# -----------------------------------------------------------------------------
# Generic ParaView domain adapter
# ------------... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-11 20:30
from __future__ import unicode_literals
import datetime
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
... |
__version__ = '0.0.1'
from .configuration import *
from .featurization import *
from .models import *
|
from enum import IntEnum
class DataFormat(IntEnum):
"""Supported formats enumeration."""
CSV = 0
TEXT = 1
|
import datetime
import pandas as pd
class TICK_SOURCE():
"""数据来源类型
"""
EQ_SINA = 1
AK_A_EM = 2
def get_formater_easy_ticks(code_list) -> list:
"""
下载处理 easyquotation ticks 数据
"""
import easyquotation
quotation = easyquotation.use('sina')
l1_ticks = quotation.stocks(code_list)... |
#!/usr/bin/env python3
import sys
import json
import gzip
__author__ = 'Bence Cserna'
def read_data(file_name):
if file_name.endswith('.gz'):
with gzip.open(file_name, "rb") as file:
return json.loads(file.read().decode("utf-8"))
with open(file_name) as file:
return json.load(fi... |
# Copyright 2020 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.
"""Contains tests which test monochrome's AndroidManifest.xml"""
from devil.android.sdk import build_tools
from devil.utils import cmd_helper
import typ
cl... |
import ConfigParser
from network.network import RandomScaleFree
from mininet.node import RemoteController
from mininet.net import Mininet
from mininet.link import TCLink
from mininet.log import setLogLevel
from mininet.cli import CLI
from time import sleep
if __name__ == "__main__":
config = ConfigParser.ConfigParse... |
#!/usr/bin/env python
"""
This program will look for any class that inherits from a class.
Examples:
Find all the classes that inherit from model_base.BASEV2 in the neutron directory.
./inherits_from.py /opt/stack/neutron/neutron model_base.BASEV2
./inherits_from.py /opt/stack/cinder/cinder rpc.RPCAPI
"""
import ... |
from .PWCNet import * |
from __future__ import print_function
import numpy as np
def get_multi_metric(pred, gt, eval_label_list=None, rm_bg=False, verbose=True):
"""
implemented iou, dice, recall, precision metrics for each label of each instance in batch
:param pred: predicted(warpped) label map Bx....
:param gt: ground ... |
from .models import BranchModel
class BranchNotExist(ValueError):
pass
class BranchOfUserNotExist(ValueError):
pass
async def is_address_unique(address):
branch = await BranchModel.query.where(
BranchModel.address == address
).gino.first()
if branch:
return False
return Tru... |
# --------------------------------------------------------------------------
# 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 cause incor... |
# Copyright (c) 2020 @ FBK - Fondazione Bruno Kessler
# Author: Roberto Doriguzzi-Corin
# Project: LUCID: A Practical, Lightweight Deep Learning Solution for DDoS Attack Detection
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You... |
from allauth.account.adapter import get_adapter
from allauth.account.forms import (
PasswordField,
PasswordVerificationMixin,
SetPasswordField,
)
from django import forms
from django.contrib.auth import get_user_model, password_validation
from django.contrib.auth.forms import UserCreationForm
from django.co... |
from allauth.account import models
from django.contrib.auth import get_user_model
User = get_user_model()
def generate_verified_user(email, password, superuser: bool = True):
if superuser:
user = User.objects.create_superuser(None, email, password)
else:
user = User.objects.create_user(None, ... |
def fib(n):
"""
Fibonacci:
fib(n) = fib(n - 1) + fib(n - 2) se n > 1
fib(n) = 1 se n <= 1
"""
if n > 1:
return fib(n - 1) + fib(n - 2)
else:
return 1
# Mostrar Fibonacci de 1 a 5
#for i in [1, 2, 3, 4, 5]:
for i in range(10+1):
print ('Fib(',i,') => ', fib(i))
|
import argparse
from PIL import Image, ImageStat
import math
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument('fname')
parser.add_argument('top')
parser.add_argument('right')
parser.add_argument('bottom')
parser.add_argument('left')
args = parser.parse_args()
def MaskEntropy(im, l, t, r, b):
... |
from django.contrib import admin
from django.core.urlresolvers import reverse
from Forum.models import Subforum, Post, PostReported, PostEdited, Thread, Poll, PollOption, Forum
from django.utils.safestring import mark_safe
from django.contrib.auth.models import Permission
from Forum.forms import FormForum, FormSubforum... |
import secrets
FLAG="ECS{R4ND0M_CRN_0B998F4513BE152B98C8CCE0BC7829F7}"
KEY=secrets.token_bytes(32)
|
from aiohttp import web as aio_web
from bolinette import web
from bolinette.decorators import topic
@topic('role')
class RoleTopic(web.Topic):
async def validate_subscription(self, socket: aio_web.WebSocketResponse, payload, current_user) -> bool:
if current_user is None:
await self.send_erro... |
"""
https://debuggercafe.com/instance-segmentation-with-pytorch-and-mask-r-cnn/
https://pytorch.org/vision/stable/models.html#object-detection-instance-segmentation-and-person-keypoint-detection
"""
import torch
from PIL import Image
from torchvision import models, transforms
import numpy as np
import cv2
... |
from django.shortcuts import get_object_or_404, render, HttpResponseRedirect
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from .forms import ImageUpload, ImageConvert
import subprocess
from PIL import Image
def index(request):
request.session.save()
upload... |
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: all,-execution,-papermill,-trusted
# formats: ipynb,py//py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.7.1
# kernelspec:
# display_name: Python 3
# ... |
"""Представление прогноза."""
import dataclasses
from typing import Tuple
import numpy as np
import pandas as pd
import poptimizer.data.views.quotes
from poptimizer.data.views import listing
from poptimizer.dl import ledoit_wolf
def ledoit_wolf_cor(
tickers: tuple, date: pd.Timestamp, history_days: int
) -> Tup... |
"""Provide the InboxToggleableMixin class."""
from ....const import API_PATH
class InboxToggleableMixin(object):
"""Interface for classes that can optionally receive inbox replies."""
def disable_inbox_replies(self):
"""Disable inbox replies for the item."""
self._reddit.post(API_PATH['sendre... |
'''
Created on 2014/9/26
@author: kepler-moment
'''
from Trie import Trie
from BK_Tree import BK_Tree
class Dictionary:
""""""
def __init__(self,dict_map):
"""
param dict_map is a map of all words which likes
dict_map['english'] = 'chinese'
"""
self.dict_trie = Trie(d... |
from django.apps import AppConfig
from . import __version__
class BuybacksConfig(AppConfig):
name = "buybacks2"
label = "buybacks2"
verbose_name = f"AA - Buybacks2 v{__version__}"
|
import os
import json
from experiment_utils.run_sweep import run_sweep
from maml_zoo.utils.utils import set_seed, ClassEncoder
from experiments.env_1d.point_1d_hand_grads import run_1d_experiment
from doodad.easy_sweep.hyper_sweep import Sweeper, kwargs_wrapper
import multiprocessing
import random
import time
INSTANCE_... |
class DimensionException(Exception):
pass
class CantAddNode(Exception):
pass
|
#Internally subscribes to changes in that component, sends them out
#Externally subscribes to componentID/* and parses/sends to component as command/value
from eventsmanager import EventsManager
class IoTInterface():
def __init__(self, componentID, mqttProvider):
self.componentID = componentID
sel... |
import numpy as np
import itertools
from scipy.special import gamma
def SBM_distbn(A, B, Z, pi, d):
return WSBM_distbn(A, B, B*(1-B), Z, pi, d)
def WSBM_distbn(A, B, C, Z, pi, d):
P = B[Z,:][:,Z]
K = len(pi)
# Spectral embeddings
UA, SA, VAt = np.linalg.svd(A); VA = VAt.T
UB, SB... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.