text
string
size
int64
token_count
int64
from guniflask.config import settings from guniflask.web import blueprint, get_route @blueprint class ConfigController: def __init__(self): pass @get_route('/settings/<name>') def get_setting(self, name): return {name: settings[name]}
266
83
from ._base_trainer import _BaseTrainer, MeasureMemory import pathlib import torch.multiprocessing as mp import torch from torch import nn import horovod.torch as hvd import numpy as np import xarray as xr import itertools from .flow_dataset import FlowDataset from .unet import UNet import sys from .visualization impor...
14,062
4,707
from spinup import vpg import tensorflow as tf import numpy as np from gym.spaces import Box, Discrete from envs.focal_point_task_us_env import FocalPointTaskUsEnv from envs.phantom import ( ScatterersPhantom, Ball, Teddy ) from envs.imaging import ImagingSystem, Probe from envs.generator import ConstPhanto...
5,557
2,075
import sys,os sys.path.append('/home/zongdaoming/cv/multi-organ/multi-organ-ijcai') from lib.losses.BaseClass import _AbstractDiceLoss from lib.losses.basic import * class DiceLoss(_AbstractDiceLoss): """Computes Dice Loss according to https://arxiv.org/abs/1606.04797. For multi-class segmentation `weight` pa...
791
254
# encoding: utf-8 # # Copyright (c) 2019 Dean Jackson <deanishe@deanishe.net> # # MIT Licence. See http://opensource.org/licenses/MIT # # Created on 2019-09-06 # """Overlay check mark on icons.""" from __future__ import print_function, absolute_import from Cocoa import ( NSBitmapImageRep, NSPNGFileType, ...
1,190
408
import datetime from threading import Thread from time import sleep import DBC.dbcreate as dbc class Tracker(Thread): max_idle_time = 720 # minutes default_sleep = 3600 # secs def track(self): dbcl = dbc.DBClient() # print(dbcl.getlasttime()) print("Tracker activated") ...
2,491
759
# Copyright 2016 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 ag...
39,197
12,045
A = ['a','b'] B = ['c','b','a'] def generatehash(A): hashA = {} for item in A: if item not in hashA: hashA[item] = 1 else: hashA[item] += 1 return hashA def compareHash(A, B): lenA = len(A) lenB = len(B) hashA = generatehash(A) if lenB < lenA: ...
592
214
# Importing required packages: import pandas as pd from tkinter import * from tkinter.ttk import * root = Tk() # To visualize input DataFrame: def generate_plot(gui_root, df, x_axis, y_axis=None, plot={'type':None, 'hue':None}, aesthetics={'style':'whitegrid', 'palette':'...
2,904
1,220
import os import torch from torch.utils.data import DataLoader, TensorDataset import requests import io import zipfile from .data_reader import read_vocabulary, read_lm_data, lm_data_producer from .pre_process_wikitext import pre_process def get_dataset(dataset, batch_size, device): """ Returns data iterator...
4,737
1,691
from tkinter import * #Cria a nossa tela instancia = Tk() #Dá um título a tela instancia.title('Calculadora para Estatística') #Dá um tamanho a tela instancia.geometry("800x600") #Dá um ícone ao aplicativo #instancia.wm_iconbitmap('icone.ico') #Inicia o programa instancia.mainloop()
289
116
# -*- coding: utf-8 -*- """ Created on Sat Mar 19 09:42:09 2022 @author: iaala """ import requests import sql_configs import datetime import os from bs4 import BeautifulSoup import time from find_tables import ( table_information_one, table_information_two, table_information_three, table_information_...
6,235
1,779
def fibonacci_iterative(n): previous = 0 current = 1 for i in range(n - 1): current_old = current current = previous + current previous = current_old return current def fibonacci_recursive(n): if n == 0 or n == 1: return n else: return fibonacci_recursive...
357
122
from django.urls import resolve, reverse from django.test import TestCase from matches.views import matches_index from matches.models import Match class AllMatchesTests(TestCase): def setUp(self): self.match = Match.objects.create( match_id=1, home_team='Netherlands', g...
1,002
311
from typing import Callable, Tuple import numpy as np def posterior_factory(y: np.ndarray, sigma_y: float, sigma_theta: float) -> Tuple[Callable]: """The banana distribution is a distribution that exhibits a characteristic banana-shaped ridge that resembles the posterior that can emerge from models that ...
5,871
1,799
from binaryninja import ( Architecture, BranchType, FlagRole, InstructionInfo, LowLevelILFlagCondition, RegisterInfo, ) from .instructions import TYPE3_INSTRUCTIONS, Instruction, Registers from .lifter import Lifter class MSP430(Architecture): name = "msp430" address_size = 2 defa...
3,141
1,061
__all__ = [ 'session', 'event', 'profile', 'consent', 'segment', 'source', 'rule', 'entity' ]
126
50
from salience_metrics import auc_judd, auc_shuff, cc, nss, similarity, normalize_map """ DHF1K paper: "we employ five classic met-rics, namely Normalized Scanpath Saliency (NSS), Sim-ilarity Metric (SIM), Linear Correlation Coefficient (CC),AUC-Judd (AUC-J), and shuffled AUC (s-AUC)."" """ import cv2 import o...
3,868
1,430
import pytest from thefuck.rules.pacman_invalid_option import get_new_command from thefuck.rules.pacman_invalid_option import match from thefuck.types import Command good_output = """community/shared_meataxe 1.0-3 A set of programs for working with matrix representations over finite fields """ bad_output = "erro...
1,061
364
# Copyright 2019 D-Wave Systems 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...
11,329
2,982
import os def test_development_config(test_app): test_app.config.from_object('flask_ecom_api.config.DevelopmentConfig') assert not test_app.config['TESTING'] assert test_app.config['SQLALCHEMY_DATABASE_URI'] == os.environ.get('DATABASE_URL') def test_testing_config(test_app): test_app.config.from_ob...
739
260
from django import forms from django.core import validators from django.core.exceptions import ValidationError from leasing.enums import ( InfillDevelopmentCompensationState, LeaseState, TenantContactType, ) from leasing.models import Contact, DecisionMaker, District, LeaseType, Municipality from leasing.v...
6,122
1,778
# polls/management/commands/create_admin_user.py import sys import logging from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from django.conf import settings class Command(BaseCommand): help = 'Creates the initial admin user' def handle(self, *args...
675
182
import unirest import json import requests import os import subprocess import time import argparse rootUrl = "https://api.unsplash.com/" unirest.default_header("Accept", "application/json") unirest.default_header("Accept-Version", "v1") unirest.default_header("Authorization","<CLIENT-ID>") def downloadPic(randomPic_...
1,597
524
# Copyright (c) 2017, Somia Reality Oy # 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 conditions an...
2,358
835
from datetime import datetime class Base(object): date_format = '%Y-%m-%d' time_format = '%H:%M:%S' datetime_format = date_format + 'T%s' % time_format full_datetime_format = date_format + 'T' + time_format + '.%f' iso_format = date_format + 'T%sZ' % time_format standard_datetime_format = date...
878
268
from caching.base import CachingManager, CachingMixin from django.db import models from tsdata.models import CensusProfile PURPOSE_CHOICES = ( (1, "Speed Limit Violation"), (2, "Stop Light/Sign Violation"), (3, "Driving While Impaired"), (4, "Safe Movement Violation"), (5, "Vehicle Equipment Violat...
5,641
1,947
from .login import LoginForm from .registration import RegistrationForm
74
19
from django.urls import path from django.contrib import admin from rest_framework_swagger.views import get_swagger_view from .views import notification schema_view = get_swagger_view(title='MAIL API') urlpatterns = [ path('front/betsy/irish/embargo/admin/', admin.site.urls), # Swagger API path( ...
552
165
from unittest import mock SOCK_STREAM = 0 set_interface = mock.Mock() interface = mock.MagicMock() getaddrinfo = mock.Mock() socket = mock.Mock() class Mocket: def __init__(self, response): self.settimeout = mock.Mock() self.close = mock.Mock() self.connect = mock.Mock() self.sen...
1,097
344
# -*- coding: utf-8 -*- import api,points from api.bottle import * II_PATH=os.path.dirname(__file__) or '.' TEMPLATE_PATH.insert(0,II_PATH) @route('/list.txt') def list_txt(): response.set_header ('content-type','text/plain; charset=utf-8') lst = api.load_echo(False)[1:] if request.query.n: retur...
2,228
889
#!/usr/bin/env python from ncclient import manager import sys from lxml import etree # Set the device variables DEVICES = ['172.16.30.101', '172.16.30.102'] USER = 'admin' PASS = 'admin' PORT = 830 LOOPBACK_IP = { '172.16.30.101': '10.99.99.1/24', '172.16.30.102': '10.99.99.2/24' } DEVICE_NAMES = {'172.16.3...
2,080
704
# To run this file, Win Start > cmd > file dir > run: python spacex_dash_app.py # Import required libraries import pandas as pd import dash from dash import html from dash import dcc from dash.dependencies import Input, Output import plotly.express as px # Read the airline data into pandas dataframe spacex_df = pd.rea...
5,704
1,615
""" The best randomly-searched ResNet reported in the paper. In the original paper there is a bug. This network sums together layers after the ReLU nonlinearity, which are not Gaussian, and also do not have mean 0. As a result, the overall network does not converge to a Gaussian process. The defined kernel is still va...
1,430
527
import matplotlib.pyplot as plt import numpy as np # daily search trend for keyword 'flowers' for a year d = [ 1.04, 1.04, 1.16, 1.22, 1.46, 2.34, 1.16, 1.12, 1.24, 1.30, 1.44, 1.22, 1.26, 1.34, 1.26, 1.40, 1.52, 2.56, 1.36, 1.30, 1.20, 1.12, 1.12, 1.12, 1.06, 1.06, 1.00, 1.02, 1.04, 1.02, 1.06, 1.02, 1.04, 0.98, 0...
2,956
2,545
from dataclasses import dataclass import logging from attributes import get_ability_modifier from sourcetree.utils import ( get_feats_list, get_feat_perks, get_feat_proficiencies, get_feat_requirements, ) from stdio import prompt log = logging.getLogger("thespian.tweaks") class AbilityScoreImproveme...
22,427
5,689
class ImpuritySpecies(object): # For storing OpenADAS data related to a particular impurity species # Loosely based on cfe316/atomic/atomic_data.py/AtomicData class (although with much less code since # all of the F77 importing is done in the seperate <<make json_update>> code since BOUT++ protocol # requires fort...
4,135
1,414
import os import platform import numpy class Matrix: def __init__(self): if platform.system() == "Windows": self.delimiterForPath = "\\" else: self.delimiterForPath = "/" self.labelsDType = numpy.int32 self.imagesDType = numpy.float32 def deleteRows(se...
9,213
2,686
# -*- coding: utf-8 -*- # Copyright (c) 2018 Tigera, 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 re...
7,906
2,408
def global_alignment(seq1, seq2, score_matrix, penalty): len1, len2 = len(seq1), len(seq2) s = [[0] * (len2 + 1) for i in range(len1 + 1)] backtrack = [[0] * (len2 + 1) for i in range(len1 + 1)] for i in range(1, len1 + 1): s[i][0] = - i * penalty for j in range(1, len2 + 1): s[0][j]...
4,359
1,718
import os, sys project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(project_path) import pickle def construct_tree_for_visual(tree, node_info_key, depth=0): tree_for_visual = {'smiles': 'http://askcos.mit.edu/draw/smiles/' + str(tree['smiles']).replace('#', '%23'), ...
10,039
3,657
''' Homework assignment for the 'Python is easy' course by Pirple. Written be Ed Yablonsky. Snowman(Hangman) game. ''' from os import ( name as os_name, system as system_call, ) from os.path import ( abspath, dirname, join as join_path, ) ''' Screen displays game output ''' class Screen: de...
3,955
1,225
""" Created on Jul 5, 2012 @author: lichtens """ import csv import os class GenericTsvReader(object): """ Read a TSV file. This class wraps a DictReader, but handles comments, which are not handled gracefully in the python csv library. The next() method assumes user is interested in the ...
2,569
706
""" ========================================================== Fitting model on imbalanced datasets and how to fight bias ========================================================== This example illustrates the problem induced by learning on datasets having imbalanced classes. Subsequently, we compare different approac...
12,376
3,818
#!/usr/bin/python import argparse import re parser = argparse.ArgumentParser(description='Fix page breaks in War of The Rebellion text') parser.add_argument('files', nargs='*', help='Files to process') args = parser.parse_args() for file in args.files: outfile = open(file + ".joined-pagebreak", ...
3,949
1,653
def main(file: str) -> None: depth = 0 distance = 0 aim = 0 with open(f"{file}.in") as f: for line in f.readlines(): line = line.rstrip().split(" ") command = line[0] unit = int(line[1]) if command == "forward": distance += unit ...
570
169
import numpy as np import tensorflow as tf import tf_seal.python.ops.seal_ops as ops from tensorflow.python.keras.utils import tf_utils from tensorflow.python.client import session as tf_session from tensorflow.python.framework import ops as tf_ops class Tensor(object): def __init__(self, value, secret_key, publ...
6,068
2,083
from django.core.exceptions import ObjectDoesNotExist from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from django.shortcuts import render from django.conf import settings from .models import Language, Type, MusicFocus, Category, Topic, RTRCategory, Host, Note, RRule, Schedule, ...
25,087
7,106
import hashlib import json from time import time import pytest from app.chaine.blockchain import Blockchain @pytest.fixture def first_block(): return { 'index': 1, 'timestamp': time(), 'transactions': [], 'proof': 1989, 'previous_hash': 1, } def test_initialization_...
2,177
760
# from django.conf.urls import patterns, url, include # from django.views.generic import TemplateView # from . import views, APP_NAME # # urlpatterns = patterns('', # url(r'^$', views.index, name='%s.index' % APP_NAME), # ) from django.urls import path, re_path, include from . import views, APP_NAME from .api impo...
886
328
import os import glob import json from pathlib import Path from flask_restful import Api, Resource, reqparse from flask_jwt_extended import jwt_required from flask import Flask, request, escape, make_response, send_from_directory import utils # incase you can't install ansi2html it's won't break the api try: from ...
1,721
513
"""Module with hahomematic services.""" from __future__ import annotations from datetime import datetime import logging from hahomematic.const import ( ATTR_ADDRESS, ATTR_INTERFACE_ID, ATTR_NAME, ATTR_PARAMETER, ATTR_VALUE, HmPlatform, ) from hahomematic.device import HmDevice from hahomematic...
13,534
4,488
# Generated by Django 3.2.3 on 2021-06-03 00:35 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Livro', fields=[ ('id', models.BigAutoField...
865
262
# Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # The Universal Permissive License (UPL), Version 1.0 # # Subject to the condition set forth below, permission is hereby granted to any # person obtaining a copy of this softw...
4,284
1,394
from brownie import accounts, Wei, chain, ApeToken, ApeVaultFactory, ApeDistributor, ApeRegistry, ApeRouter, FeeRegistry, MockRegistry, MockVaultFactory, MockToken, MockVault def deploy_token(): funds = accounts.load('moist', '\0') user = accounts.load('ape_deployer', '\0') multi_sig = '0x15B513F658f7390D8720dCE32...
6,284
2,585
from django.contrib.auth.mixins import PermissionRequiredMixin from django.urls import reverse_lazy from django.views.generic import DetailView, ListView, UpdateView from .models import Committee class CommitteeList(ListView): model = Committee template_name = 'groups/committee_list.html' context_object_...
971
277
""" Copyright (c) 2016-2019 Keith Sterling http://www.keithsterling.com 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 use, copy, m...
2,200
653
# -*- coding: utf-8 -*- # # This file is part of REANA. # Copyright (C) 2018 CERN. # # REANA is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """REANA-Commons module to manage AMQP connections on REANA.""" import json import logging fr...
6,095
1,659
from sqlalchemy import ( BigInteger, Column, DateTime, Text, String, Integer, ) from sqlalchemy.sql.functions import current_timestamp from model.base import BaseObject class Commit(BaseObject): __tablename__ = 'commits' id = Column(BigInteger, primary_key=True, autoincrement=True) ...
1,219
377
from drae import search
24
7
"""The tests for the Template select platform.""" import pytest from homeassistant import setup from homeassistant.components.input_select import ( ATTR_OPTION as INPUT_SELECT_ATTR_OPTION, ATTR_OPTIONS as INPUT_SELECT_ATTR_OPTIONS, DOMAIN as INPUT_SELECT_DOMAIN, SERVICE_SELECT_OPTION as INPUT_SELECT_SE...
13,825
4,075
import os import random import string import base64 from django.utils import timezone from django.contrib.auth.hashers import make_password, check_password from django.test import TestCase from parameterized import parameterized from core.models import Module, EntryPoint, ExternalAuthorizationSession, User AUTHORIZA...
7,211
2,005
from rhombus.lib.utils import get_dbhandler from rhombus.lib.tags import * from cmsfix.models.node import Node import re # the pattern below is either # ///123 # <<MacroName>> # [[MacroName]] pattern = re.compile('///(\d+)|///\{([\w-]+)\}|\&lt\;\&lt\;(.+)\&gt\;\&gt\;|\[\[(.+)\]\]') # syntax for Macro is: # [[MacroN...
6,729
2,182
''' #;+ #; NAME: #; sdss.qso #; Version 1.1 #; #; PURPOSE: #; Class for SDSS QSO #; 2015 Written by JXP #;- #;------------------------------------------------------------------------------ ''' # Import libraries import numpy as np import os from astropy.table import QTable, Column from astropy.coordinates i...
2,629
881
name = "module" from .module import func
41
13
import unittest import numpy as np from openmdao.utils.assert_utils import assert_near_equal from wisdem.optimization_drivers.dakota_driver import DakotaOptimizer try: import dakota except ImportError: dakota = None @unittest.skipIf(dakota is None, "only run if Dakota is installed.") class Te...
3,110
1,156
#-*- coding: utf-8 -*- #! /usr/bin/env python ''' #------------------------------------------------------------ filename: lab4_runTFCurveFitting.py This is an example for linear regression in tensorflow Which is a curve fitting example written by Jaewook Kang @ Aug 2017 #---------------------------------------...
6,848
2,292
# coding=utf-8 from app.route.stats.processor import * from app.api.base.base_router import BaseRouter from app.api.base import base_name as names class Stats(BaseRouter): def __init__(self): super().__init__() self.args = [names.face, names.post, names.socnet, names.likes, names.views, names.com...
577
183
from Bio import TogoWS import argparse import sys import os def summary(options): num_reads = 0 num_correct = 0 with open(options.input) as file_input: for line in file_input: line = line.rstrip() ele = line.split("\t") if "FAILED" in line: contin...
1,168
348
# coding=utf8 class MetaSingleton(type): def __init__(cls, *args): type.__init__(cls, *args) cls.instance = None def __call__(cls, *args, **kwargs): if not cls.instance: cls.instance = type.__call__(cls, *args, **kwargs) return cls.instance
296
97
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
5,108
1,504
__all__ = ["transformers", "vision"] from .transformers import * from .vision import *
88
27
# This sample tests the checker's ability to enforce # type invariance for type arguments. # pyright: strict from typing import Dict, Union foo: Dict[Union[int, str], str] = {} bar: Dict[str, str] = {} # This should generate an error because # both type parameters for Dict are invariant, # and str isn't assignable ...
350
110
how_many_snakes = 1 snake_string = """ Welcome to Python3! ____ / . .\\ \\ ---< \\ / __________/ / -=:___________/ <3, Juno """ print(snake_string * how_many_snakes)
224
87
from flask import Flask from flask import render_template, redirect, session, request app = Flask(__name__) app.secret_key = 'ThisIsSecret' @app.route('/') def nothing(): return render_template('index.html') @app.route('/ninja') def ninja(): x = 'tmnt' return render_template('ninjas.html', x=x) @app.route...
658
254
# -*- coding:utf-8 -*- """ Description: Inventory Class Usage: from neo.Network.Inventory import Inventory """ from neo.IO.MemoryStream import MemoryStream from neocore.IO.BinaryWriter import BinaryWriter class Inventory(object): """docstring for Inventory""" def __init__(self): """ ...
941
282
""" Copyright (C) 2021 Clariteia SL This file is part of minos framework. Minos framework can not be copied and/or distributed without the express permission of Clariteia SL. """ import unittest from minos.api_gateway.common import ( EmptyMinosModelSequenceException, MinosAttributeValidationException, Mi...
4,748
1,298
# coding: utf-8 # quote from kmaiya/HQAutomator # 谷歌搜索部分原版搬运,未做修改 import time import json import requests import webbrowser questions = [] def get_answer(): resp = requests.get('http://htpmsg.jiecaojingxuan.com/msg/current',timeout=4).text resp_dict = json.loads(resp) if resp_dict['msg']...
977
360
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: TensorflowModel.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import messa...
21,936
8,456
"""Classes representing color entries and mappings.""" # ============================================================================= # IMPORTS # ============================================================================= from __future__ import annotations # Standard Library import re from typing import TYPE_CHEC...
8,460
2,160
import math import numpy as np # return an array K of size (d_max, d_max, N, N), K[i][j] is kernel value of depth i + 1 with first j layers fixed def kernel_value_batch(X, d_max): K = np.zeros((d_max, d_max, X.shape[0], X.shape[0])) for fix_dep in range(d_max): S = np.matmul(X, X.T) H = np.ze...
1,407
613
import nltk from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer, PorterStemmer from nltk.tokenize import sent_tokenize , word_tokenize import glob import re import os import numpy as np import sys nltk.download('stopwords') nltk.download('punkt') Stopwords = set(stopwords.words('english')) all_w...
1,509
530
# Copyright 2017 Ricardo Garcia Silva # # 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 agree...
4,911
1,372
# -*- coding: utf-8 -*- # 基于python Threading模块封装的异步函数装饰器 import time from functools import wraps from threading import Thread def async_call(fn): """一次简单的异步处理操作,装饰在要异步执行的函数前,再调用该函数即可执行单次异步操作(开辟一条新的线程) Args: :fn(function):需要异步处理的方法 Return: :wrapper(function): """ @wraps(fn) # 解决...
2,210
1,007
class Person: olhos = 2 def __init__(self, *children, name=None, year=0): self.year = year self.name = name self.children = list(children) def cumprimentar(self): return 'Hello' @staticmethod def metodo_estatico(): return 123 @classmethod def metod...
872
332
"""Test combined function.""" from cmatools.combine.combine import combined def test_combined(): """Test of combined function""" assert combined() == "this hello cma"
179
53
"""Enhancement to reformat `top_events_X` from match in order to reformat and put it back to be able to use in alert message. New format: top_events_keys_XXX -- contains array of corresponding key values defined in `top_count_keys`, where `XXX` key from `top_count_keys` array. top_events_values_XXX -- contains arra...
1,323
449
import numpy import chainer import chainer.functions as F import chainer.links as L from chainer import reporter embed_init = chainer.initializers.Uniform(.25) def block_embed(embed, x, dropout=0.): """Embedding function followed by convolution Args: embed (callable): A :func:`~chainer.functions.em...
4,054
1,380
from flask_login import UserMixin class Users(UserMixin): # Luodaan näennäinen tietokanta käyttäjistä user_database = {"kayttaja": ("kayttaja", "salasana"), "tunnus": ("tunnus", "passu")} def __init__(self, id, username, password): self.id = id self.username = username self.pas...
904
289
""" matmul autotvm [batch,in_dim] x [in_dim,out_dim] search_matmul_config(batch,in_dim,out_dim,num_trials): input: batch,in_dim,out_dim,num_trials [batch,in_dim] x [in_dim,out_dim] num_trials: num of trials, default: 1000 output: log (json format) use autotvm to search configs for the matm...
13,726
5,665
from django.contrib import admin from .models import ActivityLog, ReviewActionReasonLog from olympia.reviewers.models import ReviewActionReason class ActivityLogAdmin(admin.ModelAdmin): list_display = ( 'created', 'user', '__str__', ) raw_id_fields = ('user',) readonly_fields ...
2,240
672
import subprocess import sys import time import os ############################# # COLORING YOUR SHELL # ############################# R = "\033[1;31m" # B = "\033[1;34m" # Y = "\033[1;33m" # G = "\033[1;32m" # RS = "\033[0m" # W = "\033[1;37m" ...
1,261
453
# Copyright The PyTorch Lightning team. # # 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 i...
2,041
695
import oneflow.experimental as flow from oneflow.experimental import optim import oneflow.experimental.nn as nn from utils.dataset import * from utils.tensor_utils import * from models.rnn_model import RNN import argparse import time import math import numpy as np flow.env.init() flow.enable_eager_execution() def ...
4,258
1,474
import json import os from ..metaflow_config import DATASTORE_LOCAL_DIR, DATASTORE_SYSROOT_LOCAL from .datastore_storage import CloseAfterUse, DataStoreStorage from .exceptions import DataException class LocalStorage(DataStoreStorage): TYPE = "local" METADATA_DIR = "_meta" @classmethod def get_datas...
4,763
1,324
from __future__ import division, print_function from scipy.spatial.distance import euclidean from numpy import mean from pdb import set_trace class measure: def __init__(self,model): self.mdl = model def convergence(self, obtained): """ Calculate the convergence metric with respect to ideal soluti...
669
222
''' pip3 install BeautifulSoup4 pip3 install pypinyin ''' import requests import re import os import shutil from bs4 import BeautifulSoup from util import Profile, write_poem def parse_poem_profile_td(td): container = td.find('div') if container is None: container = td title_a = contain...
2,499
885
class Animal: def __init__(self): self.name = "" self.weight = 0 self.sound = "" def setName(self, name): self.name = name def getName(self): return self.name def setWeight(self, weight): self.weight = weight def getWeight(self): return sel...
439
134
# Copyright 2020 D-Wave Systems 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 wri...
5,086
1,467
''' Neural networks. Forward propagation in an already trained network in TensorFlow 2.0-2.1 (to use the network for classification). TF 2.0: Option 0 takes 0.08 sec. Option 1 takes 0.08 sec. Option 6 takes 0.08 sec. Option 2 takes 4.7 sec. Option 3 takes 1.6 sec. Option 4 takes 5.2 sec. Option 5 takes 0.08 sec. Optio...
12,084
4,335