text
string
size
int64
token_count
int64
"""Tests for stepfunctions_activity_worker.heartbeat. Since Heartbeat inherits from threading.Timer we're testing against the functionality that we override/extending to it. """ from unittest import mock import pytest from stepfunctions_activity_worker.heartbeat import Heartbeat @pytest.fixture def heartbeat_args(...
2,110
731
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array,...
632
173
import re from bs4 import BeautifulSoup import os.path from datetime import date import requests import csv import time delay = 6 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) filename = 'ao3tags.csv' filepath = os.path.join(BASE_DIR, filename) def tagcount(): urls = [] # list of link to your otp tag...
1,251
406
table = [[0 for i in range(3)] for j in range(3)] print("Enter values for a matrix of order 3 x 3") for d1 in range(3): for d2 in range(3): table[d1][d2] = int(input()) print("Elements of the matrix are %a" % table) print("Elements of the matrix are ") for row in table: print(row) s = 0 for row in table...
412
146
from __future__ import unicode_literals from django.contrib import messages from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.shortcuts import redirect class SuperUserRequiredMixin(object): @method_decorator(login_required(login_url='login...
2,880
789
import boto3 import os import logging from datetime import datetime def lambda_handler(event, context): """This function checks and returns the import assets job status""" try: global log_level log_level = str(os.environ.get('LOG_LEVEL')).upper() valid_log_levels = ['DEBUG...
1,601
525
# cp857_5x7.py - CP857 5x7 font file for Python # # Copyright (c) 2019-2022 Ercan Ersoy # This file is written by Ercan Ersoy. # This file is licensed under CC0-1.0 Universal License. cp857_5x7 = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5F, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x14, 0x7F, 0x14, 0...
7,592
7,037
from fjord.redirector import Redirector class DummyRedirector(Redirector): def handle_redirect(self, request, redirect): if redirect.startswith('dummy:'): redirect = redirect.split(':') return 'http://example.com/' + redirect[1] return
282
78
# -*- coding: utf-8 -*- """ Created on Sat Aug 20 11:26:41 2016 @author: Administrator """ #从__init__.py中导入db,db = SQLAlchemt() from . import db,login_manager #导入Werkzeug中的security模块支持密码散列 from werkzeug.security import generate_password_hash,check_password_hash from flask.ext.login import UserMixin,Anonymo...
12,363
4,178
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from splinter import Browser from time import sleep import re import json import sys class VkDelPost: def __init__(self): self.account = self.load_cfg() def main(self): email = self.account['email'] passw = self.account['passw'] w...
2,657
808
from pandagg.node.query.compound import CompoundClause from pandagg.node.query._parameter_clause import Path, QueryP class Nested(CompoundClause): DEFAULT_OPERATOR = QueryP PARAMS_WHITELIST = ["path", "query", "score_mode", "ignore_unmapped"] KEY = "nested" def __init__(self, *args, **kwargs): ...
948
332
import time import datetime import serial import threading import json import traceback import queue import os import pty import subprocess from multiprocessing import Process import glob from elasticsearch import Elasticsearch from .data_consumers import Datastore, Logger from .http_cmd import create_usb_session_endp...
19,130
5,342
Matrix Add Top Row Matrix Add Top Row: A matrix of size R*C is given as the input to the program. The program must add the elements in the first row in each column to the elements in the below rows by equally dividing them. Then the program must print the modified matrix as the output. Note: If the integer cannot be e...
1,233
503
# MIT License # # Copyright (c) 2021 Quentin Balland # Project : https://github.com/FreeYourSoul/FreExGraph # # 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 wi...
11,044
3,999
#!/usr/bin/env python # Copyright 2016 Cisco Systems, Inc. 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....
29,073
10,680
# Copyright 2015-2018 Cisco Systems, Inc. # All rights reserved. from cxcom.rest.blue_print import blue_print from {{cookiecutter.module_name}}.api.index.index import Index BLUE_PRINT_PUBLIC = blue_print('engine_status', 'templates', [ [Index, '/', "/"] ])
264
97
""" Test the cost function from the problem 1010 """ import numpy as np import sympy as sp import quadpy import unittest from opttrj.costnonlinear import cCostNonLinear from itertools import tee class cMyCost(cCostNonLinear): def runningCost(self, _t, _tauv, _u): pass def runningCostGradient(sel...
5,141
1,968
from threading import Thread from subprocess import Popen, PIPE from wsgiref.simple_server import WSGIServer class BroadcastThread(Thread): def __init__(self, converter: Popen, websocket_server: WSGIServer): super(BroadcastThread, self).__init__() self.converter = converter self.websocket_s...
737
205
import re from manga_py.provider import Provider from .helpers.std import Std from html import escape class MangaDexOrg(Provider, Std): __content = None __chapters = None __languages = None __countries = { '': 'Other', 'bd': 'Bengali', 'bg': 'Bulgarian', 'br': 'Portugue...
5,630
1,799
import pathlib from setuptools import setup, find_packages HERE = pathlib.Path(__file__).parent README = (HERE / "README.md").read_text() VERSION = "1.3.0" DESCRIPTION="VerseGroups encryption manager class (RSA and Fernet wrapped AES sessions through RSA) for secure transmission of data. Also includes utilities such ...
1,494
466
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. # # 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 applic...
24,314
8,610
# VERSÃO FINAL - ÚNICA - V1.0 # ALTERADA EM 03/04 -- 18:30 # EXPORTAÇÕES: import plotly.express as px from pandas import read_excel from dash import Dash, dcc, html, Input, Output, State import plotly.graph_objects as go # IMPORTAÇÃO DE BOOTSTRAP PARA FAZER SITE: import dash_bootstrap_components as dbc # DECLARAÇÃ...
33,921
12,961
""" Unit testing for parts of the editline and _editline modules. """ import os import sys import unittest import subprocess from test.support import import_module # too bad this thing moved ... try: if sys.version_info[0] >= 3 and sys.version_info[1] >= 5: from test.support.script_helper import assert_pyt...
3,918
1,240
import ast from ctypes import c_int8, c_int16, c_int32, c_int64 from ctypes import c_uint8, c_uint16, c_uint32, c_uint64 from dataclasses import dataclass from typing import Optional from py2many.analysis import get_id from py2many.clike import CLikeTranspiler from py2many.tracer import is_enum @dataclass class Inf...
13,035
3,939
# Copyright (c) 2017 Chunhui_Liu@STRUCT_ICST_PKU, All rights reserved. # # evaluation protocols used for PKU-MMD dataset # http://www.icst.pku.edu.cn/struct/Projects/PKUMMD.html # # In proposal folder: # each file contains results for one video. # several lines in one file, # each line contain: label, start_fra...
7,258
2,849
from __future__ import print_function import argparse import mxnet as mx from mxnet import nd, gluon, autograd from dataset import TimeSeriesData from model import LSTNet import time import multiprocessing as mp def train(file_path, out_path): ts_data = TimeSeriesData(file_path, window=24*7, horizon=24) ct...
3,086
1,085
from calm.dsl.builtins import AhvVmDisk, AhvVmNic, AhvVmGC, AhvVmGpu from calm.dsl.builtins import basic_cred, ahv_vm_resources from calm.dsl.builtins import vm_disk_package, read_local_file from calm.dsl.config import get_context AhvVm = ahv_vm_resources() CENTOS_USERNAME = read_local_file(".tests/centos_username")...
2,821
1,184
from validator.rules_src import Rule class Dict(Rule): """ The field under validation must be a dictionary (Python map) Examples: >>> from validator import validate >>> reqs = {"data" : {"key1" : "val1", "key2" : "val2"} } >>> rule = {"data" : "dict"} >>> validate(reqs, rule) True ...
724
245
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold(arr, n): sum = 0 maxsize = - 1 for i in range(0, n - 1): sum = - 1 if (arr[i] == 0) else 1 ...
1,944
1,216
# ██╗░░░░░██╗███╗░░██╗░██████╗░░░░██████╗░██╗░░░░░░█████╗░░█████╗░██╗░░██╗ # ██║░░░░░██║████╗░██║██╔════╝░░░░██╔══██╗██║░░░░░██╔══██╗██╔══██╗██║░██╔╝ # ██║░░░░░██║██╔██╗██║██║░░██╗░░░░██████╦╝██║░░░░░███████║██║░░╚═╝█████═╝░ # ██║░░░░░██║██║╚████║██║░░╚██╗░░░██╔══██╗██║░░░░░██╔══██║██║░░██╗██╔═██╗░ # ███████╗██║██...
935
597
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class Connec...
6,826
2,005
import os import random import argparse import numpy as np import torch import torch.nn as nn import torch.distributed as dist import torch.backends.cudnn as cudnn from ptsr import model from ptsr.data import Data from ptsr.config import load_cfg from ptsr.model import get_num_params from ptsr.utils imp...
4,882
1,640
from discord import Color FACTIONS = { 'Thục': 3, 'Quần': 5, 'Ngụy': 7, 'Ngô': 11 } FACTION_COLORS = { FACTIONS['Thục']: Color.red(), FACTIONS['Quần']: Color.dark_grey(), FACTIONS['Ngụy']: Color.blue(), FACTIONS['Ngô']: Color.green(), FACTIONS['Thục']*FACTIONS['Quần']: Color.dark_r...
886
420
#!/usr/bin/env python3 print("Hello World") import sys; print(sys.path);
75
29
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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...
1,857
767
#!/usr/bin/env python3 import warnings from logging import Logger, getLogger from typing import Any, Dict, Optional, cast from graphql import ( build_ast_schema, build_client_schema, get_introspection_query, parse, ) from graphql.language.ast import DocumentNode from graphql.type.schema import GraphQL...
4,828
1,258
import boto3 import os import logging """ Create a logging function and initiate it. """ format_string = "%(asctime)s %(name)s [%(levelname)s] %(message)s" logger = logging.getLogger('comp-reg-data-load-pipeline-lambda') handler = logging.StreamHandler() logger.setLevel(logging.DEBUG) formatter = logging.Formatter(for...
1,219
363
# -*- coding=UTF-8 -*- # pyright: strict from __future__ import annotations import contextlib from typing import Text from . import sound, window class PromptDisabled(PermissionError): def __init__(self): super().__init__("prompt disabled") class g: pause_sound_path = "" prompt_sound_path = "...
1,017
320
import sys from pymongo import MongoClient from pymongo.errors import ServerSelectionTimeoutError class Mongo(): def __init__(self, username, password, host, port, db): try: self.client = MongoClient('mongodb://{}:{}@{}:{}/{}' .format(username, password, host, port, db)) ...
765
204
from rkmt.options.base_options import BaseOptions class ConvertOptions(BaseOptions): """Arguments parser for model conversion.""" def initialize(self, parser): BaseOptions.initialize(self, parser) parser.add_argument('--platform', type=str, ...
3,717
924
#!/usr/bin/env python # Python 2/3 compatibility from __future__ import (print_function, unicode_literals, division) from future.standard_library import install_aliases install_aliases() from urllib.parse import urlparse, urlencode from urllib.request import urlopen, Request from urllib.error import HTTPError __metac...
12,657
3,722
import csv from pywikibot import ItemPage, Site import properties.wikidata_properties as wp from utils import RepoUtils from .errors import SuspiciousTitlesError def read_titles(filepath): with open(filepath, "r") as f: reader = csv.reader(f) return list(reader) def create_episode_quickstateme...
5,172
1,771
#!/usr/bin/env python import re import os import json import requests versions_url = { 1 : "http://hl7.org/fhir/2017Jan/%s.profile.json", 2 : "http://hl7.org/fhir/STU3/%s.profile.json" } DATE_RE = re.compile(r'-?([1-9][0-9]{3}|0[0-9]{3})(-(0[1-9]|1[0-2])(-(0[1-9]|[12][0-9]|3[01]))?)?') DATETIME_RE = re.compil...
14,777
4,718
import os import re from typing import Union, cast import filelock from structlog import get_logger from modelkit.assets import errors from modelkit.assets.remote import RemoteAssetsStore from modelkit.assets.settings import AssetsManagerSettings, AssetSpec from modelkit.assets.versioning import ( VERSION_RE, ...
8,507
2,073
from __future__ import absolute_import from __future__ import division from __future__ import print_function # some private extra plots #from NBatchLogger import NBatchLogger import matplotlib #if no X11 use below matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np from keras import backend as K ...
2,303
820
import torch from torch_geometric.datasets import Planetoid import torch.nn.functional as F from torch_geometric.nn import GCNConv from torch_geometric.nn import GINConv,SAGEConv from torch.nn import Linear,Sequential,BatchNorm1d,ReLU device = torch.device('cuda:0') class Net(torch.nn.Module): def __init__(self,di...
1,783
713
import pandas as pd from src.config import path_raw, filename_levels, filename_attributes, filename_levels_sheet, filename_attributes_sheet, \ filename_customer_delimiter def load_levels(filename, sheet): """ Load attribute information levels from excel into a dataframe Args: filename (st...
6,893
1,944
# -*- coding: utf-8 """Module for class SubsystemInterface. This file is part of project TESPy (github.com/oemof/tespy). It's copyrighted by the contributors recorded in the version control history of the file, available from its original location tespy/components/basics/subsystem_interface.py SPDX-License-Identifi...
5,486
1,738
#!/usr/bin/env python3 -u # -*- coding: utf-8 -*- # copyright: sktime developers, BSD-3-Clause License (see LICENSE file) """Implements transformers for detecting outliers in a time series.""" __author__ = ["aiwalter"] __all__ = ["HampelFilter"] import warnings import numpy as np import pandas as pd from sktime.for...
6,820
2,056
# Self Replicating Insanity # github.com/smcclennon/SRI project_title = 'SRI' ver = '1.0.1' # Insane mode (Windows only) # Each replicated file will be ran in another console window, # and each of the files ran will replicate and run everything agian # Quickly sucks up ram, will most likely cause the machine to freez...
7,735
3,579
#!/usr/bin/env python3 import time import signal import buttonshim from weather import displayWeather import os def flash_led(interval, times, r, g, b): for i in range( times ): buttonshim.set_pixel(r, g, b) time.sleep( interval ) buttonshim.set_pixel(0, 0, 0) time.sle...
1,012
470
#!usr/bin/python 3.6 #-*-coding:utf-8-*- ''' @file: shrinkage.py, shrinkage clustering @Author: Jing Wang (jingw2@foxmail.com) @Date: 06/24/2020 @Paper reference: Shrinkage Clustering: A fast and \ size-constrained clustering algorithm for biomedical applications ''' import os import sys path = os.path.dirname(o...
3,057
1,046
import json from flask import Flask, request, jsonify,render_template app=Flask(__name__) with open("students.json") as f: data = json.load(f) @app.route('/home',methods=['GET','POST']) def index(): if request.method == 'POST': email = request.form['email'] password ...
792
242
import argparse, numpy as np, os import matplotlib as mpl, matplotlib.cm as cm, matplotlib.pyplot as plt mpl.rcParams["axes.spines.right"] = False mpl.rcParams["axes.spines.top"] = False mpl.rc('font', family='serif') def plot_bins(var, n_bins, bounds=None): # Calculate percentiles v = np.load(os.path.join('data', ...
1,678
745
# # sets # david_courses = {"History", "Music", "Arts", "Literature", "Calculus"} james_courses = {"Biology", "Chemistry", "Physics", "Statistics", "Calculus"} # intersection print(david_courses.intersection(james_courses)) # difference print(david_courses.difference(james_courses)) # union print(david_courses.unio...
338
127
import boto3 # client = boto3.client('s3') # response = client.list_buckets() # print(response) s3 = boto3.resource('s3') object_acl = s3.ObjectAcl('elieof-eoo','/artifacts/projects/autotest_artifacts_to_s3/releases/1.0.0/git_package.zip') object_acl.put(ACL='authenticated-read')
283
120
''' Some tools to convert a .plist into python objects. Incomplete. TODO: add load(s)/dump(s) functions to match the 'data shelving' interfaces of pickle, simplejson, pyyaml, etc. ''' #_type_map = dict(real = (float, 'cdata'), # integer = (int, 'cdata'), # true ...
1,460
507
# -*- Coding: utf-8 -*- print("CONVERSOR DE REAL EM DÓLAR") print("---------------------------") r = float(input("Digite o valor em real(R$): ")) d = r / 5.54 print(f"Esse valor em dólar(U$) é: {d}")
205
92
# ========================================================================== # # Copyright NumFOCUS # # 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/...
1,735
410
import os import time import logging import logging.handlers from typing import Dict, List, Union, Any, Optional from requests import Session import requests from parsel import Selector from .constants import NautaState, LogLevel, CONFIG from .user_cls import User from .utils import get_inputs, get_info, human_secs fr...
17,761
5,098
import pandas as pd from sklearn.preprocessing import MinMaxScaler import src.config.constants as constants import src.common as common import src.munging as process_data import src.ts as ts_util def reverse_min_max_scaling(logger, source_df, target_df, features, scaler_dict): for name in features: mm =...
3,995
1,354
import re from unittest.mock import patch import numpy as np import pytest from stixcore.data.test import test_data from stixcore.products.level0 import scienceL0 as sl0 from stixcore.products.level1 import scienceL1 as sl1 testpackets = [(test_data.tmtc.TM_21_6_20_complete, sl0.RawPixelData, sl1.RawPixelData, ...
2,112
964
import os # os.environ['CUDA_VISIBLE_DEVICES'] = '6' from facenet_pytorch import MTCNN from core.options import ImageFittingOptions import cv2 import face_alignment import numpy as np from core import get_recon_model import os import torch import pickle import core.utils as utils import torch.nn as nn imp...
8,344
3,388
from ueosio import gen_key_pair, get_pub_key ## Print Key Pair print(gen_key_pair()) ## Get Public Address from Private Key print(get_pub_key('5KJfEtwkMBp8t5HtgGfFZVdiUJhDejS5sbiE5siMVe1xs6RQa6y'))
200
98
''' Created on 24.10.2019 @author: JM ''' class TMC2041_register_variant: " ===== TMC2041 register variants ===== " "..."
132
60
import argparse import torch.nn.functional as F import torch.optim.lr_scheduler as lr_scheduler import torch.utils.data import torch.nn as nn import test # import test.py to get mAP after each epoch from models.yolo import * from models.experimental import * from models.common import * from utils.datasets import * fr...
11,308
4,072
import datetime import fnmatch import gzip import shutil import tarfile import time import croniter import hdfs from watchdog.events import PatternMatchingEventHandler, FileCreatedEvent, FileModifiedEvent, FileMovedEvent, os, \ FileSystemEvent def add_log_str(log_pattern, strlog): """Add log in logfile ...
23,741
6,792
""" Full of social stuff with the other characters Up ur social links dialogue.py Max Ferguson """ from main import * sLink = {"Steve": 0, "Zara": 0, "Aeyden": 0, "Emil": 0, "Douche": 0, "Diana": 0, "Cheryl": 0, "Hiram": 0, "Eduardo": 0} def steve(place, sLink, stats, name, pronouns): """ "Dykey" cis Werewol...
7,907
2,362
import pytest import tests.common as common import nomad import sys @pytest.fixture def nomad_setup(): n = nomad.Nomad(host=common.IP, port=common.NOMAD_PORT, verify=False, token=common.NOMAD_TOKEN) return n # integration tests requires nomad Vagrant VM or Binary running def test_get_leader(nomad_setup): ...
2,417
931
"""Module Enum:Matiere""" from enum import Enum class Matiere(Enum): """Enum : Matiere""" HISTOIRE = 0 MATHS = 1 INFO = 2 SPORT = 3
154
69
import pytest @pytest.fixture def viz_plugin(qtbot): from otter.plugins.viz.VizPlugin import VizPlugin plugin = VizPlugin(None) yield plugin
155
55
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 5 18:24:43 2020 @author: mlampert """ import os import copy #FLAP imports and settings import flap import flap_mdsplus flap_mdsplus.register('NSTX_MDSPlus') thisdir = os.path.dirname(os.path.realpath(__file__)) fn = os.path.join(thisdir,"flap_ns...
10,338
3,142
from itertools import product a = [1,2] b = [3,4] c = [4] prd = product(a,b) print(prd) print(list(prd)) prd = product(a,c,repeat=2) print(list(prd)) from itertools import permutations a = [1,2,3] per = permutations(a) print(list(per)) a = [1,2,3] per = permutations(a,2) print(list(per)) from itertools import combi...
1,351
571
def depth_first_search(grid, start, target): """ Search a 2d grid for a given target starting at start. Args: grid: the input grid as a List[List] start: the start grid in format (x,y) zero index target: the target value to find in the grid Returns: Coordinate of the tar...
1,234
398
from bear_todo_counter import append_todo_count def test_simple_todo(): txt = """\ Tasks + Task one - Task two - Task three""" actual = append_todo_count(txt) expected = """\ Tasks [1/3] + Task one - Task two - Task three""" assert actual == expected def test_todo_with_emoji(): txt = """\ Tasks ...
3,634
1,440
import ibmcli import re def test_plugin_list(): example_output = """Listing installed plug-ins... Plugin Name Version Status dev 2.4.0 cloud-functions/wsk/functions/fn 1.0.35 container-service/kubernetes-service 0.4.38 ...
8,915
2,742
import os from django.conf import settings from django.test import TestCase, Client from django.utils import timezone from reviews.models import Book, Publisher class Activity2Test(TestCase): @classmethod def setUpTestData(cls): p = Publisher.objects.create(name='Test Publisher') Book.object...
2,228
675
from django.conf import settings from django.conf.urls import include, patterns, url from django.contrib import admin from django.views.generic import TemplateView admin.autodiscover() urlpatterns = patterns( '', (r'^grappelli/', include('grappelli.urls')), (r'^chatterbox/', include('chatterbox.urls', nam...
955
308
from graph_embeddings.models.embedding_model import EmbeddingModel import torch class ComplEx(EmbeddingModel): def __init__(self, data_loader, entity_dim, rel_dim, loss_type, device, do_batch_norm, **kwargs): super(ComplEx, self).__init__( data_loader, entity_dim, rel_dim, los...
1,753
619
from macrobase_driver.logging import set_request_id from sentry_sdk import capture_exception from .request import RPCRequest, RPCResponse, RPCMessageType from ..endpoint import AiopikaEndpoint from ..result import AiopikaResult from aio_pika import IncomingMessage from structlog import get_logger log = get_logger('m...
1,921
523
import FWCore.ParameterSet.Config as cms process = cms.Process("A") process.maxEvents.input = 8 process.source = cms.Source("EmptySource") #process.Tracer = cms.Service("Tracer") # Process tree # A (Process) # ^ # \- B # | ^ # | \- BA # | # \- C # | # \- D # ^ # \- DA # Cases to test # - event/lumi/run/pro...
23,766
8,015
from typing import Any, Dict from lithopscloud.modules.gen2.image import ImageConfig class LithopsImageConfig(ImageConfig): def __init__(self, base_config: Dict[str, Any]) -> None: super().__init__(base_config) self.defaults['image_id'] = base_config['ibm_vpc'].get('image_id') def update_c...
511
172
from django.apps import AppConfig class PairsConfig(AppConfig): name = 'pairs'
85
28
import torch from utils import * from PIL import Image, ImageDraw, ImageFont device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def super_res(img): ## SRRESNET srresnet_checkpoint = "./checkpoint_srresnet.pth.tar" srresnet = torch.load(srresnet_checkpoint,map_location=device)['model'] ...
1,640
675
#!/usr/bin/env python # Copyright 2012 Google Inc. 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...
13,571
3,939
# coding=utf-8 def create_header(xml_document, arc_doc_info): """ Creates the Header in the DOM :param xml_document: The DOM / Document for writing the QGIS-File :return: the header element in the DOM """ header_element = xml_document.createElement("qgis") header_element.setAttribute("projectna...
1,298
368
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: import abc from easyai.helper.timer_process import TimerProcess from easyai.tasks.utility.base_task import BaseTask class BaseTest(BaseTask): def __init__(self, config_path): super().__init__() self.timer = TimerProcess() self.config...
488
157
from django.db import models from django.utils.html import strip_tags from django.utils.translation import ugettext_lazy as _ from django.contrib.sites.managers import CurrentSiteManager from django.contrib.sites.models import Site from populous.filebrowser.fields import FileBrowseField from populous.staff.models impo...
8,755
2,730
from sqlalchemy import ( create_engine, Column, Integer, String, Float, Boolean, DECIMAL, Enum, DateTime, DATE, Time, Text ) from sqlalchemy.dialects.mysql import LONGTEXT from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # 这是...
1,580
688
""" Generate the main experimental results. """ # Author: Joao Fonseca <jpmrfonseca@gmail.com> # Georgios Douzas <gdouzas@icloud.com> # License: MIT from os.path import join import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn....
5,378
1,776
from .constants import * from .utils import * import torch.nn as nn from tqdm import tqdm from .plotter import * anomaly_loss = nn.MSELoss(reduction = 'none') mse_loss = nn.MSELoss(reduction = 'mean') def custom_loss(model, pred_state, true_state, thresholds): aloss = mse_loss(pred_state.view(-1), torch.tensor(true_...
2,411
1,039
import logging import os from pathlib import Path from curation_utils.file_helper import clear_bad_chars from doc_curation import tei from doc_curation.md.file import MdFile def dump_sarit_markdown(src_dir, dest_dir): file_paths = sorted(Path(src_dir).glob("*.xml")) for file_path in file_paths: file_path = s...
1,498
637
class Characteristics: def __init__(self): self.level = None self.xp = None self.xp_next_level_floor = None self.weight = None self.weight_max = None self.health_percent = None self.jobs = None self.vi = None self.int = None self.agi ...
1,193
378
import sys from deca.ff_rtpc import Rtpc class FakeVfs: def hash_string_match(self, hash32=None, hash48=None, hash64=None): return [] in_file = sys.argv[1] with open(in_file, 'rb') as f: rtpc = Rtpc() rtpc.deserialize(f) print(rtpc.dump_to_string(FakeVfs()))
285
127
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 """ BlueButtonFHIR_API FILE: apps.v1api.contract Created: 1/4/16 1:22 AM Write consent by beneficiary to allow use of their data by third party application Status: Experimental Get FHIR Contract format from http://hl7.org/fhir/contract.html ...
5,328
1,624
from rest_framework import permissions from .models import AuthorizedAgent class AuthorizedAgentPermission(permissions.BasePermission): def has_permission(self, request, view): is_authorized = False try: AuthorizedAgent.objects.get(authorized=True, app_key=request.auth) exce...
609
161
from os import path from os.path import join DATA_PATH = join(path.sep, 'workspace', 'classification', 'data')
113
37
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import json from django.db import migrations def forwards_func(apps, schema_editor): NexusExport = apps.get_model("lexicon", "NexusExport") for export in NexusExport.objects.all(): settings = json.loads(export.exportSettin...
655
221
cars = { 'Ford': ['Falcon', 'Focus', 'Festiva', 'Fairlane'], 'Holden': ['Commodore', 'Captiva', 'Barina', 'Trailblazer'], 'Nissan': ['Maxima', 'Pulsar', '350Z', 'Navara'], 'Honda': ['Civic', 'Accord', 'Odyssey', 'Jazz'], 'Jeep': ['Grand Cherokee', 'Cherokee', 'Trailhawk', 'Trackhawk'] } def get_al...
1,622
535
""" Support for MySensors switches. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.mysensors/ """ import logging from homeassistant.components import mysensors from homeassistant.components.switch import SwitchDevice from homeassistant.const impo...
3,027
972