text
string
size
int64
token_count
int64
from django.contrib.auth import models as auth_models from django.db import models from django.urls import reverse class User(auth_models.AbstractUser): """Extends default model to add project specific fields.""" birth_date = models.DateField(help_text="Employee Date of birth.") address = models.TextFiel...
498
127
import numpy as np import pandas as pd import torch import torch.nn as nn from pytorch_model import * from pytorch_clean import * from sklearn.metrics import classification_report from torch.optim import optimizer from transformers import AutoModel, AutoTokenizer from vncorenlp import VnCoreNLP from vncorenlp.vncorenlp...
3,623
1,390
# test builtin sorted try: sorted set except: import sys print("SKIP") sys.exit() print(sorted(set(range(100)))) print(sorted(set(range(100)), key=lambda x: x + 100*(x % 2))) # need to use keyword argument try: sorted([], None) except TypeError: print("TypeError")
295
109
# -*- coding: utf-8 -*- """Serializer tests for the Mendeley addon.""" import pytest from addons.base.tests.serializers import CitationAddonSerializerTestSuiteMixin from addons.base.tests.utils import MockFolder from addons.mendeley.tests.factories import MendeleyAccountFactory from addons.mendeley.serializer import M...
643
198
from app import run_migration from flask import current_app as app from flask_testing import TestCase from project import db class BaseTestCase(TestCase): def create_app(self): app.config.from_object('project.configs.TestingConfig') return app def setUp(self): run_migration() def...
465
144
""" N layers optimistic neural network """ import torch class ThreeLayersNN(torch.nn.Module): def __init__(self, in_dim, out_dim, h_dim, activation='relu'): """ :param in_dim: (int) input dimension :param out_dim: (int) output dimension """ super(ThreeLayersNN, self).__in...
956
335
''' ? (c) 2018 - laymonage ''' import os import random import requests from .dropson import dbx_dl, get_json def surprise(safe=False): ''' ? ''' cat_api = 'http://thecatapi.com/api/images/get' prev_url = requests.get(cat_api) prev_url = prev_url.url.replace('http://', 'https://') if safe...
630
233
# Copyright 2015-2016 Tim Burke # # 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 writin...
11,019
3,209
# -*- coding: utf-8 -*- r""" Information-set decoding for linear codes Information-set decoding is a probabilistic decoding strategy that essentially tries to guess `k` correct positions in the received word, where `k` is the dimension of the code. A codeword agreeing with the received word on the guessed position can...
42,873
13,086
# coding: utf-8 """ Usage: python3 -m satelitedl --date 19900101 Authore: Ryosuke Tomita Date: 2021/11/02 """ import os from os.path import abspath, dirname, join from datetime import datetime from typing import Union from .options import parse_args from .scrapeimg import ScrapingImg def judge_date_type(date: str) ->...
3,380
1,260
from .four_momentum import FourMomentum class Particle: def __init__(self, pdg_id, momentum): self.pdg_id = pdg_id self.momentum = momentum self.momentum.set_basis( (momentum.px,momentum.py, momentum.pz, Particle.get_mass(pdg_id)), 'x,y,z,m' ...
602
225
from icolos.utils.enums.step_enums import StepBaseEnum, StepGromacsEnum from icolos.utils.enums.program_parameters import GromacsEnum from icolos.core.workflow_steps.gromacs.base import StepGromacsBase from icolos.utils.execute_external.gromacs import GromacsExecutor from pydantic import BaseModel from icolos.core.work...
2,572
811
import math import tensorflow as tf from mayo.log import log from mayo.util import ( Percent, memoize_method, memoize_property, object_from_params) from mayo.session.base import SessionBase class Train(SessionBase): mode = 'train' def __init__(self, config): super().__init__(config) sel...
6,811
2,039
def is_lazy_user(user): """ Return True if the passed user is a lazy user. """ # Anonymous users are not lazy. if user.is_anonymous: return False # Check the user backend. If the lazy signup backend # authenticated them, then the user is lazy. backend = getattr(user, 'backend', None) ...
570
171
# -*- coding: utf-8 -*- # This script copies a directory of OBS-tQ or OBS-tN markdown files to a second location. # It cleans up the files in these ways: # Ensures blank lines surrounding markdown headers. # Fixes links of this form [[:en:...]] # Removes leading spaces. # Global variables source_dir = r'C:\DC...
2,753
917
# -*- coding: utf-8 -*- """ Created on Mon Nov 20 23:06:49 2017 @author: Grant An implementation of the Thomas algorithm in Python, using just-in-time compiling from numba for additional speed """ import numpy as np from numba import njit, f8 def solve(A, d): '''Helper function for Thomas algorit...
2,620
970
from base64 import b64encode import pytest @pytest.mark.django_db def test_login_view(user, client, settings): """Test that the login view can login and logout.""" login_url = f"/{settings.LOGIN_URL.strip('/')}/" # Django doesn't store the raw password, so we need to set one we know. password = "A ...
1,444
441
from datetime import time from vnpy.app.cta_strategy import ( CtaTemplate, StopOrder, TickData, BarData, TradeData, OrderData, BarGenerator, ArrayManager ) from vnpy.app.cta_strategy.base import ( EngineType, STOPORDER_PREFIX, StopOrder, StopOrderStatus, ) from vnpy.app.c...
9,445
3,644
# run.py """ Script for running a specific pipeline from a given yaml config file """ import os import argparse import yaml from importlib import import_module import numpy as np import time import pandas as pd def import_from_path(path_to_module, obj_name = None): """ Import an object from a module based o...
4,757
1,384
import pygame from pygame.sprite import Group from button import Button from game_stats import GameStats from settings import Settings from ship import Ship from scoreboard import Scoreboard import game_funcitons as gf def run_game(): pygame.init() pygame.mixer.init() ai_settings = Settings() screen =...
1,970
722
import os from contextlib import contextmanager class LocalFS: @contextmanager def get(self, src): path = os.path.realpath(os.path.expanduser(src)) yield path
185
56
import os from pyfakefs import fake_filesystem_unittest from devbox.utilities.manifest_parser import ManifestParser class TestManifestParser(fake_filesystem_unittest.TestCase): def setUp(self): self.setUpPyfakefs() def test_manifest_parser(self): # Arrange self.fs.CreateFile('my-app/...
3,542
1,027
from enum import Enum, auto from string import Template class MessageRegister: def __init__(self, dispatch_table=None): self.dispatch = dict() if dispatch_table is None else dispatch_table def register(self, ref): def decorator(func): self.dispatch[ref] = func return func return decorator def get(sel...
2,140
693
from django.apps import AppConfig class ClxQueryConfig(AppConfig): name = "clxquery"
91
30
import os import shutil import pychemia import tempfile import unittest class MyTestCase(unittest.TestCase): def test_incar(self): """ Test (pychemia.code.vasp) [INCAR parsing and writing] : """ print(os.getcwd()) iv = pychemia.code.vasp.read_incar('tests/data/vasp_0...
5,254
2,078
import os class Material: def __init__(self, name, color, outputs): self.name = name self.color = color self.outputs = outputs materials = [Material("dilithium", 0xddcecb, ("DUST", "GEM")), Material("iron", 0xafafaf, ("SHEET", "STICK", "DUST", "PLATE")), Material("gold", 0xffff5d, ("D...
7,048
2,597
# # # 0=================================0 # | Kernel Point Convolutions | # 0=================================0 # # # ---------------------------------------------------------------------------------------------------------------------- # # Class handling SemanticKitti dataset. # ...
89,471
32,282
#!/usr/bin/env python __author__ = "Mari Wahl" __copyright__ = "Copyright 2014, The Cogent Project" __credits__ = ["Mari Wahl"] __license__ = "GPL" __version__ = "2.0" __maintainer__ = "Mari Wahl" __email__ = "marina.w4hl@gmail.com" import os from constants import SUBFOLDERS, FEATURES def create_input_files(...
1,128
410
# -*- coding: utf-8 -*- # # Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
18,361
5,082
from __future__ import absolute_import, division, print_function, unicode_literals import sqlite3 def fetchall(database, query, kwds): conn = sqlite3.connect(database) try: cursor = conn.execute(query, kwds) return cursor.fetchall() finally: conn.close()
294
87
#!/usr/bin/env python # -*- coding: utf-8 -*- # Common Python library imports import re import unicodedata # Pip package imports from flask_sqlalchemy.model import camel_to_snake_case from flask import current_app from itsdangerous import URLSafeSerializer, BadData from loguru import logger # Internal package import...
1,775
603
from typing import List import torch from detectron2.structures import ImageList, Boxes, Instances, pairwise_iou from detectron2.modeling.box_regression import Box2BoxTransform from detectron2.modeling.roi_heads import ROI_HEADS_REGISTRY, StandardROIHeads from detectron2.modeling.roi_heads.cascade_rcnn import CascadeR...
3,028
1,073
# coding=utf-8 # tensorflow tf.contrib.data api test import tensorflow as tf # file path filename = '' batch_size = 100 aa = (tf.contrib.data.TextLineDataset(filename) .map((lambda line: tf.decode_csv(line, record_defaults=[['1'], ['1'], ['1']], field_delim='\t'))) .shuffle(buffer_size=1000) .bat...
350
133
''' 实验名称:音频播放 版本:v1.0 日期:2020.12 作者:01Studio 说明:MP3/WAV音频文件播放。使用物理按键控制 ''' #导入相关模块 import audio,time from pyb import Switch from machine import Pin #构建音频对象 wm=audio.WM8978() vol = 80 #音量初始化,80 ###################### # 播放 USR按键 ###################### play_flag = 0 def music_play(): global play_flag play_fla...
1,333
706
#!/usr/bin/env python import rospy from nav_msgs.msg import Odometry lin_min = 0.0 lin_max = 0.0 ang_min = 0.0 ang_max = 0.0 def odom_cb(msg): global lin_min, lin_max, ang_min, ang_max if lin_min > msg.twist.twist.linear.x: lin_min = msg.twist.twist.linear.x if lin_max < msg.twist.twist.linear.x...
942
396
# this file is to store all custom classes import tkinter as tk # class to store tkinter window properties # font: tk font dictionary {family, size, weight, slant, underline, overstrike} # font color: string # nrows: the number of rows of lyric displayed (integer greater than 0) # width: window width (int greater tha...
5,076
1,668
""" Unit test utilities. """ import textwrap def clean_multiline_string( multiline_string, sep='\n' ): """ Dedent, split, remove first and last empty lines, rejoin. """ multiline_string = textwrap.dedent( multiline_string ) string_list = multiline_string.split( sep ) if not string_list[0]: ...
563
201
import asyncio import json def test_chunked_messages(plugin, read): request = { "jsonrpc": "2.0", "method": "install_game", "params": { "game_id": "3" } } message = json.dumps(request).encode() + b"\n" read.side_effect = [message[:5], message[5:], b""] a...
1,387
476
import os import unittest from ....BaseTestCase import BaseTestCase from kombi.Crawler import Crawler from kombi.Crawler.Fs.Image import ImageCrawler from kombi.Crawler.PathHolder import PathHolder class ImageCrawlerTest(BaseTestCase): """Test Image crawler.""" __singleFile = os.path.join(BaseTestCase.dataTes...
2,731
796
#!/usr/bin/env python import unittest, asyncio, asynctest, websockets, json from remote_params import HttpServer, Params, Server, Remote, create_sync_params, schema_list from remote_params.WebsocketServer import WebsocketServer class MockSocket: def __init__(self): self.close_count = 0 self.msgs = [] de...
3,688
1,303
import warnings import pandas as pd from nltk.sentiment.vader import SentimentIntensityAnalyzer warnings.filterwarnings("ignore") def classify_comments(text_file, page_name): """ Description: This function recives a text file and convert it into csv file to enable to label the comments inside that file, ...
3,592
1,210
import pytest @pytest.mark.parametrize( "script", (None, "test.py"), ) def test_restart_app(mocked_android_modules, app_instance, test_py_script, script): from android_here import restart_app restart_app(script) def test_script_path_resolved(mocked_android_modules, app_instance, test_py_script): fro...
846
277
import sys sys.path.append('..') from Network.facenet.API import build_face_manager, detetion_and_recongnize ''' You have to build face manager before you start detection and recongnize. ''' face_manager = build_face_manager(r"face/dataset/path") result = detetion_and_recongnize(face_manager, r"images/path/you/want/...
346
120
class DispositivoEntrada: def __init__(self, marca, tipo_entrada): self._marca = marca self.tipo_entrada = tipo_entrada
149
51
from django.urls import path from .views import HomepageView urlpatterns = [ path('', HomepageView.as_view(), name='home'), ]
132
43
import copy import logging import warnings from kolibri.plugins.registry import registered_plugins logger = logging.getLogger(__name__) def __validate_config_option( section, name, base_config_spec, plugin_specs, module_path ): # Raise an error if someone tries to overwrite a base option # except for th...
5,394
1,346
from io import open import time import math import torch import torch.nn.functional as F from config import MAX_LENGTH from config import SOS_token from config import EOS_token from config import device class Lang: def __init__(self, name): self.name = name self.word2index = {} self.word2co...
2,909
1,032
import asyncio import json import os from datetime import datetime from src.common import log_utils, pushshift from src.common.filesystem import S3FileSystem, StubFileSystem from src.common.lambda_context import local_lambda_invocation def handler(event, context): logger = log_utils.get_logger("archive-comments-...
1,941
618
import os import sys import json import argparse import progressbar from pathlib import Path from random import shuffle from time import time import torch from cpc.dataset import findAllSeqs from cpc.feature_loader import buildFeature, FeatureModule, loadModel, buildFeature_batch from cpc.criterion.clustering import kM...
11,578
3,495
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/) # # 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 appli...
1,591
526
import glob import os import os.path import sys import shutil import cPickle from types import StringType, UnicodeType from distutils.core import setup from distutils.extension import Extension from distutils.command.install import install PY3K = sys.version_info[0] > 2 with open('README.rst') as inp: long_descr...
4,140
1,285
"""Remove limit used from query model Revision ID: d7c1a0d6f2da Revises: afc69274c25a Create Date: 2019-06-04 10:12:36.675369 """ # revision identifiers, used by Alembic. revision = "d7c1a0d6f2da" down_revision = "afc69274c25a" import sqlalchemy as sa from alembic import op def upgrade(): with op.batch_alter_...
491
218
EPS = 1e-5 import threading import torch import torch.nn as nn import torch.nn.functional as F from .aggregators import AGGREGATORS from .layers import MLP, FCLayer from .scalers import SCALERS class EIGLayerComplex(nn.Module): def __init__(self, in_dim, out_dim, dropout, graph_norm, batch_norm, aggregators, sc...
13,393
4,636
# -*- coding: utf-8 -*- import os import json import hashlib from warnings import simplefilter from utils import log_util # ignore all warnings simplefilter(action='ignore') ##Global parameters scriptDir = os.path.dirname(__file__) dataPath = os.path.join(scriptDir, '..', 'training_data', 'intents') propertyFile =...
3,553
1,120
import io import json from google.auth import compute_engine from google.oauth2 import service_account def gcp_credentials(service_account_file): if service_account_file: with io.open(service_account_file, 'r', encoding='utf-8') as json_fi: credentials_info = json.load(json_fi) creden...
641
168
import requests import tweepy import random import time import os import bs4 from bs4 import BeautifulSoup from pybooru import Moebooru siteurl='https://www.sakugabooru.com/post/show/' header = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/53...
4,218
1,388
""" """ from membership.web.urls import membership_urls from public.web.urls import error_urls, public_urls, static_urls from public.web.views import home from wheezy.routing import url locale_pattern = "{locale:(en|ru)}/" locale_defaults = {"locale": "en"} locale_urls = public_urls + membership_urls locale_urls.app...
491
158
from stheno import ( B, # Linear algebra backend Graph, # Graph that keep track of the graphical model GP, # Gaussian process EQ, # Squared-exponential kernel Matern12, # Matern-1/2 kernel Matern52, # Matern-5/2 kernel Delta, # Noise kernel Normal, # Gaussian distribution Dia...
5,571
1,959
import itertools as it from tests.utilities import ( is_equivalent_atom, is_equivalent_molecule, ) def are_equivalent_functional_groups( functional_groups1, functional_groups2, ): functional_groups = it.zip_longest( functional_groups1, functional_groups2, ) for fg1, fg2 in...
1,995
683
from .pydeps import pydeps pydeps()
36
16
from os import listdir from os.path import join import os, errno def getImageNum(rootDir): return len(listdir(join(rootDir))) def safeMkdir(path:str): try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise
271
95
#coding:utf-8 import re import math from docclass import Classifier def test_infc_func(): c = Classifier(getfeatures=None) c.infc("python", "good") c.infc("python", "good") c.infc("the", "bad") c.infc("the", "good") print c.fc if __name__ == "__main__": test_infc_func()
305
124
import abc import time from dataclasses import dataclass from functools import partial from typing import TYPE_CHECKING import kubernetes from kubernetes.utils.create_from_yaml import FailToCreateError from urllib3.exceptions import MaxRetryError from hermes.cloudbreak.utils import snakeify, wait_for if TYPE_CHECKIN...
8,560
2,268
c = float(input("Enter Amount Between 0-99 :")) print(c // 20, "Twenties") c = c % 20 print(c // 10, "Tens") c = c % 10 print(c // 5, "Fives") c = c % 5 print(c // 1, "Ones") c = c % 1 print(c // 0.25, "Quarters") c = c % 0.25 print(c // 0.1, "Dimes") c = c % 0.1 print(c // 0.05, "Nickles") c = c % 0.05 print(c // 0.01...
333
190
#!/usr/bin/env python # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2019 DataONE # # Licensed under the Apache License, Version 2.0 (t...
4,772
1,477
import copy import os.path as osp import tempfile import pytest import torch from mmocr.models import build_detector def _create_dummy_vocab_file(vocab_file): with open(vocab_file, 'w') as fw: for char in list(map(chr, range(ord('a'), ord('z') + 1))): fw.write(char + '\n') def _get_config_...
2,159
788
class Cita: def __init__(self,id,solicitante,fecha,hora,motivo,estado,doctor): self.id = id self.solicitante = solicitante self.fecha = fecha self.hora = hora self.motivo = motivo self.estado = estado self.doctor = doctor def getId(self): ...
1,106
374
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/models/layers/models.layers.graph.ipynb (unless otherwise specified). __all__ = ['FiGNN_Layer', 'GraphLayer'] # Cell import torch import torch.nn as nn import torch.nn.functional as F from itertools import product # Cell class FiGNN_Layer(nn.Module): def __init__(s...
3,333
1,134
#!venv/bin/python # coding=UTF-8 # -*- coding: UTF-8 -*- # vim: set fileencoding=UTF-8 : """ Double-deck bid euchre Implementation is similar to the rules given by Craig Powers https://www.pagat.com/euchre/bideuch.html Notable differences (to match how I learned in high school calculus) include: * Minimum bid o...
20,638
6,716
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util class ErrorResponse(Model): """NOTE: This class is auto generated by the swagg...
3,908
1,195
#!/usr/bin/env python # coding: utf-8 from dh import dh_solver #from IPython.display import Latex import sympy from sympy import Symbol import numpy as np #create an object mtb = dh_solver() # ## adding the dh paramters # just use obj.add() method to add a set of dh paramters in the kinematic chain, the first o...
1,534
572
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.testutil.pants_integration_test import run_pants def test_goals() -> None: pants_run = run_pants(["goals"]) pants_run.assert_success() assert "to get help for a pa...
1,646
521
def extract_smiles(): return ["c1ccccc1", "Cc1ccccc1", "c1ccccc1", "CCO"]
78
37
""" A Python Class A simple Python graph class to do essential operations into graph. """ import operator import math from random import choice from collections import defaultdict import networkx as nx class ProA(): def __init__(self, graph): """ Initializes util object. """ self.__graph =...
9,903
2,779
#!/usr/bin/env python # -*- coding: utf-8 -*- import shutil from os.path import basename, exists, isdir, splitext from sfzparser import SFZParser def main(args=None): fn = args[0] bn = splitext(basename(fn))[0] parser = SFZParser(fn) fixed = False for name, sect in parser.sections: # fi...
1,214
387
"""Kerasの各種モデル。""" # pylint: skip-file # flake8: noqa from . import darknet53, efficientnet, xception
103
50
import unittest from huobi.rest.client import HuobiRestClient from huobi.rest.error import ( HuobiRestiApiError ) import os from os.path import join, dirname from dotenv import load_dotenv dotenv_path = join(dirname(dirname(dirname(dirname(__file__)))), '.env') load_dotenv(dotenv_path) class TestCommonEndpoint(...
1,536
494
# # Copyright 2017 Vitalii Kulanov # # 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 ...
8,477
2,150
# Copyright 2014 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. """Measures the average time used by git-push command in CQ based on data from chromium-cq-status.appspot.com.""" import argparse import json import logging...
2,928
870
import random def create_random_id(): return str(random.randint(100000,999999999999999))
93
45
from bitmovin_api_sdk.encoding.infrastructure.kubernetes.configuration.configuration_api import ConfigurationApi
113
28
# Copyright (c) 2020, NVIDIA CORPORATION. from __future__ import annotations from typing import TYPE_CHECKING, Optional, Union, overload from typing_extensions import Literal import cudf if TYPE_CHECKING: from cudf.core.column import ColumnBase class ColumnMethodsMixin: _column: ColumnBase _parent: O...
3,427
972
from selenium.common.exceptions import NoSuchElementException, TimeoutException class DomHelper(object): driver = None waiter = None def open_page(self, url): self.driver.get(url) def reload_page(self): self.driver.refresh() def print_el(self, element): print('tag: ' + e...
8,139
2,254
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.contrib.postgres.fields import ArrayField # Create your models here. """ class NewSearch(models.Model): SINGLEVIEW = 'similarityindex' MULTIVIEW = 'updated_simi...
1,491
574
from machine import Pin class simple_encoder(): def __init__(self, ra, rb, pin_irq): self.ra = ra self.rb = rb self.counter = 0 self.ra.irq(trigger=pin_irq, handler=self.turn) self.rb.irq(trigger=pin_irq, handler=self.turn) def turn(self, pin): change...
776
251
# Example of Naive Bayes implemented from Scratch in Python import csv import random import math import xgboost as xgb import matplotlib.pyplot as plt import numpy as np def loadCsv(filename): lines = csv.reader(open(filename, "r")) dataset = list(lines) for i in range(len(dataset)): dataset[i] = [flo...
7,928
2,970
from collections import namedtuple from copy import deepcopy import numpy as np # data type for 3D-Coordinates Point = namedtuple('Point', 'x y z') # monkey patch function def serializesection(self): data = dict(self._asdict()) data['pos'] = dict(self.pos._asdict()) return data class _Wing: """ ...
7,367
2,342
# -*- coding: utf-8 -*- """ Cross-docking truck data. This data is generated by a generate_dataset.py script. Created: Feb 18, 2019 at 07:30:02 PM Copyright (c) 2022, Krerkkiat Chusap This souce code is licensed under BSD 3-Clause "New" or "Revised" License (see LICENSE for details). """ from pathlib import Path # ...
3,103
2,461
import base # 开始真正的模型训练 import torch import torch.nn as nn # 实例化网络 net = base.MyCustomNet() # 定义数据集的训练迭代轮次 max_epoch = 5 # 定义学习率 learning_rate = 0.001 # 定义loss函数、定义优化器 import torch.optim as optim criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=learning_rate, momentum=0.9) # 进行模型训练 fo...
1,121
462
import os import random from typing import List, Tuple, Callable import torch from ignite.contrib.handlers import ProgressBar, LRScheduler from ignite.handlers import ModelCheckpoint from sklearn.base import BaseEstimator, TransformerMixin from torch import nn from torch import optim from torch.nn.modules.loss import _...
14,934
4,451
from random import choice from time import sleep jokenpo = ['Pedra', 'Papel', 'Tesoura'] jokenposter_stainger = choice(jokenpo) jogador = int(input('Qual a sua jogada?' '\n1. Pedra' '\n2. Papel' '\n3. Tesoura' '\nEscolha: ')) print('\nJO....
1,716
718
from django.apps import AppConfig class TextGeneratorConfig(AppConfig): name = 'text_generator'
102
29
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import stat protoc_exec = None def find_protoc(): global protoc_exec if protoc_exec is not None: return protoc_exec script_dir = os.path.dirname(os.path.realpath(__file__)) if sys.platform[0:5].lower() == "linux": protoc_ex...
760
303
from io import BytesIO import json import re import requests from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required, permission_required from django.core.exceptions import PermissionDenied from django.core.paginator import EmptyPage, PageNotAnInte...
43,253
11,723
# 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 may not u...
2,877
894
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*- import pytest from django.test import RequestFactory from django.urls import reverse from doubles import allow, expect from rest_framework import status from apps.accounts.models.choices import ActionCategory from apps.accounts.services.auth import AuthService from apps...
1,376
413
import json import time import pytest from contextlib import contextmanager from datetime import datetime, timedelta from functools import wraps from data.database import QueueItem from data.queue import ( WorkQueue, MINIMUM_EXTENSION, queue_items_locked, queue_items_available, queue_items_availa...
15,240
5,134
__version__ = '1.0.19'
24
15
import random def shuffle(cards): for i in range(len(cards)): randindex = random.randrange(0, len(cards)) cards[randindex], cards[i] = cards[i], cards[randindex] def run(): stack = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 'A'] * 4 shuffle(stack) stack_top = 51 dealer_cards = [] your_cards = [] deale...
1,432
653
#! /usr/bin/env python # Copyright (c) 2017, Cuichaowen. All rights reserved. # -*- coding: utf-8 -*- # ops helper dictionary class Dictionary(object): """ Dictionary for op param which needs to be combined """ def __init__(self): self.__dict__ = {} def set_attr(self, **kwargs): ...
11,017
2,548